X-Git-Url: https://tinc-vpn.org/git/browse?a=blobdiff_plain;f=src%2Fgcrypt%2Fprf.c;h=d11ef777ed585eec5c57394e6f389f2a052fc06c;hb=c45a3fd7319d03bd147448a017f5aaed3b46fdfe;hp=f9a21121c8016b324b1d92a8bd0d6819bcff4511;hpb=9b9230a0a79c670b86f54fadd2807b864ff9d91f;p=tinc diff --git a/src/gcrypt/prf.c b/src/gcrypt/prf.c index f9a21121..d11ef777 100644 --- a/src/gcrypt/prf.c +++ b/src/gcrypt/prf.c @@ -19,11 +19,107 @@ #include "../system.h" -#include "digest.h" -#include "../digest.h" #include "../prf.h" +#include "../ed25519/sha512.h" -bool prf(const char *secret, size_t secretlen, char *seed, size_t seedlen, char *out, size_t outlen) { - logger(DEBUG_ALWAYS, LOG_ERR, "PRF support using libgcrypt not implemented"); - return false; +static void memxor(uint8_t *buf, uint8_t c, size_t len) { + for(size_t i = 0; i < len; i++) { + buf[i] ^= c; + } +} + +static const size_t mdlen = 64; +static const size_t blklen = 128; + +static bool hmac_sha512(const uint8_t *key, size_t keylen, const uint8_t *msg, size_t msglen, uint8_t *out) { + const size_t tmplen = blklen + mdlen; + uint8_t *tmp = alloca(tmplen); + + sha512_context md; + + if(keylen <= blklen) { + memcpy(tmp, key, keylen); + memset(tmp + keylen, 0, blklen - keylen); + } else { + if(sha512(key, keylen, tmp) != 0) { + return false; + } + + memset(tmp + mdlen, 0, blklen - mdlen); + } + + if(sha512_init(&md) != 0) { + return false; + } + + // ipad + memxor(tmp, 0x36, blklen); + + if(sha512_update(&md, tmp, blklen) != 0) { + return false; + } + + // message + if(sha512_update(&md, msg, msglen) != 0) { + return false; + } + + if(sha512_final(&md, tmp + blklen) != 0) { + return false; + } + + // opad + memxor(tmp, 0x36 ^ 0x5c, blklen); + + if(sha512(tmp, tmplen, out) != 0) { + return false; + } + + return true; +} + + +/* Generate key material from a master secret and a seed, based on RFC 4346 section 5. + We use SHA512 instead of MD5 and SHA1. + */ + +bool prf(const uint8_t *secret, size_t secretlen, uint8_t *seed, size_t seedlen, uint8_t *out, size_t outlen) { + /* Data is what the "inner" HMAC function processes. + It consists of the previous HMAC result plus the seed. + */ + + const size_t datalen = mdlen + seedlen; + uint8_t *data = alloca(datalen); + + memset(data, 0, mdlen); + memcpy(data + mdlen, seed, seedlen); + + uint8_t *hash = alloca(mdlen); + + while(outlen > 0) { + /* Inner HMAC */ + if(!hmac_sha512(secret, secretlen, data, datalen, data)) { + return false; + } + + /* Outer HMAC */ + if(outlen >= mdlen) { + if(!hmac_sha512(secret, secretlen, data, datalen, out)) { + return false; + } + + out += mdlen; + outlen -= mdlen; + } else { + if(!hmac_sha512(secret, secretlen, data, datalen, hash)) { + return false; + } + + memcpy(out, hash, outlen); + out += outlen; + outlen = 0; + } + } + + return true; }