Example #1
0
static int sss_nss_crypto_ctx_destructor(struct sss_nss_crypto_ctx *cctx)
{
    if (cctx->ectx) PK11_DestroyContext(cctx->ectx, PR_TRUE);
    if (cctx->sparam) SECITEM_FreeItem(cctx->sparam, PR_TRUE);
    if (cctx->slot) PK11_FreeSlot(cctx->slot);
    if (cctx->keyobj) PK11_FreeSymKey(cctx->keyobj);

    return EOK;
}
Example #2
0
void
soft_free_ecprivkey(ECPrivateKey *key)
{
	soft_free_ecparams(&key->ecParams, B_FALSE);
	/*
	 * Don't free publicValue or privateValue
	 * as these values are copied into objects.
	 */
	SECITEM_FreeItem(&key->version, B_FALSE);
	free(key);
}
Example #3
0
SecAsn1Item *
SECITEM_AllocItem(PRArenaPool *arena, SecAsn1Item *item, size_t len)
{
    SecAsn1Item *result = NULL;
    void *mark = NULL;

    if (arena != NULL) {
	mark = PORT_ArenaMark(arena);
    }

    if (item == NULL) {
	if (arena != NULL) {
	    result = PORT_ArenaZAlloc(arena, sizeof(SecAsn1Item));
	} else {
	    result = PORT_ZAlloc(sizeof(SecAsn1Item));
	}
	if (result == NULL) {
	    goto loser;
	}
    } else {
	PORT_Assert(item->Data == NULL);
	result = item;
    }

    result->Length = len;
    if (len) {
	if (arena != NULL) {
	    result->Data = PORT_ArenaAlloc(arena, len);
	} else {
	    result->Data = PORT_Alloc(len);
	}
    }

    if (mark) {
	PORT_ArenaUnmark(arena, mark);
    }
    return(result);

loser:
    if ( arena != NULL ) {
	if (mark) {
	    PORT_ArenaRelease(arena, mark);
	}
	if (item != NULL) {
	    item->Data = NULL;
	    item->Length = 0;
	}
    } else {
	if (result != NULL) {
	    SECITEM_FreeItem(result, (item == NULL) ? PR_TRUE : PR_FALSE);
	}
    }
    return(NULL);
}
Example #4
0
void NSSCryptoKeyRSA::loadPublicExponentBase64BigNums(const char * b64, unsigned int len) {

	if (mp_exponent != NULL) {

		SECITEM_FreeItem(mp_exponent, PR_TRUE);
		mp_exponent = NULL;		// In case we get an exception

	}

  mp_exponent = NSSCryptoProvider::b642SI(b64, len);

}
Example #5
0
File: ssl3ext.c Project: jld/nss
/* Free everything that has been allocated and then reset back to
 * the starting state. */
void
ssl3_ResetExtensionData(TLSExtensionData *xtnData)
{
    /* Clean up. */
    ssl3_FreeSniNameArray(xtnData);
    PORT_Free(xtnData->clientSigSchemes);
    SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE);
    tls13_DestroyKeyShares(&xtnData->remoteKeyShares);

    /* Now reinit. */
    ssl3_InitExtensionData(xtnData);
}
Example #6
0
File: crlutil.c Project: ekr/nss
static CERTSignedCrl *
FindCRL(CERTCertDBHandle *certHandle, char *name, int type)
{
    CERTSignedCrl *crl = NULL;
    CERTCertificate *cert = NULL;
    SECItem derName;

    derName.data = NULL;
    derName.len = 0;

    cert = CERT_FindCertByNicknameOrEmailAddr(certHandle, name);
    if (!cert) {
        CERTName *certName = NULL;
        PLArenaPool *arena = NULL;
        SECStatus rv = SECSuccess;

        certName = CERT_AsciiToName(name);
        if (certName) {
            arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
            if (arena) {
                SECItem *nameItem =
                    SEC_ASN1EncodeItem(arena, NULL, (void *)certName,
                                       SEC_ASN1_GET(CERT_NameTemplate));
                if (nameItem) {
                    rv = SECITEM_CopyItem(NULL, &derName, nameItem);
                }
                PORT_FreeArena(arena, PR_FALSE);
            }
            CERT_DestroyName(certName);
        }

        if (rv != SECSuccess) {
            SECU_PrintError(progName, "SECITEM_CopyItem failed, out of memory");
            return ((CERTSignedCrl *)NULL);
        }

        if (!derName.len || !derName.data) {
            SECU_PrintError(progName, "could not find certificate named '%s'", name);
            return ((CERTSignedCrl *)NULL);
        }
    } else {
        SECITEM_CopyItem(NULL, &derName, &cert->derSubject);
        CERT_DestroyCertificate(cert);
    }

    crl = SEC_FindCrlByName(certHandle, &derName, type);
    if (crl == NULL)
        SECU_PrintError(progName, "could not find %s's CRL", name);
    if (derName.data) {
        SECITEM_FreeItem(&derName, PR_FALSE);
    }
    return (crl);
}
Example #7
0
/*
 * XXX This is a generic function that would probably make a good
 * replacement for SECU_DER_Read (which is not at all specific to DER,
 * despite its name), but that requires fixing all of the tools...
 * Still, it should be done, whenenver I/somebody has the time.
 * (Also, consider whether this actually belongs in the security
 * library itself, not just in the command library.)
 *
 * This function takes an open file (a PRFileDesc *) and reads the
 * entire file into a SECItem.  (Obviously, the file is intended to
 * be small enough that such a thing is advisable.)  Both the SECItem
 * and the buffer it points to are allocated from the heap; the caller
 * is expected to free them.  ("SECITEM_FreeItem(item, PR_TRUE)")
 */
static SECItem *
read_file_into_item (PRFileDesc *in_file, SECItemType si_type)
{
    PRStatus	 prv;
    SECItem 	*item;
    PRFileInfo	 file_info;
    PRInt32	 bytes_read;

    prv = PR_GetOpenFileInfo (in_file, &file_info);
    if (prv != PR_SUCCESS)
	return NULL;

    if (file_info.size ==  0) {
	/* XXX Need a better error; just grabbed this one for expediency. */
	PORT_SetError (SEC_ERROR_INPUT_LEN);
	return NULL;
    }

    if (file_info.size > 0xffff) {	/* I think this is too big. */
	PORT_SetError (SEC_ERROR_NO_MEMORY);
	return NULL;
    }

    item = PORT_Alloc (sizeof (SECItem));
    if (item == NULL)
	return NULL;

    item->type = si_type;
    item->len = (unsigned int) file_info.size;
    item->data = PORT_Alloc ((size_t)item->len);
    if (item->data == NULL)
	goto loser;

    bytes_read = PR_Read (in_file, item->data, (PRInt32) item->len);
    if (bytes_read < 0) {
	/* Something went wrong; error is already set for us. */
	goto loser;
    } else if (bytes_read == 0) {
	/* Something went wrong; we read nothing.  But no system/nspr error. */
	/* XXX Need to set an error here. */
	goto loser;
    } else if (item->len != (unsigned int)bytes_read) {
	/* Something went wrong; we read less (or more!?) than we expected. */
	/* XXX Need to set an error here. */
	goto loser;
    }

    return item;

loser:
    SECITEM_FreeItem (item, PR_TRUE);
    return NULL;
}
Example #8
0
/*
 * FUNCTION: pkix_pl_CRL_Destroy
 * (see comments for PKIX_PL_DestructorCallback in pkix_pl_system.h)
 */
static PKIX_Error *
pkix_pl_CRL_Destroy(
        PKIX_PL_Object *object,
        void *plContext)
{
        PKIX_PL_CRL *crl = NULL;

        PKIX_ENTER(CRL, "pkix_pl_CRL_Destroy");
        PKIX_NULLCHECK_ONE(object);

        PKIX_CHECK(pkix_CheckType(object, PKIX_CRL_TYPE, plContext),
                    PKIX_OBJECTNOTCRL);

        crl = (PKIX_PL_CRL*)object;

        PKIX_CRL_DEBUG("\t\tCalling CERT_DestroyCrl\n");
        if (crl->nssSignedCrl) {
            CERT_DestroyCrl(crl->nssSignedCrl);
        }
        if (crl->adoptedDerCrl) {
            SECITEM_FreeItem(crl->adoptedDerCrl, PR_TRUE);
        }
        crl->nssSignedCrl = NULL;
        crl->adoptedDerCrl = NULL;
        crl->crlNumberAbsent = PKIX_FALSE;

        PKIX_DECREF(crl->issuer);
        PKIX_DECREF(crl->signatureAlgId);
        PKIX_DECREF(crl->crlNumber);
        PKIX_DECREF(crl->crlEntryList);
        PKIX_DECREF(crl->critExtOids);
        if (crl->derGenName) {
            SECITEM_FreeItem(crl->derGenName, PR_TRUE);
        }

cleanup:

        PKIX_RETURN(CRL);
}
Example #9
0
/*
 * Free up a Cipher Context
 */
void
PK11_DestroyContext(PK11Context *context, PRBool freeit)
{
    pk11_CloseSession(context->slot,context->session,context->ownSession);
    /* initialize the critical fields of the context */
    if (context->savedData != NULL ) PORT_Free(context->savedData);
    if (context->key) PK11_FreeSymKey(context->key);
    if (context->param && context->param != &pk11_null_params)
        SECITEM_FreeItem(context->param, PR_TRUE);
    if (context->sessionLock) PZ_DestroyLock(context->sessionLock);
    PK11_FreeSlot(context->slot);
    if (freeit) PORT_Free(context);
}
Example #10
0
static SECStatus
ssl_PopulateSignedCertTimestamps(sslServerCert *sc,
                                 const SECItem *signedCertTimestamps)
{
    if (sc->signedCertTimestamps.len) {
        SECITEM_FreeItem(&sc->signedCertTimestamps, PR_FALSE);
    }
    if (signedCertTimestamps && signedCertTimestamps->len) {
        return SECITEM_CopyItem(NULL, &sc->signedCertTimestamps,
                                signedCertTimestamps);
    }
    return SECSuccess;
}
Example #11
0
/* BEWARE: This function gets called for both client and server SIDs !!
 * If the unreferenced sid is not in the cache, Free sid and its contents.
 */
static void
ssl_DestroySID(sslSessionID *sid)
{
    int i;
    SSL_TRC(8, ("SSL: destroy sid: sid=0x%x cached=%d", sid, sid->cached));
    PORT_Assert((sid->references == 0));

    if (sid->cached == in_client_cache)
    	return;	/* it will get taken care of next time cache is traversed. */

    if (sid->version < SSL_LIBRARY_VERSION_3_0) {
	SECITEM_ZfreeItem(&sid->u.ssl2.masterKey, PR_FALSE);
	SECITEM_ZfreeItem(&sid->u.ssl2.cipherArg, PR_FALSE);
    }
    if (sid->peerID != NULL)
	PORT_Free((void *)sid->peerID);		/* CONST */

    if (sid->urlSvrName != NULL)
	PORT_Free((void *)sid->urlSvrName);	/* CONST */

    if ( sid->peerCert ) {
	CERT_DestroyCertificate(sid->peerCert);
    }
    for (i = 0; i < MAX_PEER_CERT_CHAIN_SIZE && sid->peerCertChain[i]; i++) {
	CERT_DestroyCertificate(sid->peerCertChain[i]);
    }
    if ( sid->localCert ) {
	CERT_DestroyCertificate(sid->localCert);
    }
    if (sid->u.ssl3.sessionTicket.ticket.data) {
	SECITEM_FreeItem(&sid->u.ssl3.sessionTicket.ticket, PR_FALSE);
    }
    if (sid->u.ssl3.srvName.data) {
	SECITEM_FreeItem(&sid->u.ssl3.srvName, PR_FALSE);
    }
    
    PORT_ZFree(sid, sizeof(sslSessionID));
}
Example #12
0
/* helper functions */
static void
BIO_printf_CERTName(BIO *out, CERTName *cn, const char *msg) {
    CERTRDN **rdns;

    if (!cn) return;

    rdns = cn->rdns;
    if (!rdns) return;

    for (; *rdns; rdns++) {
        CERTAVA **avas = (*rdns)->avas;

        if (!avas) continue;

        for (; *avas; avas++) {
            CERTAVA *ava = *avas;

            BIO_printf(out, "%s", msg);

            {
                int tag = /*SECOidTag*/ CERT_GetAVATag(ava);
                const char* code;

                switch (tag) {
                    case  -1: code = "<unknown>"; break;
                    case  31: code = "E"; break;
                    case  41: code = "CN"; break;
                    case  42: code = "C"; break;
                    case  43: code = "L"; break;
                    case  44: code = "ST"; break;
                    case  45: code = "O"; break;
                    case  46: code = "OU"; break;
                    case 261: code = "SN"; break;
                    case 262: code = "serialNumber"; break;
                    case 268: code = "givenName"; break;
                    default:  code = "<?>"; break;
                }

                BIO_printf(out, "%s = ", code);
            }
            {
                SECItem *si_utf8;

                si_utf8 = CERT_DecodeAVAValue(&ava->value);
                BIO_printf(out, "'%.*s'\n", si_utf8->len, si_utf8->data);
                SECITEM_FreeItem(si_utf8, PR_TRUE);
             }
        }
    }
}
Example #13
0
/*
 * Deep free of the ECParams struct
 */
void FreeECParams(ECParams *ecparams, jboolean freeStruct)
{
    // Use B_FALSE to free the SECItem->data element, but not the SECItem itself
    // Use B_TRUE to free both

    SECITEM_FreeItem(&ecparams->fieldID.u.prime, B_FALSE);
    SECITEM_FreeItem(&ecparams->curve.a, B_FALSE);
    SECITEM_FreeItem(&ecparams->curve.b, B_FALSE);
    SECITEM_FreeItem(&ecparams->curve.seed, B_FALSE);
    SECITEM_FreeItem(&ecparams->base, B_FALSE);
    SECITEM_FreeItem(&ecparams->order, B_FALSE);
    SECITEM_FreeItem(&ecparams->DEREncoding, B_FALSE);
    SECITEM_FreeItem(&ecparams->curveOID, B_FALSE);
    if (freeStruct)
        free(ecparams);
}
NSAPI_PUBLIC void INTsession_fill_ssl(Session *sn)
{
    PRInt32 secon = -1;
    PRInt32 keySize, secretKeySize;
    char *cipher;
    char *issuer_dn;
    char *user_dn;
    char *idstr;
    SECItem *iditem;

    // we'll call SSL_SecurityStatus both when we know that SSL is on
    // or when we don't know anything.
    // either way, we can do this only when we have a descriptor.
    // if we don't have one, we're in a VSInit.
    if (sn->ssl && sn->csd_open) {
        if (!SSL_SecurityStatus(sn->csd, &secon, &cipher, &keySize,
                                &secretKeySize, &issuer_dn, &user_dn)) {
            if(secon > 0) {
                sn->ssl = 1;

                int cipher_len = cipher ? strlen(cipher) : 0;
                int issuer_dn_len = issuer_dn ? strlen(issuer_dn) : 0;
                int user_dn_len = user_dn ? strlen(user_dn) : 0;
                pblock_kvinsert(pb_key_cipher, cipher, cipher_len, sn->client);
                pblock_kninsert(pb_key_keysize, keySize, sn->client);
                pblock_kninsert(pb_key_secret_keysize, secretKeySize, sn->client);
                pblock_kvinsert(pb_key_issuer_dn, issuer_dn, issuer_dn_len, sn->client);
                pblock_kvinsert(pb_key_user_dn, user_dn, user_dn_len, sn->client);

                iditem = SSL_GetSessionID(sn->csd);
                if (iditem) {
                    /* Convert to base64 ASCII encoding */
                    idstr = BTOA_DataToAscii(iditem->data, iditem->len);
                    if (idstr) {
                        /* Add encoding to client pblock */
                        pblock_kvinsert(pb_key_ssl_id, idstr, strlen(idstr), sn->client);
                    }

                    /* Free the encoding buffer (pblock_nvinsert dups it) */
                    SECITEM_FreeItem(iditem, PR_TRUE);
                    PR_Free(idstr);
                }
            }
            if (cipher) PORT_Free (cipher);
            if (issuer_dn) PORT_Free (issuer_dn);
            if (user_dn) PORT_Free (user_dn);
        }
    }
}
Example #15
0
File: nss.c Project: flashfoxter/sx
void sxi_hmac_sha1_cleanup(sxi_hmac_sha1_ctx **ctxptr)
{
    if (!ctxptr || !*ctxptr)
        return;
    if ((*ctxptr)->context)
      PK11_DestroyContext((*ctxptr)->context, PR_TRUE);
    if ((*ctxptr)->key)
        PK11_FreeSymKey((*ctxptr)->key);
    if ((*ctxptr)->keysec)
        SECITEM_FreeItem((*ctxptr)->keysec, PR_TRUE);
    if ((*ctxptr)->slot)
        PK11_FreeSlot((*ctxptr)->slot);
    free(*ctxptr);
    *ctxptr = NULL;
}
Example #16
0
SECStatus SSLInt_Set0RttAlpn(PRFileDesc *fd, PRUint8 *data, unsigned int len) {
  sslSocket *ss = ssl_FindSocket(fd);
  if (!ss) {
    return SECFailure;
  }

  ss->ssl3.nextProtoState = SSL_NEXT_PROTO_EARLY_VALUE;
  if (ss->ssl3.nextProto.data) {
    SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
  }
  if (!SECITEM_AllocItem(NULL, &ss->ssl3.nextProto, len)) return SECFailure;
  PORT_Memcpy(ss->ssl3.nextProto.data, data, len);

  return SECSuccess;
}
Example #17
0
/*
 * FUNCTION: PKIX_PL_CRL_Create (see comments in pkix_pl_pki.h)
 */
PKIX_Error *
PKIX_PL_CRL_Create(
        PKIX_PL_ByteArray *byteArray,
        PKIX_PL_CRL **pCrl,
        void *plContext)
{
        CERTSignedCrl *nssSignedCrl = NULL;
        SECItem derItem, *derCrl = NULL;
        PKIX_PL_CRL *crl = NULL;

        PKIX_ENTER(CRL, "PKIX_PL_CRL_Create");
        PKIX_NULLCHECK_TWO(byteArray, pCrl);

        if (byteArray->length == 0){
            PKIX_ERROR(PKIX_ZEROLENGTHBYTEARRAYFORCRLENCODING);
        }
        derItem.type = siBuffer;
        derItem.data = byteArray->array;
        derItem.len = byteArray->length;
        derCrl = SECITEM_DupItem(&derItem);
        if (!derCrl) {
            PKIX_ERROR(PKIX_ALLOCERROR);
        }
        nssSignedCrl =
            CERT_DecodeDERCrlWithFlags(NULL, derCrl, SEC_CRL_TYPE,
                                       CRL_DECODE_DONT_COPY_DER |
                                       CRL_DECODE_SKIP_ENTRIES);
        if (!nssSignedCrl) {
            PKIX_ERROR(PKIX_CERTDECODEDERCRLFAILED);
        }
        PKIX_CHECK(
            pkix_pl_CRL_CreateWithSignedCRL(nssSignedCrl, derCrl, NULL,
                                            &crl, plContext),
            PKIX_CRLCREATEWITHSIGNEDCRLFAILED);
        nssSignedCrl = NULL;
        derCrl = NULL;
        *pCrl = crl;

cleanup:
        if (derCrl) {
            SECITEM_FreeItem(derCrl, PR_TRUE);
        }
        if (nssSignedCrl) {
            SEC_DestroyCrl(nssSignedCrl);
        } 

        PKIX_RETURN(CRL);
}
Example #18
0
static void
purple_aes_cipher_nss_cleanup(PurpleAESCipherNSSContext *context)
{
	g_return_if_fail(context != NULL);

	if (context->enc_context != NULL)
		PK11_DestroyContext(context->enc_context, TRUE);
	if (context->sec_param != NULL)
		SECITEM_FreeItem(context->sec_param, TRUE);
	if (context->sym_key != NULL)
		PK11_FreeSymKey(context->sym_key);
	if (context->slot != NULL)
		PK11_FreeSlot(context->slot);

	memset(context, 0, sizeof(PurpleAESCipherNSSContext));
}
Example #19
0
void
GatherKeygenTelemetry(uint32_t keyGenMechanism, int keysize, char* curve)
{
  if (keyGenMechanism == CKM_RSA_PKCS_KEY_PAIR_GEN) {
    if (keysize > 8196 || keysize < 0) {
      return;
    }

    nsCString telemetryValue("rsa");
    telemetryValue.AppendPrintf("%d", keysize);
    mozilla::Telemetry::Accumulate(
        mozilla::Telemetry::KEYGEN_GENERATED_KEY_TYPE, telemetryValue);
  } else if (keyGenMechanism == CKM_EC_KEY_PAIR_GEN) {
    nsCString secp384r1 = NS_LITERAL_CSTRING("secp384r1");
    nsCString secp256r1 = NS_LITERAL_CSTRING("secp256r1");

    SECKEYECParams* decoded = decode_ec_params(curve);
    if (!decoded) {
      switch (keysize) {
        case 2048:
          mozilla::Telemetry::Accumulate(
              mozilla::Telemetry::KEYGEN_GENERATED_KEY_TYPE, secp384r1);
          break;
        case 1024:
        case 512:
          mozilla::Telemetry::Accumulate(
              mozilla::Telemetry::KEYGEN_GENERATED_KEY_TYPE, secp256r1);
          break;
      }
    } else {
      SECITEM_FreeItem(decoded, true);
      if (secp384r1.EqualsIgnoreCase(curve, secp384r1.Length())) {
          mozilla::Telemetry::Accumulate(
              mozilla::Telemetry::KEYGEN_GENERATED_KEY_TYPE, secp384r1);
      } else if (secp256r1.EqualsIgnoreCase(curve, secp256r1.Length())) {
          mozilla::Telemetry::Accumulate(
              mozilla::Telemetry::KEYGEN_GENERATED_KEY_TYPE, secp256r1);
      } else {
        mozilla::Telemetry::Accumulate(
            mozilla::Telemetry::KEYGEN_GENERATED_KEY_TYPE, NS_LITERAL_CSTRING("other_ec"));
      }
    }
  } else {
    MOZ_CRASH("Unknown keygen algorithm");
    return;
  }
}
Example #20
0
static bool
isExtractable(SECKEYPrivateKey *privKey)
{
  SECItem value;
  bool    isExtractable = false;
  SECStatus rv;

  rv=PK11_ReadRawAttribute(PK11_TypePrivKey, privKey, CKA_EXTRACTABLE, &value);
  if (rv != SECSuccess) {
    return false;
  }
  if ((value.len == 1) && (value.data != NULL)) {
    isExtractable = !!(*(CK_BBOOL*)value.data);
  }
  SECITEM_FreeItem(&value, false);
  return isExtractable;
}
Example #21
0
// Attempt to read the CKA_EXTRACTABLE attribute on a private key inside
// a token. On success, store the attribute in |extractable| and return
// SECSuccess.
SECStatus
isExtractable(SECKEYPrivateKey *privKey, PRBool *extractable)
{
    SECItem value;
    SECStatus rv;

    rv=PK11_ReadRawAttribute(PK11_TypePrivKey, privKey, CKA_EXTRACTABLE, &value);
    if (rv != SECSuccess)
        return rv;

    if ((value.len == 1) && (value.data != NULL))
        *extractable = !!(*(CK_BBOOL*)value.data);
    else
        rv = SECFailure;
    SECITEM_FreeItem(&value, PR_FALSE);
    return rv;
}
Example #22
0
static PRBool
isExtractable(SECKEYPrivateKey *privKey)
{
  SECItem value;
  PRBool  isExtractable = PR_FALSE;
  SECStatus rv;

  rv=PK11_ReadRawAttribute(PK11_TypePrivKey, privKey, CKA_EXTRACTABLE, &value);
  if (rv != SECSuccess) {
    return PR_FALSE;
  }
  if ((value.len == 1) && (value.data != NULL)) {
    isExtractable = *(CK_BBOOL*)value.data;
  }
  SECITEM_FreeItem(&value, PR_FALSE);
  return isExtractable;
}
SECStatus
DSA_NewRandom(PLArenaPool * arena, const SECItem * q, SECItem * seed)
{
    int retries = 10;
    unsigned int i;
    PRBool good;

    if (q == NULL || q->data == NULL || q->len == 0 ||
        (q->data[0] == 0 && q->len == 1)) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }

    if (!SECITEM_AllocItem(arena, seed, q->len)) {
        return SECFailure;
    }

    do {
	/* Generate seed bytes for x according to FIPS 186-1 appendix 3 */
        if (dsa_GenerateGlobalRandomBytes(q, seed->data, &seed->len,
                                          seed->len)) {
            goto loser;
        }
	/* Disallow values of 0 and 1 for x. */
	good = PR_FALSE;
	for (i = 0; i < seed->len-1; i++) {
	    if (seed->data[i] != 0) {
		good = PR_TRUE;
		break;
	    }
	}
	if (!good && seed->data[i] > 1) {
	    good = PR_TRUE;
	}
    } while (!good && --retries > 0);

    if (!good) {
	PORT_SetError(SEC_ERROR_NEED_RANDOM);
loser:	if (arena != NULL) {
            SECITEM_FreeItem(seed, PR_FALSE);
        }
	return SECFailure;
    }

    return SECSuccess;
}
Example #24
0
void
soft_free_ecparams(ECParams *params, boolean_t freeit)
{
	SECITEM_FreeItem(&params->fieldID.u.prime, B_FALSE);
	SECITEM_FreeItem(&params->curve.a, B_FALSE);
	SECITEM_FreeItem(&params->curve.b, B_FALSE);
	SECITEM_FreeItem(&params->curve.seed, B_FALSE);
	SECITEM_FreeItem(&params->base, B_FALSE);
	SECITEM_FreeItem(&params->order, B_FALSE);
	if (freeit)
		free(params);
}
nsresult
nsStreamCipher::InitWithIV_(nsIKeyObject *aKey, SECItem* aIV)
{
  NS_ENSURE_ARG_POINTER(aKey);

  // Make sure we have a SYM_KEY.
  PRInt16 keyType;
  nsresult rv = aKey->GetType(&keyType);
  NS_ENSURE_SUCCESS(rv, rv);
  if (keyType != nsIKeyObject::SYM_KEY)
    return NS_ERROR_INVALID_ARG;

  if (mContext)
    PK11_DestroyContext(mContext, true /* free sub-objects */);

  // Get the PK11SymKey out of the key object and create the PK11Context.
  void* keyObj;
  rv = aKey->GetKeyObj(&keyObj);
  NS_ENSURE_SUCCESS(rv, rv);

  PK11SymKey *symkey = reinterpret_cast<PK11SymKey*>(keyObj);
  if (!symkey)
    return NS_ERROR_FAILURE;

  CK_MECHANISM_TYPE cipherMech = PK11_GetMechanism(symkey);

  SECItem *param = nullptr;
  // aIV may be null
  param = PK11_ParamFromIV(cipherMech, aIV);
  if (!param)
    return NS_ERROR_FAILURE;

  mContext = PK11_CreateContextBySymKey(cipherMech, CKA_ENCRYPT,
                                        symkey, param);

  SECITEM_FreeItem(param, true);

  // Something went wrong if mContext doesn't exist.
  if (!mContext)
    return NS_ERROR_FAILURE;

  // Everything went ok.      
  mValue.Truncate();
  return NS_OK;
}
Example #26
0
/*
 * FUNCTION: pkix_pl_OID_Destroy
 * (see comments for PKIX_PL_DestructorCallback in pkix_pl_system.h)
 */
static PKIX_Error *
pkix_pl_OID_Destroy(
        PKIX_PL_Object *object,
        void *plContext)
{
        PKIX_PL_OID *oid = NULL;

        PKIX_ENTER(OID, "pkix_pl_OID_Destroy");
        PKIX_NULLCHECK_ONE(object);

        PKIX_CHECK(pkix_CheckType(object, PKIX_OID_TYPE, plContext),
                    PKIX_OBJECTNOTANOID);
        oid = (PKIX_PL_OID*)object;
        SECITEM_FreeItem(&oid->derOid, PR_FALSE);

cleanup:
        PKIX_RETURN(OID);
}
Example #27
0
SecCertificateRef CERT_FindCertBySubjectKeyID (CFTypeRef keychainOrArray, 
    CSSM_DATA_PTR *rawCerts, const SECItem *subjKeyID)
{
    SecCertificateRef certificate;
    int numRawCerts = SecCmsArrayCount((void **)rawCerts);
    int dex;
    OSStatus ortn;
    SECItem skid;
    
    /* 
     * First search the rawCerts array.
     */
    for(dex=0; dex<numRawCerts; dex++) {
	int match;
	ortn = SecCertificateCreateFromData(rawCerts[dex], 
	    CSSM_CERT_X_509v3, CSSM_CERT_ENCODING_DER,
	    &certificate);
	if(ortn) {
	    continue;
	}
	if(CERT_FindSubjectKeyIDExtension(certificate, &skid)) {
	    CFRelease(certificate);
	    /* not present */
	    continue;
	}
	match = compareCssmData(subjKeyID, &skid);
	SECITEM_FreeItem(&skid, PR_FALSE);
	if(match) {
	    /* got it */
	    return certificate;
	}
	CFRelease(certificate);
    }

    /* now search keychain(s) */
    OSStatus status = SecCertificateFindBySubjectKeyID(keychainOrArray,subjKeyID,&certificate);
    if (status)
    {
	PORT_SetError(SEC_ERROR_NO_EMAIL_CERT);
	certificate = NULL;
    }

    return certificate;
}
Example #28
0
SECStatus
cmmf_PKIStatusInfoSetStatus(CMMFPKIStatusInfo *statusInfo,
                            PLArenaPool *poolp,
                            CMMFPKIStatus inStatus)
{
    SECItem *dummy;

    if (inStatus < cmmfGranted || inStatus >= cmmfNumPKIStatus) {
        return SECFailure;
    }

    dummy = SEC_ASN1EncodeInteger(poolp, &statusInfo->status, inStatus);
    PORT_Assert(dummy == &statusInfo->status);
    if (dummy != &statusInfo->status) {
        SECITEM_FreeItem(dummy, PR_TRUE);
        return SECFailure;
    }
    return SECSuccess;
}
Example #29
0
/*
** Generate and return a new DSA public and private key pair,
**	both of which are encoded into a single DSAPrivateKey struct.
**	"params" is a pointer to the PQG parameters for the domain
**	Uses a random seed.
*/
SECStatus 
DSA_NewKey(const PQGParams *params, DSAPrivateKey **privKey)
{
    SECItem seed;
    SECStatus rv;

    seed.data = NULL;

    rv = DSA_NewRandom(NULL, &params->subPrime, &seed);
    if (rv == SECSuccess) {
        if (seed.len != DSA_SUBPRIME_LEN) {
            PORT_SetError(SEC_ERROR_INVALID_ARGS);
            rv = SECFailure;
        } else {
            rv = dsa_NewKeyExtended(params, &seed, privKey);
        }
    }
    SECITEM_FreeItem(&seed, PR_FALSE);
    return rv;
}
static nsresult
GetCertFingerprintByDottedOidString(CERTCertificate* nsscert,
                                    const nsCString &dottedOid,
                                    nsCString &fp)
{
    SECItem oid;
    oid.data = nsnull;
    oid.len = 0;
    SECStatus srv = SEC_StringToOID(nsnull, &oid,
                                    dottedOid.get(), dottedOid.Length());
    if (srv != SECSuccess)
        return NS_ERROR_FAILURE;

    SECOidTag oid_tag = SECOID_FindOIDTag(&oid);
    SECITEM_FreeItem(&oid, PR_FALSE);

    if (oid_tag == SEC_OID_UNKNOWN)
        return NS_ERROR_FAILURE;

    return GetCertFingerprintByOidTag(nsscert, oid_tag, fp);
}