Пример #1
0
cli::Error_e cmdHmac( CLIARGS args, cli::Param_t prm) {

   tstring tsText = args[1];
   tstring tsKey  = args[2];   
   if ((0 == tsText.length()) || (0 == tsKey.length())) { 
      printf( "***ERROR: You must enter text and key strings." );
      return cli::ERR_MISSINGARG;
   }
      
   CvtStrA sText( tsText.c_str() );   
   CvtStrA sKey ( tsKey .c_str() );      
   MemBuf sOut( SHA1_LEN );
   hmac_sha1( sText, sKey, sOut );
   
   std::string s;
   printf( "%s\n", FmtHex( s, sOut, sOut.size() ));
   
   return cli::ERR_NOERROR;         
}
Пример #2
0
static int
capwriteuse(uchar *a, int len)
{
	int n;
	uchar digest[SHA1dlen];
	char buf[128], *p, *users[3];
	Caps *c, **l;

	if(len >= sizeof(buf)-1)
		return -1;
	memmove(buf, a, len);
	buf[len] = 0;
	p = strrchr(buf, '@');
	if(p == nil)
		return -1;
	*p++ = 0;
	len = strlen(p);
	n = strlen(buf);
	if(len == 0 || n == 0)
		return -1;
	hmac_sha1((uchar*)buf, n, (uchar*)p, len, digest, nil);
	n = getfields(buf, users, nelem(users), 0, "@");
	if(n == 1)
		users[1] = users[0];
	else if(n != 2)
		return -1;
	if(*users[0] == 0 || *users[1] == 0)
		return -1;
	qlock(&allcaps.l);
	for(l = &allcaps.caps; (c = *l) != nil; l = &c->next)
		if(memcmp(c->hash, digest, sizeof(c->hash)) == 0){
			*l = c->next;
			qunlock(&allcaps.l);
			free(c);
			if(n == 2 && strcmp(up->env->user, users[0]) != 0)
				return -1;
			setid(users[1], 0);	/* could use users[2] to mean `host OS user' */
			return 0;
		}
	qunlock(&allcaps.l);
	return -1;
}
Пример #3
0
char *getTicketHash() {

    const char *codeToHash = "";

    if( downloadCode != NULL ) {
        codeToHash = downloadCode;
        }

    
    // strip out "-" separators
    int numParts;
    char **codeParts = split( codeToHash, "-", &numParts );
    
    char *pureCode =
        join( codeParts, numParts, "" );
    
    for( int i=0; i<numParts; i++ ) {
        delete [] codeParts[i];
        }
    delete [] codeParts;



    char *toHash = autoSprintf( "%d%d%s", 
                                serverSequenceNumber,
                                ticketHashVersionNumber,
                                sharedServerSecret );
    
    char *hash = hmac_sha1( pureCode, toHash );
    
    delete [] pureCode;
    delete [] toHash;

    char *result = autoSprintf( "sequence_number=%d&ticket_hmac=%s",
                                serverSequenceNumber,
                                hash );
    delete [] hash;

    serverSequenceNumber++;
    
    return result;
    }
static unsigned int computeTimeCode(unsigned int tm,unsigned char *secret, int secretLen) {
			unsigned char hash[SHA1_DIGEST_LENGTH];
			unsigned long chlg = tm ;
			unsigned char challenge[8];
			unsigned int truncatedHash = 0;
			int j;
			for (j = 8; j--; chlg >>= 8) {
				challenge[j] = chlg;
			}
			hmac_sha1(secret, secretLen, challenge, 8, hash, SHA1_DIGEST_LENGTH);
			int offset = hash[SHA1_DIGEST_LENGTH - 1] & 0xF;
			for (j = 0; j < 4; ++j) {
				truncatedHash <<= 8;
				truncatedHash  |= hash[offset + j];
			}
			memset(hash, 0, sizeof(hash));
			truncatedHash &= 0x7FFFFFFF;
			truncatedHash %= 1000000;
			return truncatedHash;
}
Пример #5
0
void
BCMROMFN(wpa_calc_pmkid)(struct ether_addr *auth_ea, struct ether_addr *sta_ea,
                         uint8 *pmk, uint pmk_len, uint8 *pmkid, uint8 *data, uint8 *digest)
{
	/* PMKID = HMAC-SHA1-128(PMK, "PMK Name" | AA | SPA) */
	const char prefix[] = "PMK Name";
	int data_len = 0;

	/* create the the data portion */
	bcopy(prefix, data, strlen(prefix));
	data_len += strlen(prefix);
	bcopy((uint8 *)auth_ea, &data[data_len], ETHER_ADDR_LEN);
	data_len += ETHER_ADDR_LEN;
	bcopy((uint8 *)sta_ea, &data[data_len], ETHER_ADDR_LEN);
	data_len += ETHER_ADDR_LEN;

	/* generate the pmkid */
	hmac_sha1(data, data_len, pmk, pmk_len, digest);
	bcopy(digest, pmkid, WPA2_PMKID_LEN);
}
Пример #6
0
attr_string*
sice_stun_form_username(        const attr_addr4*   source_attr ) {
    
    unsigned long time = 0;
    sice_stun_stamp_secs( &time );
    unsigned int ltime =(unsigned int)( time & 0xFFFFFFFF); 
    attr_string* username = NULL;
    char buf[1024];
    char hmac[20];
    char key[] = "Gustom";
    int  buflen = 0;
    char hexHmac[41];
    
    sprintf (   buf, "%08x%08x%08x",
                (unsigned int)source_attr->ip.addr,
                (unsigned int)sice_stun_rand_32b(),
                (unsigned int) ltime );

    if( (strlen(buf) < 1024) && ((strlen(buf) +41) < MAX_STRING) ) {
    
        hmac_sha1(      key, 
                        strlen(key), 
                        buf, 
                        strlen( buf ), hmac); 
        
        sice_stun_hexer( hmac, 20, hexHmac );
        strcat( buf, hexHmac );
        buflen = strlen( buf );
       
        printf("%d\n",buflen);
        if ( ((buflen +1) < MAX_STRING) && (buflen % 4 == 0) ) {
            username = (attr_string*)malloc( sizeof(attr_string) );
            memset(username, 0, sizeof(attr_string));
            username->val_size = buflen;
            memcpy( username->val, buf, buflen );
            username->val[buflen] = 0;
        }   
    }
    /* if any failures, return null*/
    return username;
}
Пример #7
0
static int auth_handler(const char *user, uint8_t *ha1)
{
	uint8_t key[MD5_SIZE], digest[SHA_DIGEST_LENGTH];
	const char *username;
	time_t expires, now;
	char pass[28];
	size_t len;
	int err;

	err = decode_user(&expires, &username, user);
	if (err)
		return err;

	now = time(NULL);

	if (expires < now) {
		restund_debug("restauth: user '%s' expired %lli seconds ago\n",
			      user, now - expires);
		return ETIMEDOUT;
	}

	/* avoid recursive loops */
	restund_db_set_auth_handler(NULL);
	err = restund_get_ha1(username, key);
	restund_db_set_auth_handler(auth_handler);
	if (err)
		return err;

	hmac_sha1(key, sizeof(key),
		  (uint8_t *)user, strlen(user),
		  digest, sizeof(digest));

	len = sizeof(pass);
	err = base64_encode(digest, sizeof(digest), pass, &len);
	if (err)
		return err;

	return md5_printf(ha1, "%s:%s:%b", user, restund_realm(), pass, len);
}
Пример #8
0
static int l_tm_hmac_sha1 (lua_State *L)
{
  size_t key_len = 0;
  uint8_t *key = (uint8_t *) colony_toconstdata(L, 1, &key_len);
  size_t msg_len = 0;
  uint8_t *msg = (uint8_t *) colony_toconstdata(L, 2, &msg_len);

  SHA1_CTX context;

  if (key_len > 64) {
    uint8_t* hashedkey = lua_newuserdata(L, 64);
    SHA1_Init(&context);
    SHA1_Update(&context, key, key_len);
    SHA1_Final(hashedkey, &context);
    key_len = 20;
    key = hashedkey;
  }

  uint8_t* sha1 = colony_createbuffer(L, 20);
  hmac_sha1(msg, msg_len, key, key_len, sha1);

  return 1;
}
Пример #9
0
/**
 * wpa_eapol_key_mic - Calculate EAPOL-Key MIC
 * @key: EAPOL-Key Key Confirmation Key (KCK)
 * @ver: Key descriptor version (WPA_KEY_INFO_TYPE_*)
 * @buf: Pointer to the beginning of the EAPOL header (version field)
 * @len: Length of the EAPOL frame (from EAPOL header to the end of the frame)
 * @mic: Pointer to the buffer to which the EAPOL-Key MIC is written
 * Returns: 0 on success, -1 on failure
 *
 * Calculate EAPOL-Key MIC for an EAPOL-Key packet. The EAPOL-Key MIC field has
 * to be cleared (all zeroes) when calling this function.
 *
 * Note: 'IEEE Std 802.11i-2004 - 8.5.2 EAPOL-Key frames' has an error in the
 * description of the Key MIC calculation. It includes packet data from the
 * beginning of the EAPOL-Key header, not EAPOL header. This incorrect change
 * happened during final editing of the standard and the correct behavior is
 * defined in the last draft (IEEE 802.11i/D10).
 */
int wpa_eapol_key_mic(const u8 *key, int ver, const u8 *buf, size_t len,
		      u8 *mic)
{
	u8 hash[SHA1_MAC_LEN];

	switch (ver) {
	case WPA_KEY_INFO_TYPE_HMAC_MD5_RC4:
		return hmac_md5(key, 16, buf, len, mic);
	case WPA_KEY_INFO_TYPE_HMAC_SHA1_AES:
		if (hmac_sha1(key, 16, buf, len, hash))
			return -1;
		os_memcpy(mic, hash, MD5_MAC_LEN);
		break;
#if defined(CONFIG_IEEE80211R) || defined(CONFIG_IEEE80211W)
	case WPA_KEY_INFO_TYPE_AES_128_CMAC:
		return omac1_aes_128(key, buf, len, mic);
#endif /* CONFIG_IEEE80211R || CONFIG_IEEE80211W */
	default:
		return -1;
	}

	return 0;
}
Пример #10
0
static
vector<u8> H2(const vector<u8>& s,
              const vector<u8>& rc,
              const vector<u8>& rs)
{
    vector<u8> message;
    message.insert(message.end(), rc.begin(), rc.end());
    message.insert(message.end(), rs.begin(), rs.end());
    message.insert(message.end(), kPad2.begin(), kPad2.end());

    vector<u8> ret;

    vector<u8> a = hmac_md5(s, message);
    ret.insert(ret.end(), a.begin(), a.end());

    vector<u8> b = hmac_sha1(s, message);
    ret.insert(ret.end(), b.begin(), b.end());

    vector<u8> c = hmac_whirlpool(s, message);
    ret.insert(ret.end(), c.begin(), c.end());

    return ret;
}
Пример #11
0
void
CJaiku::MakeOAuthRequest(
        const char *url,
        const char *method,
        char       *request,
        char       *key,
        char       *base,
        char       *param
    )
{
    char    digest[SHA1HashSize * 4];

    sprintf( base + strlen(base),
             "%s",
             encodeURLi(param, FALSE) );

    memset( digest, 0x00, SHA1HashSize );
    hmac_sha1( (unsigned char *)base, strlen(base),
               (unsigned char *)key, strlen(key),
               digest );
    strcpy( digest, base64( (unsigned char *)digest, SHA1HashSize ) );

    if ( !strcmpi( method, "GET" ) )
        sprintf( request,
                 "%s?"
                 "%s&"
                 "oauth_signature=%s",
                 url,
                 param,
                 encodeURLi( digest, TRUE ) );
    else
        sprintf( request,
                 "%s&"
                 "oauth_signature=%s",
                 param,
                 encodeURLi( digest, TRUE ) );
}
Пример #12
0
static int
chuid(char* to)
{
	int fd, r;
	char *cap, *p;
	uint8_t hash[SHA1dlen];

	if((fd = open("#¤/caphash", OWRITE)) < 0){
		werrstr("open #¤/caphash: %r");
		return -1;
	}
	
	cap = smprint("%s@Why can't we all just get along?", to);
	p = strrchr(cap, '@');
	hmac_sha1((uint8_t*)cap, p-cap, (uint8_t*)p+1, strlen(p+1), hash,
		  nil);
	if(write(fd, hash, SHA1dlen) < 0){
		free(cap);
		werrstr("write #¤/caphash: %r");
		return -1;
	}
	close(fd);

	if((fd = open("#¤/capuse", OWRITE)) < 0){
		free(cap);
		werrstr("open #¤/capuse: %r");
		return -1;
	}
	r = write(fd, cap, strlen(cap));
	close(fd);
	free(cap);

	if(r < 0)
		werrstr("write #¤/capuse: %r");

	return r;
}
Пример #13
0
/*
 * MIC Calculation / Verification
 *
 * for WPA
 * 	MICAP = HMAC-MD5(PTK-802.1X-MIC-Key , STA-ID | RSNIEAP | RN |
 * 		KeyIDunicast | KeyIDmulticast | RSC | MulticastKeyLength | EGTK)
 *
 * for WPA2
 * 	MICAP = HMAC-SHA1(PTK-802.1X-MIC-Key , STA-ID | RSNIEAP | RN |
 * 		KeyIDunicast | KeyIDmulticast | RSC | MulticastKeyLength | EGTK)
 */
static int cckm_verify_mic(struct wpa_sm *sm, struct cckm_ie_rsp *cie, u8* kck)
{
	u8 data[128];
	u8 mic[32];
	u32 data_len = ETH_ALEN;

	os_memcpy(data, sm->own_addr, ETH_ALEN);

	if (sm->ap_rsn_ie && sm->ap_rsn_ie_len) {
		os_memcpy(data+data_len, sm->ap_rsn_ie, sm->ap_rsn_ie_len);
		data_len += sm->ap_rsn_ie_len;
	} else if (sm->ap_wpa_ie && sm->ap_wpa_ie_len) {
		os_memcpy(data+data_len, sm->ap_wpa_ie, sm->ap_wpa_ie_len);
		data_len += sm->ap_wpa_ie_len;
	} else if (sm->assoc_wpa_ie && sm->assoc_wpa_ie_len) {
		os_memcpy(data + data_len, sm->assoc_wpa_ie,
				sm->assoc_wpa_ie_len);
		data_len += sm->assoc_wpa_ie_len;
	}
	os_memcpy(data+data_len, cie->rn, 4);
	data_len += 4;
	os_memcpy(data+data_len, &cie->unicast_keyid, 12);
	data_len += 12;
	os_memcpy(data+data_len, &cie->gtk, WPA_GET_LE16(cie->gtk_len));
	data_len += WPA_GET_LE16(cie->gtk_len);

	if (sm->proto == WPA_PROTO_RSN) {
		hmac_sha1(kck, 16, data, data_len, mic);
	} else {
		hmac_md5(kck, 16, data, data_len, mic);
	}

	wpa_hexdump(MSG_DEBUG, "GTK MIC", mic, 8);
	wpa_hexdump(MSG_DEBUG, "RIE MIC", cie->ap_mic, 8);

	return os_memcmp(mic, cie->ap_mic, 8);
}
Пример #14
0
int ikev2_integ_hash(int alg, const u8 *key, size_t key_len, const u8 *data,
		     size_t data_len, u8 *hash)
{
	u8 tmphash[IKEV2_MAX_HASH_LEN];

	switch (alg) {
	case AUTH_HMAC_SHA1_96:
		if (key_len != 20)
			return -1;
		hmac_sha1(key, key_len, data, data_len, tmphash);
		os_memcpy(hash, tmphash, 12);
		break;
	case AUTH_HMAC_MD5_96:
		if (key_len != 16)
			return -1;
		hmac_md5(key, key_len, data, data_len, tmphash);
		os_memcpy(hash, tmphash, 12);
		break;
	default:
		return -1;
	}

	return 0;
}
Пример #15
0
static int HOTP(unsigned char *secret, size_t sec_len, uint64_t ctr, int digits)
{
    ctr = htobe64(ctr);
    unsigned char hash[20];
    if(hmac_sha1(secret, sec_len, &ctr, 8, hash))
    {
        return -1;
    }

    int offs = hash[19] & 0xF;
    uint32_t code = (hash[offs] & 0x7F) << 24 |
        hash[offs + 1] << 16 |
        hash[offs + 2] << 8  |
        hash[offs + 3];

    int mod = 1;
    for(int i = 0; i < digits; ++i)
        mod *= 10;

    // debug
    // rb->splashf(HZ * 5, "HOTP %*s, %llu, %d: %d", sec_len, secret, htobe64(ctr), digits, code % mod);

    return code % mod;
}
Пример #16
0
QString signature_make(QString http_verb, QString hostname, QString url, QMap<QString, QString> params, QString api_key){
	QString to_sign = http_verb + " " + hostname.remove(0, 7) + url + "\n";
	QUrl request = QUrl("", QUrl::TolerantMode);
	QMapIterator<QString, QString> i(params);
	while (i.hasNext()) {
		i.next();
		//QString val = i.value();
		//QUrl::toPercentEncoding(val);
		//to_sign += i.key() + "=" +  QUrl::toPercentEncoding(i.value(), "", " +;");
		request.addEncodedQueryItem(QByteArray(i.key().toStdString().c_str()), QUrl::toPercentEncoding(i.value(), "", "+; "));
		//request.addQueryItem(i.key(), i.value());
		//if(i.hasNext()) to_sign += "&";
	}
	
	QString str_req(request.toEncoded());
	to_sign += str_req.remove(0, 1);

	std::cout << to_sign.toStdString() << "\n";
	QString sig = hmac_sha1(to_sign, api_key);

	//QUrl::toPercentEncoding(sig);
	std::cout << "[signature_make] " << sig.toStdString() << "\n";
	return sig;
}
Пример #17
0
static void eap_fast_write_crypto_binding(
	struct eap_tlv_crypto_binding_tlv *rbind,
	struct eap_tlv_crypto_binding_tlv *_bind, const u8 *cmk)
{
	rbind->tlv_type = host_to_be16(EAP_TLV_TYPE_MANDATORY |
				       EAP_TLV_CRYPTO_BINDING_TLV);
	rbind->length = host_to_be16(sizeof(*rbind) -
				     sizeof(struct eap_tlv_hdr));
	rbind->version = EAP_FAST_VERSION;
	rbind->received_version = _bind->version;
	rbind->subtype = EAP_TLV_CRYPTO_BINDING_SUBTYPE_RESPONSE;
	os_memcpy(rbind->nonce, _bind->nonce, sizeof(_bind->nonce));
	inc_byte_array(rbind->nonce, sizeof(rbind->nonce));
	hmac_sha1(cmk, EAP_FAST_CMK_LEN, (u8 *) rbind, sizeof(*rbind),
		  rbind->compound_mac);

	wpa_printf(MSG_DEBUG, "EAP-FAST: Reply Crypto-Binding TLV: Version %d "
		   "Received Version %d SubType %d",
		   rbind->version, rbind->received_version, rbind->subtype);
	wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: NONCE",
		    rbind->nonce, sizeof(rbind->nonce));
	wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: Compound MAC",
		    rbind->compound_mac, sizeof(rbind->compound_mac));
}
Пример #18
0
int
main (int argc, char *argv[])
{
  {
    char *key =
      "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b";
    size_t key_len = 16;
    char *data = "Hi There";
    size_t data_len = 8;
    char *digest =
      "\x67\x5b\x0b\x3a\x1b\x4d\xdf\x4e\x12\x48\x72\xda\x6c\x2f\x63\x2b\xfe\xd9\x57\xe9";
    char out[20];

    if (hmac_sha1 (key, key_len, data, data_len, out) != 0)
      {
        printf ("call failure\n");
        return 1;
      }

    if (memcmp (digest, out, 20) != 0)
      {
        size_t i;
        printf ("hash 1 mismatch. expected:\n");
        for (i = 0; i < 20; i++)
          printf ("%02x ", digest[i] & 0xFF);
        printf ("\ncomputed:\n");
        for (i = 0; i < 20; i++)
          printf ("%02x ", out[i] & 0xFF);
        printf ("\n");
        return 1;
      }
  }

  {
    char *key = "Jefe";
    size_t key_len = 4;
    char *data = "what do ya want for nothing?";
    size_t data_len = 28;
    char *digest =
      "\xef\xfc\xdf\x6a\xe5\xeb\x2f\xa2\xd2\x74\x16\xd5\xf1\x84\xdf\x9c\x25\x9a\x7c\x79";
    char out[20];

    if (hmac_sha1 (key, key_len, data, data_len, out) != 0)
      {
        printf ("call failure\n");
        return 1;
      }

    if (memcmp (digest, out, 20) != 0)
      {
        size_t i;
        printf ("hash 2 mismatch. expected:\n");
        for (i = 0; i < 20; i++)
          printf ("%02x ", digest[i] & 0xFF);
        printf ("\ncomputed:\n");
        for (i = 0; i < 20; i++)
          printf ("%02x ", out[i] & 0xFF);
        printf ("\n");
        return 1;
      }
  }

  {
    char *key =
      "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA";
    size_t key_len = 16;
    char *data = "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD"
      "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD"
      "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD"
      "\xDD\xDD";
    size_t data_len = 50;
    char *digest =
      "\xd7\x30\x59\x4d\x16\x7e\x35\xd5\x95\x6f\xd8\x00\x3d\x0d\xb3\xd3\xf4\x6d\xc7\xbb";
    char out[20];

    if (hmac_sha1 (key, key_len, data, data_len, out) != 0)
      {
        printf ("call failure\n");
        return 1;
      }

    if (memcmp (digest, out, 20) != 0)
      {
        size_t i;
        printf ("hash 3 mismatch. expected:\n");
        for (i = 0; i < 20; i++)
          printf ("%02x ", digest[i] & 0xFF);
        printf ("\ncomputed:\n");
        for (i = 0; i < 20; i++)
          printf ("%02x ", out[i] & 0xFF);
        printf ("\n");
        return 1;
      }
  }

  return 0;
}
Пример #19
0
int fko_set_spa_hmac(fko_ctx_t ctx,
    const char * const hmac_key, const int hmac_key_len)
{
    unsigned char hmac[SHA512_DIGEST_STR_LEN] = {0};
    char *hmac_base64 = NULL;
    int   hmac_digest_str_len = 0;
    int   hmac_digest_len = 0;

    /* Must be initialized
    */
    if(!CTX_INITIALIZED(ctx))
        return(FKO_ERROR_CTX_NOT_INITIALIZED);

    if(hmac_key_len > MAX_DIGEST_BLOCK_LEN)
        return(FKO_ERROR_INVALID_HMAC_KEY_LEN);

    if(ctx->hmac_type == FKO_HMAC_MD5)
    {
        hmac_md5(ctx->encrypted_msg,
            ctx->encrypted_msg_len, hmac, hmac_key, hmac_key_len);

        hmac_digest_len     = MD5_DIGEST_LEN;
        hmac_digest_str_len = MD5_DIGEST_STR_LEN;
    }
    else if(ctx->hmac_type == FKO_HMAC_SHA1)
    {
        hmac_sha1(ctx->encrypted_msg,
            ctx->encrypted_msg_len, hmac, hmac_key, hmac_key_len);

        hmac_digest_len     = SHA1_DIGEST_LEN;
        hmac_digest_str_len = SHA1_DIGEST_STR_LEN;
    }
    else if(ctx->hmac_type == FKO_HMAC_SHA256)
    {
        hmac_sha256(ctx->encrypted_msg,
            ctx->encrypted_msg_len, hmac, hmac_key, hmac_key_len);

        hmac_digest_len     = SHA256_DIGEST_LEN;
        hmac_digest_str_len = SHA256_DIGEST_STR_LEN;
    }
    else if(ctx->hmac_type == FKO_HMAC_SHA384)
    {
        hmac_sha384(ctx->encrypted_msg,
            ctx->encrypted_msg_len, hmac, hmac_key, hmac_key_len);

        hmac_digest_len     = SHA384_DIGEST_LEN;
        hmac_digest_str_len = SHA384_DIGEST_STR_LEN;
    }
    else if(ctx->hmac_type == FKO_HMAC_SHA512)
    {
        hmac_sha512(ctx->encrypted_msg,
            ctx->encrypted_msg_len, hmac, hmac_key, hmac_key_len);

        hmac_digest_len     = SHA512_DIGEST_LEN;
        hmac_digest_str_len = SHA512_DIGEST_STR_LEN;
    }

    hmac_base64 = calloc(1, MD_HEX_SIZE(hmac_digest_len)+1);
    if (hmac_base64 == NULL)
        return(FKO_ERROR_MEMORY_ALLOCATION);

    b64_encode(hmac, hmac_base64, hmac_digest_len);
    strip_b64_eq(hmac_base64);

    if(ctx->msg_hmac != NULL)
        free(ctx->msg_hmac);

    ctx->msg_hmac     = strdup(hmac_base64);
    ctx->msg_hmac_len = strnlen(ctx->msg_hmac, hmac_digest_str_len);

    free(hmac_base64);

    switch(ctx->msg_hmac_len)
    {
        case MD5_B64_LEN:
            break;
        case SHA1_B64_LEN:
            break;
        case SHA256_B64_LEN:
            break;
        case SHA384_B64_LEN:
            break;
        case SHA512_B64_LEN:
            break;
        default:
            return(FKO_ERROR_INVALID_DATA_HMAC_LEN_VALIDFAIL);
    }

    return FKO_SUCCESS;
}
Пример #20
0
static long
capwrite(Chan *c, void *va, long n, vlong vl)
{
	Caphash *p;
	char *cp;
	uchar hash[Hashlen];
	char *key, *from, *to;
	char err[256];

	switch((ulong)c->qid.path){
	case Qhash:
		if(!iseve())
			error(Eperm);
		if(n < Hashlen)
			error(Eshort);
		memmove(hash, va, Hashlen);
		addcap(hash);
		break;

	case Quse:
		/* copy key to avoid a fault in hmac_xx */
		cp = nil;
		if(waserror()){
			free(cp);
			nexterror();
		}
		cp = smalloc(n+1);
		memmove(cp, va, n);
		cp[n] = 0;

		from = cp;
		key = strrchr(cp, '@');
		if(key == nil)
			error(Eshort);
		*key++ = 0;

		hmac_sha1((uchar*)from, strlen(from), (uchar*)key, strlen(key), hash, nil);

		p = remcap(hash);
		if(p == nil){
			snprint(err, sizeof err, "invalid capability %s@%s", from, key);
			error(err);
		}

		/* if a from user is supplied, make sure it matches */
		to = strchr(from, '@');
		if(to == nil){
			to = from;
		} else {
			*to++ = 0;
			if(strcmp(from, up->user) != 0)
				error("capability must match user");
		}

		/* set user id */
		kstrdup(&up->user, to);
		up->basepri = PriNormal;

		free(p);
		free(cp);
		poperror();
		break;

	default:
		error(Eperm);
		break;
	}

	return n;
}
/* Implement PKCS#5 PBKDF2 as per RFC 2898.  The PRF to use is hard
   coded to be HMAC-SHA1.  Inputs are the password P of length PLEN,
   the salt S of length SLEN, the iteration counter C (> 0), and the
   desired derived output length DKLEN.  Output buffer is DK which
   must have room for at least DKLEN octets.  The output buffer will
   be filled with the derived data.  */
/*Gc_rc*/ int
/*gc_*/pbkdf2_sha1 (const char *P, size_t Plen,
                    const char *S, size_t Slen,
                    unsigned int c,
                    char *DK, size_t dkLen)
{
    unsigned int hLen = 20;
    char U[20];
    char T[20];
    unsigned int u;
    unsigned int l;
    unsigned int r;
    unsigned int i;
    unsigned int k;
    int rc;
    char *tmp;
    size_t tmplen = Slen + 4;

    if (c == 0)
        return /*GC_PKCS5_INVALID_ITERATION_COUNT*/ -1;

    if (dkLen == 0)
        return /*GC_PKCS5_INVALID_DERIVED_KEY_LENGTH*/ -1;

    if (dkLen > 4294967295U)
        return /*GC_PKCS5_DERIVED_KEY_TOO_LONG*/ -1;

    l = ((dkLen - 1) / hLen) + 1;
    r = dkLen - (l - 1) * hLen;

    tmp = (char*)malloc (tmplen);
    if (tmp == NULL)
        return /*GC_MALLOC_ERROR*/ -1;

    memcpy (tmp, S, Slen);

    for (i = 1; i <= l; i++)
    {
        memset (T, 0, hLen);

        for (u = 1; u <= c; u++)
        {
            if (u == 1)
            {
                tmp[Slen + 0] = (i & 0xff000000) >> 24;
                tmp[Slen + 1] = (i & 0x00ff0000) >> 16;
                tmp[Slen + 2] = (i & 0x0000ff00) >> 8;
                tmp[Slen + 3] = (i & 0x000000ff) >> 0;

                rc = /*gc_*/hmac_sha1 (P, Plen, tmp, tmplen, U);
            }
            else
                rc = /*gc_*/hmac_sha1 (P, Plen, U, hLen, U);

            if (rc != /*GC_OK*/ 0)
            {
                free (tmp);
                return rc;
            }

            for (k = 0; k < hLen; k++)
                T[k] ^= U[k];
        }
Пример #22
0
static int test_eap_fast(void)
{
	/* RFC 4851, Appendix B.1 */
	const u8 pac_key[] = {
		0x0B, 0x97, 0x39, 0x0F, 0x37, 0x51, 0x78, 0x09,
		0x81, 0x1E, 0xFD, 0x9C, 0x6E, 0x65, 0x94, 0x2B,
		0x63, 0x2C, 0xE9, 0x53, 0x89, 0x38, 0x08, 0xBA,
		0x36, 0x0B, 0x03, 0x7C, 0xD1, 0x85, 0xE4, 0x14
	};
	const u8 seed[] = {
		0x3F, 0xFB, 0x11, 0xC4, 0x6C, 0xBF, 0xA5, 0x7A,
		0x54, 0x40, 0xDA, 0xE8, 0x22, 0xD3, 0x11, 0xD3,
		0xF7, 0x6D, 0xE4, 0x1D, 0xD9, 0x33, 0xE5, 0x93,
		0x70, 0x97, 0xEB, 0xA9, 0xB3, 0x66, 0xF4, 0x2A,
		0x00, 0x00, 0x00, 0x02, 0x6A, 0x66, 0x43, 0x2A,
		0x8D, 0x14, 0x43, 0x2C, 0xEC, 0x58, 0x2D, 0x2F,
		0xC7, 0x9C, 0x33, 0x64, 0xBA, 0x04, 0xAD, 0x3A,
		0x52, 0x54, 0xD6, 0xA5, 0x79, 0xAD, 0x1E, 0x00
	};
	const u8 master_secret[] = {
		0x4A, 0x1A, 0x51, 0x2C, 0x01, 0x60, 0xBC, 0x02,
		0x3C, 0xCF, 0xBC, 0x83, 0x3F, 0x03, 0xBC, 0x64,
		0x88, 0xC1, 0x31, 0x2F, 0x0B, 0xA9, 0xA2, 0x77,
		0x16, 0xA8, 0xD8, 0xE8, 0xBD, 0xC9, 0xD2, 0x29,
		0x38, 0x4B, 0x7A, 0x85, 0xBE, 0x16, 0x4D, 0x27,
		0x33, 0xD5, 0x24, 0x79, 0x87, 0xB1, 0xC5, 0xA2  
	};
	const u8 key_block[] = {
		0x59, 0x59, 0xBE, 0x8E, 0x41, 0x3A, 0x77, 0x74,
		0x8B, 0xB2, 0xE5, 0xD3, 0x60, 0xAC, 0x4D, 0x35,
		0xDF, 0xFB, 0xC8, 0x1E, 0x9C, 0x24, 0x9C, 0x8B,
		0x0E, 0xC3, 0x1D, 0x72, 0xC8, 0x84, 0x9D, 0x57,
		0x48, 0x51, 0x2E, 0x45, 0x97, 0x6C, 0x88, 0x70,
		0xBE, 0x5F, 0x01, 0xD3, 0x64, 0xE7, 0x4C, 0xBB,
		0x11, 0x24, 0xE3, 0x49, 0xE2, 0x3B, 0xCD, 0xEF,
		0x7A, 0xB3, 0x05, 0x39, 0x5D, 0x64, 0x8A, 0x44,
		0x11, 0xB6, 0x69, 0x88, 0x34, 0x2E, 0x8E, 0x29,
		0xD6, 0x4B, 0x7D, 0x72, 0x17, 0x59, 0x28, 0x05,
		0xAF, 0xF9, 0xB7, 0xFF, 0x66, 0x6D, 0xA1, 0x96,
		0x8F, 0x0B, 0x5E, 0x06, 0x46, 0x7A, 0x44, 0x84,
		0x64, 0xC1, 0xC8, 0x0C, 0x96, 0x44, 0x09, 0x98,
		0xFF, 0x92, 0xA8, 0xB4, 0xC6, 0x42, 0x28, 0x71
	};
	const u8 sks[] = {
		0xD6, 0x4B, 0x7D, 0x72, 0x17, 0x59, 0x28, 0x05,
		0xAF, 0xF9, 0xB7, 0xFF, 0x66, 0x6D, 0xA1, 0x96,
		0x8F, 0x0B, 0x5E, 0x06, 0x46, 0x7A, 0x44, 0x84,
		0x64, 0xC1, 0xC8, 0x0C, 0x96, 0x44, 0x09, 0x98,
		0xFF, 0x92, 0xA8, 0xB4, 0xC6, 0x42, 0x28, 0x71
	};
	const u8 isk[] = {
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
	};
	const u8 imck[] = {
		0x16, 0x15, 0x3C, 0x3F, 0x21, 0x55, 0xEF, 0xD9,
		0x7F, 0x34, 0xAE, 0xC8, 0x1A, 0x4E, 0x66, 0x80,
		0x4C, 0xC3, 0x76, 0xF2, 0x8A, 0xA9, 0x6F, 0x96,
		0xC2, 0x54, 0x5F, 0x8C, 0xAB, 0x65, 0x02, 0xE1,
		0x18, 0x40, 0x7B, 0x56, 0xBE, 0xEA, 0xA7, 0xC5,
		0x76, 0x5D, 0x8F, 0x0B, 0xC5, 0x07, 0xC6, 0xB9,
		0x04, 0xD0, 0x69, 0x56, 0x72, 0x8B, 0x6B, 0xB8,
		0x15, 0xEC, 0x57, 0x7B
	};
	const u8 msk[] = {
		0x4D, 0x83, 0xA9, 0xBE, 0x6F, 0x8A, 0x74, 0xED,
		0x6A, 0x02, 0x66, 0x0A, 0x63, 0x4D, 0x2C, 0x33,
		0xC2, 0xDA, 0x60, 0x15, 0xC6, 0x37, 0x04, 0x51,
		0x90, 0x38, 0x63, 0xDA, 0x54, 0x3E, 0x14, 0xB9,
		0x27, 0x99, 0x18, 0x1E, 0x07, 0xBF, 0x0F, 0x5A,
		0x5E, 0x3C, 0x32, 0x93, 0x80, 0x8C, 0x6C, 0x49,
		0x67, 0xED, 0x24, 0xFE, 0x45, 0x40, 0xA0, 0x59,
		0x5E, 0x37, 0xC2, 0xE9, 0xD0, 0x5D, 0x0A, 0xE3
	};
	const u8 emsk[] = {
		0x3A, 0xD4, 0xAB, 0xDB, 0x76, 0xB2, 0x7F, 0x3B,
		0xEA, 0x32, 0x2C, 0x2B, 0x74, 0xF4, 0x28, 0x55,
		0xEF, 0x2D, 0xBA, 0x78, 0xC9, 0x57, 0x2F, 0x0D,
		0x06, 0xCD, 0x51, 0x7C, 0x20, 0x93, 0x98, 0xA9,
		0x76, 0xEA, 0x70, 0x21, 0xD7, 0x0E, 0x25, 0x54,
		0x97, 0xED, 0xB2, 0x8A, 0xF6, 0xED, 0xFD, 0x0A,
		0x2A, 0xE7, 0xA1, 0x58, 0x90, 0x10, 0x50, 0x44,
		0xB3, 0x82, 0x85, 0xDB, 0x06, 0x14, 0xD2, 0xF9
	};
	/* RFC 4851, Appendix B.2 */
	u8 tlv[] = {
		0x80, 0x0C, 0x00, 0x38, 0x00, 0x01, 0x01, 0x00,
		0xD8, 0x6A, 0x8C, 0x68, 0x3C, 0x32, 0x31, 0xA8,
		0x56, 0x63, 0xB6, 0x40, 0x21, 0xFE, 0x21, 0x14,
		0x4E, 0xE7, 0x54, 0x20, 0x79, 0x2D, 0x42, 0x62,
		0xC9, 0xBF, 0x53, 0x7F, 0x54, 0xFD, 0xAC, 0x58,
		0x43, 0x24, 0x6E, 0x30, 0x92, 0x17, 0x6D, 0xCF,
		0xE6, 0xE0, 0x69, 0xEB, 0x33, 0x61, 0x6A, 0xCC,
		0x05, 0xC5, 0x5B, 0xB7
	};
	const u8 compound_mac[] = {
		0x43, 0x24, 0x6E, 0x30, 0x92, 0x17, 0x6D, 0xCF,
		0xE6, 0xE0, 0x69, 0xEB, 0x33, 0x61, 0x6A, 0xCC,
		0x05, 0xC5, 0x5B, 0xB7
	};
	u8 buf[512];
	const u8 *simck, *cmk;
	int errors = 0;

	printf("EAP-FAST test cases\n");

	printf("- T-PRF (SHA1) test case / master_secret\n");
	sha1_t_prf(pac_key, sizeof(pac_key), "PAC to master secret label hash",
		   seed, sizeof(seed), buf, sizeof(master_secret));
	if (memcmp(master_secret, buf, sizeof(master_secret)) != 0) {
		printf("T-PRF test - FAILED!\n");
		errors++;
	}

	printf("- PRF (TLS, SHA1/MD5) test case / key_block\n");
	if (tls_prf(master_secret, sizeof(master_secret), "key expansion",
		    seed, sizeof(seed), buf, sizeof(key_block)) ||
	    memcmp(key_block, buf, sizeof(key_block)) != 0) {
		printf("PRF test - FAILED!\n");
		errors++;
	}

	printf("- T-PRF (SHA1) test case / IMCK\n");
	sha1_t_prf(sks, sizeof(sks), "Inner Methods Compound Keys",
		   isk, sizeof(isk), buf, sizeof(imck));
	if (memcmp(imck, buf, sizeof(imck)) != 0) {
		printf("T-PRF test - FAILED!\n");
		errors++;
	}

	simck = imck;
	cmk = imck + 40;

	printf("- T-PRF (SHA1) test case / MSK\n");
	sha1_t_prf(simck, 40, "Session Key Generating Function",
		   (u8 *) "", 0, buf, sizeof(msk));
	if (memcmp(msk, buf, sizeof(msk)) != 0) {
		printf("T-PRF test - FAILED!\n");
		errors++;
	}

	printf("- T-PRF (SHA1) test case / EMSK\n");
	sha1_t_prf(simck, 40, "Extended Session Key Generating Function",
		   (u8 *) "", 0, buf, sizeof(msk));
	if (memcmp(emsk, buf, sizeof(emsk)) != 0) {
		printf("T-PRF test - FAILED!\n");
		errors++;
	}

	printf("- Compound MAC test case\n");
	memset(tlv + sizeof(tlv) - 20, 0, 20);
	hmac_sha1(cmk, 20, tlv, sizeof(tlv), tlv + sizeof(tlv) - 20);
	if (memcmp(tlv + sizeof(tlv) - 20, compound_mac, sizeof(compound_mac))
	    != 0) {
		printf("Compound MAC test - FAILED!\n");
		errors++;
	}

	return errors;
}
Пример #23
0
void stepLineageLog() {
    if( ! useLineageServer ) {
        return;
        }
    
    for( int i=0; i<records.size(); i++ ) {
        LineageRecord *r = records.getElement( i );
        
        int result = r->request->step();
            
        char recordDone = false;

        if( result == -1 ) {
            AppLog::info( "Request to lineage server failed." );
            recordDone = true;
            }
        else if( result == 1 ) {
            // done, have result

            char *webResult = r->request->getResult();
            
            if( r->sequenceNumber == -1 ) {
                // still waiting for sequence number response

                int numRead = sscanf( webResult, "%d", &( r->sequenceNumber ) );

                if( numRead != 1 ) {
                    AppLog::info( "Failed to read sequence number "
                                  "from lineage server response." );
                    recordDone = true;
                    }
                else {
                    delete r->request;
                    
                    // start lineage-posting request

                    char *seqString = autoSprintf( "%d", r->sequenceNumber );
                    
                    char *lineageServerSharedSecret = 
                        SettingsManager::getStringSetting( 
                            "lineageServerSharedSecret", 
                            "secret_phrase" );


                    char *hash = hmac_sha1( lineageServerSharedSecret,
                                            seqString );
                    
                    delete [] lineageServerSharedSecret;

                    delete [] seqString;
                    
                    char *encodedEmail = URLUtils::urlEncode( r->email );
                    char *encodedName = URLUtils::urlEncode( r->name );
                    char *encodedLastSay = URLUtils::urlEncode( r->lastSay );
                    
                    int maleInt = 0;
                    if( r->male ) {
                        maleInt = 1;
                        }
                    
                    char *url = autoSprintf( 
                        "%s?action=log_life"
                        "&server=%s"
                        "&email=%s"
                        "&age=%f"
                        "&player_id=%d"
                        "&parent_id=%d"
                        "&display_id=%d"
                        "&killer_id=%d"
                        "&name=%s"
                        "&last_words=%s"
                        "&male=%d"
                        "&sequence_number=%d"
                        "&hash_value=%s",
                        lineageServerURL,
                        serverID,
                        encodedEmail,
                        r->age,
                        r->playerID,
                        r->parentID,
                        r->displayID,
                        r->killerID,
                        encodedName,
                        encodedLastSay,
                        maleInt,
                        r->sequenceNumber,
                        hash );
                    
                    delete [] encodedEmail;
                    delete [] encodedName;
                    delete [] encodedLastSay;
                    delete [] hash;

                    r->request = new WebRequest( "GET", url, NULL );
                    printf( "Starting new web request for %s\n", url );
                    
                    delete [] url;
                    }
                }
            else {
                
                if( strstr( webResult, "DENIED" ) != NULL ) {
                    AppLog::info( 
                        "Server log_life request rejected by lineage server" );
                    }
                recordDone = true;
                }
            
            delete [] webResult;
            }

        if( recordDone ) {
            delete r->request;
            delete [] r->email;
            delete [] r->name;
            delete [] r->lastSay;
            
            records.deleteElement( i );
            i--;
            }
        }
    }
Пример #24
0
static struct wpabuf * eap_fast_build_crypto_binding(
	struct eap_sm *sm, struct eap_fast_data *data)
{
	struct wpabuf *buf;
	struct eap_tlv_result_tlv *result;
	struct eap_tlv_crypto_binding_tlv *binding;

	buf = wpabuf_alloc(2 * sizeof(*result) + sizeof(*binding));
	if (buf == NULL)
		return NULL;

	if (data->send_new_pac || data->anon_provisioning ||
	    data->phase2_method)
		data->final_result = 0;
	else
		data->final_result = 1;

	if (!data->final_result || data->eap_seq > 1) {
		/* Intermediate-Result */
		wpa_printf(MSG_DEBUG, "EAP-FAST: Add Intermediate-Result TLV "
			   "(status=SUCCESS)");
		result = wpabuf_put(buf, sizeof(*result));
		result->tlv_type = host_to_be16(
			EAP_TLV_TYPE_MANDATORY |
			EAP_TLV_INTERMEDIATE_RESULT_TLV);
		result->length = host_to_be16(2);
		result->status = host_to_be16(EAP_TLV_RESULT_SUCCESS);
	}

	if (data->final_result) {
		/* Result TLV */
		wpa_printf(MSG_DEBUG, "EAP-FAST: Add Result TLV "
			   "(status=SUCCESS)");
		result = wpabuf_put(buf, sizeof(*result));
		result->tlv_type = host_to_be16(EAP_TLV_TYPE_MANDATORY |
						EAP_TLV_RESULT_TLV);
		result->length = host_to_be16(2);
		result->status = host_to_be16(EAP_TLV_RESULT_SUCCESS);
	}

	/* Crypto-Binding TLV */
	binding = wpabuf_put(buf, sizeof(*binding));
	binding->tlv_type = host_to_be16(EAP_TLV_TYPE_MANDATORY |
					 EAP_TLV_CRYPTO_BINDING_TLV);
	binding->length = host_to_be16(sizeof(*binding) -
				       sizeof(struct eap_tlv_hdr));
	binding->version = EAP_FAST_VERSION;
	binding->received_version = data->peer_version;
	binding->subtype = EAP_TLV_CRYPTO_BINDING_SUBTYPE_REQUEST;
	if (random_get_bytes(binding->nonce, sizeof(binding->nonce)) < 0) {
		wpabuf_free(buf);
		return NULL;
	}

	/*
	 * RFC 4851, Section 4.2.8:
	 * The nonce in a request MUST have its least significant bit set to 0.
	 */
	binding->nonce[sizeof(binding->nonce) - 1] &= ~0x01;

	os_memcpy(data->crypto_binding_nonce, binding->nonce,
		  sizeof(binding->nonce));

	/*
	 * RFC 4851, Section 5.3:
	 * CMK = CMK[j]
	 * Compound-MAC = HMAC-SHA1( CMK, Crypto-Binding TLV )
	 */

	hmac_sha1(data->cmk, EAP_FAST_CMK_LEN,
		  (u8 *) binding, sizeof(*binding),
		  binding->compound_mac);

	wpa_printf(MSG_DEBUG, "EAP-FAST: Add Crypto-Binding TLV: Version %d "
		   "Received Version %d SubType %d",
		   binding->version, binding->received_version,
		   binding->subtype);
	wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: NONCE",
		    binding->nonce, sizeof(binding->nonce));
	wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: Compound MAC",
		    binding->compound_mac, sizeof(binding->compound_mac));

	return buf;
}
Пример #25
0
static int LAME_ssh2_load_userkey(char *passphrase)
{
	int passlen = strlen(passphrase);
	unsigned char out[sizeof(cur_salt->private_blob)];
	AES_KEY akey;
	unsigned char iv[32];

	/* Decrypt the private blob. */
	if (cur_salt->cipher) {
		unsigned char key[40];
		SHA_CTX s;
		if (cur_salt->private_blob_len % cur_salt->cipherblk)
			goto error;

		SHA1_Init(&s);
		SHA1_Update(&s, (void*)"\0\0\0\0", 4);
		SHA1_Update(&s, passphrase, passlen);
		SHA1_Final(key + 0, &s);
		SHA1_Init(&s);
		SHA1_Update(&s, (void*)"\0\0\0\1", 4);
		SHA1_Update(&s, passphrase, passlen);
		SHA1_Final(key + 20, &s);
		memset(iv, 0, 32);
		memset(&akey, 0, sizeof(AES_KEY));
		if(AES_set_decrypt_key(key, 256, &akey) < 0) {
			fprintf(stderr, "AES_set_decrypt_key failed!\n");
		}
		AES_cbc_encrypt(cur_salt->private_blob, out , cur_salt->private_blob_len, &akey, iv, AES_DECRYPT);
	}
	/* Verify the MAC. */
	{
		char realmac[41];
		unsigned char binary[20];
		unsigned char *macdata;
		unsigned char macdata_ar[4*5+sizeof(cur_salt->alg)+sizeof(cur_salt->encryption)+sizeof(cur_salt->comment)+sizeof(cur_salt->public_blob_len)+sizeof(cur_salt->private_blob_len)+1];
		int maclen;
		int i;
		if (cur_salt->old_fmt) {
			/* MAC (or hash) only covers the private blob. */
			macdata = out;
			maclen = cur_salt->private_blob_len;
		} else {
			unsigned char *p;
			int namelen = strlen(cur_salt->alg);
			int enclen = strlen(cur_salt->encryption);
			int commlen = strlen(cur_salt->comment);
			maclen = (4 + namelen +
					4 + enclen +
					4 + commlen +
					4 + cur_salt->public_blob_len +
					4 + cur_salt->private_blob_len);
			p = macdata_ar;
#define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
			DO_STR(cur_salt->alg, namelen);
			DO_STR(cur_salt->encryption, enclen);
			DO_STR(cur_salt->comment, commlen);
			DO_STR(cur_salt->public_blob, cur_salt->public_blob_len);
			DO_STR(out, cur_salt->private_blob_len);
			macdata = macdata_ar;
		}
		if (cur_salt->is_mac) {
			SHA_CTX s;
			unsigned char mackey[20];
			unsigned int length = 20;
			// HMAC_CTX ctx;
			char header[] = "putty-private-key-file-mac-key";
			SHA1_Init(&s);
			SHA1_Update(&s, header, sizeof(header)-1);
			if (cur_salt->cipher && passphrase)
				SHA_Update(&s, passphrase, passlen);
			SHA1_Final(mackey, &s);
			hmac_sha1(mackey, 20, macdata, maclen, binary, length);
			/* HMAC_Init(&ctx, mackey, 20, EVP_sha1());
			 * HMAC_Update(&ctx, macdata, maclen);
			 * HMAC_Final(&ctx, binary, &length);
			 * HMAC_CTX_cleanup(&ctx); */
		} else {
			SHA_Simple(macdata, maclen, binary);
		}
		for (i = 0; i < 20; i++)
			sprintf(realmac + 2 * i, "%02x", binary[i]);

		if (strcmp(cur_salt->mac, realmac) == 0)
			return 1;
	}

error:
	return 0;
}
Пример #26
0
int main(void)
{
/*
 *	MD5 test vectors from RFC 1321 "The MD5 Message-Digest Algorithm"
 */
	static const char *md5_tests[] = {
		"",
		"a",
		"abc",
		"message digest",
		"abcdefghijklmnopqrstuvwxyz",
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
		"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
		NULL
	};
	static const char *md5_results[] = {
		"d41d8cd98f00b204e9800998ecf8427e",
		"0cc175b9c0f1b6a831c399e269772661",
		"900150983cd24fb0d6963f7d28e17f72",
		"f96b697d7cb7938d525a2f31aaf161d0",
		"c3fcd3d76192e4007dfb496cca67e13b",
		"d174ab98d277d9f5a5611c2c9f419d9f",
		"57edf4a22be3c955ac49da2e2107b67a"
	};
/*
 *	SHA1 test vectors from RFC 3174 "US Secure Hash Algorithm 1 (SHA1)"
 */
	static const char *sha1_tests[] = {
		"abc",
		"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
		NULL
	};
	static const char *sha1_results[] = {
		"a9993e364706816aba3e25717850c26c9cd0d89d",
		"84983e441c3bd26ebaae4aa1f95129e5e54670f1",
	};
/*
 *	HMAC-MD5 test vectors from RFC 2104
 *	"HMAC: Keyed-Hashing for Message Authentication"
 */
	static const struct hmac_md5_test_struct {
		unsigned char key[16];
		int key_len;
		unsigned char data[64];
		int data_len;
		char *digest;
	} hmac_md5_tests[NUM_HMAC_TESTS] = {
		{ "Jefe",
		  4,
		  "what do ya want for nothing?",
		  28,
		  "750c783e6ab0b503eaa86e310a5db738" }
	};

/*
 *	HMAC-SHA1 test vectors from RFC 2202
 *	"Test Cases for HMAC-MD5 and HMAC-SHA-1"
 */
	static const struct hmac_sha1_test_struct {
		unsigned char key[20];
		int key_len;
		unsigned char data[64];
		int data_len;
		char *digest;
	} hmac_sha1_tests[NUM_HMAC_TESTS] = {
		{ "Jefe",
		  4,
		  "what do ya want for nothing?",
		  28,
		  "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79" }
	};

	const char **testp;
	const char **resultp;
	int i;

	int error = 0;

#ifdef HAVE_OPENSSL
	printf("\nUsing OpenSSL hash and HMAC functions.\n");
#else
	printf("\nUsing built-in hash and HMAC functions.\n");
#endif

	printf("\nChecking MD5 hash function...\n");
	testp = md5_tests;
	resultp = md5_results;
	while (*testp != NULL) {
		const char *expected;
		char *actual;
		printf("\"%s\"\t", *testp);
		expected = *resultp;
		actual =
			hexstring(MD5((const unsigned char *) *testp,
				      strlen(*testp),
				      NULL), 16);
		if (strcmp(actual, expected)) {
			error++;
			printf("FAIL (expected %s, got %s)\n", expected,
			       actual);
		} else {
			printf("ok\n");
		}
		testp++;
		resultp++;
	}

	printf("\nChecking SHA1 hash function...\n");
	testp = sha1_tests;
	resultp = sha1_results;
	while (*testp != NULL) {
		const char *expected;
		char *actual;
		printf("\"%s\"\t", *testp);
		expected = *resultp;
		actual =
			hexstring(SHA1((const unsigned char *) *testp,
				       strlen(*testp),
				       NULL), 20);
		if (strcmp(actual, expected)) {
			error++;
			printf("FAIL (expected %s, got %s)\n", expected,
			       actual);
		} else {
			printf("ok\n");
		}
		testp++;
		resultp++;
	}

	printf("\nChecking HMAC-MD5 keyed hash function...\n");
	for (i = 0; i < NUM_HMAC_TESTS; i++) {
		const char *expected;
		char *actual;
		printf("\"%s\" \"%s\"\t", hmac_md5_tests[i].key,
		       hmac_md5_tests[i].data);
		expected = hmac_md5_tests[i].digest;
		actual = hexstring(hmac_md5(hmac_md5_tests[i].data,
					    hmac_md5_tests[i].data_len,
					    hmac_md5_tests[i].key,
					    hmac_md5_tests[i].key_len,
					    NULL), 16);
		if (strcmp(actual, expected)) {
			error++;
			printf("FAIL (expected %s, got %s)\n", expected,
			       actual);
		} else {
			printf("ok\n");
		}
	}

	printf("\nChecking HMAC-SHA1 keyed hash function...\n");
	for (i = 0; i < NUM_HMAC_TESTS; i++) {
		const char *expected;
		char *actual;
		printf("\"%s\" \"%s\"\t", hmac_sha1_tests[i].key,
		       hmac_sha1_tests[i].data);
		expected = hmac_sha1_tests[i].digest;
		actual = hexstring(hmac_sha1(hmac_sha1_tests[i].data,
					     hmac_sha1_tests[i].data_len,
					     hmac_sha1_tests[i].key,
					     hmac_sha1_tests[i].key_len,
					     NULL), 20);
		if (strcmp(actual, expected)) {
			error++;
			printf("FAIL (expected %s, got %s)\n", expected,
			       actual);
		} else {
			printf("ok\n");
		}
	}

	printf("\nChecking HMAC-MD5 PSK cracking speed...\n");
	do {
/*
 *	The values below are observed values from a Firewall-1 system
 *	using IKE Aggressive mode with PSK authentication and MD5 hash.
 *	The ID used was "test", and the valid pre-shared key is "abc123".
 *      The expected hash_r is "f995ec2968f695aeb1d4e4b437f49d26".
 */
		char *g_xr_hex =
			"9c1e0e07828af45086a4eb559ad8dafb7d655bab38656609426653565ef7e332bed7212cf24a05048032240256a169a68ee304ca500abe073d150bc50239350446ab568132aebcf34acd25ce23b30d0de9f8e7a89c22ce0dec2dabf0409bc25f0988d5d956916dce220c630d2a1fda846667fdecb20b2dc2d5c5b8273a07095c";
		char *g_xi_hex =
			"6f8c74c15bb4dd09b7af8d1c23e7b381a38dddcd4c5afb3b1335ff766f0267df8fdca0ea907ef4482d8164506817d10ba4aed8f108d32c1b082b91772df956bcd5f7a765759bada21c11f28429c48fcd7267be7b3aea96421528b9432110fff607a65b7c41091e5d1a10e143d4701147d7cfc211ba5853cf800d12a11d129724";
		char *cky_r_hex = "6d08132c8abb6931";
		char *cky_i_hex = "eac82ea45cbe59e6";
		char *sai_b_hex =
			"00000001000000010000002c01010001000000240101000080010001800200018003000180040002800b0001000c000400007080";
		char *idir_b_hex = "01000000ac100202";
		char *ni_b_hex = "64745a975dbcd95c2abf7d2eeeb93ac4633a03f1";
		char *nr_b_hex = "502c0b3872518fa1e7ff8f5a28a3d797f65e2cb1";

		unsigned char *g_xr;
		unsigned char *g_xi;
		unsigned char *cky_r;
		unsigned char *cky_i;
		unsigned char *sai_b;
		unsigned char *idir_b;
		unsigned char *ni_b;
		unsigned char *nr_b;

		size_t g_xr_len;
		size_t g_xi_len;
		size_t cky_r_len;
		size_t cky_i_len;
		size_t sai_b_len;
		size_t idir_b_len;
		size_t ni_b_len;
		size_t nr_b_len;

		unsigned char *skeyid;
		unsigned char *hash_r;

		unsigned char *skeyid_data;
		unsigned char *hash_r_data;

		size_t skeyid_data_len;
		size_t hash_r_data_len;

		unsigned char *cp;

		unsigned char *psk = (unsigned char *) "abc123"; /* correct key */
		size_t psk_len = 6;

		struct timeval start_time;
		struct timeval end_time;
		struct timeval elapsed_time;
		double elapsed_seconds;

		g_xr = hex2data(g_xr_hex, &g_xr_len);
		g_xi = hex2data(g_xi_hex, &g_xi_len);
		cky_r = hex2data(cky_r_hex, &cky_r_len);
		cky_i = hex2data(cky_i_hex, &cky_i_len);
		sai_b = hex2data(sai_b_hex, &sai_b_len);
		idir_b = hex2data(idir_b_hex, &idir_b_len);
		ni_b = hex2data(ni_b_hex, &ni_b_len);
		nr_b = hex2data(nr_b_hex, &nr_b_len);

		skeyid_data_len = ni_b_len + nr_b_len;
		skeyid_data = Malloc(skeyid_data_len);
		cp = skeyid_data;
		memcpy(cp, ni_b, ni_b_len);
		cp += ni_b_len;
		memcpy(cp, nr_b, nr_b_len);
		skeyid = Malloc(16);
		hash_r_data_len = g_xr_len + g_xi_len + cky_r_len + cky_i_len +
				  sai_b_len + idir_b_len;
		hash_r_data = Malloc(hash_r_data_len);
		cp = hash_r_data;
		memcpy(cp, g_xr, g_xr_len);
		cp += g_xr_len;
		memcpy(cp, g_xi, g_xi_len);
		cp += g_xi_len;
		memcpy(cp, cky_r, cky_r_len);
		cp += cky_r_len;
		memcpy(cp, cky_i, cky_i_len);
		cp += cky_i_len;
		memcpy(cp, sai_b, sai_b_len);
		cp += sai_b_len;
		memcpy(cp, idir_b, idir_b_len);
		hash_r = Malloc(16);

		Gettimeofday(&start_time);
		for (i = 0; i < HMAC_SPEED_ITERATIONS; i++) {
			hmac_md5(skeyid_data, skeyid_data_len, psk, psk_len,
				 skeyid);
			hmac_md5(hash_r_data, hash_r_data_len, skeyid, 16,
				 hash_r);
		}
		Gettimeofday(&end_time);
		timeval_diff(&end_time, &start_time, &elapsed_time);
		elapsed_seconds = elapsed_time.tv_sec +
				  (elapsed_time.tv_usec / 1000000.0);
		printf(
			"%u MD5 HASH_R calculations in %.6f seconds (%.2f per sec)\n",
			HMAC_SPEED_ITERATIONS, elapsed_seconds,
			HMAC_SPEED_ITERATIONS / elapsed_seconds);
	} while (0);

	printf("\nChecking HMAC-SHA1 PSK cracking speed...\n");
	do {
/*
 *	The values below are observed values from a Firewall-1 NG AI system
 *	using IKE Aggressive mode with PSK authentication and SHA1 hash.
 *	The ID used was "test", and the valid pre-shared key is "abc123".
 *      The expected hash_r is "543ea42889c07b17390cc6f0440246c0148422df".
 */
		char *g_xr_hex =
			"6c5559243259d5293df34a766561b8ffa78a9f8ee03d8a05916aadeeba9997864e0cd712f2a08104366c5e48f391ee7ce7b0ac08c59b8001c888c9f0343fd7d7d2d1da8e672c4ff05a7dd3c4eb6adc09bec712128ed951f7fcde2c31431643eb04d5ffc0be68e17aa80168e9635cb6f4c80af8ea1432c2b095b25f3d79ac4e55";
		char *g_xi_hex =
			"857209de96faf07bad57ff1aba648a2c61a6802e4db3ab54c5593fa8abd9b1304bbb0fe2b5ff5d63565c7d10c1073d22adbd51fb70fc4f35568ede01678f32b24a41940040f263964ee0a70fe8e43295a18390117fdf46d56d24d7d4b40987fe4a1bfe8a0d61205c42c76b2aab9dbf4c20505da02fa4759dc84c717c55f87b9f";
		char *cky_r_hex = "963c61ef1778b6c5";
		char *cky_i_hex = "efa6639971a91c08";
		char *sai_b_hex =
			"00000001000000010000002c01010001000000240101000080010001800200028003000180040002800b0001000c000400007080";
		char *idir_b_hex = "01000000ac100202";
		char *ni_b_hex = "6d62656f72fd1c53cda7337d0612aeebe3529a09";
		char *nr_b_hex = "8e83c48eb087b8276b4bb2976ea23bf426abde8f";

		unsigned char *g_xr;
		unsigned char *g_xi;
		unsigned char *cky_r;
		unsigned char *cky_i;
		unsigned char *sai_b;
		unsigned char *idir_b;
		unsigned char *ni_b;
		unsigned char *nr_b;

		size_t g_xr_len;
		size_t g_xi_len;
		size_t cky_r_len;
		size_t cky_i_len;
		size_t sai_b_len;
		size_t idir_b_len;
		size_t ni_b_len;
		size_t nr_b_len;

		unsigned char *skeyid;
		unsigned char *hash_r;

		unsigned char *skeyid_data;
		unsigned char *hash_r_data;

		size_t skeyid_data_len;
		size_t hash_r_data_len;

		unsigned char *cp;

		unsigned char *psk = (unsigned char *) "abc123"; /* correct key */
		size_t psk_len = 6;

		struct timeval start_time;
		struct timeval end_time;
		struct timeval elapsed_time;
		double elapsed_seconds;

		g_xr = hex2data(g_xr_hex, &g_xr_len);
		g_xi = hex2data(g_xi_hex, &g_xi_len);
		cky_r = hex2data(cky_r_hex, &cky_r_len);
		cky_i = hex2data(cky_i_hex, &cky_i_len);
		sai_b = hex2data(sai_b_hex, &sai_b_len);
		idir_b = hex2data(idir_b_hex, &idir_b_len);
		ni_b = hex2data(ni_b_hex, &ni_b_len);
		nr_b = hex2data(nr_b_hex, &nr_b_len);

		skeyid_data_len = ni_b_len + nr_b_len;
		skeyid_data = Malloc(skeyid_data_len);
		cp = skeyid_data;
		memcpy(cp, ni_b, ni_b_len);
		cp += ni_b_len;
		memcpy(cp, nr_b, nr_b_len);
		skeyid = Malloc(20);
		hash_r_data_len = g_xr_len + g_xi_len + cky_r_len + cky_i_len +
				  sai_b_len + idir_b_len;
		hash_r_data = Malloc(hash_r_data_len);
		cp = hash_r_data;
		memcpy(cp, g_xr, g_xr_len);
		cp += g_xr_len;
		memcpy(cp, g_xi, g_xi_len);
		cp += g_xi_len;
		memcpy(cp, cky_r, cky_r_len);
		cp += cky_r_len;
		memcpy(cp, cky_i, cky_i_len);
		cp += cky_i_len;
		memcpy(cp, sai_b, sai_b_len);
		cp += sai_b_len;
		memcpy(cp, idir_b, idir_b_len);
		hash_r = Malloc(20);

		Gettimeofday(&start_time);
		for (i = 0; i < HMAC_SPEED_ITERATIONS; i++) {
			hmac_sha1(skeyid_data, skeyid_data_len, psk, psk_len,
				  skeyid);
			hmac_sha1(hash_r_data, hash_r_data_len, skeyid, 20,
				  hash_r);
		}
		Gettimeofday(&end_time);
		timeval_diff(&end_time, &start_time, &elapsed_time);
		elapsed_seconds = elapsed_time.tv_sec +
				  (elapsed_time.tv_usec / 1000000.0);
		printf(
			"%u SHA1 HASH_R calculations in %.6f seconds (%.2f per sec)\n",
			HMAC_SPEED_ITERATIONS, elapsed_seconds,
			HMAC_SPEED_ITERATIONS / elapsed_seconds);
	} while (0);

	printf("\nChecking MD5 hash speed...\n");
	do {
		size_t hash_data_len;
		unsigned char *hash_result;
		struct timeval start_time;
		struct timeval end_time;
		struct timeval elapsed_time;
		double elapsed_seconds;
		unsigned char hash_speed_data[] = "12345678";
		size_t memcpy_len;

		hash_data_len = strlen((char *) hash_speed_data);
		memcpy_len = hash_data_len > 16 ? 16 : hash_data_len;
		Gettimeofday(&start_time);
		for (i = 0; i < HASH_SPEED_ITERATIONS; i++) {
			hash_result =
				MD5(hash_speed_data, hash_data_len, NULL);
			memcpy(hash_speed_data, hash_result, memcpy_len);
		}
		Gettimeofday(&end_time);
		timeval_diff(&end_time, &start_time, &elapsed_time);
		elapsed_seconds = elapsed_time.tv_sec +
				  (elapsed_time.tv_usec / 1000000.0);
		printf("%u MD5 calculations in %.6f seconds (%.2f per sec)\n",
		       HASH_SPEED_ITERATIONS, elapsed_seconds,
		       HASH_SPEED_ITERATIONS / elapsed_seconds);
	} while (0);

	printf("\nChecking SHA1 hash speed...\n");
	do {
		size_t hash_data_len;
		unsigned char *hash_result;
		struct timeval start_time;
		struct timeval end_time;
		struct timeval elapsed_time;
		double elapsed_seconds;
		unsigned char hash_speed_data[] = "12345678";
		size_t memcpy_len;

		hash_data_len = strlen((char *) hash_speed_data);
		memcpy_len = hash_data_len > 20 ? 20 : hash_data_len;
		Gettimeofday(&start_time);
		for (i = 0; i < HASH_SPEED_ITERATIONS; i++) {
			hash_result =
				SHA1(hash_speed_data, hash_data_len, NULL);
			memcpy(hash_speed_data, hash_result, memcpy_len);
		}
		Gettimeofday(&end_time);
		timeval_diff(&end_time, &start_time, &elapsed_time);
		elapsed_seconds = elapsed_time.tv_sec +
				  (elapsed_time.tv_usec / 1000000.0);
		printf("%u SHA1 calculations in %.6f seconds (%.2f per sec)\n",
		       HASH_SPEED_ITERATIONS, elapsed_seconds,
		       HASH_SPEED_ITERATIONS / elapsed_seconds);
	} while (0);

	if (error)
		return EXIT_FAILURE;
	else
		return EXIT_SUCCESS;
}
Пример #27
0
Файл: p12.c Проект: Lembed/uTLS
/*
 * Take a raw pkcs12 block and the decrypt it and turn it into a certificate(s)
 * and keys.
 */
int pkcs12_decode(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj, const char *password)
{
    uint8_t *buf = ssl_obj->buf;
    int len, iterations, auth_safes_start,
        auth_safes_end, auth_safes_len, key_offset, offset = 0;
    int all_certs = 0;
    uint8_t *version = NULL, *auth_safes = NULL, *cert, *orig_mac;
    uint8_t key[SHA1_SIZE];
    uint8_t mac[SHA1_SIZE];
    const uint8_t *salt;
    int uni_pass_len, ret = SSL_OK;
    char *uni_pass = make_uni_pass(password, &uni_pass_len);
    static const uint8_t pkcs_data[] = /* pkc7 data */
    { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01 };
    static const uint8_t pkcs_encrypted[] = /* pkc7 encrypted */
    { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x06 };
    static const uint8_t pkcs8_key_bag[] = /* 1.2.840.113549.1.12.10.1.2 */
    { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02 };

    if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0) {
#ifdef CONFIG_SSL_FULL_MODE
        printf("Error: Invalid p12 ASN.1 file\n");
#endif
        goto error;
    }

    if (asn1_get_int(buf, &offset, &version) < 0 || *version != 3) {
        ret = SSL_ERROR_INVALID_VERSION;
        goto error;
    }

    /* remove all the boring pcks7 bits */
    if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 ||
        len != sizeof(pkcs_data) ||
        memcmp(&buf[offset], pkcs_data, sizeof(pkcs_data)))
        goto error;

    offset += len;

    if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 ||
        asn1_next_obj(buf, &offset, ASN1_OCTET_STRING) < 0)
        goto error;

    /* work out the MAC start/end points (done on AuthSafes) */
    auth_safes_start = offset;
    auth_safes_end = offset;
    if (asn1_skip_obj(buf, &auth_safes_end, ASN1_SEQUENCE) < 0)
        goto error;

    auth_safes_len = auth_safes_end - auth_safes_start;
    auth_safes = malloc(auth_safes_len);

    memcpy(auth_safes, &buf[auth_safes_start], auth_safes_len);

    if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 ||
        (len != sizeof(pkcs_encrypted) ||
         memcmp(&buf[offset], pkcs_encrypted, sizeof(pkcs_encrypted))))
        goto error;

    offset += len;

    if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 ||
        asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        asn1_skip_obj(buf, &offset, ASN1_INTEGER) < 0 ||
        asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 ||
        len != sizeof(pkcs_data) ||
        memcmp(&buf[offset], pkcs_data, sizeof(pkcs_data)))
        goto error;

    offset += len;

    /* work out the salt for the certificate */
    if (get_pbe_params(buf, &offset, &salt, &iterations) < 0 ||
        (len = asn1_next_obj(buf, &offset, ASN1_IMPLICIT_TAG)) < 0)
        goto error;

    /* decrypt the certificate */
    cert = &buf[offset];
    if ((ret = p8_decrypt(uni_pass, uni_pass_len, salt, iterations, cert,
                          len, PKCS12_KEY_ID)) < 0)
        goto error;

    offset += len;

    /* load the certificate */
    key_offset = 0;
    all_certs = asn1_next_obj(cert, &key_offset, ASN1_SEQUENCE);

    /* keep going until all certs are loaded */
    while (key_offset < all_certs) {
        int cert_offset = key_offset;

        if (asn1_skip_obj(cert, &cert_offset, ASN1_SEQUENCE) < 0 ||
            asn1_next_obj(cert, &key_offset, ASN1_SEQUENCE) < 0 ||
            asn1_skip_obj(cert, &key_offset, ASN1_OID) < 0 ||
            asn1_next_obj(cert, &key_offset, ASN1_EXPLICIT_TAG) < 0 ||
            asn1_next_obj(cert, &key_offset, ASN1_SEQUENCE) < 0 ||
            asn1_skip_obj(cert, &key_offset, ASN1_OID) < 0 ||
            asn1_next_obj(cert, &key_offset, ASN1_EXPLICIT_TAG) < 0 ||
            (len = asn1_next_obj(cert, &key_offset, ASN1_OCTET_STRING)) < 0)
            goto error;

        if ((ret = add_cert(ssl_ctx, &cert[key_offset], len)) < 0)
            goto error;

        key_offset = cert_offset;
    }

    if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 ||
        len != sizeof(pkcs_data) ||
        memcmp(&buf[offset], pkcs_data, sizeof(pkcs_data)))
        goto error;

    offset += len;

    if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 ||
        asn1_next_obj(buf, &offset, ASN1_OCTET_STRING) < 0 ||
        asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        (len = asn1_next_obj(buf, &offset, ASN1_OID)) < 0 ||
        (len != sizeof(pkcs8_key_bag)) ||
        memcmp(&buf[offset], pkcs8_key_bag, sizeof(pkcs8_key_bag)))
        goto error;

    offset += len;

    /* work out the salt for the private key */
    if (asn1_next_obj(buf, &offset, ASN1_EXPLICIT_TAG) < 0 ||
        asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        get_pbe_params(buf, &offset, &salt, &iterations) < 0 ||
        (len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0)
        goto error;

    /* decrypt the private key */
    cert = &buf[offset];
    if ((ret = p8_decrypt(uni_pass, uni_pass_len, salt, iterations, cert,
                          len, PKCS12_KEY_ID)) < 0)
        goto error;

    offset += len;

    /* load the private key */
    if ((ret = p8_add_key(ssl_ctx, cert)) < 0)
        goto error;

    /* miss out on friendly name, local key id etc */
    if (asn1_skip_obj(buf, &offset, ASN1_SET) < 0)
        goto error;

    /* work out the MAC */
    if (asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        asn1_next_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        asn1_skip_obj(buf, &offset, ASN1_SEQUENCE) < 0 ||
        (len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0 ||
        len != SHA1_SIZE)
        goto error;

    orig_mac = &buf[offset];
    offset += len;

    /* get the salt */
    if ((len = asn1_next_obj(buf, &offset, ASN1_OCTET_STRING)) < 0 || len != 8)
        goto error;

    salt = &buf[offset];

    /* work out what the mac should be */
    if ((ret = p8_decrypt(uni_pass, uni_pass_len, salt, iterations,
                          key, SHA1_SIZE, PKCS12_MAC_ID)) < 0)
        goto error;

    hmac_sha1(auth_safes, auth_safes_len, key, SHA1_SIZE, mac);

    if (memcmp(mac, orig_mac, SHA1_SIZE)) {
        ret = SSL_ERROR_INVALID_HMAC;
        goto error;
    }

error:
    free(version);
    free(uni_pass);
    free(auth_safes);
    return ret;
}
Пример #28
0
/* main */
int main(int argc, char **argv)
{
#ifndef USE_AIM
	uint64_t eid0_size;
	uint8_t eid0[4096];
#endif
	uint8_t value, idps[IDPS_SIZE], seed[TOKEN_SIZE], token[TOKEN_SIZE];
	AES_KEY aes_ctx;
	int i, result;

	netInitialize();
	udp_printf_init();
	PRINTF("%s:%d: start\n", __func__, __LINE__);

#ifdef USE_AIM 

	result = lv2_ss_aim_if(AIM_PACKET_ID_GET_DEV_ID, (uint64_t) &idps);
	if (result) {
		PRINTF("%s:%d: lv2_ss_aim_if(GET_DEV_ID) failed (0x%08x)\n", __func__, __LINE__, result);
		goto done;
	}

#else

	result = lv2_ss_indi_info_mgr_if(INDI_INFO_MGR_PACKET_ID_GET_DATA_SIZE_BY_INDEX, EID0_INDEX, (uint64_t) &eid0_size, 0, 0);
	if (result) {
		PRINTF("%s:%d: lv2_ss_indi_info_mgr_if(GET_DATA_SIZE_BY_INDEX) failed (0x%08x)\n", __func__, __LINE__, result);
		goto done;
	}

	PRINTF("%s:%d: EID0 size %ld\n", __func__, __LINE__, eid0_size);

	result = lv2_ss_indi_info_mgr_if(INDI_INFO_MGR_PACKET_ID_GET_DATA_BY_INDEX, EID0_INDEX, (uint64_t) eid0, sizeof(eid0), (uint64_t) &eid0_size);
	if (result) {
		PRINTF("%s:%d: lv2_ss_indi_info_mgr_if(GET_DATA_BY_INDEX) failed (0x%08x)\n", __func__, __LINE__, result);
		goto done;
	}

	PRINTF("%s:%d: EID0 size %ld\n", __func__, __LINE__, eid0_size);

	memcpy(idps, eid0, IDPS_SIZE);

#endif

	PRINTF("%s: %d: IDPS: %02x %02x %02x %02x %02x %02x %02x %02x "
		"%02x %02x %02x %02x %02x %02x %02x %02x\n", __func__, __LINE__,
		idps[0], idps[1], idps[ 2], idps[ 3], idps[ 4], idps[ 5], idps[ 6], idps[ 7],
		idps[8], idps[9], idps[10], idps[11], idps[12], idps[13], idps[14], idps[15]);
	
	memset(seed, 0, TOKEN_SIZE);
	memcpy(seed + 4, idps, IDPS_SIZE);
	seed[3] = 1;

	hmac_sha1(hmac, sizeof(hmac), seed, 60, seed + 60);

	result = AES_set_encrypt_key(erk, 256, &aes_ctx);
	if (result) {
		PRINTF("%s:%d: AES_set_encrypt_key failed (0x%08x)\n", __func__, __LINE__, result);
		goto done;
	}

	AES_cbc_encrypt(iv, seed, token, TOKEN_SIZE, &aes_ctx);

	PRINTF("%s: %d: TOKEN SEED:\n", __func__, __LINE__);
	for (i = 0; i < TOKEN_SIZE; i += 16)
		PRINTF("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
			seed[i +  0], seed[i +  1], seed[i +  2], seed[i +  3], seed[i +  4], seed[i +  5],
			seed[i +  6], seed[i +  7], seed[i +  8], seed[i +  9], seed[i + 10], seed[i + 11],
			seed[i + 12], seed[i + 13], seed[i + 14], seed[i + 15]);

	PRINTF("%s: %d: TOKEN:\n", __func__, __LINE__);
	for (i = 0; i < TOKEN_SIZE; i += 16)
		PRINTF("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
			token[i +  0], token[i +  1], token[i +  2], token[i +  3], token[i +  4], token[i +  5],
			token[i +  6], token[i +  7], token[i +  8], token[i +  9], token[i + 10], token[i + 11],
			token[i + 12], token[i + 13], token[i + 14], token[i + 15]);

	result = lv2_ss_update_mgr_if(UPDATE_MGR_PACKET_ID_SET_TOKEN, (uint64_t) token, TOKEN_SIZE, 0, 0, 0, 0);
	if (result) {
		PRINTF("%s:%d: lv1_ss_update_mgr_if(SET_TOKEN) failed (0x%08x)\n", __func__, __LINE__, result);
		goto done;
	}

	result = lv2_ss_update_mgr_if(UPDATE_MGR_PACKET_ID_READ_EPROM, EPROM_QA_FLAG_OFFSET, (uint64_t) &value, 0, 0, 0, 0);
	if (result) {
		PRINTF("%s:%d: lv1_ss_update_mgr_if(READ_EPROM) failed (0x%08x)\n", __func__, __LINE__, result);
		goto done;
	}

	PRINTF("%s:%d: current QA flag 0x%02x\n", __func__, __LINE__, value);

	result = lv2_ss_update_mgr_if(UPDATE_MGR_PACKET_ID_WRITE_EPROM, EPROM_QA_FLAG_OFFSET, 0xff /* disable QA token */, 0, 0, 0, 0);
	if (result) {
		PRINTF("%s:%d: lv1_ss_update_mgr_if(WRITE_EPROM) failed (0x%08x)\n", __func__, __LINE__, result);
		goto done;
	}

	PRINTF("%s:%d: end\n", __func__, __LINE__);

	lv2_sm_ring_buzzer(0x1004, 0xa, 0x1b6);

done:

	udp_printf_deinit();
	netDeinitialize();

	return 0;
}
void
nidh (dckey *priv, dckey *pub, char *priv_id, char *pub_id, char *label)
{
  rawpub rpub;
  rawpriv rpriv;

  int reserve;
  /* Let's name it that! */

  /* step 0: check that the private and public keys are compatible,
     i.e., they use the same group parameters */
  if ((-1 == get_rawpub (&rpub, pub)) 
      || (-1 == get_rawpriv (&rpriv, priv))) {
    printf ("%s: trouble importing GMP values from ElGamal-like keys\n",
	    getprogname ());

    printf ("priv:\n%s\n", dcexport_priv (priv));
    printf ("pub:\n%s\n", dcexport_pub (pub));

    exit (-1);    
  } else if (mpz_cmp (rpub.p, rpriv.p)
	     || mpz_cmp (rpub.q, rpriv.q)
	     || mpz_cmp (rpub.g, rpriv.g)) {
        printf ("%s:  the private and public keys are incompatible\n",
	    getprogname ());
        printf ("priv:\n%s\n", dcexport_priv (priv));
        printf ("pub:\n%s\n", dcexport_pub (pub));

        exit (-1);
  } else {
    
    /* step 1a: compute the Diffie-Hellman secret
                (use mpz_init, mpz_powm, mpz_clear; look at elgamal.c in 
                 the libdcrypt source directory for sample usage 
     */
    char *Diffie_Hellman_Secret_String = 0;
    {
      
      mpz_t dhSecretInt;
      mpz_init(dhSecretInt);
      mpz_powm(dhSecretInt, rpub.y, rpriv.x, rpub.p); 
      reserve = cat_mpz(&Diffie_Hellman_Secret_String, dhSecretInt); /* EC need 0; MALLOC */
      mpz_clear(dhSecretInt);
      if (reserve) {
          free(Diffie_Hellman_Secret_String);
          printf("error allocating memory\n");
          exit(1);
      }
      /* printf("Diffie_Hellman_Secret_String: %s\n",Diffie_Hellman_Secret_String); */
    }

    /* step 1b: order the IDs lexicographically */
    char *firstId = NULL, *secondId = NULL;
    
    if (strcmp (priv_id, pub_id) < 0) {
      firstId = priv_id;
      secondId = pub_id;
    } else {
      firstId = pub_id;
      secondId = priv_id;
    }    
    
    /* step 1c: hash DH secret and ordered id pair into a master key */
    char key_master[20];
    {
      sha1_ctx shaCipherText;
      sha1_init(&shaCipherText);
      sha1_update(&shaCipherText, Diffie_Hellman_Secret_String, strlen(Diffie_Hellman_Secret_String));

      char *id12;
      size_t len1, len2;
      len1 = strlen(firstId); len2 = strlen(secondId);
      id12 = (char*)malloc(len1+len2+1); /* +1 for \0 */
      strcpy(id12, firstId);
      strcat(id12, secondId);
      assert(strlen(id12) == len1+len2); 
      sha1_update(&shaCipherText, id12, len1+len2);
      free(id12);
      
      sha1_final(&shaCipherText, (void*)key_master);
      /*20 bytes*/
      
    }    
    
    /* step 2: derive the shared key from the label and the master key */
    /*I will work with minimum requirement satisfaction model. Thanks to the open source community for providing me with enough reasoning for that.*/
    char sizeofkey[32];
    {
      char sizeofkey_0[20];
      size_t len0 = strlen(label)+7;
      char *label0 = (char*)malloc(len0);
      strcpy(label0, label);
      strcat(label0, "AES-CTR");
      hmac_sha1(key_master, 20, sizeofkey_0, label0, len0);
      free(label0);

      char sizeofkey_1[20];
      size_t len1 = strlen(label)+9;
      char *label1 = (char*)malloc(len1);
      strcpy(label1, label);
      strcat(label1, "CBC-MAC");
      hmac_sha1(key_master, 20, sizeofkey_1, label1, len1);
      free(label1);

      strncpy(sizeofkey, sizeofkey_0, 16);
      strncpy(sizeofkey+16, sizeofkey_1, 16);
    
    }
    
    /*
	step 3: armor the shared key and write it to file.
    Filename should be of the form <label>-<priv_id>.b64
	 
	size_t fn_len = strlen(label)+1+strlen(priv_id)+1+strlen(pub_id)+4+1;
	*/

    char *fn = (char *) malloc(32);
	fn = armor64(sizeofkey, 32);
	*(fn + 32) = '\0';
	int fdsk;
	fdsk = open (label, O_WRONLY|O_TRUNC|O_CREAT, 0600);
	int status;
	status = write (fdsk, fn, strlen (fn));
	printf("value of status: %d\n", status);
	status = write (fdsk, "\n", 1);
	printf("value of status: %d\n", status);
    free (fn);
    close (fdsk);	
  }
}
Пример #30
0
JNIEXPORT jobjectArray JNICALL
Java_com_sunshuzhou_experiment_1miracl_Verify_computeForServer(JNIEnv *env, jobject instance,
                                                               jstring ux_, jstring uy_,
                                                               jstring u1x_, jstring u1y_,
                                                               jstring wx_, jstring wy_,
                                                               jstring com1x_, jstring com1y_,
                                                               jstring N1_, jstring sid_,
                                                               jstring alpha_, jstring beta_,
                                                               jstring zeta_) {
    const char *ux = (*env)->GetStringUTFChars(env, ux_, 0);
    const char *uy = (*env)->GetStringUTFChars(env, uy_, 0);
    const char *u1x = (*env)->GetStringUTFChars(env, u1x_, 0);
    const char *u1y = (*env)->GetStringUTFChars(env, u1y_, 0);
    const char *wx = (*env)->GetStringUTFChars(env, wx_, 0);
    const char *wy = (*env)->GetStringUTFChars(env, wy_, 0);
    const char *com1x = (*env)->GetStringUTFChars(env, com1x_, 0);
    const char *com1y = (*env)->GetStringUTFChars(env, com1y_, 0);
    const char *N1 = (*env)->GetStringUTFChars(env, N1_, 0);
    const char *sid = (*env)->GetStringUTFChars(env, sid_, 0);
    const char *alpha = (*env)->GetStringUTFChars(env, alpha_, 0);
    const char *beta = (*env)->GetStringUTFChars(env, beta_, 0);
    const char *zeta = (*env)->GetStringUTFChars(env, zeta_, 0);

    big x, y, d, k1, N2, sum, big1;
    epoint *u, *u1, *w, *com1, *w1, *epoint1, *com, *K;
    int message_len, i;
    unsigned char key[300], tag[SHA1_HASH_SIZE], hexdigest[SHA1_HASH_SIZE * 2 + 1], message[1000], tempChars[300];
    jclass jclass1 = (*env)->FindClass(env, "java/lang/String");
    jobjectArray result;

    envirment_init();
    x = mirvar(0);
    y = mirvar(0);
    d = mirvar(0);
    k1 = mirvar(0);
    N2 = mirvar(0);
    sum = mirvar(0);
    big1 = mirvar(0);
    u = epoint_init();
    u1 = epoint_init();
    w = epoint_init();
    com1 = epoint_init();
    w1 = epoint_init();
    epoint1 = epoint_init();
    com = epoint_init();
    K = epoint_init();

    cinstr(x, ux);
    cinstr(y, uy);
    epoint_set(x, y, 0, u);
    cinstr(x, u1x);
    cinstr(y, u1y);
    epoint_set(x, y, 0, u1);
    cinstr(x, wx);
    cinstr(y, wy);
    epoint_set(x, y, 0, w);
    cinstr(x, com1x);
    cinstr(y, com1y);
    epoint_set(x, y, 0, com1);

    irand((long)time(0));
    bigrand(ECC_N, d);
    bigrand(ECC_N, k1);
    bigbits(80, N2);


    // sum = alpha + beta + zeta
    cinstr(big1, alpha);
    cinstr(sum, beta);
    add(big1, sum, sum);
    cinstr(big1, zeta);
    add(big1, sum, sum);

    // w1 = k1 * H
    ecurve_mult(k1, ECC_H, w1);

    // com = (alpha + beta + zeta) * u + d * H
    ecurve_mult(sum, u, com);
    ecurve_mult(d, ECC_H, epoint1);
    ecurve_add(epoint1, com);

    // K = d * w + k1 * (com1 - sum * u1)
    ecurve_mult(d, w, K);
    ecurve_mult(sum, u1, epoint1);
    ecurve_sub(epoint1, com1);
    ecurve_mult(k1, com1, com1);
    ecurve_add(com1, K);


    // K.y as key
    epoint_get(K, x, y);
    cotstr(y, key);
    // message: u.y || u1.y || w.y || com1.y || N1 || sid
    epoint_get(u, x, y);
    cotstr(y, message);
    message_len = strlen(message);
    epoint_get(u1, x, y);
    cotstr(y, &message[message_len]);
    message_len = strlen(message);
    epoint_get(w, x, y);
    cotstr(y, &message[message_len]);
    message_len = strlen(message);
    epoint_get(com1, x, y);
    cotstr(x, &message[message_len]);
    message_len = strlen(message);
    strcpy(&message[message_len], N1);
    message_len = strlen(message);
    strcpy(&message[message_len], sid);
    message_len = strlen(message);

    hmac_sha1(key, strlen(key), message, message_len, tag, SHA1_HASH_SIZE);

    for (i = 0; i < SHA1_HASH_SIZE; ++i) {
        sprintf(&hexdigest[i * 2], "%02x", tag[i]);
    }
    hexdigest[40] = '\0';

    (*env)->ReleaseStringUTFChars(env, ux_, ux);
    (*env)->ReleaseStringUTFChars(env, uy_, uy);
    (*env)->ReleaseStringUTFChars(env, u1x_, u1x);
    (*env)->ReleaseStringUTFChars(env, u1y_, u1y);
    (*env)->ReleaseStringUTFChars(env, wx_, wx);
    (*env)->ReleaseStringUTFChars(env, wy_, wy);
    (*env)->ReleaseStringUTFChars(env, com1x_, com1x);
    (*env)->ReleaseStringUTFChars(env, com1y_, com1y);
    (*env)->ReleaseStringUTFChars(env, N1_, N1);
    (*env)->ReleaseStringUTFChars(env, sid_, sid);
    (*env)->ReleaseStringUTFChars(env, alpha_, alpha);
    (*env)->ReleaseStringUTFChars(env, beta_, beta);
    (*env)->ReleaseStringUTFChars(env, zeta_, zeta);

    result = (*env)->NewObjectArray(env, 8, jclass1, (*env)->NewStringUTF(env, ""));
    epoint_get(w1, x, y);
    cotstr(x, tempChars);
    (*env)->SetObjectArrayElement(env, result, 0, (*env)->NewStringUTF(env, tempChars));
    cotstr(y, tempChars);
    (*env)->SetObjectArrayElement(env, result, 1, (*env)->NewStringUTF(env, tempChars));

    epoint_get(com, x, y);
    cotstr(x, tempChars);
    (*env)->SetObjectArrayElement(env, result, 2, (*env)->NewStringUTF(env, tempChars));
    cotstr(y, tempChars);
    (*env)->SetObjectArrayElement(env, result, 3, (*env)->NewStringUTF(env, tempChars));

    cotstr(N2, tempChars);
    (*env)->SetObjectArrayElement(env, result, 4, (*env)->NewStringUTF(env, tempChars));
    (*env)->SetObjectArrayElement(env, result, 5, (*env)->NewStringUTF(env, message));
    (*env)->SetObjectArrayElement(env, result, 6, (*env)->NewStringUTF(env, hexdigest));

    (*env)->SetObjectArrayElement(env, result, 7, (*env)->NewStringUTF(env, key));

    mirkill(x);
    mirkill(y);
    mirkill(d);
    mirkill(k1);
    mirkill(N2);
    mirkill(sum);
    mirkill(big1);

    return result;
}