2 * Copyright (c) 2003 - 2007 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the Institute nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * @page page_cms CMS/PKCS7 message functions.
39 * CMS is defined in RFC 3369 and is an continuation of the RSA Labs
40 * standard PKCS7. The basic messages in CMS is
43 * Data signed with private key (RSA, DSA, ECDSA) or secret
46 * Data encrypted with private key (RSA)
48 * Data encrypted with secret (symmetric) key.
50 * Wrapper structure including type and data.
53 * See the library functions here: @ref hx509_cms
56 #define ALLOC(X, N) (X) = calloc((N), sizeof(*(X)))
57 #define ALLOC_SEQ(X, N) do { (X)->len = (N); ALLOC((X)->val, (N)); } while(0)
60 * Wrap data and oid in a ContentInfo and encode it.
62 * @param oid type of the content.
63 * @param buf data to be wrapped. If a NULL pointer is passed in, the
64 * optional content field in the ContentInfo is not going be filled
66 * @param res the encoded buffer, the result should be freed with
67 * der_free_octet_string().
69 * @return Returns an hx509 error code.
75 hx509_cms_wrap_ContentInfo(const heim_oid
*oid
,
76 const heim_octet_string
*buf
,
77 heim_octet_string
*res
)
83 memset(res
, 0, sizeof(*res
));
84 memset(&ci
, 0, sizeof(ci
));
86 ret
= der_copy_oid(oid
, &ci
.contentType
);
91 if (ci
.content
== NULL
) {
92 free_ContentInfo(&ci
);
95 ci
.content
->data
= malloc(buf
->length
);
96 if (ci
.content
->data
== NULL
) {
97 free_ContentInfo(&ci
);
100 memcpy(ci
.content
->data
, buf
->data
, buf
->length
);
101 ci
.content
->length
= buf
->length
;
104 ASN1_MALLOC_ENCODE(ContentInfo
, res
->data
, res
->length
, &ci
, &size
, ret
);
105 free_ContentInfo(&ci
);
108 if (res
->length
!= size
)
109 _hx509_abort("internal ASN.1 encoder error");
115 * Decode an ContentInfo and unwrap data and oid it.
117 * @param in the encoded buffer.
118 * @param oid type of the content.
119 * @param out data to be wrapped.
120 * @param have_data since the data is optional, this flags show dthe
121 * diffrence between no data and the zero length data.
123 * @return Returns an hx509 error code.
129 hx509_cms_unwrap_ContentInfo(const heim_octet_string
*in
,
131 heim_octet_string
*out
,
138 memset(oid
, 0, sizeof(*oid
));
139 memset(out
, 0, sizeof(*out
));
141 ret
= decode_ContentInfo(in
->data
, in
->length
, &ci
, &size
);
145 ret
= der_copy_oid(&ci
.contentType
, oid
);
147 free_ContentInfo(&ci
);
151 ret
= der_copy_octet_string(ci
.content
, out
);
154 free_ContentInfo(&ci
);
158 memset(out
, 0, sizeof(*out
));
161 *have_data
= (ci
.content
!= NULL
) ? 1 : 0;
163 free_ContentInfo(&ci
);
169 #define CMS_ID_NAME 1
172 fill_CMSIdentifier(const hx509_cert cert
,
180 id
->element
= choice_CMSIdentifier_subjectKeyIdentifier
;
181 ret
= _hx509_find_extension_subject_key_id(_hx509_get_cert(cert
),
182 &id
->u
.subjectKeyIdentifier
);
189 id
->element
= choice_CMSIdentifier_issuerAndSerialNumber
;
190 ret
= hx509_cert_get_issuer(cert
, &name
);
193 ret
= hx509_name_to_Name(name
, &id
->u
.issuerAndSerialNumber
.issuer
);
194 hx509_name_free(&name
);
198 ret
= hx509_cert_get_serialnumber(cert
, &id
->u
.issuerAndSerialNumber
.serialNumber
);
202 _hx509_abort("CMS fill identifier with unknown type");
208 unparse_CMSIdentifier(hx509_context context
,
215 switch (id
->element
) {
216 case choice_CMSIdentifier_issuerAndSerialNumber
: {
217 IssuerAndSerialNumber
*iasn
;
220 iasn
= &id
->u
.issuerAndSerialNumber
;
222 ret
= _hx509_Name_to_string(&iasn
->issuer
, &name
);
225 ret
= der_print_hex_heim_integer(&iasn
->serialNumber
, &serial
);
230 asprintf(str
, "certificate issued by %s with serial number %s",
236 case choice_CMSIdentifier_subjectKeyIdentifier
: {
237 KeyIdentifier
*ki
= &id
->u
.subjectKeyIdentifier
;
241 len
= hex_encode(ki
->data
, ki
->length
, &keyid
);
245 asprintf(str
, "certificate with id %s", keyid
);
250 asprintf(str
, "certificate have unknown CMSidentifier type");
259 find_CMSIdentifier(hx509_context context
,
260 CMSIdentifier
*client
,
263 hx509_cert
*signer_cert
,
271 memset(&c
, 0, sizeof(c
));
272 _hx509_query_clear(&q
);
276 switch (client
->element
) {
277 case choice_CMSIdentifier_issuerAndSerialNumber
:
278 q
.serial
= &client
->u
.issuerAndSerialNumber
.serialNumber
;
279 q
.issuer_name
= &client
->u
.issuerAndSerialNumber
.issuer
;
280 q
.match
= HX509_QUERY_MATCH_SERIALNUMBER
|HX509_QUERY_MATCH_ISSUER_NAME
;
282 case choice_CMSIdentifier_subjectKeyIdentifier
:
283 q
.subject_id
= &client
->u
.subjectKeyIdentifier
;
284 q
.match
= HX509_QUERY_MATCH_SUBJECT_KEY_ID
;
287 hx509_set_error_string(context
, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
288 "unknown CMS identifier element");
289 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
294 q
.match
|= HX509_QUERY_MATCH_TIME
;
296 q
.timenow
= time_now
;
298 q
.timenow
= time(NULL
);
300 ret
= hx509_certs_find(context
, certs
, &q
, &cert
);
301 if (ret
== HX509_CERT_NOT_FOUND
) {
304 ret
= unparse_CMSIdentifier(context
, client
, &str
);
306 hx509_set_error_string(context
, 0,
307 HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
308 "Failed to find %s", str
);
310 hx509_clear_error_string(context
);
311 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
313 hx509_set_error_string(context
, HX509_ERROR_APPEND
,
314 HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
315 "Failed to find CMS id in cert store");
316 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
325 * Decode and unencrypt EnvelopedData.
327 * Extract data and parameteres from from the EnvelopedData. Also
328 * supports using detached EnvelopedData.
330 * @param context A hx509 context.
331 * @param certs Certificate that can decrypt the EnvelopedData
333 * @param flags HX509_CMS_UE flags to control the behavior.
334 * @param data pointer the structure the contains the DER/BER encoded
335 * EnvelopedData stucture.
336 * @param length length of the data that data point to.
337 * @param encryptedContent in case of detached signature, this
338 * contains the actual encrypted data, othersize its should be NULL.
339 * @param time_now set the current time, if zero the library uses now as the date.
340 * @param contentType output type oid, should be freed with der_free_oid().
341 * @param content the data, free with der_free_octet_string().
347 hx509_cms_unenvelope(hx509_context context
,
352 const heim_octet_string
*encryptedContent
,
354 heim_oid
*contentType
,
355 heim_octet_string
*content
)
357 heim_octet_string key
;
360 AlgorithmIdentifier
*ai
;
361 const heim_octet_string
*enccontent
;
362 heim_octet_string
*params
, params_data
;
363 heim_octet_string ivec
;
365 int ret
, matched
= 0, findflags
= 0;
369 memset(&key
, 0, sizeof(key
));
370 memset(&ed
, 0, sizeof(ed
));
371 memset(&ivec
, 0, sizeof(ivec
));
372 memset(content
, 0, sizeof(*content
));
373 memset(contentType
, 0, sizeof(*contentType
));
375 if ((flags
& HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT
) == 0)
376 findflags
|= HX509_QUERY_KU_ENCIPHERMENT
;
378 ret
= decode_EnvelopedData(data
, length
, &ed
, &size
);
380 hx509_set_error_string(context
, 0, ret
,
381 "Failed to decode EnvelopedData");
385 if (ed
.recipientInfos
.len
== 0) {
386 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
387 hx509_set_error_string(context
, 0, ret
,
388 "No recipient info in enveloped data");
392 enccontent
= ed
.encryptedContentInfo
.encryptedContent
;
393 if (enccontent
== NULL
) {
394 if (encryptedContent
== NULL
) {
395 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
396 hx509_set_error_string(context
, 0, ret
,
397 "Content missing from encrypted data");
400 enccontent
= encryptedContent
;
401 } else if (encryptedContent
!= NULL
) {
402 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
403 hx509_set_error_string(context
, 0, ret
,
404 "Both internal and external encrypted data");
409 for (i
= 0; i
< ed
.recipientInfos
.len
; i
++) {
410 KeyTransRecipientInfo
*ri
;
414 ri
= &ed
.recipientInfos
.val
[i
];
416 ret
= find_CMSIdentifier(context
, &ri
->rid
, certs
,
418 HX509_QUERY_PRIVATE_KEY
|findflags
);
422 matched
= 1; /* found a matching certificate, let decrypt */
424 ret
= _hx509_cert_private_decrypt(context
,
426 &ri
->keyEncryptionAlgorithm
.algorithm
,
429 hx509_cert_free(cert
);
431 break; /* succuessfully decrypted cert */
433 ret2
= unparse_CMSIdentifier(context
, &ri
->rid
, &str
);
435 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
436 "Failed to decrypt with %s", str
);
442 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
443 hx509_set_error_string(context
, 0, ret
,
444 "No private key matched any certificate");
449 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
450 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
451 "No private key decrypted the transfer key");
455 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
457 hx509_set_error_string(context
, 0, ret
,
458 "Failed to copy EnvelopedData content oid");
462 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
463 if (ai
->parameters
) {
464 params_data
.data
= ai
->parameters
->data
;
465 params_data
.length
= ai
->parameters
->length
;
466 params
= ¶ms_data
;
473 ret
= hx509_crypto_init(context
, NULL
, &ai
->algorithm
, &crypto
);
477 if (flags
& HX509_CMS_UE_ALLOW_WEAK
)
478 hx509_crypto_allow_weak(crypto
);
481 ret
= hx509_crypto_set_params(context
, crypto
, params
, &ivec
);
483 hx509_crypto_destroy(crypto
);
488 ret
= hx509_crypto_set_key_data(crypto
, key
.data
, key
.length
);
490 hx509_crypto_destroy(crypto
);
491 hx509_set_error_string(context
, 0, ret
,
492 "Failed to set key for decryption "
497 ret
= hx509_crypto_decrypt(crypto
,
500 ivec
.length
? &ivec
: NULL
,
502 hx509_crypto_destroy(crypto
);
504 hx509_set_error_string(context
, 0, ret
,
505 "Failed to decrypt EnvelopedData");
512 free_EnvelopedData(&ed
);
513 der_free_octet_string(&key
);
515 der_free_octet_string(&ivec
);
517 der_free_oid(contentType
);
518 der_free_octet_string(content
);
525 * Encrypt end encode EnvelopedData.
527 * Encrypt and encode EnvelopedData. The data is encrypted with a
528 * random key and the the random key is encrypted with the
529 * certificates private key. This limits what private key type can be
532 * @param context A hx509 context.
533 * @param flags flags to control the behavior.
534 * - HX509_CMS_EV_NO_KU_CHECK - Dont check KU on certificate
535 * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crytpo
536 * - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number
537 * @param cert Certificate to encrypt the EnvelopedData encryption key
539 * @param data pointer the data to encrypt.
540 * @param length length of the data that data point to.
541 * @param encryption_type Encryption cipher to use for the bulk data,
542 * use NULL to get default.
543 * @param contentType type of the data that is encrypted
544 * @param content the output of the function,
545 * free with der_free_octet_string().
551 hx509_cms_envelope_1(hx509_context context
,
556 const heim_oid
*encryption_type
,
557 const heim_oid
*contentType
,
558 heim_octet_string
*content
)
560 KeyTransRecipientInfo
*ri
;
561 heim_octet_string ivec
;
562 heim_octet_string key
;
563 hx509_crypto crypto
= NULL
;
568 memset(&ivec
, 0, sizeof(ivec
));
569 memset(&key
, 0, sizeof(key
));
570 memset(&ed
, 0, sizeof(ed
));
571 memset(content
, 0, sizeof(*content
));
573 if (encryption_type
== NULL
)
574 encryption_type
= &asn1_oid_id_aes_256_cbc
;
576 if ((flags
& HX509_CMS_EV_NO_KU_CHECK
) == 0) {
577 ret
= _hx509_check_key_usage(context
, cert
, 1 << 2, TRUE
);
582 ret
= hx509_crypto_init(context
, NULL
, encryption_type
, &crypto
);
586 if (flags
& HX509_CMS_EV_ALLOW_WEAK
)
587 hx509_crypto_allow_weak(crypto
);
589 ret
= hx509_crypto_set_random_key(crypto
, &key
);
591 hx509_set_error_string(context
, 0, ret
,
592 "Create random key for EnvelopedData content");
596 ret
= hx509_crypto_random_iv(crypto
, &ivec
);
598 hx509_set_error_string(context
, 0, ret
,
599 "Failed to create a random iv");
603 ret
= hx509_crypto_encrypt(crypto
,
607 &ed
.encryptedContentInfo
.encryptedContent
);
609 hx509_set_error_string(context
, 0, ret
,
610 "Failed to encrypt EnvelopedData content");
615 AlgorithmIdentifier
*enc_alg
;
616 enc_alg
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
617 ret
= der_copy_oid(encryption_type
, &enc_alg
->algorithm
);
619 hx509_set_error_string(context
, 0, ret
,
620 "Failed to set crypto oid "
621 "for EnvelopedData");
624 ALLOC(enc_alg
->parameters
, 1);
625 if (enc_alg
->parameters
== NULL
) {
627 hx509_set_error_string(context
, 0, ret
,
628 "Failed to allocate crypto paramaters "
629 "for EnvelopedData");
633 ret
= hx509_crypto_get_params(context
,
636 enc_alg
->parameters
);
642 ALLOC_SEQ(&ed
.recipientInfos
, 1);
643 if (ed
.recipientInfos
.val
== NULL
) {
645 hx509_set_error_string(context
, 0, ret
,
646 "Failed to allocate recipients info "
647 "for EnvelopedData");
651 ri
= &ed
.recipientInfos
.val
[0];
653 if (flags
& HX509_CMS_EV_ID_NAME
) {
655 cmsidflag
= CMS_ID_NAME
;
658 cmsidflag
= CMS_ID_SKI
;
661 ret
= fill_CMSIdentifier(cert
, cmsidflag
, &ri
->rid
);
663 hx509_set_error_string(context
, 0, ret
,
664 "Failed to set CMS identifier info "
665 "for EnvelopedData");
669 ret
= hx509_cert_public_encrypt(context
,
671 &ri
->keyEncryptionAlgorithm
.algorithm
,
674 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
675 "Failed to encrypt transport key for "
685 ed
.originatorInfo
= NULL
;
687 ret
= der_copy_oid(contentType
, &ed
.encryptedContentInfo
.contentType
);
689 hx509_set_error_string(context
, 0, ret
,
690 "Failed to copy content oid for "
695 ed
.unprotectedAttrs
= NULL
;
697 ASN1_MALLOC_ENCODE(EnvelopedData
, content
->data
, content
->length
,
700 hx509_set_error_string(context
, 0, ret
,
701 "Failed to encode EnvelopedData");
704 if (size
!= content
->length
)
705 _hx509_abort("internal ASN.1 encoder error");
709 hx509_crypto_destroy(crypto
);
711 der_free_octet_string(content
);
712 der_free_octet_string(&key
);
713 der_free_octet_string(&ivec
);
714 free_EnvelopedData(&ed
);
720 any_to_certs(hx509_context context
, const SignedData
*sd
, hx509_certs certs
)
725 if (sd
->certificates
== NULL
)
728 for (i
= 0; i
< sd
->certificates
->len
; i
++) {
731 ret
= hx509_cert_init_data(context
,
732 sd
->certificates
->val
[i
].data
,
733 sd
->certificates
->val
[i
].length
,
737 ret
= hx509_certs_add(context
, certs
, c
);
746 static const Attribute
*
747 find_attribute(const CMSAttributes
*attr
, const heim_oid
*oid
)
750 for (i
= 0; i
< attr
->len
; i
++)
751 if (der_heim_oid_cmp(&attr
->val
[i
].type
, oid
) == 0)
752 return &attr
->val
[i
];
757 * Decode SignedData and verify that the signature is correct.
759 * @param context A hx509 context.
760 * @param ctx a hx509 verify context.
761 * @param flags to control the behaivor of the function.
762 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
763 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
764 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
765 * @param data pointer to CMS SignedData encoded data.
766 * @param length length of the data that data point to.
767 * @param signedContent external data used for signature.
768 * @param pool certificate pool to build certificates paths.
769 * @param contentType free with der_free_oid().
770 * @param content the output of the function, free with
771 * der_free_octet_string().
772 * @param signer_certs list of the cerficates used to sign this
773 * request, free with hx509_certs_free().
779 hx509_cms_verify_signed(hx509_context context
,
780 hx509_verify_ctx ctx
,
784 const heim_octet_string
*signedContent
,
786 heim_oid
*contentType
,
787 heim_octet_string
*content
,
788 hx509_certs
*signer_certs
)
790 SignerInfo
*signer_info
;
791 hx509_cert cert
= NULL
;
792 hx509_certs certs
= NULL
;
795 int ret
, found_valid_sig
;
798 *signer_certs
= NULL
;
799 content
->data
= NULL
;
801 contentType
->length
= 0;
802 contentType
->components
= NULL
;
804 memset(&sd
, 0, sizeof(sd
));
806 ret
= decode_SignedData(data
, length
, &sd
, &size
);
808 hx509_set_error_string(context
, 0, ret
,
809 "Failed to decode SignedData");
813 if (sd
.encapContentInfo
.eContent
== NULL
&& signedContent
== NULL
) {
814 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
815 hx509_set_error_string(context
, 0, ret
,
816 "No content data in SignedData");
819 if (sd
.encapContentInfo
.eContent
&& signedContent
) {
820 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
821 hx509_set_error_string(context
, 0, ret
,
822 "Both external and internal SignedData");
826 if (sd
.encapContentInfo
.eContent
)
827 ret
= der_copy_octet_string(sd
.encapContentInfo
.eContent
, content
);
829 ret
= der_copy_octet_string(signedContent
, content
);
831 hx509_set_error_string(context
, 0, ret
, "malloc: out of memory");
835 ret
= hx509_certs_init(context
, "MEMORY:cms-cert-buffer",
840 ret
= hx509_certs_init(context
, "MEMORY:cms-signer-certs",
841 0, NULL
, signer_certs
);
845 /* XXX Check CMS version */
847 ret
= any_to_certs(context
, &sd
, certs
);
852 ret
= hx509_certs_merge(context
, certs
, pool
);
857 for (found_valid_sig
= 0, i
= 0; i
< sd
.signerInfos
.len
; i
++) {
858 heim_octet_string signed_data
;
859 const heim_oid
*match_oid
;
862 signer_info
= &sd
.signerInfos
.val
[i
];
865 if (signer_info
->signature
.length
== 0) {
866 ret
= HX509_CMS_MISSING_SIGNER_DATA
;
867 hx509_set_error_string(context
, 0, ret
,
868 "SignerInfo %d in SignedData "
869 "missing sigature", i
);
873 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
874 _hx509_verify_get_time(ctx
), &cert
,
875 HX509_QUERY_KU_DIGITALSIGNATURE
);
878 * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
879 * search for matching certificates by not considering
880 * KeyUsage bits on the certificates.
882 if ((flags
& HX509_CMS_VS_NO_KU_CHECK
) == 0)
885 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
886 _hx509_verify_get_time(ctx
), &cert
,
893 if (signer_info
->signedAttrs
) {
894 const Attribute
*attr
;
897 heim_octet_string os
;
899 sa
.val
= signer_info
->signedAttrs
->val
;
900 sa
.len
= signer_info
->signedAttrs
->len
;
902 /* verify that sigature exists */
903 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_messageDigest
);
905 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
906 hx509_set_error_string(context
, 0, ret
,
907 "SignerInfo have signed attributes "
908 "but messageDigest (signature) "
912 if (attr
->value
.len
!= 1) {
913 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
914 hx509_set_error_string(context
, 0, ret
,
915 "SignerInfo have more then one "
916 "messageDigest (signature)");
920 ret
= decode_MessageDigest(attr
->value
.val
[0].data
,
921 attr
->value
.val
[0].length
,
925 hx509_set_error_string(context
, 0, ret
,
927 "messageDigest (signature)");
931 ret
= _hx509_verify_signature(context
,
933 &signer_info
->digestAlgorithm
,
936 der_free_octet_string(&os
);
938 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
939 "Failed to verify messageDigest");
944 * Fetch content oid inside signedAttrs or set it to
947 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_contentType
);
949 match_oid
= &asn1_oid_id_pkcs7_data
;
951 if (attr
->value
.len
!= 1) {
952 ret
= HX509_CMS_DATA_OID_MISMATCH
;
953 hx509_set_error_string(context
, 0, ret
,
954 "More then one oid in signedAttrs");
958 ret
= decode_ContentType(attr
->value
.val
[0].data
,
959 attr
->value
.val
[0].length
,
963 hx509_set_error_string(context
, 0, ret
,
965 "oid in signedAttrs");
968 match_oid
= &decode_oid
;
971 ASN1_MALLOC_ENCODE(CMSAttributes
,
977 if (match_oid
== &decode_oid
)
978 der_free_oid(&decode_oid
);
979 hx509_clear_error_string(context
);
982 if (size
!= signed_data
.length
)
983 _hx509_abort("internal ASN.1 encoder error");
986 signed_data
.data
= content
->data
;
987 signed_data
.length
= content
->length
;
988 match_oid
= &asn1_oid_id_pkcs7_data
;
992 * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
993 * encapContentInfo mismatch with the oid in signedAttributes
994 * (or if no signedAttributes where use, pkcs7-data oid).
995 * This is only needed to work with broken CMS implementations
996 * that doesn't follow CMS signedAttributes rules.
999 if (der_heim_oid_cmp(match_oid
, &sd
.encapContentInfo
.eContentType
) &&
1000 (flags
& HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH
) == 0) {
1001 ret
= HX509_CMS_DATA_OID_MISMATCH
;
1002 hx509_set_error_string(context
, 0, ret
,
1003 "Oid in message mismatch from the expected");
1005 if (match_oid
== &decode_oid
)
1006 der_free_oid(&decode_oid
);
1009 ret
= hx509_verify_signature(context
,
1011 &signer_info
->signatureAlgorithm
,
1013 &signer_info
->signature
);
1015 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
1016 "Failed to verify signature in "
1019 if (signer_info
->signedAttrs
)
1020 free(signed_data
.data
);
1025 * If HX509_CMS_VS_NO_VALIDATE flags is set, do not verify the
1026 * signing certificates and leave that up to the caller.
1029 if ((flags
& HX509_CMS_VS_NO_VALIDATE
) == 0) {
1030 ret
= hx509_verify_path(context
, ctx
, cert
, certs
);
1035 ret
= hx509_certs_add(context
, *signer_certs
, cert
);
1043 hx509_cert_free(cert
);
1047 * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
1048 * SignerInfo (no signatures). If SignedData have no signatures,
1049 * the function will return 0 with signer_certs set to NULL. Zero
1050 * signers is allowed by the standard, but since its only useful
1051 * in corner cases, it make into a flag that the caller have to
1054 if (sd
.signerInfos
.len
== 0 && (flags
& HX509_CMS_VS_ALLOW_ZERO_SIGNER
)) {
1056 hx509_certs_free(signer_certs
);
1057 } else if (found_valid_sig
== 0) {
1059 ret
= HX509_CMS_SIGNER_NOT_FOUND
;
1060 hx509_set_error_string(context
, 0, ret
,
1061 "No signers where found");
1066 ret
= der_copy_oid(&sd
.encapContentInfo
.eContentType
, contentType
);
1068 hx509_clear_error_string(context
);
1073 free_SignedData(&sd
);
1075 hx509_certs_free(&certs
);
1078 der_free_octet_string(content
);
1080 hx509_certs_free(signer_certs
);
1081 der_free_oid(contentType
);
1082 der_free_octet_string(content
);
1089 add_one_attribute(Attribute
**attr
,
1091 const heim_oid
*oid
,
1092 heim_octet_string
*data
)
1097 d
= realloc(*attr
, sizeof((*attr
)[0]) * (*len
+ 1));
1102 ret
= der_copy_oid(oid
, &(*attr
)[*len
].type
);
1106 ALLOC_SEQ(&(*attr
)[*len
].value
, 1);
1107 if ((*attr
)[*len
].value
.val
== NULL
) {
1108 der_free_oid(&(*attr
)[*len
].type
);
1112 (*attr
)[*len
].value
.val
[0].data
= data
->data
;
1113 (*attr
)[*len
].value
.val
[0].length
= data
->length
;
1121 * Decode SignedData and verify that the signature is correct.
1123 * @param context A hx509 context.
1125 * @param eContentType the type of the data.
1126 * @param data data to sign
1127 * @param length length of the data that data point to.
1128 * @param digest_alg digest algorithm to use, use NULL to get the
1129 * default or the peer determined algorithm.
1130 * @param cert certificate to use for sign the data.
1131 * @param peer info about the peer the message to send the message to,
1132 * like what digest algorithm to use.
1133 * @param anchors trust anchors that the client will use, used to
1134 * polulate the certificates included in the message
1135 * @param pool certificates to use in try to build the path to the
1137 * @param signed_data the output of the function, free with
1138 * der_free_octet_string().
1140 * @ingroup hx509_cms
1144 hx509_cms_create_signed_1(hx509_context context
,
1146 const heim_oid
*eContentType
,
1147 const void *data
, size_t length
,
1148 const AlgorithmIdentifier
*digest_alg
,
1150 hx509_peer_info peer
,
1151 hx509_certs anchors
,
1153 heim_octet_string
*signed_data
)
1158 signed_data
->data
= NULL
;
1159 signed_data
->length
= 0;
1161 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &certs
);
1164 ret
= hx509_certs_add(context
, certs
, cert
);
1168 ret
= hx509_cms_create_signed(context
, flags
, eContentType
, data
, length
,
1169 digest_alg
, certs
, peer
, anchors
, pool
,
1173 hx509_certs_free(&certs
);
1179 const AlgorithmIdentifier
*digest_alg
;
1180 const heim_oid
*eContentType
;
1181 heim_octet_string content
;
1182 hx509_peer_info peer
;
1186 hx509_certs anchors
;
1191 sig_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1193 struct sigctx
*sigctx
= ctx
;
1194 heim_octet_string buf
, sigdata
= { 0, NULL
};
1195 SignerInfo
*signer_info
= NULL
;
1196 AlgorithmIdentifier digest
;
1200 SignedData
*sd
= &sigctx
->sd
;
1203 memset(&digest
, 0, sizeof(digest
));
1204 memset(&path
, 0, sizeof(path
));
1206 if (_hx509_cert_private_key(cert
) == NULL
) {
1207 hx509_set_error_string(context
, 0, HX509_PRIVATE_KEY_MISSING
,
1208 "Private key missing for signing");
1209 return HX509_PRIVATE_KEY_MISSING
;
1212 if (sigctx
->digest_alg
) {
1213 ret
= copy_AlgorithmIdentifier(sigctx
->digest_alg
, &digest
);
1215 hx509_clear_error_string(context
);
1217 ret
= hx509_crypto_select(context
, HX509_SELECT_DIGEST
,
1218 _hx509_cert_private_key(cert
),
1219 sigctx
->peer
, &digest
);
1225 * Allocate on more signerInfo and do the signature processing
1228 ptr
= realloc(sd
->signerInfos
.val
,
1229 (sd
->signerInfos
.len
+ 1) * sizeof(sd
->signerInfos
.val
[0]));
1234 sd
->signerInfos
.val
= ptr
;
1236 signer_info
= &sd
->signerInfos
.val
[sd
->signerInfos
.len
];
1238 memset(signer_info
, 0, sizeof(*signer_info
));
1240 signer_info
->version
= 1;
1242 ret
= fill_CMSIdentifier(cert
, sigctx
->cmsidflag
, &signer_info
->sid
);
1244 hx509_clear_error_string(context
);
1248 signer_info
->signedAttrs
= NULL
;
1249 signer_info
->unsignedAttrs
= NULL
;
1251 ret
= copy_AlgorithmIdentifier(&digest
, &signer_info
->digestAlgorithm
);
1253 hx509_clear_error_string(context
);
1258 * If it isn't pkcs7-data send signedAttributes
1261 if (der_heim_oid_cmp(sigctx
->eContentType
, &asn1_oid_id_pkcs7_data
) != 0) {
1263 heim_octet_string sig
;
1265 ALLOC(signer_info
->signedAttrs
, 1);
1266 if (signer_info
->signedAttrs
== NULL
) {
1271 ret
= _hx509_create_signature(context
,
1280 ASN1_MALLOC_ENCODE(MessageDigest
,
1286 der_free_octet_string(&sig
);
1288 hx509_clear_error_string(context
);
1291 if (size
!= buf
.length
)
1292 _hx509_abort("internal ASN.1 encoder error");
1294 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1295 &signer_info
->signedAttrs
->len
,
1296 &asn1_oid_id_pkcs9_messageDigest
,
1300 hx509_clear_error_string(context
);
1305 ASN1_MALLOC_ENCODE(ContentType
,
1308 sigctx
->eContentType
,
1313 if (size
!= buf
.length
)
1314 _hx509_abort("internal ASN.1 encoder error");
1316 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1317 &signer_info
->signedAttrs
->len
,
1318 &asn1_oid_id_pkcs9_contentType
,
1322 hx509_clear_error_string(context
);
1326 sa
.val
= signer_info
->signedAttrs
->val
;
1327 sa
.len
= signer_info
->signedAttrs
->len
;
1329 ASN1_MALLOC_ENCODE(CMSAttributes
,
1336 hx509_clear_error_string(context
);
1339 if (size
!= sigdata
.length
)
1340 _hx509_abort("internal ASN.1 encoder error");
1342 sigdata
.data
= sigctx
->content
.data
;
1343 sigdata
.length
= sigctx
->content
.length
;
1347 AlgorithmIdentifier sigalg
;
1349 ret
= hx509_crypto_select(context
, HX509_SELECT_PUBLIC_SIG
,
1350 _hx509_cert_private_key(cert
), sigctx
->peer
,
1355 ret
= _hx509_create_signature(context
,
1356 _hx509_cert_private_key(cert
),
1359 &signer_info
->signatureAlgorithm
,
1360 &signer_info
->signature
);
1361 free_AlgorithmIdentifier(&sigalg
);
1366 sigctx
->sd
.signerInfos
.len
++;
1370 * Provide best effort path
1372 if (sigctx
->certs
) {
1375 if (sigctx
->pool
&& sigctx
->leafonly
== 0) {
1376 _hx509_calculate_path(context
,
1377 HX509_CALCULATE_PATH_NO_ANCHOR
,
1385 _hx509_path_append(context
, &path
, cert
);
1387 for (i
= 0; i
< path
.len
; i
++) {
1388 /* XXX remove dups */
1389 ret
= hx509_certs_add(context
, sigctx
->certs
, path
.val
[i
]);
1391 hx509_clear_error_string(context
);
1399 free_SignerInfo(signer_info
);
1400 if (sigdata
.data
!= sigctx
->content
.data
)
1401 der_free_octet_string(&sigdata
);
1402 _hx509_path_free(&path
);
1403 free_AlgorithmIdentifier(&digest
);
1409 cert_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1411 struct sigctx
*sigctx
= ctx
;
1412 const unsigned int i
= sigctx
->sd
.certificates
->len
;
1416 ptr
= realloc(sigctx
->sd
.certificates
->val
,
1417 (i
+ 1) * sizeof(sigctx
->sd
.certificates
->val
[0]));
1420 sigctx
->sd
.certificates
->val
= ptr
;
1422 ret
= hx509_cert_binary(context
, cert
,
1423 &sigctx
->sd
.certificates
->val
[i
]);
1425 sigctx
->sd
.certificates
->len
++;
1431 cmp_AlgorithmIdentifier(const AlgorithmIdentifier
*p
, const AlgorithmIdentifier
*q
)
1433 return der_heim_oid_cmp(&p
->algorithm
, &q
->algorithm
);
1437 hx509_cms_create_signed(hx509_context context
,
1439 const heim_oid
*eContentType
,
1440 const void *data
, size_t length
,
1441 const AlgorithmIdentifier
*digest_alg
,
1443 hx509_peer_info peer
,
1444 hx509_certs anchors
,
1446 heim_octet_string
*signed_data
)
1452 struct sigctx sigctx
;
1454 memset(&sigctx
, 0, sizeof(sigctx
));
1455 memset(&name
, 0, sizeof(name
));
1457 if (eContentType
== NULL
)
1458 eContentType
= &asn1_oid_id_pkcs7_data
;
1460 sigctx
.digest_alg
= digest_alg
;
1461 sigctx
.content
.data
= rk_UNCONST(data
);
1462 sigctx
.content
.length
= length
;
1463 sigctx
.eContentType
= eContentType
;
1466 * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name
1467 * and serial number if possible. Otherwise subject key identifier
1470 if (flags
& HX509_CMS_SIGNATURE_ID_NAME
)
1471 sigctx
.cmsidflag
= CMS_ID_NAME
;
1473 sigctx
.cmsidflag
= CMS_ID_SKI
;
1476 * Use HX509_CMS_SIGNATURE_LEAF_ONLY to only request leaf
1477 * certificates to be added to the SignedData.
1479 sigctx
.leafonly
= (flags
& HX509_CMS_SIGNATURE_LEAF_ONLY
) ? 1 : 0;
1482 * Use HX509_CMS_NO_CERTS to make the SignedData contain no
1483 * certificates, overrides HX509_CMS_SIGNATURE_LEAF_ONLY.
1486 if ((flags
& HX509_CMS_SIGNATURE_NO_CERTS
) == 0) {
1487 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &sigctx
.certs
);
1492 sigctx
.anchors
= anchors
;
1495 sigctx
.sd
.version
= CMSVersion_v3
;
1497 der_copy_oid(eContentType
, &sigctx
.sd
.encapContentInfo
.eContentType
);
1500 * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
1502 if ((flags
& HX509_CMS_SIGNATURE_DETACHED
) == 0) {
1503 ALLOC(sigctx
.sd
.encapContentInfo
.eContent
, 1);
1504 if (sigctx
.sd
.encapContentInfo
.eContent
== NULL
) {
1505 hx509_clear_error_string(context
);
1510 sigctx
.sd
.encapContentInfo
.eContent
->data
= malloc(length
);
1511 if (sigctx
.sd
.encapContentInfo
.eContent
->data
== NULL
) {
1512 hx509_clear_error_string(context
);
1516 memcpy(sigctx
.sd
.encapContentInfo
.eContent
->data
, data
, length
);
1517 sigctx
.sd
.encapContentInfo
.eContent
->length
= length
;
1521 * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
1524 if ((flags
& HX509_CMS_SIGNATURE_NO_SIGNER
) == 0) {
1525 ret
= hx509_certs_iter_f(context
, certs
, sig_process
, &sigctx
);
1530 if (sigctx
.sd
.signerInfos
.len
) {
1533 * For each signerInfo, collect all different digest types.
1535 for (i
= 0; i
< sigctx
.sd
.signerInfos
.len
; i
++) {
1536 AlgorithmIdentifier
*di
=
1537 &sigctx
.sd
.signerInfos
.val
[i
].digestAlgorithm
;
1539 for (j
= 0; j
< sigctx
.sd
.digestAlgorithms
.len
; j
++)
1540 if (cmp_AlgorithmIdentifier(di
, &sigctx
.sd
.digestAlgorithms
.val
[j
]) == 0)
1542 if (j
== sigctx
.sd
.digestAlgorithms
.len
) {
1543 ret
= add_DigestAlgorithmIdentifiers(&sigctx
.sd
.digestAlgorithms
, di
);
1545 hx509_clear_error_string(context
);
1553 * Add certs we think are needed, build as part of sig_process
1556 ALLOC(sigctx
.sd
.certificates
, 1);
1557 if (sigctx
.sd
.certificates
== NULL
) {
1558 hx509_clear_error_string(context
);
1563 ret
= hx509_certs_iter_f(context
, sigctx
.certs
, cert_process
, &sigctx
);
1568 ASN1_MALLOC_ENCODE(SignedData
,
1569 signed_data
->data
, signed_data
->length
,
1570 &sigctx
.sd
, &size
, ret
);
1572 hx509_clear_error_string(context
);
1575 if (signed_data
->length
!= size
)
1576 _hx509_abort("internal ASN.1 encoder error");
1579 hx509_certs_free(&sigctx
.certs
);
1580 free_SignedData(&sigctx
.sd
);
1586 hx509_cms_decrypt_encrypted(hx509_context context
,
1590 heim_oid
*contentType
,
1591 heim_octet_string
*content
)
1593 heim_octet_string cont
;
1594 CMSEncryptedData ed
;
1595 AlgorithmIdentifier
*ai
;
1598 memset(content
, 0, sizeof(*content
));
1599 memset(&cont
, 0, sizeof(cont
));
1601 ret
= decode_CMSEncryptedData(data
, length
, &ed
, NULL
);
1603 hx509_set_error_string(context
, 0, ret
,
1604 "Failed to decode CMSEncryptedData");
1608 if (ed
.encryptedContentInfo
.encryptedContent
== NULL
) {
1609 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
1610 hx509_set_error_string(context
, 0, ret
,
1611 "No content in EncryptedData");
1615 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
1617 hx509_clear_error_string(context
);
1621 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
1622 if (ai
->parameters
== NULL
) {
1623 ret
= HX509_ALG_NOT_SUPP
;
1624 hx509_clear_error_string(context
);
1628 ret
= _hx509_pbe_decrypt(context
,
1631 ed
.encryptedContentInfo
.encryptedContent
,
1643 free_CMSEncryptedData(&ed
);