Exemple #1
0
HMAC_CTX *HMAC_CTX_new(void)
{
    HMAC_CTX *ctx = OPENSSL_zalloc(sizeof(HMAC_CTX));

    if (ctx != NULL) {
        if (!HMAC_CTX_reset(ctx)) {
            HMAC_CTX_free(ctx);
            return NULL;
        }
    }
    return ctx;
}
int compute_keys(UNUSED REQUEST *request, pwd_session_t *session, uint8_t *peer_confirm, uint8_t *msk, uint8_t *emsk)
{
	HMAC_CTX	*hmac_ctx;
	uint8_t		mk[SHA256_DIGEST_LENGTH], *cruft;
	uint8_t		session_id[SHA256_DIGEST_LENGTH + 1];
	uint8_t		msk_emsk[128];		/* 64 each */
	int	 	offset;

	MEM(cruft = talloc_array(session, uint8_t, BN_num_bytes(session->prime)));
	MEM(hmac_ctx = HMAC_CTX_new());

	/*
	 * first compute the session-id = TypeCode | H(ciphersuite | scal_p |
	 *	scal_s)
	 */
	session_id[0] = FR_EAP_METHOD_PWD;
	HMAC_Init_ex(hmac_ctx, allzero, SHA256_DIGEST_LENGTH, EVP_sha256(), NULL);
	HMAC_Update(hmac_ctx, (uint8_t *)&session->ciphersuite, sizeof(session->ciphersuite));
	offset = BN_num_bytes(session->order) - BN_num_bytes(session->peer_scalar);
	memset(cruft, 0, BN_num_bytes(session->prime));
	BN_bn2bin(session->peer_scalar, cruft + offset);
	HMAC_Update(hmac_ctx, cruft, BN_num_bytes(session->order));
	offset = BN_num_bytes(session->order) - BN_num_bytes(session->my_scalar);
	memset(cruft, 0, BN_num_bytes(session->prime));
	BN_bn2bin(session->my_scalar, cruft + offset);
	HMAC_Update(hmac_ctx, cruft, BN_num_bytes(session->order));
	pwd_hmac_final(hmac_ctx, (uint8_t *)&session_id[1]);

	/* then compute MK = H(k | commit-peer | commit-server) */
	HMAC_Init_ex(hmac_ctx, allzero, SHA256_DIGEST_LENGTH, EVP_sha256(), NULL);

	memset(cruft, 0, BN_num_bytes(session->prime));
	offset = BN_num_bytes(session->prime) - BN_num_bytes(session->k);
	BN_bn2bin(session->k, cruft + offset);
	HMAC_Update(hmac_ctx, cruft, BN_num_bytes(session->prime));

	HMAC_Update(hmac_ctx, peer_confirm, SHA256_DIGEST_LENGTH);

	HMAC_Update(hmac_ctx, session->my_confirm, SHA256_DIGEST_LENGTH);

	pwd_hmac_final(hmac_ctx, mk);

	/* stretch the mk with the session-id to get MSK | EMSK */
	eap_pwd_kdf(mk, SHA256_DIGEST_LENGTH, (char const *)session_id,
		    SHA256_DIGEST_LENGTH + 1, msk_emsk, 1024);  /* it's bits, ((64 + 64) * 8) */

	memcpy(msk, msk_emsk, 64);
	memcpy(emsk, msk_emsk + 64, 64);

	HMAC_CTX_free(hmac_ctx);
	talloc_free(cruft);
	return 0;
}
Exemple #3
0
krb5_error_code
_krb5_evp_hmac_iov(krb5_context context,
                   krb5_crypto crypto,
                   struct _krb5_key_data *key,
                   const struct krb5_crypto_iov *iov,
                   int niov,
                   void *hmac,
                   unsigned int *hmaclen,
                   const EVP_MD *md,
                   ENGINE *engine)
{
    HMAC_CTX *ctx;
    krb5_data current = {0, 0};
    int i;

    if (crypto != NULL) {
	if (crypto->hmacctx == NULL)
	    crypto->hmacctx = HMAC_CTX_new();
	ctx = crypto->hmacctx;
    } else {
	ctx = HMAC_CTX_new();
    }
    if (ctx == NULL)
        return krb5_enomem(context);

    HMAC_Init_ex(ctx, key->key->keyvalue.data, key->key->keyvalue.length,
                 md, engine);

    for (i = 0; i < niov; i++) {
        if (_krb5_crypto_iov_should_sign(&iov[i])) {
	    if ((char *)current.data + current.length == iov[i].data.data) {
		current.length += iov[i].data.length;
	    } else {
		if (current.data)
		    HMAC_Update(ctx, current.data, current.length);
		current = iov[i].data;
	    }
	}
    }

    if (current.data)
	HMAC_Update(ctx, current.data, current.length);

    HMAC_Final(ctx, hmac, hmaclen);

    if (crypto == NULL)
        HMAC_CTX_free(ctx);

    return 0;
}
Exemple #4
0
unsigned char *HMAC(const EVP_MD *evp_md, const void *key, int key_len,
                    const unsigned char *d, size_t n, unsigned char *md,
                    unsigned int *md_len)
{
    HMAC_CTX *c = NULL;
    static unsigned char m[EVP_MAX_MD_SIZE];

    if (md == NULL)
        md = m;
    if ((c = HMAC_CTX_new()) == NULL)
        goto err;
    if (!HMAC_Init_ex(c, key, key_len, evp_md, NULL))
        goto err;
    if (!HMAC_Update(c, d, n))
        goto err;
    if (!HMAC_Final(c, md, md_len))
        goto err;
    HMAC_CTX_free(c);
    return md;
err:
    HMAC_CTX_free(c);
    return NULL;
}
Exemple #5
0
static void
xmlSecOpenSSLHmacFinalize(xmlSecTransformPtr transform) {
    xmlSecOpenSSLHmacCtxPtr ctx;

    xmlSecAssert(xmlSecOpenSSLHmacCheckId(transform));
    xmlSecAssert(xmlSecTransformCheckSize(transform, xmlSecOpenSSLHmacSize));

    ctx = xmlSecOpenSSLHmacGetCtx(transform);
    xmlSecAssert(ctx != NULL);

    if(ctx->hmacCtx != NULL) {
        HMAC_CTX_free(ctx->hmacCtx);
    }

    memset(ctx, 0, sizeof(xmlSecOpenSSLHmacCtx));
}
Exemple #6
0
static int openssl_hmac(lua_State *L)
{
    if (lua_istable(L, 1))
    {
        if (lua_getmetatable(L, 1) && lua_equal(L, 1, -1))
        {
            lua_pop(L, 1);
            lua_remove(L, 1);
        }
        else
            luaL_error(L, "call function with invalid state");
    }
    {

        const EVP_MD *type = get_digest(L, 1);
        size_t len;
        const char *dat = luaL_checklstring(L, 2, &len);
        size_t l;
        const char *k = luaL_checklstring(L, 3, &l);
        int raw = (lua_isnoneornil(L, 4)) ? 0 : lua_toboolean(L, 4);
        ENGINE* e = lua_isnoneornil(L, 5) ? NULL : CHECK_OBJECT(5, ENGINE, "openssl.engine");

        unsigned char digest[EVP_MAX_MD_SIZE];

        HMAC_CTX *c = HMAC_CTX_new();
        HMAC_Init_ex(c, k, (int)l, type, e);

        HMAC_Update(c, (unsigned char *)dat, len);
        len = EVP_MAX_MD_SIZE;
        HMAC_Final(c, digest, (unsigned int*)&len);

        HMAC_CTX_free(c);

        if (raw)
            lua_pushlstring(L, (char *)digest, len);
        else
        {
            char hex[2 * EVP_MAX_MD_SIZE + 1];
            to_hex((const char*)digest, len, hex);
            lua_pushstring(L, hex);
        }
    }
    return 1;
}
/* a counter-based KDF based on NIST SP800-108 */
static void eap_pwd_kdf(uint8_t *key, int keylen, char const *label,
			int label_len, uint8_t *retult, int retult_bit_len)
{
	HMAC_CTX	*hmac_ctx;
	uint8_t		digest[SHA256_DIGEST_LENGTH];
	uint16_t	i, ctr, L;
	int		retult_byte_len, len = 0;
	unsigned int	mdlen = SHA256_DIGEST_LENGTH;
	uint8_t		mask = 0xff;

	MEM(hmac_ctx = HMAC_CTX_new());
	retult_byte_len = (retult_bit_len + 7) / 8;

	ctr = 0;
	L = htons(retult_bit_len);
	while (len < retult_byte_len) {
		ctr++; i = htons(ctr);

		HMAC_Init_ex(hmac_ctx, key, keylen, EVP_sha256(), NULL);
		if (ctr > 1) HMAC_Update(hmac_ctx, digest, mdlen);
		HMAC_Update(hmac_ctx, (uint8_t *) &i, sizeof(uint16_t));
		HMAC_Update(hmac_ctx, (uint8_t const *)label, label_len);
		HMAC_Update(hmac_ctx, (uint8_t *) &L, sizeof(uint16_t));
		HMAC_Final(hmac_ctx, digest, &mdlen);
		if ((len + (int) mdlen) > retult_byte_len) {
			memcpy(retult + len, digest, retult_byte_len - len);
		} else {
			memcpy(retult + len, digest, mdlen);
		}
		len += mdlen;
		HMAC_CTX_reset(hmac_ctx);
	}

	/* since we're expanding to a bit length, mask off the excess */
	if (retult_bit_len % 8) {
		mask <<= (8 - (retult_bit_len % 8));
		retult[retult_byte_len - 1] &= mask;
	}

	HMAC_CTX_free(hmac_ctx);
}
Exemple #8
0
static void kderive_update(struct kderive_context *ctx)
{
	uint32_t i;
#if (OPENSSL_VERSION_NUMBER < 0x1010002f)
	HMAC_CTX hctx;
#endif
        HMAC_CTX *phctx = NULL;
	unsigned char *pos = ctx->out;
	uint32_t *p_iter = (uint32_t *)ctx->fid;
	uint32_t num_iters = ctx->out_len / PRF_OUTPUT_SIZE;

	check_prf_iters(num_iters);

#if (OPENSSL_VERSION_NUMBER < 0x1010002f)
	HMAC_CTX_init(&hctx);
        phctx = &hctx;
#else
        phctx = HMAC_CTX_new();
        /* I guess we presume it was successful? */
#endif
	for (i = 0; i < num_iters; i++) {
		/*
		 * update the iteration number in the fid
		 */
		*p_iter = htobe32(i);
		HMAC_Init_ex(phctx,
			     ctx->pkey, ctx->pkey_len >> 3,
			     EVP_sha256(),
			     NULL);
		HMAC_Update(phctx, ctx->fid, ctx->fid_len);
		HMAC_Final(phctx, pos, NULL);

		pos += PRF_OUTPUT_SIZE;
	}
#if (OPENSSL_VERSION_NUMBER < 0x1010002f)
	HMAC_CTX_cleanup(phctx);
#else
        HMAC_CTX_free(phctx);
#endif
}
Exemple #9
0
void winpr_HMAC_Free(WINPR_HMAC_CTX* ctx)
{
#if defined(WITH_OPENSSL)
	HMAC_CTX* hmac = (HMAC_CTX*) ctx;
	if (hmac)
	{
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
		HMAC_CTX_cleanup(hmac);
		free(hmac);
#else
		HMAC_CTX_free(hmac);
#endif
	}

#elif defined(WITH_MBEDTLS)
	mbedtls_md_context_t* hmac = (mbedtls_md_context_t*) ctx;
	if (hmac)
	{
		mbedtls_md_free(hmac);
		free(hmac);
	}
#endif
}
Exemple #10
0
static int sqlcipher_openssl_hmac(void *ctx, int algorithm, unsigned char *hmac_key, int key_sz, unsigned char *in, int in_sz, unsigned char *in2, int in2_sz, unsigned char *out) {
  unsigned int outlen;
  int rc = SQLITE_OK;
  HMAC_CTX* hctx = NULL;

  if(in == NULL) goto error;

  hctx = HMAC_CTX_new();
  if(hctx == NULL) goto error;

  switch(algorithm) {
    case SQLCIPHER_HMAC_SHA1:
      if(!HMAC_Init_ex(hctx, hmac_key, key_sz, EVP_sha1(), NULL)) goto error;
      break;
    case SQLCIPHER_HMAC_SHA256:
      if(!HMAC_Init_ex(hctx, hmac_key, key_sz, EVP_sha256(), NULL)) goto error;
      break;
    case SQLCIPHER_HMAC_SHA512:
      if(!HMAC_Init_ex(hctx, hmac_key, key_sz, EVP_sha512(), NULL)) goto error;
      break;
    default:
      goto error;
  }

  if(!HMAC_Update(hctx, in, in_sz)) goto error;
  if(in2 != NULL) {
    if(!HMAC_Update(hctx, in2, in2_sz)) goto error;
  }
  if(!HMAC_Final(hctx, out, &outlen)) goto error;
  
  goto cleanup;
error:
  rc = SQLITE_ERROR;
cleanup:
  if(hctx) HMAC_CTX_free(hctx);
  return rc;
}
Exemple #11
0
HMACCTX hmac_init(const void *key, int len, enum ssh_hmac_e type) {
  HMACCTX ctx = NULL;

  ctx = HMAC_CTX_new();
  if (ctx == NULL) {
    return NULL;
  }

#ifndef OLD_CRYPTO
  HMAC_CTX_reset(ctx); // openssl 0.9.7 requires it.
#endif

  switch(type) {
    case SSH_HMAC_SHA1:
      HMAC_Init_ex(ctx, key, len, EVP_sha1(), NULL);
      break;
    case SSH_HMAC_SHA256:
      HMAC_Init_ex(ctx, key, len, EVP_sha256(), NULL);
      break;
    case SSH_HMAC_SHA384:
      HMAC_Init_ex(ctx, key, len, EVP_sha384(), NULL);
      break;
    case SSH_HMAC_SHA512:
      HMAC_Init_ex(ctx, key, len, EVP_sha512(), NULL);
      break;
    case SSH_HMAC_MD5:
      HMAC_Init_ex(ctx, key, len, EVP_md5(), NULL);
      break;
    default:
      HMAC_CTX_free(ctx);
      SAFE_FREE(ctx);
      ctx = NULL;
  }

  return ctx;
}
Exemple #12
0
/*
 * Private
 */
static void
ossl_hmac_free(void *ctx)
{
    HMAC_CTX_free(ctx);
}
Exemple #13
0
HmacHash<HashCreator, DigestLength>::~HmacHash()
{
    HMAC_CTX_free(_ctx);
}
Exemple #14
0
int
res_tsig_sign(u_char * query,
              size_t query_length,
              struct name_server *ns,
              u_char ** signed_query, 
              size_t *signed_length)
{
    int buflen;
    u_char *cp, *p;
    u_char *hp;
    HEADER *header;
    struct timeval now;
    HMAC_CTX *ctx;
    const EVP_MD *md;
    u_char hash[MAX_DIGEST_LENGTH];
    unsigned int len;
    u_int16_t arcount;

    if (!signed_query || !signed_length)
        return SR_TS_FAIL;
    *signed_query = NULL;
    *signed_length = 0;

    if (query && query_length && query_length > sizeof(HEADER)) {
        if (!(ns->ns_security_options & ZONE_USE_TSIG)) {
            *signed_query = (u_char *) MALLOC(query_length * sizeof(u_char));
            if (*signed_query == NULL) 
                return SR_TS_FAIL;
            memcpy(*signed_query, query, query_length * sizeof(u_char));
            *signed_length = query_length;
            return SR_TS_OK;
        } else if (!ns->ns_tsig) {
            return SR_TS_FAIL;
        }

        switch(ns->ns_tsig->alg) {
            case TSIG_ALG_HMAC_MD5:
               md = EVP_md5();
               break; 
            case TSIG_ALG_HMAC_SHA1:
               md = EVP_sha1();
               break; 
            case TSIG_ALG_HMAC_SHA256:
               md = EVP_sha256();
               break; 
            default:
               return SR_TS_FAIL;
        } 

        ctx = HMAC_CTX_new();
        HMAC_Init_ex(ctx, ns->ns_tsig->key, ns->ns_tsig->keylen,
                md, NULL);

        /* Create a TSIG RR and add it to the additional section */
        buflen = query_length + ns->ns_tsig->buf_size;
        *signed_query = (u_char *) MALLOC(buflen * sizeof(u_char));
        if (*signed_query == NULL) 
            return SR_TS_FAIL;
        *signed_length = buflen;
        cp = *signed_query;

        p = cp;
        memcpy(cp, query, query_length * sizeof(u_char));
        cp += query_length;
        HMAC_Update(ctx, p, cp-p); 

        /* Bump up the additional section count */
        header = (HEADER *) p;
        arcount = ntohs(header->arcount);
        arcount++;
        header->arcount = htons(arcount);;

        p = cp;
        memcpy(cp, ns->ns_tsig->name_n, wire_name_length(ns->ns_tsig->name_n));
        cp += wire_name_length(ns->ns_tsig->name_n);
        HMAC_Update(ctx, p, cp-p); 

        /* don't digest type */
        RES_PUT16(ns_t_tsig, cp);

        p = cp;
        RES_PUT16(ns_t_any, cp);
        RES_PUT32(0, cp);
        HMAC_Update(ctx, p, cp-p); 

        /* don't digest rdatalen */
        RES_PUT16(ns->ns_tsig->rdatalen, cp);

        p = cp;
        memcpy(cp, ns->ns_tsig->alg_n, wire_name_length(ns->ns_tsig->alg_n));
        cp += wire_name_length(ns->ns_tsig->alg_n);
        HMAC_Update(ctx, p, cp-p); 

        gettimeofday(&now, NULL);
        p = cp;
        RES_PUT48((u_int64_t)now.tv_sec, cp);
        RES_PUT16(ns->ns_tsig->fudge, cp);
        HMAC_Update(ctx, p, cp-p); 

        /* don't digest the mac_size */
        RES_PUT16(ns->ns_tsig->mac_size, cp);

        /* save the location for the hmac */
        hp = cp;
        cp += ns->ns_tsig->mac_size;
    
        /* don't digest the header ID */
        RES_PUT16(ntohs(header->id), cp);

        p = cp;
        RES_PUT16(0, cp);
        RES_PUT16(0, cp);
        HMAC_Update(ctx, p, cp-p); 

        HMAC_Final(ctx, hash, &len);

        if (len != ns->ns_tsig->mac_size) {
            FREE(*signed_query);
            *signed_query = NULL;
            return SR_TS_FAIL;
        }
        memcpy(hp, hash, len);

        HMAC_CTX_free(ctx);
        return SR_TS_OK;

    } else
        return SR_TS_CALL_ERROR;
}
Exemple #15
0
static int drbg_hmac_uninstantiate(DRBG_CTX *dctx)
{
    HMAC_CTX_free(dctx->d.hmac.hctx);
    OPENSSL_cleanse(&dctx->d.hmac, sizeof(DRBG_HMAC_CTX));
    return 1;
}
Exemple #16
0
void
hmac_ctx_free(HMAC_CTX *ctx)
{
    HMAC_CTX_free(ctx);
}
int compute_peer_confirm(REQUEST *request, pwd_session_t *session, uint8_t *out, BN_CTX *bn_ctx)
{
	BIGNUM		*x = NULL, *y = NULL;
	HMAC_CTX	*hmac_ctx = NULL;
	uint8_t		*cruft = NULL;
	int		offset, req = -1;

	/*
	 * Each component of the cruft will be at most as big as the prime
	 */
	MEM(cruft = talloc_zero_array(session, uint8_t, BN_num_bytes(session->prime)));
	MEM(x = BN_new());
	MEM(y = BN_new());

	/*
	 * commit is H(k | server_element | server_scalar | peer_element |
	 *	       peer_scalar | ciphersuite)
	 */
	MEM(hmac_ctx = HMAC_CTX_new());
	HMAC_Init_ex(hmac_ctx, allzero, SHA256_DIGEST_LENGTH, EVP_sha256(), NULL);

	/*
	 * Zero the memory each time because this is mod prime math and some
	 * value may start with a few zeros and the previous one did not.
	 *
	 * First is k
	 */
	offset = BN_num_bytes(session->prime) - BN_num_bytes(session->k);
	BN_bn2bin(session->k, cruft + offset);
	HMAC_Update(hmac_ctx, cruft, BN_num_bytes(session->prime));

	/*
	* then peer element: x, y
	*/
	if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->peer_element, x, y, bn_ctx)) {
		REDEBUG("Unable to get coordinates of peer's element");
		goto finish;
	}

	memset(cruft, 0, BN_num_bytes(session->prime));
	offset = BN_num_bytes(session->prime) - BN_num_bytes(x);
	BN_bn2bin(x, cruft + offset);
	HMAC_Update(hmac_ctx, cruft, BN_num_bytes(session->prime));

	memset(cruft, 0, BN_num_bytes(session->prime));
	offset = BN_num_bytes(session->prime) - BN_num_bytes(y);
	BN_bn2bin(y, cruft + offset);
	HMAC_Update(hmac_ctx, cruft, BN_num_bytes(session->prime));

	/*
	 * and peer scalar
	 */
	memset(cruft, 0, BN_num_bytes(session->prime));
	offset = BN_num_bytes(session->order) - BN_num_bytes(session->peer_scalar);
	BN_bn2bin(session->peer_scalar, cruft + offset);
	HMAC_Update(hmac_ctx, cruft, BN_num_bytes(session->order));

	/*
	 * then server element: x, y
	 */
	if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->my_element, x, y, bn_ctx)) {
		REDEBUG("Unable to get coordinates of server element");
		goto finish;
	}
	memset(cruft, 0, BN_num_bytes(session->prime));
	offset = BN_num_bytes(session->prime) - BN_num_bytes(x);
	BN_bn2bin(x, cruft + offset);
	HMAC_Update(hmac_ctx, cruft, BN_num_bytes(session->prime));

	memset(cruft, 0, BN_num_bytes(session->prime));
	offset = BN_num_bytes(session->prime) - BN_num_bytes(y);
	BN_bn2bin(y, cruft + offset);
	HMAC_Update(hmac_ctx, cruft, BN_num_bytes(session->prime));

	/*
	 * and server scalar
	 */
	memset(cruft, 0, BN_num_bytes(session->prime));
	offset = BN_num_bytes(session->order) - BN_num_bytes(session->my_scalar);
	BN_bn2bin(session->my_scalar, cruft + offset);
	HMAC_Update(hmac_ctx, cruft, BN_num_bytes(session->order));

	/*
	 * finally, ciphersuite
	 */
	HMAC_Update(hmac_ctx, (uint8_t *)&session->ciphersuite, sizeof(session->ciphersuite));

	pwd_hmac_final(hmac_ctx, out);

	req = 0;
finish:
	HMAC_CTX_free(hmac_ctx);
	talloc_free(cruft);
	BN_free(x);
	BN_free(y);

	return req;
}
Exemple #18
0
static void mz_crypt_hmac_free(void *handle)
{
    mz_crypt_hmac *hmac = (mz_crypt_hmac *)handle;
    HMAC_CTX_free(hmac->ctx);
}
Exemple #19
0
static void
__hmac_sha1_cleanup(archive_hmac_sha1_ctx *ctx)
{
	HMAC_CTX_free(*ctx);
	*ctx = NULL;
}
int compute_password_element(REQUEST *request, pwd_session_t *session, uint16_t grp_num,
			     char const *password, int password_len,
			     char const *id_server, int id_server_len,
			     char const *id_peer, int id_peer_len,
			     uint32_t *token)
{
	BIGNUM		*x_candidate = NULL, *rnd = NULL, *cofactor = NULL;
	HMAC_CTX	*hmac_ctx = NULL;
	uint8_t		pwe_digest[SHA256_DIGEST_LENGTH], *prf_buf = NULL, ctr;
	int		nid, is_odd, prime_bit_len, prime_byte_len, ret = 0;

	switch (grp_num) { /* from IANA registry for IKE D-H groups */
	case 19:
		nid = NID_X9_62_prime256v1;
		break;

	case 20:
		nid = NID_secp384r1;
		break;

	case 21:
		nid = NID_secp521r1;
		break;

	case 25:
		nid = NID_X9_62_prime192v1;
		break;

	case 26:
		nid = NID_secp224r1;
		break;

	default:
		REDEBUG("Unknown group %d", grp_num);
	error:
		ret = -1;
		goto finish;
	}

	session->pwe = NULL;
	session->order = NULL;
	session->prime = NULL;
	session->group = EC_GROUP_new_by_curve_name(nid);
	if (!session->group) {
		REDEBUG("Unable to create EC_GROUP");
		goto error;
	}

	MEM(session->pwe = EC_POINT_new(session->group));
	MEM(session->order = BN_new());
	MEM(session->prime = BN_new());

	MEM(rnd = BN_new());
	MEM(cofactor = BN_new());
	MEM(x_candidate = BN_new());

	if (!EC_GROUP_get_curve_GFp(session->group, session->prime, NULL, NULL, NULL)) {
		REDEBUG("Unable to get prime for GFp curve");
		goto error;
	}

	if (!EC_GROUP_get_order(session->group, session->order, NULL)) {
		REDEBUG("Unable to get order for curve");
		goto error;
	}

	if (!EC_GROUP_get_cofactor(session->group, cofactor, NULL)) {
		REDEBUG("unable to get cofactor for curve");
		goto error;
	}

	prime_bit_len = BN_num_bits(session->prime);
	prime_byte_len = BN_num_bytes(session->prime);
	MEM(prf_buf = talloc_zero_array(session, uint8_t, prime_byte_len));
	MEM(hmac_ctx = HMAC_CTX_new());
	ctr = 0;
	for (;;) {
		if (ctr > 10) {
			REDEBUG("Unable to find random point on curve for group %d, something's fishy", grp_num);
			goto error;
		}
		ctr++;

		/*
		 * compute counter-mode password value and stretch to prime
		 *    pwd-seed = H(token | peer-id | server-id | password |
		 *		   counter)
		 */
		HMAC_Init_ex(hmac_ctx, allzero, SHA256_DIGEST_LENGTH, EVP_sha256(), NULL);
		HMAC_Update(hmac_ctx, (uint8_t *)token, sizeof(*token));
		HMAC_Update(hmac_ctx, (uint8_t const *)id_peer, id_peer_len);
		HMAC_Update(hmac_ctx, (uint8_t const *)id_server, id_server_len);
		HMAC_Update(hmac_ctx, (uint8_t const *)password, password_len);
		HMAC_Update(hmac_ctx, (uint8_t *)&ctr, sizeof(ctr));
		pwd_hmac_final(hmac_ctx, pwe_digest);

		BN_bin2bn(pwe_digest, SHA256_DIGEST_LENGTH, rnd);
		eap_pwd_kdf(pwe_digest, SHA256_DIGEST_LENGTH, "EAP-pwd Hunting And Pecking",
			    strlen("EAP-pwd Hunting And Pecking"), prf_buf, prime_bit_len);

		BN_bin2bn(prf_buf, prime_byte_len, x_candidate);
		/*
		 * eap_pwd_kdf() returns a string of bits 0..prime_bit_len but
		 * BN_bin2bn will treat that string of bits as a big endian
		 * number. If the prime_bit_len is not an even multiple of 8
		 * then excessive bits-- those _after_ prime_bit_len-- so now
		 * we have to shift right the amount we masked off.
		 */
		if (prime_bit_len % 8) BN_rshift(x_candidate, x_candidate, (8 - (prime_bit_len % 8)));
		if (BN_ucmp(x_candidate, session->prime) >= 0) continue;

		/*
		 * need to unambiguously identify the solution, if there is
		 * one...
		 */
		is_odd = BN_is_odd(rnd) ? 1 : 0;

		/*
		 * solve the quadratic equation, if it's not solvable then we
		 * don't have a point
		 */
		if (!EC_POINT_set_compressed_coordinates_GFp(session->group, session->pwe, x_candidate, is_odd, NULL)) {
			continue;
		}

		/*
		 * If there's a solution to the equation then the point must be
		 * on the curve so why check again explicitly? OpenSSL code
		 * says this is required by X9.62. We're not X9.62 but it can't
		 * hurt just to be sure.
		 */
		if (!EC_POINT_is_on_curve(session->group, session->pwe, NULL)) {
			REDEBUG("Point is not on curve");
			continue;
		}

		if (BN_cmp(cofactor, BN_value_one())) {
			/* make sure the point is not in a small sub-group */
			if (!EC_POINT_mul(session->group, session->pwe, NULL, session->pwe,
				cofactor, NULL)) {
				RDEBUG("Cannot multiply generator by order");
				continue;
			}

			if (EC_POINT_is_at_infinity(session->group, session->pwe)) {
				REDEBUG("Point is at infinity");
				continue;
			}
		}
		/* if we got here then we have a new generator. */
		break;
	}

	session->group_num = grp_num;

finish:
	/* cleanliness and order.... */
	HMAC_CTX_free(hmac_ctx);
	BN_clear_free(cofactor);
	BN_clear_free(x_candidate);
	BN_clear_free(rnd);
	talloc_free(prf_buf);

	return ret;
}
Exemple #21
0
static int openssl_hmac_free(lua_State *L)
{
    HMAC_CTX *c = CHECK_OBJECT(1, HMAC_CTX, "openssl.hmac_ctx");
    HMAC_CTX_free(c);
    return 0;
}
Exemple #22
0
HMACAuth::~HMACAuth()
{
    HMAC_CTX_free(_hmacContext);
}
Exemple #23
0
static unsigned char *HKDF_Expand(const EVP_MD *evp_md,
                                  const unsigned char *prk, size_t prk_len,
                                  const unsigned char *info, size_t info_len,
                                  unsigned char *okm, size_t okm_len)
{
    HMAC_CTX *hmac;

    unsigned int i;

    unsigned char prev[EVP_MAX_MD_SIZE];

    size_t done_len = 0, dig_len = EVP_MD_size(evp_md);

    size_t n = okm_len / dig_len;
    if (okm_len % dig_len)
        n++;

    if (n > 255 || okm == NULL)
        return NULL;

    if ((hmac = HMAC_CTX_new()) == NULL)
        return NULL;

    if (!HMAC_Init_ex(hmac, prk, prk_len, evp_md, NULL))
        goto err;

    for (i = 1; i <= n; i++) {
        size_t copy_len;
        const unsigned char ctr = i;

        if (i > 1) {
            if (!HMAC_Init_ex(hmac, NULL, 0, NULL, NULL))
                goto err;

            if (!HMAC_Update(hmac, prev, dig_len))
                goto err;
        }

        if (!HMAC_Update(hmac, info, info_len))
            goto err;

        if (!HMAC_Update(hmac, &ctr, 1))
            goto err;

        if (!HMAC_Final(hmac, prev, NULL))
            goto err;

        copy_len = (done_len + dig_len > okm_len) ?
                       okm_len - done_len :
                       dig_len;

        memcpy(okm + done_len, prev, copy_len);

        done_len += copy_len;
    }

    HMAC_CTX_free(hmac);
    return okm;

 err:
    HMAC_CTX_free(hmac);
    return NULL;
}
Exemple #24
0
static bool _cjose_jws_build_dig_hmac_sha(cjose_jws_t *jws, const cjose_jwk_t *jwk, cjose_err *err)
{
    bool retval = false;
    HMAC_CTX *ctx = NULL;

    // make sure we have an alg header
    json_t *alg_obj = json_object_get(jws->hdr, CJOSE_HDR_ALG);
    if (NULL == alg_obj)
    {
        CJOSE_ERROR(err, CJOSE_ERR_INVALID_ARG);
        return false;
    }
    const char *alg = json_string_value(alg_obj);

    // build digest using SHA-256/384/512 digest algorithm
    const EVP_MD *digest_alg = NULL;
    if (strcmp(alg, CJOSE_HDR_ALG_HS256) == 0)
        digest_alg = EVP_sha256();
    else if (strcmp(alg, CJOSE_HDR_ALG_HS384) == 0)
        digest_alg = EVP_sha384();
    else if (strcmp(alg, CJOSE_HDR_ALG_HS512) == 0)
        digest_alg = EVP_sha512();

    if (NULL == digest_alg)
    {
        CJOSE_ERROR(err, CJOSE_ERR_CRYPTO);
        goto _cjose_jws_build_dig_hmac_sha_cleanup;
    }

    // allocate buffer for digest
    jws->dig_len = EVP_MD_size(digest_alg);
    jws->dig = (uint8_t *)cjose_get_alloc()(jws->dig_len);
    if (NULL == jws->dig)
    {
        CJOSE_ERROR(err, CJOSE_ERR_NO_MEMORY);
        goto _cjose_jws_build_dig_hmac_sha_cleanup;
    }

// instantiate and initialize a new mac digest context
#if defined(CJOSE_OPENSSL_11X)
    ctx = HMAC_CTX_new();
#else
    ctx = cjose_get_alloc()(sizeof(HMAC_CTX));
#endif
    if (NULL == ctx)
    {
        CJOSE_ERROR(err, CJOSE_ERR_NO_MEMORY);
        goto _cjose_jws_build_dig_hmac_sha_cleanup;
    }

#if !defined(CJOSE_OPENSSL_11X)
    HMAC_CTX_init(ctx);
#endif

    // create digest as DIGEST(B64U(HEADER).B64U(DATA))
    if (HMAC_Init_ex(ctx, jwk->keydata, jwk->keysize / 8, digest_alg, NULL) != 1)
    {
        CJOSE_ERROR(err, CJOSE_ERR_CRYPTO);
        goto _cjose_jws_build_dig_hmac_sha_cleanup;
    }
    if (HMAC_Update(ctx, (const unsigned char *)jws->hdr_b64u, jws->hdr_b64u_len) != 1)
    {
        CJOSE_ERROR(err, CJOSE_ERR_CRYPTO);
        goto _cjose_jws_build_dig_hmac_sha_cleanup;
    }
    if (HMAC_Update(ctx, (const unsigned char *)".", 1) != 1)
    {
        CJOSE_ERROR(err, CJOSE_ERR_CRYPTO);
        goto _cjose_jws_build_dig_hmac_sha_cleanup;
    }
    if (HMAC_Update(ctx, (const unsigned char *)jws->dat_b64u, jws->dat_b64u_len) != 1)
    {
        CJOSE_ERROR(err, CJOSE_ERR_CRYPTO);
        goto _cjose_jws_build_dig_hmac_sha_cleanup;
    }
    if (HMAC_Final(ctx, jws->dig, NULL) != 1)
    {
        CJOSE_ERROR(err, CJOSE_ERR_CRYPTO);
        goto _cjose_jws_build_dig_hmac_sha_cleanup;
    }

    // if we got this far - success
    retval = true;

_cjose_jws_build_dig_hmac_sha_cleanup:
    if (NULL != ctx)
    {
#if defined(CJOSE_OPENSSL_11X)
        HMAC_CTX_free(ctx);
#else
        HMAC_CTX_cleanup(ctx);
        cjose_get_dealloc()(ctx);
#endif
    }

    return retval;
}
Exemple #25
0
int main(int argc, char *argv[])
{
# ifndef OPENSSL_NO_MD5
    int i;
    char *p;
# endif
    int err = 0;
    HMAC_CTX *ctx = NULL, *ctx2 = NULL;
    unsigned char buf[EVP_MAX_MD_SIZE];
    unsigned int len;

# ifdef OPENSSL_NO_MD5
    printf("test skipped: MD5 disabled\n");
# else

#  ifdef CHARSET_EBCDIC
    ebcdic2ascii(test[0].data, test[0].data, test[0].data_len);
    ebcdic2ascii(test[1].data, test[1].data, test[1].data_len);
    ebcdic2ascii(test[2].key, test[2].key, test[2].key_len);
    ebcdic2ascii(test[2].data, test[2].data, test[2].data_len);
#  endif

    for (i = 0; i < 4; i++) {
        p = pt(HMAC(EVP_md5(),
                    test[i].key, test[i].key_len,
                    test[i].data, test[i].data_len, NULL, NULL),
                    MD5_DIGEST_LENGTH);

        if (strcmp(p, (char *)test[i].digest) != 0) {
            printf("Error calculating HMAC on %d entry'\n", i);
            printf("got %s instead of %s\n", p, test[i].digest);
            err++;
        } else
            printf("test %d ok\n", i);
    }
# endif                         /* OPENSSL_NO_MD5 */

/* test4 */
    ctx = HMAC_CTX_new();
    if (ctx == NULL) {
        printf("HMAC malloc failure (test 4)\n");
        err++;
        goto end;
    }
    if (HMAC_CTX_get_md(ctx) != NULL) {
        printf("Message digest not NULL for HMAC (test 4)\n");
        err++;
        goto test5;
    }
    if (HMAC_Init_ex(ctx, NULL, 0, NULL, NULL)) {
        printf("Should fail to initialise HMAC with empty MD and key (test 4)\n");
        err++;
        goto test5;
    }
    if (HMAC_Update(ctx, test[4].data, test[4].data_len)) {
        printf("Should fail HMAC_Update with ctx not set up (test 4)\n");
        err++;
        goto test5;
    }
    if (HMAC_Init_ex(ctx, NULL, 0, EVP_sha1(), NULL)) {
        printf("Should fail to initialise HMAC with empty key (test 4)\n");
        err++;
        goto test5;
    }
    if (HMAC_Update(ctx, test[4].data, test[4].data_len)) {
        printf("Should fail HMAC_Update with ctx not set up (test 4)\n");
        err++;
        goto test5;
    }
    printf("test 4 ok\n");
test5:
    /* Test 5 has empty key; test that single-shot accepts a NULL key. */
    p = pt(HMAC(EVP_sha1(), NULL, 0, test[4].data, test[4].data_len,
                NULL, NULL), SHA_DIGEST_LENGTH);
    if (strcmp(p, (char *)test[4].digest) != 0) {
        printf("Error calculating HMAC on %d entry'\n", i);
        printf("got %s instead of %s\n", p, test[4].digest);
        err++;
    }

    HMAC_CTX_reset(ctx);
    if (HMAC_CTX_get_md(ctx) != NULL) {
        printf("Message digest not NULL for HMAC (test 5)\n");
        err++;
        goto test6;
    }
    if (HMAC_Init_ex(ctx, test[4].key, test[4].key_len, NULL, NULL)) {
        printf("Should fail to initialise HMAC with empty MD (test 5)\n");
        err++;
        goto test6;
    }
    if (HMAC_Update(ctx, test[4].data, test[4].data_len)) {
        printf("Should fail HMAC_Update with ctx not set up (test 5)\n");
        err++;
        goto test6;
    }
    if (HMAC_Init_ex(ctx, test[4].key, -1, EVP_sha1(), NULL)) {
        printf("Should fail to initialise HMAC with invalid key len(test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Init_ex(ctx, test[4].key, test[4].key_len, EVP_sha1(), NULL)) {
        printf("Failed to initialise HMAC (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Update(ctx, test[4].data, test[4].data_len)) {
        printf("Error updating HMAC with data (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Final(ctx, buf, &len)) {
        printf("Error finalising data (test 5)\n");
        err++;
        goto test6;
    }
    p = pt(buf, len);
    if (strcmp(p, (char *)test[4].digest) != 0) {
        printf("Error calculating interim HMAC on test 5\n");
        printf("got %s instead of %s\n", p, test[4].digest);
        err++;
        goto test6;
    }
    if (HMAC_Init_ex(ctx, NULL, 0, EVP_sha256(), NULL)) {
        printf("Should disallow changing MD without a new key (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Init_ex(ctx, test[5].key, test[5].key_len, EVP_sha256(), NULL)) {
        printf("Failed to reinitialise HMAC (test 5)\n");
        err++;
        goto test6;
    }
    if (HMAC_CTX_get_md(ctx) != EVP_sha256()) {
        printf("Unexpected message digest for HMAC (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Update(ctx, test[5].data, test[5].data_len)) {
        printf("Error updating HMAC with data (sha256) (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Final(ctx, buf, &len)) {
        printf("Error finalising data (sha256) (test 5)\n");
        err++;
        goto test6;
    }
    p = pt(buf, len);
    if (strcmp(p, (char *)test[5].digest) != 0) {
        printf("Error calculating 2nd interim HMAC on test 5\n");
        printf("got %s instead of %s\n", p, test[5].digest);
        err++;
        goto test6;
    }
    if (!HMAC_Init_ex(ctx, test[6].key, test[6].key_len, NULL, NULL)) {
        printf("Failed to reinitialise HMAC with key (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Update(ctx, test[6].data, test[6].data_len)) {
        printf("Error updating HMAC with data (new key) (test 5)\n");
        err++;
        goto test6;
    }
    if (!HMAC_Final(ctx, buf, &len)) {
        printf("Error finalising data (new key) (test 5)\n");
        err++;
        goto test6;
    }
    p = pt(buf, len);
    if (strcmp(p, (char *)test[6].digest) != 0) {
        printf("error calculating HMAC on test 5\n");
        printf("got %s instead of %s\n", p, test[6].digest);
        err++;
    } else {
        printf("test 5 ok\n");
    }
test6:
    HMAC_CTX_reset(ctx);
    ctx2 = HMAC_CTX_new();
    if (ctx2 == NULL) {
        printf("HMAC malloc failure (test 6)\n");
        err++;
        goto end;
    }
    if (!HMAC_Init_ex(ctx, test[7].key, test[7].key_len, EVP_sha1(), NULL)) {
        printf("Failed to initialise HMAC (test 6)\n");
        err++;
        goto end;
    }
    if (!HMAC_Update(ctx, test[7].data, test[7].data_len)) {
        printf("Error updating HMAC with data (test 6)\n");
        err++;
        goto end;
    }
    if (!HMAC_CTX_copy(ctx2, ctx)) {
        printf("Failed to copy HMAC_CTX (test 6)\n");
        err++;
        goto end;
    }
    if (!HMAC_Final(ctx2, buf, &len)) {
        printf("Error finalising data (test 6)\n");
        err++;
        goto end;
    }
    p = pt(buf, len);
    if (strcmp(p, (char *)test[7].digest) != 0) {
        printf("Error calculating HMAC on test 6\n");
        printf("got %s instead of %s\n", p, test[7].digest);
        err++;
    } else {
        printf("test 6 ok\n");
    }
end:
    HMAC_CTX_free(ctx2);
    HMAC_CTX_free(ctx);
    EXIT(err);
}
static void _hmac_md5_ctx_free_on_exit(void *arg)
{
	HMAC_CTX_free(arg);
}
Exemple #27
0
static int ntlm2_auth(krb5_context context, struct kcrap_auth_req_data *req,
                      int *errnum,
                      krb5_data *error_data, struct kcrap_data *extra)
{
	int retval;
	int nkeys;
	struct keyblocks keyblocks[5];
	HMAC_CTX *ctx;
	unsigned char *tmpbuf;
	int i, j;
	unsigned char v2hash[EVP_MAX_MD_SIZE];
	unsigned int v2hlen;
	unsigned char resp[EVP_MAX_MD_SIZE];
	unsigned int resplen;

	if (req->server_challenge.length < 1) {
		*errnum = EINVAL;
		error_data->data = strdup("Invalid server challenge length");
		error_data->length = strlen(error_data->data);
		return 0;
	}

	if (req->client_challenge.length < 1) {
		*errnum = EINVAL;
		error_data->data = strdup("Invalid client challenge length");
		error_data->length = strlen(error_data->data);
		return 0;
	}

	if (req->response.length != 16) {
		*errnum = EINVAL;
		error_data->data = strdup("Invalid response length");
		error_data->length = strlen(error_data->data);
		return 0;
	}

	nkeys = sizeof(keyblocks) / sizeof(struct keyblocks);

	if ((retval = kcrap_getkey(context, req->principal, ENCTYPE_ARCFOUR_HMAC,
	                           &nkeys,
	                           keyblocks)))
		goto fail0;

	tmpbuf = malloc((req->principal.length + req->alt_username.length) * 2);

	if (tmpbuf == NULL) {
		retval = errno;
		perror("malloc");
		goto fail;
	}

	j = 0;

	for(i = 0; i < req->principal.length; i++) {
		tmpbuf[j++] = toupper(req->principal.data[i]);
		tmpbuf[j++] = 0;
	}

	for(i = 0; i < req->alt_username.length; i++) {
		tmpbuf[j++] = req->alt_username.data[i];
		tmpbuf[j++] = 0;
	}


	for (i = 0; i < nkeys; i++) {
		if (keyblocks[i].key.length != 16) continue;

		HMAC(EVP_md5(), (unsigned char*)keyblocks[i].key.contents, 16, tmpbuf, j,
		     v2hash,
		     &v2hlen);

#ifdef DEBUG_PASSWORD
		fprintf(stderr, "principal:\n");
		dump_data(tmpbuf, j);
		fprintf(stderr, "principal hash:\n");
		dump_data(v2hash, v2hlen);
#endif

		ctx = HMAC_CTX_new();
		HMAC_Init_ex(ctx, v2hash, v2hlen, EVP_md5(), NULL);
		HMAC_Update(ctx, (unsigned char*)req->server_challenge.data,
		            req->server_challenge.length);
		HMAC_Update(ctx, (unsigned char*)req->client_challenge.data,
		            req->client_challenge.length);
		HMAC_Final(ctx, resp, &resplen);
		HMAC_CTX_free(ctx);

		if (resplen != 16) {
			if (tmpbuf) free(tmpbuf);

			for (i = 0; i < nkeys; i++)
				krb5_free_keyblock_contents(context, &keyblocks[i].key);

			*errnum = KRB5_CRYPTO_INTERNAL;
			error_data->data = strdup("Server internal error: NTLMv2 resplen != 16");
			error_data->length = strlen(error_data->data);
			return 0;
		}

#ifdef DEBUG_PASSWORD
		fprintf(stderr, "server challenge:\n");
		dump_data(req->server_challenge.data, req->server_challenge.length);
		fprintf(stderr, "client challenge:\n");
		dump_data(req->client_challenge.data, req->client_challenge.length);
		fprintf(stderr, "expected response:\n");
		dump_data(resp, resplen);
		fprintf(stderr, "client response:\n");
		dump_data(req->response.data, req->response.length);
#endif

		if (memcmp(resp, req->response.data, 16) == 0) {
			*errnum = 0;
			goto ok;
		}
	}

	for (i = 0; i < nkeys; i++)
		krb5_free_keyblock_contents(context, &keyblocks[i].key);

	*errnum = 0;
	error_data->data = strdup("Invalid response");
	error_data->length = strlen(error_data->data);
	return 0;

ok:

	if (tmpbuf) free(tmpbuf);

	for (i = 0; i < nkeys; i++)
		krb5_free_keyblock_contents(context, &keyblocks[i].key);

	return KCRAP_AUTH_OK;

fail:

	if (tmpbuf) free(tmpbuf);

	for (i = 0; i < nkeys; i++)
		krb5_free_keyblock_contents(context, &keyblocks[i].key);

fail0:
	*errnum = retval;
	error_data->data = strdup(error_message(retval));
	error_data->length = strlen(error_data->data);
	return 0;
}
HmacHash::~HmacHash()
{
    HMAC_CTX_free(m_ctx);
}