Example #1
0
nsresult
PublicDhKeyToSpki(SECKEYPublicKey* aPubKey,
                  CERTSubjectPublicKeyInfo* aSpki)
{
  SECItem* params = ::SECITEM_AllocItem(aSpki->arena, nullptr, 0);
  if (!params) {
    return NS_ERROR_DOM_OPERATION_ERR;
  }

  SECItem* rvItem = SEC_ASN1EncodeItem(aSpki->arena, params, aPubKey,
                                       SECKEY_DHParamKeyTemplate);
  if (!rvItem) {
    return NS_ERROR_DOM_OPERATION_ERR;
  }

  SECStatus rv = SECOID_SetAlgorithmID(aSpki->arena, &aSpki->algorithm,
                                       SEC_OID_X942_DIFFIE_HELMAN_KEY, params);
  if (rv != SECSuccess) {
    return NS_ERROR_DOM_OPERATION_ERR;
  }

  rvItem = SEC_ASN1EncodeItem(aSpki->arena, &aSpki->subjectPublicKey, aPubKey,
                              SECKEY_DHPublicKeyTemplate);
  if (!rvItem) {
    return NS_ERROR_DOM_OPERATION_ERR;
  }

  // The public value is a BIT_STRING encoded as an INTEGER. After encoding
  // an INT we need to adjust the length to reflect the number of bits.
  aSpki->subjectPublicKey.len <<= 3;

  return NS_OK;
}
Example #2
0
/*
 * Given a raw modulus and exponent, cook up a
 * BER-encoded RSA public key blob.
 */
OSStatus sslEncodeRsaBlob(
	const SSLBuffer	*modulus,
	const SSLBuffer	*exponent,
	SSLBuffer		*blob)			/* data mallocd and RETURNED */
{
    PLArenaPool *pool;
	OSStatus srtn;
    SECItem *encBlob, dest = {};
	NSS_RSAPublicKeyPKCS1 nssPubKey;

	assert((modulus != NULL) && (exponent != NULL));

	/* convert to NSS_RSAPublicKeyPKCS1 */
	SSLBUF_TO_SECITEM(modulus, &nssPubKey.modulus);
	SSLBUF_TO_SECITEM(exponent, &nssPubKey.publicExponent);

	/* DER encode */
    pool = PORT_NewArena(CHUNKSIZE_DEF);
    encBlob = SEC_ASN1EncodeItem(pool, &dest, &nssPubKey,
        kSecAsn1RSAPublicKeyPKCS1Template);
	if (!encBlob)
		srtn = memFullErr;
    else {
        /* copy out to caller */
        srtn = SSLCopyBufferFromData(encBlob->Data, encBlob->Length, blob);
    }

    PORT_FreeArena(pool, PR_TRUE);
    return srtn;
}
Example #3
0
/*
 * Given a prime and generator, cook up a BER-encoded DHParameter blob.
 */
OSStatus sslEncodeDhParams(
	const SSLBuffer	*prime,
	const SSLBuffer	*generator,
	SSLBuffer		*blob)			/* data mallocd and RETURNED */
{
    PLArenaPool *pool;
	OSStatus srtn;
    SECItem *encBlob, dest = {};
	NSS_DHParameter dhParams;

	assert((prime != NULL) && (generator != NULL));

	/* convert to NSS_DHParameter */
	SSLBUF_TO_SECITEM(prime, &dhParams.prime);
	SSLBUF_TO_SECITEM(generator, &dhParams.base);
	dhParams.privateValueLength.Data = NULL;
	dhParams.privateValueLength.Length = 0;

	/* DER encode */
    pool = PORT_NewArena(CHUNKSIZE_DEF);
    encBlob = SEC_ASN1EncodeItem(pool, &dest, &dhParams,
        kSecAsn1DHParameterTemplate);
	if (!encBlob)
		srtn = memFullErr;
    else {
        /* copy out to caller */
        srtn = SSLCopyBufferFromData(encBlob->Data, encBlob->Length, blob);
    }

    PORT_FreeArena(pool, PR_TRUE);
    return srtn;
}
Example #4
0
static int
generate_spc_indirect_data_content(cms_context *cms, SECItem *idcp)
{
	SpcIndirectDataContent idc;
	memset(&idc, '\0', sizeof (idc));
	int rc;

	rc = generate_spc_attribute_yadda_yadda(cms, &idc.data);
	if (rc < 0)
		return rc;

	rc = generate_spc_digest_info(cms, &idc.messageDigest);
	if (rc < 0) {
		SECITEM_FreeItem(&idc.data, PR_FALSE);
		return rc;
	}

	if (SEC_ASN1EncodeItem(cms->arena, idcp, &idc,
			SpcIndirectDataContentTemplate) == NULL) {
		cms->log(cms, LOG_ERR, "could not encode "
			"SpcIndirectDataContent: %s",
			PORT_ErrorToString(PORT_GetError()));
		return -1;
	}
	return 0;
}
Example #5
0
/*
 * NSS_SMIMEUtil_CreateSMIMEEncKeyPrefs - create S/MIME encryption key preferences attr value using MS oid
 *
 * "poolp" - arena pool to create the attr value on
 * "dest" - SECItem to put the data in
 * "cert" - certificate that should be marked as preferred encryption key
 *          cert is expected to have been verified for EmailRecipient usage.
 */
SECStatus
NSS_SMIMEUtil_CreateMSSMIMEEncKeyPrefs(PLArenaPool *poolp, SECItem *dest, CERTCertificate *cert)
{
    SECItem *dummy = NULL;
    PLArenaPool *tmppoolp = NULL;
    CERTIssuerAndSN *isn;

    if (cert == NULL)
	goto loser;

    tmppoolp = PORT_NewArena(1024);
    if (tmppoolp == NULL)
	goto loser;

    isn = CERT_GetCertIssuerAndSN(tmppoolp, cert);
    if (isn == NULL)
	goto loser;

    dummy = SEC_ASN1EncodeItem(poolp, dest, isn, SEC_ASN1_GET(CERT_IssuerAndSNTemplate));

loser:
    if (tmppoolp) PORT_FreeArena(tmppoolp, PR_FALSE);

    return (dummy == NULL) ? SECFailure : SECSuccess;
}
Example #6
0
static int
generate_spc_indirect_data_content(PRArenaPool *arena, SECItem *idcp,
				cms_context *ctx)
{
	SpcIndirectDataContent idc;
	memset(&idc, '\0', sizeof (idc));

	if (generate_spc_attribute_yadda_yadda(arena, &idc.data) < 0) {
		fprintf(stderr, "got here %s:%d\n",__func__,__LINE__);
		return -1;
	}

	if (generate_spc_digest_info(arena, &idc.messageDigest, ctx) < 0) {
		fprintf(stderr, "got here %s:%d\n",__func__,__LINE__);
		return -1;
	}

	if (SEC_ASN1EncodeItem(arena, idcp, &idc,
			SpcIndirectDataContentTemplate) == NULL) {
		fprintf(stderr,
			"Could not encode SpcIndirectDataContent: %s\n",
			PORT_ErrorToString(PORT_GetError()));
		return -1;
	}
	return 0;
}
Example #7
0
/* Generate DER for SpcAttributeTypeAndValue, which is basically just
 * a DER_SEQUENCE containing the OID 1.3.6.1.4.1.311.2.1.15
 * (SPC_PE_IMAGE_DATA_OBJID) and the SpcPeImageData.
 */
static int
generate_spc_attribute_yadda_yadda(cms_context *cms, SECItem *ataovp)
{
	SpcAttributeTypeAndOptionalValue ataov;
	memset(&ataov, '\0', sizeof (ataov));

	int rc;

	rc = get_ms_oid_secitem(SPC_PE_IMAGE_DATA_OBJID, &ataov.contentType);
	if (rc < 0) {
		cms->log(cms, LOG_ERR, "could not get SPC_PE_IMAGE_DATA_OBJID");
		return -1;
	}

	rc = generate_spc_pe_image_data(cms, &ataov.value);
	if (rc < 0)
		return rc;

	if (SEC_ASN1EncodeItem(cms->arena, ataovp, &ataov,
			SpcAttributeTypeAndOptionalValueTemplate) == NULL) {
		cms->log(cms, LOG_ERR, "could not encode "
			"SpcAttributeTypeAndOptionalValue: %s",
			PORT_ErrorToString(PORT_GetError()));

		return -1;
	}
	return 0;
}
Example #8
0
static int
generate_spc_digest_info(cms_context *cms, SECItem *dip)
{
	DigestInfo di;
	memset(&di, '\0', sizeof (di));

	if (generate_algorithm_id(cms, &di.digestAlgorithm,
			digest_get_digest_oid(cms)) < 0)
		return -1;
	int i = cms->selected_digest;
	memcpy(&di.digest, cms->digests[i].pe_digest, sizeof (di.digest));

	if (content_is_empty(di.digest.data, di.digest.len)) {
		cms->log(cms, LOG_ERR, "got empty digest");
		return -1;
	}

	if (SEC_ASN1EncodeItem(cms->arena, dip, &di,
						DigestInfoTemplate) == NULL) {
		cms->log(cms, LOG_ERR, "could not encode DigestInfo: %s",
			PORT_ErrorToString(PORT_GetError()));
		return -1;
	}
	return 0;
}
Example #9
0
/*
 * NSS_SMIMEUtil_CreateSMIMECapabilities - get S/MIME capabilities for this instance of NSS
 *
 * scans the list of allowed and enabled ciphers and construct a PKCS9-compliant
 * S/MIME capabilities attribute value.
 *
 * XXX Please note that, in contradiction to RFC2633 2.5.2, the capabilities only include
 * symmetric ciphers, NO signature algorithms or key encipherment algorithms.
 *
 * "poolp" - arena pool to create the S/MIME capabilities data on
 * "dest" - SECItem to put the data in
 */
SECStatus
NSS_SMIMEUtil_CreateSMIMECapabilities(PLArenaPool *poolp, SECItem *dest)
{
    NSSSMIMECapability *cap;
    NSSSMIMECapability **smime_capabilities;
    smime_cipher_map_entry *map;
    SECOidData *oiddata;
    SECItem *dummy;
    int i, capIndex;

    /* if we have an old NSSSMIMECapability array, we'll reuse it (has the right size) */
    /* smime_cipher_map_count + 1 is an upper bound - we might end up with less */
    smime_capabilities = (NSSSMIMECapability **)PORT_ZAlloc((smime_cipher_map_count + 1)
				      * sizeof(NSSSMIMECapability *));
    if (smime_capabilities == NULL)
	return SECFailure;

    capIndex = 0;

    /* Add all the symmetric ciphers
     * We walk the cipher list backwards, as it is ordered by increasing strength,
     * we prefer the stronger cipher over a weaker one, and we have to list the
     * preferred algorithm first */
    for (i = smime_cipher_map_count - 1; i >= 0; i--) {
	/* Find the corresponding entry in the cipher map. */
	map = &(smime_cipher_map[i]);
	if (!map->enabled)
	    continue;

	/* get next SMIME capability */
	cap = (NSSSMIMECapability *)PORT_ZAlloc(sizeof(NSSSMIMECapability));
	if (cap == NULL)
	    break;
	smime_capabilities[capIndex++] = cap;

	oiddata = SECOID_FindOIDByTag(map->algtag);
	if (oiddata == NULL)
	    break;

	cap->capabilityID.data = oiddata->oid.data;
	cap->capabilityID.len = oiddata->oid.len;
	cap->parameters.data = map->parms ? map->parms->data : NULL;
	cap->parameters.len = map->parms ? map->parms->len : 0;
	cap->cipher = smime_cipher_map[i].cipher;
    }

    /* XXX add signature algorithms */
    /* XXX add key encipherment algorithms */

    smime_capabilities[capIndex] = NULL;	/* last one - now encode */
    dummy = SEC_ASN1EncodeItem(poolp, dest, &smime_capabilities, NSSSMIMECapabilitiesTemplate);

    /* now that we have the proper encoded SMIMECapabilities (or not),
     * free the work data */
    for (i = 0; smime_capabilities[i] != NULL; i++)
	PORT_Free(smime_capabilities[i]);
    PORT_Free(smime_capabilities);

    return (dummy == NULL) ? SECFailure : SECSuccess;
}
Example #10
0
nsresult
CryptoKey::PublicKeyToSpki(SECKEYPublicKey* aPubKey,
                     CryptoBuffer& aRetVal,
                     const nsNSSShutDownPreventionLock& /*proofOfLock*/)
{
  ScopedCERTSubjectPublicKeyInfo spki(SECKEY_CreateSubjectPublicKeyInfo(aPubKey));
  if (!spki) {
    return NS_ERROR_DOM_OPERATION_ERR;
  }

  // Per WebCrypto spec we must export ECDH SPKIs with the algorithm OID
  // id-ecDH (1.3.132.112). NSS doesn't know about that OID and there is
  // no way to specify the algorithm to use when exporting a public key.
  if (aPubKey->keyType == ecKey) {
    SECStatus rv = SECITEM_CopyItem(spki->arena, &spki->algorithm.algorithm,
                                    &SEC_OID_DATA_EC_DH);
    if (rv != SECSuccess) {
      return NS_ERROR_DOM_OPERATION_ERR;
    }
  }

  const SEC_ASN1Template* tpl = SEC_ASN1_GET(CERT_SubjectPublicKeyInfoTemplate);
  ScopedSECItem spkiItem(SEC_ASN1EncodeItem(nullptr, nullptr, spki, tpl));

  aRetVal.Assign(spkiItem.get());
  return NS_OK;
}
Example #11
0
SECStatus
CERT_EncodeInfoAccessExtension(PRArenaPool *arena,
				   CERTAuthInfoAccess **info,
				   SECItem *dest)
{
    SECItem *dummy;
    int i;

    PORT_Assert(info != NULL);
    PORT_Assert(dest != NULL);
    if (info == NULL || dest == NULL) {
	return SECFailure;
    }

    for (i = 0; info[i] != NULL; i++) {
	if (CERT_EncodeGeneralName(info[i]->location, &(info[i]->derLocation),
				   arena) == NULL)
	    /* Note that this may leave some of the locations filled in. */
	    return SECFailure;
    }
    dummy = SEC_ASN1EncodeItem(arena, dest, &info,
			       CERTAuthInfoAccessTemplate);
    if (dummy == NULL) {
	return SECFailure;
    }
    return SECSuccess;
}
/*
 * Lookup a certificate in the database by name
 */
CERTCertificate *
CERT_FindCertByNameString(CERTCertDBHandle *handle, char *nameStr)
{
    CERTName *name;
    SECItem *nameItem;
    CERTCertificate *cert = NULL;
    PRArenaPool *arena = NULL;
    
    arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
    
    if ( arena == NULL ) {
	goto loser;
    }
    
    name = CERT_AsciiToName(nameStr);
    
    if ( name ) {
	nameItem = SEC_ASN1EncodeItem (arena, NULL, (void *)name,
				       CERT_NameTemplate);
	if ( nameItem != NULL ) {
            cert = CERT_FindCertByName(handle, nameItem);
	}
	CERT_DestroyName(name);
    }

loser:
    if ( arena ) {
	PORT_FreeArena(arena, PR_FALSE);
    }
    
    return(cert);
}
Example #13
0
/*
 * NSS_SMIMEUtil_CreateSMIMEEncKeyPrefs - create S/MIME encryption key preferences attr value
 *
 * "poolp" - arena pool to create the attr value on
 * "dest" - SECItem to put the data in
 * "cert" - certificate that should be marked as preferred encryption key
 *          cert is expected to have been verified for EmailRecipient usage.
 */
SECStatus
NSS_SMIMEUtil_CreateSMIMEEncKeyPrefs(PLArenaPool *poolp, SECItem *dest, CERTCertificate *cert)
{
    NSSSMIMEEncryptionKeyPreference ekp;
    SECItem *dummy = NULL;
    PLArenaPool *tmppoolp = NULL;

    if (cert == NULL)
	goto loser;

    tmppoolp = PORT_NewArena(1024);
    if (tmppoolp == NULL)
	goto loser;

    /* XXX hardcoded IssuerSN choice for now */
    ekp.selector = NSSSMIMEEncryptionKeyPref_IssuerSN;
    ekp.id.issuerAndSN = CERT_GetCertIssuerAndSN(tmppoolp, cert);
    if (ekp.id.issuerAndSN == NULL)
	goto loser;

    dummy = SEC_ASN1EncodeItem(poolp, dest, &ekp, smime_encryptionkeypref_template);

loser:
    if (tmppoolp) PORT_FreeArena(tmppoolp, PR_FALSE);

    return (dummy == NULL) ? SECFailure : SECSuccess;
}
Example #14
0
static int
generate_spc_pe_image_data(cms_context *cms, SECItem *spidp)
{
	SpcPeImageData spid;

	SECITEM_AllocItem(cms->arena, &spid.flags, 1);
	if (!spid.flags.data)
		return -1;
	spid.flags.data[0] = 0;

	char obsolete[28] = "";
	int rc;
	rc = generate_spc_link(cms, &spid.link, SpcLinkTypeFile, obsolete, 0);
	if (rc < 0)
		return rc;

	if (SEC_ASN1EncodeItem(cms->arena, spidp, &spid,
			SpcPeImageDataTemplate) == NULL) {
		cms->log(cms, LOG_ERR, "could not encode SpcPeImageData: %s",
			PORT_ErrorToString(PORT_GetError()));
		return -1;
	}

	/* XXX OMG FIX THIS */
	/* manually bang it from NULL to BIT STRING because I can't figure out
	 * how to make the f*****g templates work right for the bitstring size
	 */
	spidp->data[2] = DER_BIT_STRING;
	return 0;
}
Example #15
0
static int
generate_spc_pe_image_data(PRArenaPool *arena, SECItem *spidp)
{
	SpcPeImageData spid;

	SECITEM_AllocItem(arena, &spid.flags, 1);
	if (!spid.flags.data)
		return -1;
	spid.flags.data[0] = 0;

	char obsolete[28] = "\0<\0<\0<\0O\0b\0s\0o\0l\0e\0t\0e\0>\0>\0>";
	if (generate_spc_link(arena, &spid.link, SpcLinkTypeFile, obsolete,
			28) < 0) {
		fprintf(stderr, "got here %s:%d\n",__func__,__LINE__);
		return -1;
	}

	if (SEC_ASN1EncodeItem(arena, spidp, &spid,
			SpcPeImageDataTemplate) == NULL) {
		fprintf(stderr, "Could not encode SpcPeImageData: %s\n",
			PORT_ErrorToString(PORT_GetError()));
		return -1;
	}

	/* XXX OMG FIX THIS */
	/* manually bang it from NULL to BIT STRING because I can't figure out
	 * how to make the f*****g templates work right for the bitstring size
	 */
	spidp->data[2] = DER_BIT_STRING;
	return 0;
}
Example #16
0
/* Generate DER for SpcAttributeTypeAndValue, which is basically just
 * a DER_SEQUENCE containing the OID 1.3.6.1.4.1.311.2.1.15
 * (SPC_PE_IMAGE_DATA_OBJID) and the SpcPeImageData.
 */
static int
generate_spc_attribute_yadda_yadda(PRArenaPool *arena, SECItem *ataovp)
{
	SpcAttributeTypeAndOptionalValue ataov;
	memset(&ataov, '\0', sizeof (ataov));

	if (get_ms_oid_secitem(SPC_PE_IMAGE_DATA_OBJID, &ataov.contentType) < 0){
		fprintf(stderr, "got here %s:%d\n",__func__,__LINE__);
		return -1;
	}

	if (generate_spc_pe_image_data(arena, &ataov.value) < 0) {
		fprintf(stderr, "got here %s:%d\n",__func__,__LINE__);
		return -1;
	}

	if (SEC_ASN1EncodeItem(arena, ataovp, &ataov,
			SpcAttributeTypeAndOptionalValueTemplate) == NULL) {
		fprintf(stderr,
			"Could not encode SpcAttributeTypeAndOptionalValue:"
			"%s\n",
			PORT_ErrorToString(PORT_GetError()));
		return -1;
	}
	return 0;
}
Example #17
0
/*
 * SecSMIMECreateSMIMEEncKeyPrefs - create S/MIME encryption key preferences attr value using MS oid
 *
 * "poolp" - arena pool to create the attr value on
 * "dest" - CSSM_DATA to put the data in
 * "cert" - certificate that should be marked as preferred encryption key
 *          cert is expected to have been verified for EmailRecipient usage.
 */
OSStatus
SecSMIMECreateMSSMIMEEncKeyPrefs(SecArenaPoolRef pool, CSSM_DATA_PTR dest, SecCertificateRef cert)
{
    PLArenaPool *poolp = (PLArenaPool *)pool;
    CSSM_DATA_PTR dummy = NULL;
    PLArenaPool *tmppoolp = NULL;
    SecCmsIssuerAndSN *isn;

    if (cert == NULL)
	goto loser;

    tmppoolp = PORT_NewArena(1024);
    if (tmppoolp == NULL)
	goto loser;

    isn = CERT_GetCertIssuerAndSN(tmppoolp, cert);
    if (isn == NULL)
	goto loser;

    dummy = SEC_ASN1EncodeItem(poolp, dest, isn, SEC_ASN1_GET(SecCmsIssuerAndSNTemplate));

loser:
    if (tmppoolp) PORT_FreeArena(tmppoolp, PR_FALSE);

    return (dummy == NULL) ? SECFailure : SECSuccess;
}
Example #18
0
/*
 * SecSMIMECreateSMIMEEncKeyPrefs - create S/MIME encryption key preferences attr value
 *
 * "poolp" - arena pool to create the attr value on
 * "dest" - CSSM_DATA to put the data in
 * "cert" - certificate that should be marked as preferred encryption key
 *          cert is expected to have been verified for EmailRecipient usage.
 */
OSStatus
SecSMIMECreateSMIMEEncKeyPrefs(SecArenaPoolRef pool, CSSM_DATA_PTR dest, SecCertificateRef cert)
{
    PLArenaPool *poolp = (PLArenaPool *)pool;
    NSSSMIMEEncryptionKeyPreference ekp;
    CSSM_DATA_PTR dummy = NULL;
    PLArenaPool *tmppoolp = NULL;

    if (cert == NULL)
	goto loser;

    tmppoolp = PORT_NewArena(1024);
    if (tmppoolp == NULL)
	goto loser;

    /* XXX hardcoded IssuerSN choice for now */
    ekp.selector = NSSSMIMEEncryptionKeyPref_IssuerSN;
    ekp.id.issuerAndSN = CERT_GetCertIssuerAndSN(tmppoolp, cert);
    if (ekp.id.issuerAndSN == NULL)
	goto loser;

    dummy = SEC_ASN1EncodeItem(poolp, dest, &ekp, smime_encryptionkeypref_template);

loser:
    if (tmppoolp) PORT_FreeArena(tmppoolp, PR_FALSE);

    return (dummy == NULL) ? SECFailure : SECSuccess;
}
Example #19
0
static CRMFPKIArchiveOptions *
crmf_create_arch_rem_gen_privkey(PRBool archiveRemGenPrivKey)
{
    unsigned char value;
    SECItem *dummy;
    CRMFPKIArchiveOptions *newArchOptions;

    value = (archiveRemGenPrivKey) ? hexTrue : hexFalse;
    newArchOptions = PORT_ZNew(CRMFPKIArchiveOptions);
    if (newArchOptions == NULL) {
        goto loser;
    }
    dummy = SEC_ASN1EncodeItem(NULL,
                               &newArchOptions->option.archiveRemGenPrivKey,
                               &value, SEC_ASN1_GET(SEC_BooleanTemplate));
    PORT_Assert(dummy == &newArchOptions->option.archiveRemGenPrivKey);
    if (dummy != &newArchOptions->option.archiveRemGenPrivKey) {
        SECITEM_FreeItem(dummy, PR_TRUE);
        goto loser;
    }
    newArchOptions->archOption = crmfArchiveRemGenPrivKey;
    return newArchOptions;
loser:
    if (newArchOptions != NULL) {
        CRMF_DestroyPKIArchiveOptions(newArchOptions);
    }
    return NULL;
}
Example #20
0
/********************************************************************
 *
 * s i g n _ c e r t
 */
static SECItem *
sign_cert(CERTCertificate *cert, SECKEYPrivateKey *privk)
{
    SECStatus rv;

    SECItem der2;
    SECItem * result2;

    void	*dummy;
    SECOidTag alg = SEC_OID_UNKNOWN;

    alg = SEC_GetSignatureAlgorithmOidTag(privk->keyType, SEC_OID_UNKNOWN);
    if (alg == SEC_OID_UNKNOWN) {
	FatalError("Unknown key type");
    }

    rv = SECOID_SetAlgorithmID (cert->arena, &cert->signature, alg, 0);

    if (rv != SECSuccess) {
	PR_fprintf(errorFD, "%s: unable to set signature alg id\n",
	     PROGRAM_NAME);
	errorCount++;
	exit (ERRX);
    }

    der2.len = 0;
    der2.data = NULL;

    dummy = SEC_ASN1EncodeItem
        (cert->arena, &der2, cert, SEC_ASN1_GET(CERT_CertificateTemplate));

    if (rv != SECSuccess) {
	PR_fprintf(errorFD, "%s: error encoding cert\n", PROGRAM_NAME);
	errorCount++;
	exit (ERRX);
    }

    result2 = (SECItem * ) PORT_ArenaZAlloc (cert->arena, sizeof (SECItem));
    if (result2 == NULL)
	out_of_memory();

    rv = SEC_DerSignData 
        (cert->arena, result2, der2.data, der2.len, privk, alg);

    if (rv != SECSuccess) {
	PR_fprintf(errorFD, "can't sign encoded certificate data\n");
	errorCount++;
	exit (ERRX);
    } else if (verbosity >= 0) {
	PR_fprintf(outputFD, "certificate has been signed\n");
    }

    cert->derCert = *result2;

    return result2;
}
Example #21
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 #22
0
SECStatus
CERT_EncodePrivateKeyUsagePeriod(PRArenaPool *arena, 
                                CERTPrivKeyUsagePeriod *pkup, 
				SECItem *encodedValue)
{
    SECStatus rv = SECSuccess;

    if (SEC_ASN1EncodeItem (arena, encodedValue, pkup,
			    CERTPrivateKeyUsagePeriodTemplate) == NULL) {
	rv = SECFailure;
    }
    return(rv);
}
Example #23
0
SECStatus
CERT_EncodeAltNameExtension(PRArenaPool *arena,  CERTGeneralName  *value, SECItem *encodedValue)
{
    SECItem                **encodedGenName;
    SECStatus              rv = SECSuccess;

    encodedGenName = cert_EncodeGeneralNames(arena, value);
    if (SEC_ASN1EncodeItem (arena, encodedValue, &encodedGenName,
			    CERT_GeneralNamesTemplate) == NULL) {
	rv = SECFailure;
    }

    return rv;
}
Example #24
0
SECStatus NSS_CMSRecipientInfo_Encode(PLArenaPool* poolp,
                                      const NSSCMSRecipientInfo *src,
                                      SECItem* returned)
{
    extern const SEC_ASN1Template NSSCMSRecipientInfoTemplate[];
    SECStatus rv = SECFailure;
    if (!src || !returned) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
    } else if (SEC_ASN1EncodeItem(poolp, returned, src,
        NSSCMSRecipientInfoTemplate))   {
        rv = SECSuccess;
    }
    return rv;
}
Example #25
0
SECItem *
PK11_ExportDERPrivateKeyInfo(SECKEYPrivateKey *pk, void *wincx)
{
    SECKEYPrivateKeyInfo *pki = PK11_ExportPrivKeyInfo(pk, wincx);
    SECItem *derPKI;

    if (!pki) {
        return NULL;
    }
    derPKI = SEC_ASN1EncodeItem(NULL, NULL, pki,
                                SECKEY_PrivateKeyInfoTemplate);
    SECKEY_DestroyPrivateKeyInfo(pki, PR_TRUE);
    return derPKI;
}
Example #26
0
/*
 * SecCmsArraySortByDER - sort array of objects by objects' DER encoding
 *
 * make sure that the order of the objects guarantees valid DER (which must be
 * in lexigraphically ascending order for a SET OF); if reordering is necessary it
 * will be done in place (in objs).
 */
OSStatus
SecCmsArraySortByDER(void **objs, const SecAsn1Template *objtemplate, void **objs2)
{
    PRArenaPool *poolp;
    int num_objs;
    SecAsn1Item **enc_objs;
    OSStatus rv = SECFailure;
    int i;

    if (objs == NULL)					/* already sorted */
	return SECSuccess;

    num_objs = SecCmsArrayCount((void **)objs);
    if (num_objs == 0 || num_objs == 1)		/* already sorted. */
	return SECSuccess;

    poolp = PORT_NewArena (1024);	/* arena for temporaries */
    if (poolp == NULL)
	return SECFailure;		/* no memory; nothing we can do... */

    /*
     * Allocate arrays to hold the individual encodings which we will use
     * for comparisons and the reordered attributes as they are sorted.
     */
    // Security check to prevent under-allocation
    if (num_objs<0 || num_objs>=(int)((INT_MAX/sizeof(SecAsn1Item *))-1)) {
        goto loser;
    }
    enc_objs = (SecAsn1Item **)PORT_ArenaZAlloc(poolp, (num_objs + 1) * sizeof(SecAsn1Item *));
    if (enc_objs == NULL)
	goto loser;

    /* DER encode each individual object. */
    for (i = 0; i < num_objs; i++) {
	enc_objs[i] = SEC_ASN1EncodeItem(poolp, NULL, objs[i], objtemplate);
	if (enc_objs[i] == NULL)
	    goto loser;
    }
    enc_objs[num_objs] = NULL;

    /* now compare and sort objs by the order of enc_objs */
    SecCmsArraySort((void **)enc_objs, SecCmsUtilDERCompare, objs, objs2);

    rv = SECSuccess;

loser:
    PORT_FreeArena (poolp, PR_FALSE);
    return rv;
}
Example #27
0
SECStatus CERT_EncodeBasicConstraintValue
   (PRArenaPool *arena, CERTBasicConstraints *value, SECItem *encodedValue)
{
    EncodedContext encodeContext;
    PRArenaPool *our_pool = NULL;   
    SECStatus rv = SECSuccess;

    do {
	PORT_Memset (&encodeContext, 0, sizeof (encodeContext));
	if (!value->isCA && value->pathLenConstraint >= 0) {
	    PORT_SetError (SEC_ERROR_EXTENSION_VALUE_INVALID);
	    GEN_BREAK (SECFailure);
	}

        encodeContext.arena = arena;
	if (value->isCA == PR_TRUE) {
	    encodeContext.isCA.data =  &hexTrue ;
	    encodeContext.isCA.len = 1;
	}

	/* If the pathLenConstraint is less than 0, then it should be
	 * omitted from the encoding.
	 */
	if (value->isCA && value->pathLenConstraint >= 0) {
	    our_pool = PORT_NewArena (SEC_ASN1_DEFAULT_ARENA_SIZE);
	    if (our_pool == NULL) {
		PORT_SetError (SEC_ERROR_NO_MEMORY);
		GEN_BREAK (SECFailure);
	    }
	    if (SEC_ASN1EncodeUnsignedInteger
		(our_pool, &encodeContext.pathLenConstraint,
		 (unsigned long)value->pathLenConstraint) == NULL) {
		PORT_SetError (SEC_ERROR_NO_MEMORY);
		GEN_BREAK (SECFailure);
	    }
	}
	if (SEC_ASN1EncodeItem (arena, encodedValue, &encodeContext,
				CERTBasicConstraintsTemplate) == NULL) {
	    GEN_BREAK (SECFailure);
	}
    } while (0);
    if (our_pool)
	PORT_FreeArena (our_pool, PR_FALSE);
    return(rv);

}
Example #28
0
SECStatus 
CERT_EncodeSubjectKeyID(PRArenaPool *arena, const SECItem* srcString,
                        SECItem *encodedValue)
{
    SECStatus rv = SECSuccess;

    if (!srcString) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }
    if (SEC_ASN1EncodeItem (arena, encodedValue, srcString,
			    CERTSubjectKeyIDTemplate) == NULL) {
	rv = SECFailure;
    }
    
    return(rv);
}
Example #29
0
/*
 * NSS_CMSArray_SortByDER - sort array of objects by objects' DER encoding
 *
 * make sure that the order of the objects guarantees valid DER (which must be
 * in lexigraphically ascending order for a SET OF); if reordering is necessary it
 * will be done in place (in objs).
 */
SECStatus
NSS_CMSArray_SortByDER(void **objs, const SEC_ASN1Template *objtemplate, void **objs2)
{
    PRArenaPool *poolp;
    int num_objs;
    SECItem **enc_objs;
    SECStatus rv = SECFailure;
    int i;

    if (objs == NULL)					/* already sorted */
	return SECSuccess;

    num_objs = NSS_CMSArray_Count((void **)objs);
    if (num_objs == 0 || num_objs == 1)		/* already sorted. */
	return SECSuccess;

    poolp = PORT_NewArena (1024);	/* arena for temporaries */
    if (poolp == NULL)
	return SECFailure;		/* no memory; nothing we can do... */

    /*
     * Allocate arrays to hold the individual encodings which we will use
     * for comparisons and the reordered attributes as they are sorted.
     */
    enc_objs = (SECItem **)PORT_ArenaZAlloc(poolp, (num_objs + 1) * sizeof(SECItem *));
    if (enc_objs == NULL)
	goto loser;

    /* DER encode each individual object. */
    for (i = 0; i < num_objs; i++) {
	enc_objs[i] = SEC_ASN1EncodeItem(poolp, NULL, objs[i], objtemplate);
	if (enc_objs[i] == NULL)
	    goto loser;
    }
    enc_objs[num_objs] = NULL;

    /* now compare and sort objs by the order of enc_objs */
    NSS_CMSArray_Sort((void **)enc_objs, NSS_CMSUtil_DERCompare, objs, objs2);

    rv = SECSuccess;

loser:
    PORT_FreeArena (poolp, PR_FALSE);
    return rv;
}
Example #30
0
SECStatus
CERT_EncodeInhibitAnyExtension(PLArenaPool *arena,
                               CERTCertificateInhibitAny *certInhibitAny,
                               SECItem *dest)
{
    SECStatus rv = SECSuccess;

    PORT_Assert(certInhibitAny != NULL && dest != NULL);
    if (certInhibitAny == NULL || dest == NULL) {
	return SECFailure;
    }

    if (SEC_ASN1EncodeItem (arena, dest, certInhibitAny,
                            CERT_InhibitAnyTemplate) == NULL) {
	rv = SECFailure;
    }
    return(rv);
}