Commit 18e84623 authored by Vowstar's avatar Vowstar
Browse files

Merge pull request #463 from DiUS/newcrypto

Crypto module, take 2
parents d8a8746b d855584b
......@@ -37,7 +37,8 @@ SUBDIRS= \
wofs \
modules \
spiffs \
cjson
cjson \
crypto \
endif # } PDIR
......@@ -86,6 +87,7 @@ COMPONENTS_eagle.app.v6 = \
wofs/wofs.a \
spiffs/spiffs.a \
cjson/libcjson.a \
crypto/libcrypto.a \
modules/libmodules.a
LINKFLAGS_eagle.app.v6 = \
......
#############################################################
# Required variables for each makefile
# Discard this section from all parent makefiles
# Expected variables (with automatic defaults):
# CSRCS (all "C" files in the dir)
# SUBDIRS (all subdirs with a Makefile)
# GEN_LIBS - list of libs to be generated ()
# GEN_IMAGES - list of images to be generated ()
# COMPONENTS_xxx - a list of libs/objs in the form
# subdir/lib to be extracted and rolled up into
# a generated lib/image xxx.a ()
#
ifndef PDIR
GEN_LIBS = libcrypto.a
endif
#############################################################
# Configuration i.e. compile options etc.
# Target specific stuff (defines etc.) goes in here!
# Generally values applying to a tree are captured in the
# makefile at its root level - these are then overridden
# for a subtree within the makefile rooted therein
#
#DEFINES +=
#############################################################
# Recursion Magic - Don't touch this!!
#
# Each subtree potentially has an include directory
# corresponding to the common APIs applicable to modules
# rooted at that subtree. Accordingly, the INCLUDE PATH
# of a module can only contain the include directories up
# its parent path, and not its siblings
#
# Required for each makefile to inherit from the parent
#
INCLUDES := $(INCLUDES) -I $(PDIR)include
INCLUDES += -I ./
INCLUDES += -I ../libc
PDIR := ../$(PDIR)
sinclude $(PDIR)Makefile
/*
* Copyright (c) 2015, DiUS Computing Pty Ltd (jmattsson@dius.com.au)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#include "digests.h"
#include "user_config.h"
#include "lwip/mem.h"
#include "lwip/arch.h"
#include "ssl/ssl_crypto.h"
#include "sha2.h"
#include <string.h>
#include <c_errno.h>
typedef char ensure_int_and_size_t_same[(sizeof(int)==sizeof(size_t)) ? 0 : -1];
/* None of the functions match the prototype fully due to the void *, and in
some cases also the int vs size_t len, so wrap declarations in a macro. */
#define MECH(pfx, ds, bs) \
{ #pfx, \
(create_ctx_fn)pfx ## _Init, \
(update_ctx_fn)pfx ## _Update, \
(finalize_ctx_fn)pfx ## _Final, \
sizeof(pfx ## _CTX), \
ds, \
bs }
static const digest_mech_info_t hash_mechs[] =
{
MECH(MD2, MD2_SIZE, 16)
,MECH(MD5, MD5_SIZE, 64)
,MECH(SHA1, SHA1_SIZE, 64)
#ifdef SHA2_ENABLE
,MECH(SHA256, SHA256_DIGEST_LENGTH, SHA256_BLOCK_LENGTH)
,MECH(SHA384, SHA384_DIGEST_LENGTH, SHA384_BLOCK_LENGTH)
,MECH(SHA512, SHA512_DIGEST_LENGTH, SHA512_BLOCK_LENGTH)
#endif
};
#undef MECH
const digest_mech_info_t *crypto_digest_mech (const char *mech)
{
if (!mech)
return 0;
size_t i;
for (i = 0; i < (sizeof (hash_mechs) / sizeof (digest_mech_info_t)); ++i)
{
const digest_mech_info_t *mi = hash_mechs + i;
if (strcasecmp (mech, mi->name) == 0)
return mi;
}
return 0;
}
static const char hex[] = "0123456789abcdef";
// note: supports in-place encoding
void crypto_encode_asciihex (const char *bin, size_t binlen, char *outbuf)
{
size_t aidx = binlen * 2 -1;
int i;
for (i = binlen -1; i >= 0; --i)
{
outbuf[aidx--] = hex[bin[i] & 0xf];
outbuf[aidx--] = hex[bin[i] >> 4];
}
}
size_t crypto_digest_size (const char *mech)
{
const digest_mech_info_t *mi = crypto_digest_mech (mech);
return mi ? mi->digest_size : 0;
}
int crypto_hash (const digest_mech_info_t *mi,
const char *data, size_t data_len,
uint8_t *digest)
{
if (!mi)
return EINVAL;
void *ctx = os_malloc (mi->ctx_size);
if (!ctx)
return ENOMEM;
mi->create (ctx);
mi->update (ctx, data, data_len);
mi->finalize (digest, ctx);
os_free (ctx);
return 0;
}
int crypto_hmac (const digest_mech_info_t *mi,
const char *data, size_t data_len,
const char *key, size_t key_len,
uint8_t *digest)
{
if (!mi)
return EINVAL;
void *ctx = os_malloc (mi->ctx_size);
if (!ctx)
return ENOMEM;
// If key too long, it needs to be hashed before use
if (key_len > mi->block_size)
{
mi->create (ctx);
mi->update (ctx, key, key_len);
mi->finalize (digest, ctx);
key = digest;
key_len = mi->block_size;
}
const size_t bs = mi->block_size;
uint8_t k_ipad[bs];
uint8_t k_opad[bs];
os_memset (k_ipad, 0x36, bs);
os_memset (k_opad, 0x5c, bs);
size_t i;
for (i = 0; i < key_len; ++i)
{
k_ipad[i] ^= key[i];
k_opad[i] ^= key[i];
}
mi->create (ctx);
mi->update (ctx, k_ipad, bs);
mi->update (ctx, data, data_len);
mi->finalize (digest, ctx);
mi->create (ctx);
mi->update (ctx, k_opad, bs);
mi->update (ctx, digest, mi->digest_size);
mi->finalize (digest, ctx);
os_free (ctx);
return 0;
}
#ifndef _CRYPTO_DIGESTS_H_
#define _CRYPTO_DIGESTS_H_
#include <c_types.h>
typedef void (*create_ctx_fn)(void *ctx);
typedef void (*update_ctx_fn)(void *ctx, const uint8_t *msg, int len);
typedef void (*finalize_ctx_fn)(uint8_t *digest, void *ctx);
/**
* Description of a message digest mechanism.
*
* Typical usage (if not using the crypto_xxxx() functions below):
* digest_mech_info_t *mi = crypto_digest_mech (chosen_algorithm);
* void *ctx = os_malloc (mi->ctx_size);
* mi->create (ctx);
* mi->update (ctx, data, len);
* ...
* uint8_t *digest = os_malloc (mi->digest_size);
* mi->finalize (digest, ctx);
* ...
* os_free (ctx);
* os_free (digest);
*/
typedef struct
{
const char * name;
create_ctx_fn create;
update_ctx_fn update;
finalize_ctx_fn finalize;
uint16_t ctx_size;
uint16_t digest_size;
uint16_t block_size;
} digest_mech_info_t;
/**
* Looks up the mech data for a specified digest algorithm.
* @param mech The name of the algorithm, e.g. "MD5", "SHA256"
* @returns The mech data, or null if the mech is unknown.
*/
const digest_mech_info_t *crypto_digest_mech (const char *mech);
/**
* Wrapper function for performing a one-in-all hashing operation.
* @param mi A mech from @c crypto_digest_mech(). A null pointer @c mi
* is harmless, but will of course result in an error return.
* @param data The data to create a digest for.
* @param data_len Number of bytes at @c data to digest.
* @param digest Output buffer, must be at least @c mi->digest_size in size.
* @return 0 on success, non-zero on error.
*/
int crypto_hash (const digest_mech_info_t *mi, const char *data, size_t data_len, uint8_t *digest);
/**
* Generate a HMAC signature.
* @param mi A mech from @c crypto_digest_mech(). A null pointer @c mi
* is harmless, but will of course result in an error return.
* @param data The data to generate a signature for.
* @param data_len Number of bytes at @c data to process.
* @param key The key to use.
* @param key_len Number of bytes the @c key comprises.
* @param digest Output buffer, must be at least @c mi->digest_size in size.
* @return 0 on success, non-zero on error.
*/
int crypto_hmac (const digest_mech_info_t *mi, const char *data, size_t data_len, const char *key, size_t key_len, uint8_t *digest);
/**
* Perform ASCII Hex encoding. Does not null-terminate the buffer.
*
* @param bin The buffer to ascii-hex encode.
* @param bin_len Number of bytes in @c bin to encode.
* @param outbuf Output buffer, must be at least @c bin_len*2 bytes in size.
* Note that in-place encoding is supported, and as such
* bin==outbuf is safe, provided the buffer is large enough.
*/
void crypto_encode_asciihex (const char *bin, size_t bin_len, char *outbuf);
#endif
This diff is collapsed.
#ifndef __SHA2_H__
#define __SHA2_H__
#include <c_types.h>
/**************************************************************************
* SHA256/384/512 declarations
**************************************************************************/
#define SHA256_BLOCK_LENGTH 64
#define SHA256_DIGEST_LENGTH 32
typedef struct
{
uint32_t state[8];
uint64_t bitcount;
uint8_t buffer[SHA256_BLOCK_LENGTH];
} SHA256_CTX;
void SHA256_Init(SHA256_CTX *);
void SHA256_Update(SHA256_CTX *, const uint8_t *msg, size_t len);
void SHA256_Final(uint8_t[SHA256_DIGEST_LENGTH], SHA256_CTX*);
#define SHA384_BLOCK_LENGTH 128
#define SHA384_DIGEST_LENGTH 48
typedef struct
{
uint64_t state[8];
uint64_t bitcount[2];
uint8_t buffer[SHA384_BLOCK_LENGTH];
} SHA384_CTX;
void SHA384_Init(SHA384_CTX*);
void SHA384_Update(SHA384_CTX*, const uint8_t *msg, size_t len);
void SHA384_Final(uint8_t[SHA384_DIGEST_LENGTH], SHA384_CTX*);
#define SHA512_BLOCK_LENGTH 128
#define SHA512_DIGEST_LENGTH 64
typedef SHA384_CTX SHA512_CTX;
void SHA512_Init(SHA512_CTX*);
void SHA512_Update(SHA512_CTX*, const uint8_t *msg, size_t len);
void SHA512_Final(uint8_t[SHA512_DIGEST_LENGTH], SHA512_CTX*);
#endif
......@@ -41,6 +41,7 @@
#define CLIENT_SSL_ENABLE
#define GPIO_INTERRUPT_ENABLE
#define SHA2_ENABLE
// #define BUILD_WOFS 1
#define BUILD_SPIFFS 1
......
......@@ -8,6 +8,7 @@
#include "lrotable.h"
#include "c_types.h"
#include "c_stdlib.h"
#include "../crypto/digests.h"
#include "user_interface.h"
......@@ -39,7 +40,7 @@ static int crypto_sha1( lua_State* L )
static const char* bytes64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* encoded = crypto.base64Encode(raw)
* encoded = crypto.toBase64(raw)
*
* Encodes raw binary string as base64 string.
*/
......@@ -66,7 +67,7 @@ static int crypto_base64_encode( lua_State* L )
static const char* byteshex = "0123456789abcdef";
/**
* encoded = crypto.hexEncode(raw)
* encoded = crypto.toHex(raw)
*
* Encodes raw binary string as hex string.
*/
......@@ -105,6 +106,53 @@ static int crypto_mask( lua_State* L )
return 1;
}
static inline int bad_mech (lua_State *L) { return luaL_error (L, "unknown hash mech"); }
static inline int bad_mem (lua_State *L) { return luaL_error (L, "insufficient memory"); }
/* rawdigest = crypto.hash("MD5", str)
* strdigest = crypto.toHex(rawdigest)
*/
static int crypto_lhash (lua_State *L)
{
const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
if (!mi)
return bad_mech (L);
size_t len = 0;
const char *data = luaL_checklstring (L, 2, &len);
uint8_t digest[mi->digest_size];
if (crypto_hash (mi, data, len, digest) != 0)
return bad_mem (L);
lua_pushlstring (L, digest, sizeof (digest));
return 1;
}
/* rawsignature = crypto.hmac("SHA1", str, key)
* strsignature = crypto.toHex(rawsignature)
*/
static int crypto_lhmac (lua_State *L)
{
const digest_mech_info_t *mi = crypto_digest_mech (luaL_checkstring (L, 1));
if (!mi)
return bad_mech (L);
size_t len = 0;
const char *data = luaL_checklstring (L, 2, &len);
size_t klen = 0;
const char *key = luaL_checklstring (L, 3, &klen);
uint8_t digest[mi->digest_size];
if (crypto_hmac (mi, data, len, key, klen, digest) != 0)
return bad_mem (L);
lua_pushlstring (L, digest, sizeof (digest));
return 1;
}
// Module function map
#define MIN_OPT_LEVEL 2
#include "lrodefs.h"
......@@ -114,6 +162,8 @@ const LUA_REG_TYPE crypto_map[] =
{ LSTRKEY( "toBase64" ), LFUNCVAL( crypto_base64_encode ) },
{ LSTRKEY( "toHex" ), LFUNCVAL( crypto_hex_encode ) },
{ LSTRKEY( "mask" ), LFUNCVAL( crypto_mask ) },
{ LSTRKEY( "hash" ), LFUNCVAL( crypto_lhash ) },
{ LSTRKEY( "hmac" ), LFUNCVAL( crypto_lhmac ) },
#if LUA_OPTIMIZE_MEMORY > 0
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment