Example #1
0
void
import_raw_signature(pesign_context *pctx)
{
	if (pctx->rawsigfd < 0 || pctx->insattrsfd < 0) {
		fprintf(stderr, "pesign: raw signature and signed attributes "
			"must both be imported.\n");
		exit(1);
	}

	cms_context *ctx = pctx->cms_ctx;

	ctx->raw_signature = SECITEM_AllocItem(ctx->arena, NULL, 0);
	ctx->raw_signature->type = siBuffer;
	int rc = read_file(pctx->rawsigfd,
				(char **)&ctx->raw_signature->data,
				(size_t *)&ctx->raw_signature->len);
	if (rc < 0) {
		fprintf(stderr, "pesign: could not read raw signature: %m\n");
		exit(1);
	}

	ctx->raw_signed_attrs = SECITEM_AllocItem(ctx->arena, NULL, 0);
	ctx->raw_signed_attrs->type = siBuffer;
	rc = read_file(pctx->insattrsfd,
				(char **)&ctx->raw_signed_attrs->data,
				(size_t *)&ctx->raw_signed_attrs->len);
	if (rc < 0) {
		fprintf(stderr, "pesign: could not read raw signed attributes"
				": %m\n");
		exit(1);
	}
}
Example #2
0
ocspCertStatus*
ocsp_CreateCertStatus(PLArenaPool *arena,
                      ocspCertStatusType status,
                      PRTime revocationTime)
{
    ocspCertStatus *cs;

    if (!arena) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return NULL;
    }

    switch (status) {
        case ocspCertStatus_good:
        case ocspCertStatus_unknown:
        case ocspCertStatus_revoked:
            break;
        default:
            PORT_SetError(SEC_ERROR_INVALID_ARGS);
            return NULL;
    }
    
    cs = PORT_ArenaZNew(arena, ocspCertStatus);
    if (!cs)
        return NULL;
    cs->certStatusType = status;
    switch (status) {
        case ocspCertStatus_good:
            cs->certStatusInfo.goodInfo = SECITEM_AllocItem(arena, NULL, 0);
            if (!cs->certStatusInfo.goodInfo)
                return NULL;
            break;
        case ocspCertStatus_unknown:
            cs->certStatusInfo.unknownInfo = SECITEM_AllocItem(arena, NULL, 0);
            if (!cs->certStatusInfo.unknownInfo)
                return NULL;
            break;
        case ocspCertStatus_revoked:
            cs->certStatusInfo.revokedInfo =
                PORT_ArenaZNew(arena, ocspRevokedInfo);
            if (!cs->certStatusInfo.revokedInfo)
                return NULL;
            cs->certStatusInfo.revokedInfo->revocationReason =
                SECITEM_AllocItem(arena, NULL, 0);
            if (!cs->certStatusInfo.revokedInfo->revocationReason)
                return NULL;
            if (DER_TimeToGeneralizedTimeArena(arena,
                    &cs->certStatusInfo.revokedInfo->revocationTime,
                    revocationTime) != SECSuccess)
                return NULL;
            break;
        default:
            PORT_Assert(PR_FALSE);
    }
    return cs;
}
/*
** Generate some random bytes, using the global random number generator
** object.  In DSA mode, so there is a q.
*/
static SECStatus 
dsa_GenerateGlobalRandomBytes(const SECItem * qItem, PRUint8 * dest,
                              unsigned int * destLen, unsigned int maxDestLen)
{
    SECStatus rv;
    SECItem w;
    const PRUint8 * q = qItem->data;
    unsigned int qLen = qItem->len;

    if (*q == 0) {
        ++q;
        --qLen;
    }
    if (maxDestLen < qLen) {
        /* This condition can occur when DSA_SignDigest is passed a group
           with a subprime that is larger than DSA_MAX_SUBPRIME_LEN. */
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }
    w.data = NULL; /* otherwise SECITEM_AllocItem asserts */
    if (!SECITEM_AllocItem(NULL, &w, 2*qLen)) {
        return SECFailure;
    }
    *destLen = qLen;

    rv = RNG_GenerateGlobalRandomBytes(w.data, w.len);
    if (rv == SECSuccess) {
        rv = fips186Change_ReduceModQForDSA(w.data, q, qLen, dest);
    }

    SECITEM_FreeItem(&w, PR_FALSE);
    return rv;
}
Example #4
0
/* 
 * NSS_CMSSignerInfo_AddSMIMECaps - add a SMIMECapabilities attribute to the
 * authenticated (i.e. signed) attributes of "signerinfo". 
 *
 * This is expected to be included in outgoing signed
 * messages for email (S/MIME).
 */
SECStatus
NSS_CMSSignerInfo_AddSMIMECaps(NSSCMSSignerInfo *signerinfo)
{
    NSSCMSAttribute *attr;
    SECItem *smimecaps = NULL;
    void *mark;
    PLArenaPool *poolp;

    poolp = signerinfo->cmsg->poolp;

    mark = PORT_ArenaMark(poolp);

    smimecaps = SECITEM_AllocItem(poolp, NULL, 0);
    if (smimecaps == NULL)
	goto loser;

    /* create new signing time attribute */
    if (NSS_SMIMEUtil_CreateSMIMECapabilities(poolp, smimecaps) != SECSuccess)
	goto loser;

    if ((attr = NSS_CMSAttribute_Create(poolp, SEC_OID_PKCS9_SMIME_CAPABILITIES, smimecaps, PR_TRUE)) == NULL)
	goto loser;

    if (NSS_CMSSignerInfo_AddAuthAttr(signerinfo, attr) != SECSuccess)
	goto loser;

    PORT_ArenaUnmark (poolp, mark);
    return SECSuccess;

loser:
    PORT_ArenaRelease (poolp, mark);
    return SECFailure;
}
Example #5
0
OSStatus
SecCmsContentInfoSetContentOther(SecCmsMessageRef cmsg, SecCmsContentInfoRef cinfo, CSSM_DATA_PTR data, Boolean detached, const CSSM_OID *eContentType)
{
    SECStatus srtn;
    SECOidData *tmpOidData;
    
    /* just like SecCmsContentInfoSetContentData, except override the contentType and
     * contentTypeTag. This OID is for encoding... */
    srtn = SECITEM_CopyItem (cmsg->poolp, &(cinfo->contentType), eContentType);
    if (srtn != SECSuccess) {
	return memFullErr;
    }
    
    /* this serves up a contentTypeTag with an empty OID */
    tmpOidData = SECOID_FindOIDByTag(SEC_OID_OTHER);
    /* but that's const: cook up a new one we can write to */
    cinfo->contentTypeTag = (SECOidData *)PORT_ArenaZAlloc(cmsg->poolp, sizeof(SECOidData));
    *cinfo->contentTypeTag = *tmpOidData;
    /* now fill in the OID */
    srtn = SECITEM_CopyItem (cmsg->poolp, &(cinfo->contentTypeTag->oid), eContentType);
    if (srtn != SECSuccess) {
	return memFullErr;
    }
    cinfo->content.pointer = data;
    cinfo->rawContent = (detached) ? 
			    NULL : (data) ? 
				data : SECITEM_AllocItem(cmsg->poolp, NULL, 1);
    return noErr;
}
NS_IMETHODIMP
nsNSSCertificateFakeTransport::Read(nsIObjectInputStream* aStream)
{
  // This serialization has to match that of nsNSSCertificate,
  // so read the cachedEVStatus but don't actually use it.
  uint32_t cachedEVStatus;
  nsresult rv = aStream->Read32(&cachedEVStatus);
  if (NS_FAILED(rv)) {
    return rv;
  }

  uint32_t len;
  rv = aStream->Read32(&len);
  if (NS_FAILED(rv)) {
    return rv;
  }

  nsXPIDLCString str;
  rv = aStream->ReadBytes(len, getter_Copies(str));
  if (NS_FAILED(rv)) {
    return rv;
  }

  // On a non-chrome process we cannot instatiate mCert because we lack
  // nsNSSComponent. nsNSSCertificateFakeTransport object is used only to
  // carry the certificate serialization.

  mCertSerialization = SECITEM_AllocItem(nullptr, nullptr, len);
  if (!mCertSerialization)
      return NS_ERROR_OUT_OF_MEMORY;
  PORT_Memcpy(mCertSerialization->data, str.Data(), len);

  return NS_OK;
}
Example #7
0
/*
 * SecCmsContentInfoSetContent - set content type & content
 */
OSStatus
SecCmsContentInfoSetContent(SecCmsMessageRef cmsg, SecCmsContentInfoRef cinfo, SECOidTag type, void *ptr)
{
    OSStatus rv;

    cinfo->contentTypeTag = SECOID_FindOIDByTag(type);
    if (cinfo->contentTypeTag == NULL)
	return paramErr;
    
    /* do not copy the oid, just create a reference */
    rv = SECITEM_CopyItem (cmsg->poolp, &(cinfo->contentType), &(cinfo->contentTypeTag->oid));
    if (rv != SECSuccess)
	return memFullErr;

    cinfo->content.pointer = ptr;

    if (type != SEC_OID_PKCS7_DATA) {
	/* as we always have some inner data,
	 * we need to set it to something, just to fool the encoder enough to work on it
	 * and get us into nss_cms_encoder_notify at that point */
	cinfo->rawContent = SECITEM_AllocItem(cmsg->poolp, NULL, 1);
	if (cinfo->rawContent == NULL) {
	    PORT_SetError(SEC_ERROR_NO_MEMORY);
	    return memFullErr;
	}
    }

    return noErr;
}
Example #8
0
File: nss.c Project: flashfoxter/sx
int sxi_hmac_sha1_init_ex(sxi_hmac_sha1_ctx *ctx,
                     const void *key, int key_len)
{
    if (!ctx)
        return 0;
    /* NOTE: params must be provided, but may be empty */
    SECItem noParams;
    noParams.type = siBuffer;
    noParams.data = 0;
    noParams.len = 0;

    if (ctx->context)
      PK11_DestroyContext(ctx->context, PR_TRUE);
    if (ctx->key)
        PK11_FreeSymKey(ctx->key);
    if (ctx->keysec)
        SECITEM_FreeItem(ctx->keysec, PR_TRUE);
    ctx->keysec = SECITEM_AllocItem(NULL, NULL, key_len);
    if (ctx->keysec) {
        memcpy(ctx->keysec->data, key, key_len);
        ctx->key = PK11_ImportSymKey(ctx->slot, CKM_SHA_1_HMAC, PK11_OriginDerive, CKA_SIGN,
                                     ctx->keysec, &noParams);
        if(ctx->key) {
            ctx->context = PK11_CreateContextBySymKey(CKM_SHA_1_HMAC, CKA_SIGN, ctx->key, &noParams);
            if (ctx->context && PK11_DigestBegin(ctx->context) == SECSuccess)
                return 1;
        }
    }
    return 0;
}
Example #9
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 #10
0
/* Caller must set error code upon failure */
static SECStatus
hexToBin(PLArenaPool *pool, SECItem * destItem, const char * src, int len)
{
    PRUint8 * dest;

    destItem->data = NULL;
    if (len <= 0 || (len & 1)) {
        goto loser;
    }
    len >>= 1;
    if (!SECITEM_AllocItem(pool, destItem, len))
        goto loser;
    dest = destItem->data;
    for (; len > 0; len--, src += 2) {
        PRInt16 bin = (x2b[(PRUint8)src[0]] << 4) | x2b[(PRUint8)src[1]];
        if (bin < 0)
            goto loser;
        *dest++ = (PRUint8)bin;
    }
    return SECSuccess;
loser:
    if (!pool)
        SECITEM_FreeItem(destItem, PR_FALSE);
    return SECFailure;
}
Example #11
0
SECStatus
SECU_FileToItem(SECItem *dst, PRFileDesc *src)
{
    PRFileInfo info;
    PRInt32 numBytes;
    PRStatus prStatus;

    if (src == PR_STDIN)
        return secu_StdinToItem(dst);

    prStatus = PR_GetOpenFileInfo(src, &info);

    if (prStatus != PR_SUCCESS) {
        PORT_SetError(SEC_ERROR_IO);
        return SECFailure;
    }

    /* XXX workaround for 3.1, not all utils zero dst before sending */
    dst->data = 0;
    if (!SECITEM_AllocItem(NULL, dst, info.size))
        goto loser;

    numBytes = PR_Read(src, dst->data, info.size);
    if (numBytes != info.size) {
        PORT_SetError(SEC_ERROR_IO);
        goto loser;
    }

    return SECSuccess;
loser:
    SECITEM_FreeItem(dst, PR_FALSE);
    dst->data = NULL;
    return SECFailure;
}
Example #12
0
/* MAC is generated per PKCS 12 section 6.  It is expected that key, msg
 * and mac_dest are pre allocated, non-NULL arrays.  msg_len is passed in
 * because it is not known how long the message actually is.  String
 * manipulation routines will not necessarily work because msg may have
 * imbedded NULLs
 */
SECItem *
sec_pkcs12_generate_mac(SECItem *key, 
			SECItem *msg,
			PRBool old_method)
{
    SECStatus res = SECFailure;
    SECItem *mac = NULL;
    PK11Context *pk11cx = NULL;    
    SECItem ignore = {0};

    if((key == NULL) || (msg == NULL)) {
	return NULL;
    }

    if(old_method == PR_TRUE) {
	return sec_pkcs12_generate_old_mac(key, msg);
    }

    /* allocate return item */
    mac = SECITEM_AllocItem(NULL, NULL, SHA1_LENGTH);
    if (mac == NULL) {
	return NULL;
    }

    pk11cx = PK11_CreateContextByRawKey(NULL, CKM_SHA_1_HMAC, PK11_OriginDerive,
                                        CKA_SIGN, key, &ignore, NULL);
    if (pk11cx == NULL) {
	goto loser;
    }

    res = PK11_DigestBegin(pk11cx);
    if (res == SECFailure) {
	goto loser;
    }

    res = PK11_DigestOp(pk11cx, msg->data, msg->len);
    if (res == SECFailure) {
	goto loser;
    }

    res = PK11_DigestFinal(pk11cx, mac->data, &mac->len, SHA1_LENGTH);
    if (res == SECFailure) {
	goto loser;
    }

    PK11_DestroyContext(pk11cx, PR_TRUE);
    pk11cx = NULL;

loser:

    if(res != SECSuccess) {
	SECITEM_ZfreeItem(mac, PR_TRUE);
	mac = NULL;
	if (pk11cx) {
	    PK11_DestroyContext(pk11cx, PR_TRUE);
	}
    }

    return mac;
}
Example #13
0
SECStatus
ssl_NamedGroup2ECParams(PLArenaPool *arena, const sslNamedGroupDef *ecGroup,
                        SECKEYECParams *params)
{
    SECOidData *oidData = NULL;

    if (!params) {
        PORT_Assert(0);
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }

    if (!ecGroup || ecGroup->keaType != ssl_kea_ecdh ||
        (oidData = SECOID_FindOIDByTag(ecGroup->oidTag)) == NULL) {
        PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE);
        return SECFailure;
    }

    if (SECITEM_AllocItem(arena, params, (2 + oidData->oid.len)) == NULL) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return SECFailure;
    }

    /*
     * params->data needs to contain the ASN encoding of an object ID (OID)
     * representing the named curve. The actual OID is in
     * oidData->oid.data so we simply prepend 0x06 and OID length
     */
    params->data[0] = SEC_ASN1_OBJECT_ID;
    params->data[1] = oidData->oid.len;
    memcpy(params->data + 2, oidData->oid.data, oidData->oid.len);

    return SECSuccess;
}
Example #14
0
SECStatus
EC_DecodeParams(const SECItem *encodedParams, ECParams **ecparams)
{
    PLArenaPool *arena;
    ECParams *params;
    SECStatus rv = SECFailure;

    /* Initialize an arena for the ECParams structure */
    if (!(arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE)))
        return SECFailure;

    params = (ECParams *)PORT_ArenaZAlloc(arena, sizeof(ECParams));
    if (!params) {
        PORT_FreeArena(arena, PR_TRUE);
        return SECFailure;
    }

    /* Copy the encoded params */
    SECITEM_AllocItem(arena, &(params->DEREncoding),
                      encodedParams->len);
    memcpy(params->DEREncoding.data, encodedParams->data, encodedParams->len);

    /* Fill out the rest of the ECParams structure based on
     * the encoded params
     */
    rv = EC_FillParams(arena, encodedParams, params);
    if (rv == SECFailure) {
        PORT_FreeArena(arena, PR_TRUE);
        return SECFailure;
    } else {
        *ecparams = params;
        ;
        return SECSuccess;
    }
}
Example #15
0
int
generate_algorithm_id(cms_context *ctx, SECAlgorithmID *idp, SECOidTag tag)
{
	SECAlgorithmID id;

	if (!idp)
		return -1;

	SECOidData *oiddata;
	oiddata = SECOID_FindOIDByTag(tag);
	if (!oiddata) {
		PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
		return -1;
	}
	if (SECITEM_CopyItem(ctx->arena, &id.algorithm, &oiddata->oid))
		return -1;

	SECITEM_AllocItem(ctx->arena, &id.parameters, 2);
	if (id.parameters.data == NULL)
		goto err;
	id.parameters.data[0] = SEC_ASN1_NULL;
	id.parameters.data[1] = 0;
	id.parameters.type = siBuffer;

	memcpy(idp, &id, sizeof (id));
	return 0;

err:
	SECITEM_FreeItem(&id.algorithm, PR_FALSE);
	return -1;
}
Example #16
0
File: ssl3ecc.c Project: nmav/nss
SECStatus 
ssl3_ECName2Params(PLArenaPool * arena, ECName curve, SECKEYECParams * params)
{
    SECOidData *oidData = NULL;
    PRUint32 policyFlags = 0;

    if ((curve <= ec_noName) || (curve >= ec_pastLastName) ||
	((oidData = SECOID_FindOIDByTag(ecName2OIDTag[curve])) == NULL)) {
        PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE);
	return SECFailure;
    }

    if (NSS_GetAlgorithmPolicy(ecName2OIDTag[curve], &policyFlags) == SECFailure ||
    	!(policyFlags & NSS_USE_ALG_IN_SSL_KX)) {
        PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE);
	return SECFailure;
    }

    SECITEM_AllocItem(arena, params, (2 + oidData->oid.len));
    /* 
     * params->data needs to contain the ASN encoding of an object ID (OID)
     * representing the named curve. The actual OID is in 
     * oidData->oid.data so we simply prepend 0x06 and OID length
     */
    params->data[0] = SEC_ASN1_OBJECT_ID;
    params->data[1] = oidData->oid.len;
    memcpy(params->data + 2, oidData->oid.data, oidData->oid.len);

    return SECSuccess;
}
Example #17
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;
}
NS_IMETHODIMP
nsNSSCertificateFakeTransport::Read(nsIObjectInputStream* aStream)
{
  PRUint32 len;
  nsresult rv = aStream->Read32(&len);
  if (NS_FAILED(rv)) {
    return rv;
  }

  nsXPIDLCString str;
  rv = aStream->ReadBytes(len, getter_Copies(str));
  if (NS_FAILED(rv)) {
    return rv;
  }

  // On a non-chrome process we cannot instatiate mCert because we lack
  // nsNSSComponent.  nsNSSCertificateFakeTransport object is used only to carry the
  // certificate serialization.

  mCertSerialization = SECITEM_AllocItem(nsnull, nsnull, len);
  if (!mCertSerialization)
      return NS_ERROR_OUT_OF_MEMORY;
  PORT_Memcpy(mCertSerialization->data, str.Data(), len);

  return NS_OK;
}
Example #19
0
static SECStatus nss_load_crl(const char* crlfilename)
{
  PRFileDesc *infile;
  PRFileInfo  info;
  SECItem filedata = { 0, NULL, 0 };
  SECItem crlDER = { 0, NULL, 0 };
  char *body;

  infile = PR_Open(crlfilename, PR_RDONLY, 0);
  if(!infile)
    return SECFailure;

  if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
    goto fail;

  if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
    goto fail;

  if(info.size != PR_Read(infile, filedata.data, info.size))
    goto fail;

  /* place a trailing zero right after the visible data */
  body = (char*)filedata.data;
  body[--filedata.len] = '\0';

  body = strstr(body, "-----BEGIN");
  if(body) {
    /* assume ASCII */
    char *trailer;
    char *begin = PORT_Strchr(body, '\n');
    if(!begin)
      begin = PORT_Strchr(body, '\r');
    if(!begin)
      goto fail;

    trailer = strstr(++begin, "-----END");
    if(!trailer)
      goto fail;

    /* retrieve DER from ASCII */
    *trailer = '\0';
    if(ATOB_ConvertAsciiToItem(&crlDER, begin))
      goto fail;

    SECITEM_FreeItem(&filedata, PR_FALSE);
  }
  else
    /* assume DER */
    crlDER = filedata;

  PR_Close(infile);
  return nss_cache_crl(&crlDER);

fail:
  PR_Close(infile);
  SECITEM_FreeItem(&filedata, PR_FALSE);
  return SECFailure;
}
Example #20
0
/*
 * NSS_CMSSignedData_SetDigests - set a signedData's digests member
 *
 * "digestalgs" - array of digest algorithm IDs
 * "digests"    - array of digests corresponding to the digest algorithms
 */
SECStatus
NSS_CMSSignedData_SetDigests(NSSCMSSignedData *sigd,
                             SECAlgorithmID **digestalgs,
                             SECItem **digests)
{
    int cnt, i, idx;

    if (!sigd || !digestalgs || !digests) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }

    if (sigd->digestAlgorithms == NULL) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
    }

    /* we assume that the digests array is just not there yet */
    PORT_Assert(sigd->digests == NULL);
    if (sigd->digests != NULL) {
        PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
        return SECFailure;
    }

    /* now allocate one (same size as digestAlgorithms) */
    cnt = NSS_CMSArray_Count((void **)sigd->digestAlgorithms);
    sigd->digests = PORT_ArenaZAlloc(sigd->cmsg->poolp, (cnt + 1) * sizeof(SECItem *));
    if (sigd->digests == NULL) {
        PORT_SetError(SEC_ERROR_NO_MEMORY);
        return SECFailure;
    }

    for (i = 0; sigd->digestAlgorithms[i] != NULL; i++) {
        /* try to find the sigd's i'th digest algorithm in the array we passed in */
        idx = NSS_CMSAlgArray_GetIndexByAlgID(digestalgs, sigd->digestAlgorithms[i]);
        if (idx < 0) {
            PORT_SetError(SEC_ERROR_DIGEST_NOT_FOUND);
            return SECFailure;
        }
        if (!digests[idx]) {
            /* We have no digest for this algorithm, probably because it is
            ** unrecognized or unsupported.  We'll ignore this here.  If this
            ** digest is needed later, an error will be be generated then.
            */
            continue;
        }

        /* found it - now set it */
        if ((sigd->digests[i] = SECITEM_AllocItem(sigd->cmsg->poolp, NULL, 0)) == NULL ||
                SECITEM_CopyItem(sigd->cmsg->poolp, sigd->digests[i], digests[idx]) != SECSuccess)
        {
            PORT_SetError(SEC_ERROR_NO_MEMORY);
            return SECFailure;
        }
    }
    return SECSuccess;
}
Example #21
0
static int
xmlSecNssAppReadSECItem(SECItem *contents, const char *fn) {
    PRFileInfo info;
    PRFileDesc *file = NULL;
    PRInt32 numBytes;
    PRStatus prStatus;
    int ret = -1;

    xmlSecAssert2(contents != NULL, -1);
    xmlSecAssert2(fn != NULL, -1);

    file = PR_Open(fn, PR_RDONLY, 00660);
    if (file == NULL) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "PR_Open",
                    XMLSEC_ERRORS_R_IO_FAILED,
                    "filename=%s",
                    xmlSecErrorsSafeString(fn));
        goto done;
    }

    prStatus = PR_GetOpenFileInfo(file, &info);
    if (prStatus != PR_SUCCESS) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "PR_GetOpenFileInfo",
                    XMLSEC_ERRORS_R_IO_FAILED,
                    "filename=%s",
                    xmlSecErrorsSafeString(fn));
        goto done;
    }

    contents->data = 0;
    if (!SECITEM_AllocItem(NULL, contents, info.size)) {
        xmlSecError(XMLSEC_ERRORS_HERE,
                    NULL,
                    "SECITEM_AllocItem",
                    XMLSEC_ERRORS_R_CRYPTO_FAILED,
                    XMLSEC_ERRORS_NO_MESSAGE);
        goto done;
    }

    numBytes = PR_Read(file, contents->data, info.size);
    if (numBytes != info.size) {
        SECITEM_FreeItem(contents, PR_FALSE);
        goto done;
    }

    ret = 0;
done:
    if (file) {
        PR_Close(file);
    }

    return (ret);
}
Example #22
0
/*
 * data == NULL -> pass in data via SecCmsEncoderUpdate
 * data != NULL -> take this data
 */
OSStatus
SecCmsContentInfoSetContentData(SecCmsMessageRef cmsg, SecCmsContentInfoRef cinfo, CSSM_DATA_PTR data, Boolean detached)
{
    if (SecCmsContentInfoSetContent(cmsg, cinfo, SEC_OID_PKCS7_DATA, (void *)data) != SECSuccess)
	return PORT_GetError();
    cinfo->rawContent = (detached) ? 
			    NULL : (data) ? 
				data : SECITEM_AllocItem(cmsg->poolp, NULL, 1);
    return noErr;
}
Example #23
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 #24
0
SECStatus
SECU_TextFileToItem(SECItem *dst, PRFileDesc *src)
{
    PRFileInfo info;
    PRInt32 numBytes;
    PRStatus prStatus;
    unsigned char *buf;

    if (src == PR_STDIN)
        return secu_StdinToItem(dst);

    prStatus = PR_GetOpenFileInfo(src, &info);

    if (prStatus != PR_SUCCESS) {
        PORT_SetError(SEC_ERROR_IO);
        return SECFailure;
    }

    buf = (unsigned char *)PORT_Alloc(info.size);
    if (!buf)
        return SECFailure;

    numBytes = PR_Read(src, buf, info.size);
    if (numBytes != info.size) {
        PORT_SetError(SEC_ERROR_IO);
        goto loser;
    }

    if (buf[numBytes - 1] == '\n')
        numBytes--;
#ifdef _WINDOWS
    if (buf[numBytes - 1] == '\r')
        numBytes--;
#endif

    /* XXX workaround for 3.1, not all utils zero dst before sending */
    dst->data = 0;
    if (!SECITEM_AllocItem(NULL, dst, numBytes))
        goto loser;

    memcpy(dst->data, buf, numBytes);

    PORT_Free(buf);
    return SECSuccess;
loser:
    PORT_Free(buf);
    return SECFailure;
}
Example #25
0
/*
 * Initializes a SECItem from a hexadecimal string
 *
 * Warning: This function ignores leading 00's, so any leading 00's
 * in the hexadecimal string must be optional.
 */
static SECItem *
hexString2SECItem(PLArenaPool *arena, SECItem *item, const char *str)
{
    int i = 0;
    int byteval = 0;
    int tmp = PORT_Strlen(str);

    PORT_Assert(arena);
    PORT_Assert(item);

    if ((tmp % 2) != 0) {
        return NULL;
    }

    /* skip leading 00's unless the hex string is "00" */
    while ((tmp > 2) && (str[0] == '0') && (str[1] == '0')) {
        str += 2;
        tmp -= 2;
    }

    item = SECITEM_AllocItem(arena, item, tmp / 2);
    if (item == NULL) {
        return NULL;
    }

    while (str[i]) {
        if ((str[i] >= '0') && (str[i] <= '9')) {
            tmp = str[i] - '0';
        } else if ((str[i] >= 'a') && (str[i] <= 'f')) {
            tmp = str[i] - 'a' + 10;
        } else if ((str[i] >= 'A') && (str[i] <= 'F')) {
            tmp = str[i] - 'A' + 10;
        } else {
            /* item is in arena and gets freed by the caller */
            return NULL;
        }

        byteval = byteval * 16 + tmp;
        if ((i % 2) != 0) {
            item->data[i / 2] = byteval;
            byteval = 0;
        }
        i++;
    }

    return item;
}
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 #27
0
/*
 * SecCmsSignedDataSetDigests - set a signedData's digests member
 *
 * "digestalgs" - array of digest algorithm IDs
 * "digests"    - array of digests corresponding to the digest algorithms
 */
OSStatus
SecCmsSignedDataSetDigests(SecCmsSignedDataRef sigd,
				SECAlgorithmID **digestalgs,
				CSSM_DATA_PTR *digests)
{
    int cnt, i, idx;

    if (sigd->digestAlgorithms == NULL) {
	PORT_SetError(SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }

    /* we assume that the digests array is just not there yet */
    PORT_Assert(sigd->digests == NULL);
    if (sigd->digests != NULL) {
	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
	return SECFailure;
    }

    /* now allocate one (same size as digestAlgorithms) */
    cnt = SecCmsArrayCount((void **)sigd->digestAlgorithms);
    sigd->digests = PORT_ArenaZAlloc(sigd->cmsg->poolp, (cnt + 1) * sizeof(CSSM_DATA_PTR));
    if (sigd->digests == NULL) {
	PORT_SetError(SEC_ERROR_NO_MEMORY);
	return SECFailure;
    }

    for (i = 0; sigd->digestAlgorithms[i] != NULL; i++) {
	/* try to find the sigd's i'th digest algorithm in the array we passed in */
	idx = SecCmsAlgArrayGetIndexByAlgID(digestalgs, sigd->digestAlgorithms[i]);
	if (idx < 0) {
	    PORT_SetError(SEC_ERROR_DIGEST_NOT_FOUND);
	    return SECFailure;
	}

	/* found it - now set it */
	if ((sigd->digests[i] = SECITEM_AllocItem(sigd->cmsg->poolp, NULL, 0)) == NULL ||
	    SECITEM_CopyItem(sigd->cmsg->poolp, sigd->digests[i], digests[idx]) != SECSuccess)
	{
	    PORT_SetError(SEC_ERROR_NO_MEMORY);
	    return SECFailure;
	}
    }
    return SECSuccess;
}
Example #28
0
/* 
 * SecCmsSignerInfoAddMSSMIMEEncKeyPrefs - add a SMIMEEncryptionKeyPreferences attribute to the
 * authenticated (i.e. signed) attributes of "signerinfo", using the OID prefered by Microsoft.
 *
 * This is expected to be included in outgoing signed messages for email (S/MIME),
 * if compatibility with Microsoft mail clients is wanted.
 */
OSStatus
SecCmsSignerInfoAddMSSMIMEEncKeyPrefs(SecCmsSignerInfoRef signerinfo, SecCertificateRef cert, SecKeychainRef keychainOrArray)
{
    SecCmsAttribute *attr;
    CSSM_DATA_PTR smimeekp = NULL;
    void *mark;
    PLArenaPool *poolp;

#if 0
    CFTypeRef policy;

    /* verify this cert for encryption */
    policy = CERT_PolicyForCertUsage(certUsageEmailRecipient);
    if (CERT_VerifyCert(keychainOrArray, cert, policy, CFAbsoluteTimeGetCurrent(), NULL) != SECSuccess) {
	CFRelease(policy);
	return SECFailure;
    }
    CFRelease(policy);
#endif

    poolp = signerinfo->cmsg->poolp;
    mark = PORT_ArenaMark(poolp);

    smimeekp = SECITEM_AllocItem(poolp, NULL, 0);
    if (smimeekp == NULL)
	goto loser;

    /* create new signing time attribute */
    if (SecSMIMECreateMSSMIMEEncKeyPrefs((SecArenaPoolRef)poolp, smimeekp, cert) != SECSuccess)
	goto loser;

    if ((attr = SecCmsAttributeCreate(poolp, SEC_OID_MS_SMIME_ENCRYPTION_KEY_PREFERENCE, smimeekp, PR_TRUE)) == NULL)
	goto loser;

    if (SecCmsSignerInfoAddAuthAttr(signerinfo, attr) != SECSuccess)
	goto loser;

    PORT_ArenaUnmark (poolp, mark);
    return SECSuccess;

loser:
    PORT_ArenaRelease (poolp, mark);
    return SECFailure;
}
Example #29
0
static CERTOCSPSingleResponse*
ocsp_CreateSingleResponse(PLArenaPool *arena,
                          CERTOCSPCertID *id, ocspCertStatus *status,
                          PRTime thisUpdate, const PRTime *nextUpdate)
{
    CERTOCSPSingleResponse *sr;

    if (!arena || !id || !status) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return NULL;
    }

    sr = PORT_ArenaZNew(arena, CERTOCSPSingleResponse);
    if (!sr)
        return NULL;
    sr->arena = arena;
    sr->certID = id;
    sr->certStatus = status;
    if (DER_TimeToGeneralizedTimeArena(arena, &sr->thisUpdate, thisUpdate)
             != SECSuccess)
        return NULL;
    sr->nextUpdate = NULL;
    if (nextUpdate) {
        sr->nextUpdate = SECITEM_AllocItem(arena, NULL, 0);
        if (!sr->nextUpdate)
            return NULL;
        if (DER_TimeToGeneralizedTimeArena(arena, sr->nextUpdate, *nextUpdate)
             != SECSuccess)
            return NULL;
    }

    sr->singleExtensions = PORT_ArenaNewArray(arena, CERTCertExtension*, 1);
    if (!sr->singleExtensions)
        return NULL;

    sr->singleExtensions[0] = NULL;
    
    if (!SEC_ASN1EncodeItem(arena, &sr->derCertStatus,
                            status, ocsp_CertStatusTemplate))
        return NULL;

    return sr;
}
/*
 * SecCmsAttributeCreate - create an attribute
 *
 * if value is NULL, the attribute won't have a value. It can be added later
 * with SecCmsAttributeAddValue.
 */
SecCmsAttribute *
SecCmsAttributeCreate(PRArenaPool *poolp, SECOidTag oidtag, CSSM_DATA_PTR value, Boolean encoded)
{
    SecCmsAttribute *attr;
    CSSM_DATA_PTR copiedvalue;
    void *mark;

    PORT_Assert (poolp != NULL);

    mark = PORT_ArenaMark (poolp);

    attr = (SecCmsAttribute *)PORT_ArenaZAlloc(poolp, sizeof(SecCmsAttribute));
    if (attr == NULL)
	goto loser;

    attr->typeTag = SECOID_FindOIDByTag(oidtag);
    if (attr->typeTag == NULL)
	goto loser;

    if (SECITEM_CopyItem(poolp, &(attr->type), &(attr->typeTag->oid)) != SECSuccess)
	goto loser;

    if (value != NULL) {
	if ((copiedvalue = SECITEM_AllocItem(poolp, NULL, (unsigned int)value->Length)) == NULL)
	    goto loser;

	if (SECITEM_CopyItem(poolp, copiedvalue, value) != SECSuccess)
	    goto loser;

	SecCmsArrayAdd(poolp, (void ***)&(attr->values), (void *)copiedvalue);
    }

    attr->encoded = encoded;

    PORT_ArenaUnmark (poolp, mark);

    return attr;

loser:
    PORT_Assert (mark != NULL);
    PORT_ArenaRelease (poolp, mark);
    return NULL;
}