/* RSA sign/decrypt with the key, signature happens 'in place' */ vcard_7816_status_t vcard_emul_rsa_op(VCard *card, VCardKey *key, unsigned char *buffer, int buffer_size) { SECKEYPrivateKey *priv_key; unsigned signature_len; SECStatus rv; if ((!nss_emul_init) || (key == NULL)) { /* couldn't get the key, indicate that we aren't logged in */ return VCARD7816_STATUS_ERROR_CONDITION_NOT_SATISFIED; } priv_key = vcard_emul_get_nss_key(key); /* * this is only true of the rsa signature */ signature_len = PK11_SignatureLen(priv_key); if (buffer_size != signature_len) { return VCARD7816_STATUS_ERROR_DATA_INVALID; } rv = PK11_PrivDecryptRaw(priv_key, buffer, &signature_len, signature_len, buffer, buffer_size); if (rv != SECSuccess) { return vcard_emul_map_error(PORT_GetError()); } assert(buffer_size == signature_len); return VCARD7816_STATUS_SUCCESS; }
/** * Obtains a signing context. * * @param ctx A pointer to the signing context to fill * @return 0 on success * -1 on error */ int NSSSignBegin(const char *certName, SGNContext **ctx, SECKEYPrivateKey **privKey, CERTCertificate **cert, uint32_t *signatureLength) { secuPWData pwdata = { PW_NONE, 0 }; if (!certName || !ctx || !privKey || !cert || !signatureLength) { fprintf(stderr, "ERROR: Invalid parameter passed to NSSSignBegin\n"); return -1; } /* Get the cert and embedded public key out of the database */ *cert = PK11_FindCertFromNickname(certName, &pwdata); if (!*cert) { fprintf(stderr, "ERROR: Could not find cert from nickname\n"); return -1; } /* Get the private key out of the database */ *privKey = PK11_FindKeyByAnyCert(*cert, &pwdata); if (!*privKey) { fprintf(stderr, "ERROR: Could not find private key\n"); return -1; } *signatureLength = PK11_SignatureLen(*privKey); if (*signatureLength > BLOCKSIZE) { fprintf(stderr, "ERROR: Program must be compiled with a larger block size" " to support signing with signatures this large: %u.\n", *signatureLength); return -1; } /* Check that the key length is large enough for our requirements */ if (*signatureLength < XP_MIN_SIGNATURE_LEN_IN_BYTES) { fprintf(stderr, "ERROR: Key length must be >= %d bytes\n", XP_MIN_SIGNATURE_LEN_IN_BYTES); return -1; } *ctx = SGN_NewContext (SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE, *privKey); if (!*ctx) { fprintf(stderr, "ERROR: Could not create signature context\n"); return -1; } if (SGN_Begin(*ctx) != SECSuccess) { fprintf(stderr, "ERROR: Could not begin signature\n"); return -1; } return 0; }
SECStatus SGN_Digest(SECKEYPrivateKey *privKey, SECOidTag algtag, SECItem *result, SECItem *digest) { int modulusLen; SECStatus rv; SECItem digder; PLArenaPool *arena = 0; SGNDigestInfo *di = 0; result->data = 0; if (privKey->keyType == rsaKey) { arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if ( !arena ) { rv = SECFailure; goto loser; } /* Construct digest info */ di = SGN_CreateDigestInfo(algtag, digest->data, digest->len); if (!di) { rv = SECFailure; goto loser; } /* Der encode the digest as a DigestInfo */ rv = DER_Encode(arena, &digder, SGNDigestInfoTemplate, di); if (rv != SECSuccess) { goto loser; } } else { digder.data = digest->data; digder.len = digest->len; } /* ** Encrypt signature after constructing appropriate PKCS#1 signature ** block */ modulusLen = PK11_SignatureLen(privKey); if (modulusLen <= 0) { PORT_SetError(SEC_ERROR_INVALID_KEY); rv = SECFailure; goto loser; } result->len = modulusLen; result->data = (unsigned char*) PORT_Alloc(modulusLen); result->type = siBuffer; if (result->data == NULL) { rv = SECFailure; goto loser; } rv = PK11_Sign(privKey, result, &digder); if (rv != SECSuccess) { PORT_Free(result->data); result->data = NULL; } loser: SGN_DestroyDigestInfo(di); if (arena != NULL) { PORT_FreeArena(arena, PR_FALSE); } return rv; }
SECStatus SEC_DerSignData(PLArenaPool *arena, SECItem *result, const unsigned char *buf, int len, SECKEYPrivateKey *pk, SECOidTag algID) { SECItem it; CERTSignedData sd; SECStatus rv; it.data = 0; /* XXX We should probably have some asserts here to make sure the key type * and algID match */ if (algID == SEC_OID_UNKNOWN) { switch(pk->keyType) { case rsaKey: algID = SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION; break; case dsaKey: /* get Signature length (= q_len*2) and work from there */ switch (PK11_SignatureLen(pk)) { case 448: algID = SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA224_DIGEST; break; case 512: algID = SEC_OID_NIST_DSA_SIGNATURE_WITH_SHA256_DIGEST; break; default: algID = SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST; break; } break; case ecKey: algID = SEC_OID_ANSIX962_ECDSA_SIGNATURE_WITH_SHA1_DIGEST; break; default: PORT_SetError(SEC_ERROR_INVALID_KEY); return SECFailure; } } /* Sign input buffer */ rv = SEC_SignData(&it, buf, len, pk, algID); if (rv) goto loser; /* Fill out SignedData object */ PORT_Memset(&sd, 0, sizeof(sd)); sd.data.data = (unsigned char*) buf; sd.data.len = len; sd.signature.data = it.data; sd.signature.len = it.len << 3; /* convert to bit string */ rv = SECOID_SetAlgorithmID(arena, &sd.signatureAlgorithm, algID, 0); if (rv) goto loser; /* DER encode the signed data object */ rv = DER_Encode(arena, result, CERTSignedDataTemplate, &sd); /* FALL THROUGH */ loser: PORT_Free(it.data); return rv; }
SECStatus SGN_End(SGNContext *cx, SECItem *result) { unsigned char digest[HASH_LENGTH_MAX]; unsigned part1; int signatureLen; SECStatus rv; SECItem digder, sigitem; PLArenaPool *arena = 0; SECKEYPrivateKey *privKey = cx->key; SGNDigestInfo *di = 0; result->data = 0; digder.data = 0; /* Finish up digest function */ if (cx->hashcx == NULL) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } (*cx->hashobj->end)(cx->hashcx, digest, &part1, sizeof(digest)); if (privKey->keyType == rsaKey) { arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if ( !arena ) { rv = SECFailure; goto loser; } /* Construct digest info */ di = SGN_CreateDigestInfo(cx->hashalg, digest, part1); if (!di) { rv = SECFailure; goto loser; } /* Der encode the digest as a DigestInfo */ rv = DER_Encode(arena, &digder, SGNDigestInfoTemplate, di); if (rv != SECSuccess) { goto loser; } } else { digder.data = digest; digder.len = part1; } /* ** Encrypt signature after constructing appropriate PKCS#1 signature ** block */ signatureLen = PK11_SignatureLen(privKey); if (signatureLen <= 0) { PORT_SetError(SEC_ERROR_INVALID_KEY); rv = SECFailure; goto loser; } sigitem.len = signatureLen; sigitem.data = (unsigned char*) PORT_Alloc(signatureLen); if (sigitem.data == NULL) { rv = SECFailure; goto loser; } rv = PK11_Sign(privKey, &sigitem, &digder); if (rv != SECSuccess) { PORT_Free(sigitem.data); sigitem.data = NULL; goto loser; } if ((cx->signalg == SEC_OID_ANSIX9_DSA_SIGNATURE) || (cx->signalg == SEC_OID_ANSIX962_EC_PUBLIC_KEY)) { /* DSAU_EncodeDerSigWithLen works for DSA and ECDSA */ rv = DSAU_EncodeDerSigWithLen(result, &sigitem, sigitem.len); PORT_Free(sigitem.data); if (rv != SECSuccess) goto loser; } else { result->len = sigitem.len; result->data = sigitem.data; } loser: SGN_DestroyDigestInfo(di); if (arena != NULL) { PORT_FreeArena(arena, PR_FALSE); } return rv; }
/* RSA sign/decrypt with the key, signature happens 'in place' */ vcard_7816_status_t vcard_emul_rsa_op(VCard *card, VCardKey *key, unsigned char *buffer, int buffer_size) { SECKEYPrivateKey *priv_key; unsigned signature_len; PK11SlotInfo *slot; SECStatus rv; unsigned char buf[2048]; unsigned char *bp = NULL; int pad_len; vcard_7816_status_t ret = VCARD7816_STATUS_SUCCESS; if ((!nss_emul_init) || (key == NULL)) { /* couldn't get the key, indicate that we aren't logged in */ return VCARD7816_STATUS_ERROR_CONDITION_NOT_SATISFIED; } priv_key = vcard_emul_get_nss_key(key); if (priv_key == NULL) { /* couldn't get the key, indicate that we aren't logged in */ return VCARD7816_STATUS_ERROR_CONDITION_NOT_SATISFIED; } slot = vcard_emul_card_get_slot(card); /* * this is only true of the rsa signature */ signature_len = PK11_SignatureLen(priv_key); if (buffer_size != signature_len) { return VCARD7816_STATUS_ERROR_DATA_INVALID; } /* be able to handle larger keys if necessariy */ bp = &buf[0]; if (sizeof(buf) < signature_len) { bp = g_malloc(signature_len); } /* * do the raw operations. Some tokens claim to do CKM_RSA_X_509, but then * choke when they try to do the actual operations. Try to detect * those cases and treat them as if the token didn't claim support for * X_509. */ if (key->failedX509 != VCardEmulTrue && PK11_DoesMechanism(slot, CKM_RSA_X_509)) { rv = PK11_PrivDecryptRaw(priv_key, bp, &signature_len, signature_len, buffer, buffer_size); if (rv == SECSuccess) { assert(buffer_size == signature_len); memcpy(buffer, bp, signature_len); key->failedX509 = VCardEmulFalse; goto cleanup; } /* * we've had a successful X509 operation, this failure must be * somethine else */ if (key->failedX509 == VCardEmulFalse) { ret = vcard_emul_map_error(PORT_GetError()); goto cleanup; } /* * key->failedX509 must be Unknown at this point, try the * non-x_509 case */ } /* token does not support CKM_RSA_X509, emulate that with CKM_RSA_PKCS */ /* is this a PKCS #1 formatted signature? */ if ((buffer[0] == 0) && (buffer[1] == 1)) { int i; for (i = 2; i < buffer_size; i++) { /* rsa signature pad */ if (buffer[i] != 0xff) { break; } } if ((i < buffer_size) && (buffer[i] == 0)) { /* yes, we have a properly formated PKCS #1 signature */ /* * NOTE: even if we accidentally got an encrypt buffer, which * through shear luck started with 00, 01, ff, 00, it won't matter * because the resulting Sign operation will effectively decrypt * the real buffer. */ SECItem signature; SECItem hash; i++; hash.data = &buffer[i]; hash.len = buffer_size - i; signature.data = bp; signature.len = signature_len; rv = PK11_Sign(priv_key, &signature, &hash); if (rv != SECSuccess) { ret = vcard_emul_map_error(PORT_GetError()); goto cleanup; } assert(buffer_size == signature.len); memcpy(buffer, bp, signature.len); /* * we got here because either the X509 attempt failed, or the * token couldn't do the X509 operation, in either case stay * with the PKCS version for future operations on this key */ key->failedX509 = VCardEmulTrue; goto cleanup; } } pad_len = buffer_size - signature_len; assert(pad_len < 4); /* * OK now we've decrypted the payload, package it up in PKCS #1 for the * upper layer. */ buffer[0] = 0; buffer[1] = 2; /* RSA_encrypt */ pad_len -= 3; /* format is 0 || 2 || pad || 0 || data */ /* * padding for PKCS #1 encrypted data is a string of random bytes. The * random butes protect against potential decryption attacks against RSA. * Since PrivDecrypt has already stripped those bytes, we can't reconstruct * them. This shouldn't matter to the upper level code which should just * strip this code out anyway, so We'll pad with a constant 3. */ memset(&buffer[2], 0x03, pad_len); pad_len += 2; /* index to the end of the pad */ buffer[pad_len] = 0; pad_len++; /* index to the start of the data */ memcpy(&buffer[pad_len], bp, signature_len); /* * we got here because either the X509 attempt failed, or the * token couldn't do the X509 operation, in either case stay * with the PKCS version for future operations on this key */ key->failedX509 = VCardEmulTrue; cleanup: if (bp != buf) { g_free(bp); } return ret; }
SECStatus SGN_End(SGNContext *cx, SECItem *result) { unsigned char digest[HASH_LENGTH_MAX]; unsigned part1; int signatureLen; SECStatus rv; SECItem digder, sigitem; PLArenaPool *arena = 0; SECKEYPrivateKey *privKey = cx->key; SGNDigestInfo *di = 0; result->data = 0; digder.data = 0; sigitem.data = 0; /* Finish up digest function */ if (cx->hashcx == NULL) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } (*cx->hashobj->end)(cx->hashcx, digest, &part1, sizeof(digest)); if (privKey->keyType == rsaKey && cx->signalg != SEC_OID_PKCS1_RSA_PSS_SIGNATURE) { arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (!arena) { rv = SECFailure; goto loser; } /* Construct digest info */ di = SGN_CreateDigestInfo(cx->hashalg, digest, part1); if (!di) { rv = SECFailure; goto loser; } /* Der encode the digest as a DigestInfo */ rv = DER_Encode(arena, &digder, SGNDigestInfoTemplate, di); if (rv != SECSuccess) { goto loser; } } else { digder.data = digest; digder.len = part1; } /* ** Encrypt signature after constructing appropriate PKCS#1 signature ** block */ signatureLen = PK11_SignatureLen(privKey); if (signatureLen <= 0) { PORT_SetError(SEC_ERROR_INVALID_KEY); rv = SECFailure; goto loser; } sigitem.len = signatureLen; sigitem.data = (unsigned char *)PORT_Alloc(signatureLen); if (sigitem.data == NULL) { rv = SECFailure; goto loser; } if (cx->signalg == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) { CK_RSA_PKCS_PSS_PARAMS mech; SECItem mechItem = { siBuffer, (unsigned char *)&mech, sizeof(mech) }; PORT_Memset(&mech, 0, sizeof(mech)); if (cx->params && cx->params->data) { SECKEYRSAPSSParams params; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (!arena) { rv = SECFailure; goto loser; } PORT_Memset(¶ms, 0, sizeof(params)); rv = SEC_QuickDERDecodeItem(arena, ¶ms, SECKEY_RSAPSSParamsTemplate, cx->params); if (rv != SECSuccess) { goto loser; } rv = sec_RSAPSSParamsToMechanism(&mech, ¶ms); if (rv != SECSuccess) { goto loser; } } else { mech.hashAlg = CKM_SHA_1; mech.mgf = CKG_MGF1_SHA1; mech.sLen = digder.len; } rv = PK11_SignWithMechanism(privKey, CKM_RSA_PKCS_PSS, &mechItem, &sigitem, &digder); if (rv != SECSuccess) { goto loser; } } else { rv = PK11_Sign(privKey, &sigitem, &digder); if (rv != SECSuccess) { goto loser; } } if ((cx->signalg == SEC_OID_ANSIX9_DSA_SIGNATURE) || (cx->signalg == SEC_OID_ANSIX962_EC_PUBLIC_KEY)) { /* DSAU_EncodeDerSigWithLen works for DSA and ECDSA */ rv = DSAU_EncodeDerSigWithLen(result, &sigitem, sigitem.len); if (rv != SECSuccess) goto loser; SECITEM_FreeItem(&sigitem, PR_FALSE); } else { result->len = sigitem.len; result->data = sigitem.data; } loser: if (rv != SECSuccess) { SECITEM_FreeItem(&sigitem, PR_FALSE); } SGN_DestroyDigestInfo(di); if (arena != NULL) { PORT_FreeArena(arena, PR_FALSE); } return rv; }