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
, i
, matched
= 0, findflags
= 0;
368 memset(&key
, 0, sizeof(key
));
369 memset(&ed
, 0, sizeof(ed
));
370 memset(&ivec
, 0, sizeof(ivec
));
371 memset(content
, 0, sizeof(*content
));
372 memset(contentType
, 0, sizeof(*contentType
));
374 if ((flags
& HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT
) == 0)
375 findflags
|= HX509_QUERY_KU_ENCIPHERMENT
;
377 ret
= decode_EnvelopedData(data
, length
, &ed
, &size
);
379 hx509_set_error_string(context
, 0, ret
,
380 "Failed to decode EnvelopedData");
384 if (ed
.recipientInfos
.len
== 0) {
385 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
386 hx509_set_error_string(context
, 0, ret
,
387 "No recipient info in enveloped data");
391 enccontent
= ed
.encryptedContentInfo
.encryptedContent
;
392 if (enccontent
== NULL
) {
393 if (encryptedContent
== NULL
) {
394 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
395 hx509_set_error_string(context
, 0, ret
,
396 "Content missing from encrypted data");
399 enccontent
= encryptedContent
;
400 } else if (encryptedContent
!= NULL
) {
401 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
402 hx509_set_error_string(context
, 0, ret
,
403 "Both internal and external encrypted data");
408 for (i
= 0; i
< ed
.recipientInfos
.len
; i
++) {
409 KeyTransRecipientInfo
*ri
;
413 ri
= &ed
.recipientInfos
.val
[i
];
415 ret
= find_CMSIdentifier(context
, &ri
->rid
, certs
,
417 HX509_QUERY_PRIVATE_KEY
|findflags
);
421 matched
= 1; /* found a matching certificate, let decrypt */
423 ret
= _hx509_cert_private_decrypt(context
,
425 &ri
->keyEncryptionAlgorithm
.algorithm
,
428 hx509_cert_free(cert
);
430 break; /* succuessfully decrypted cert */
432 ret2
= unparse_CMSIdentifier(context
, &ri
->rid
, &str
);
434 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
435 "Failed to decrypt with %s", str
);
441 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
442 hx509_set_error_string(context
, 0, ret
,
443 "No private key matched any certificate");
448 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
449 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
450 "No private key decrypted the transfer key");
454 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
456 hx509_set_error_string(context
, 0, ret
,
457 "Failed to copy EnvelopedData content oid");
461 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
462 if (ai
->parameters
) {
463 params_data
.data
= ai
->parameters
->data
;
464 params_data
.length
= ai
->parameters
->length
;
465 params
= ¶ms_data
;
472 ret
= hx509_crypto_init(context
, NULL
, &ai
->algorithm
, &crypto
);
476 if (flags
& HX509_CMS_UE_ALLOW_WEAK
)
477 hx509_crypto_allow_weak(crypto
);
480 ret
= hx509_crypto_set_params(context
, crypto
, params
, &ivec
);
482 hx509_crypto_destroy(crypto
);
487 ret
= hx509_crypto_set_key_data(crypto
, key
.data
, key
.length
);
489 hx509_crypto_destroy(crypto
);
490 hx509_set_error_string(context
, 0, ret
,
491 "Failed to set key for decryption "
496 ret
= hx509_crypto_decrypt(crypto
,
499 ivec
.length
? &ivec
: NULL
,
501 hx509_crypto_destroy(crypto
);
503 hx509_set_error_string(context
, 0, ret
,
504 "Failed to decrypt EnvelopedData");
511 free_EnvelopedData(&ed
);
512 der_free_octet_string(&key
);
514 der_free_octet_string(&ivec
);
516 der_free_oid(contentType
);
517 der_free_octet_string(content
);
524 * Encrypt end encode EnvelopedData.
526 * Encrypt and encode EnvelopedData. The data is encrypted with a
527 * random key and the the random key is encrypted with the
528 * certificates private key. This limits what private key type can be
531 * @param context A hx509 context.
532 * @param flags flags to control the behavior.
533 * - HX509_CMS_EV_NO_KU_CHECK - Dont check KU on certificate
534 * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crytpo
535 * @param cert Certificate to encrypt the EnvelopedData encryption key
537 * @param data pointer the data to encrypt.
538 * @param length length of the data that data point to.
539 * @param encryption_type Encryption cipher to use for the bulk data,
540 * use NULL to get default.
541 * @param contentType type of the data that is encrypted
542 * @param content the output of the function,
543 * free with der_free_octet_string().
549 hx509_cms_envelope_1(hx509_context context
,
554 const heim_oid
*encryption_type
,
555 const heim_oid
*contentType
,
556 heim_octet_string
*content
)
558 KeyTransRecipientInfo
*ri
;
559 heim_octet_string ivec
;
560 heim_octet_string key
;
561 hx509_crypto crypto
= NULL
;
566 memset(&ivec
, 0, sizeof(ivec
));
567 memset(&key
, 0, sizeof(key
));
568 memset(&ed
, 0, sizeof(ed
));
569 memset(content
, 0, sizeof(*content
));
571 if (encryption_type
== NULL
)
572 encryption_type
= &asn1_oid_id_aes_256_cbc
;
574 if ((flags
& HX509_CMS_EV_NO_KU_CHECK
) == 0) {
575 ret
= _hx509_check_key_usage(context
, cert
, 1 << 2, TRUE
);
580 ret
= hx509_crypto_init(context
, NULL
, encryption_type
, &crypto
);
584 if (flags
& HX509_CMS_EV_ALLOW_WEAK
)
585 hx509_crypto_allow_weak(crypto
);
587 ret
= hx509_crypto_set_random_key(crypto
, &key
);
589 hx509_set_error_string(context
, 0, ret
,
590 "Create random key for EnvelopedData content");
594 ret
= hx509_crypto_random_iv(crypto
, &ivec
);
596 hx509_set_error_string(context
, 0, ret
,
597 "Failed to create a random iv");
601 ret
= hx509_crypto_encrypt(crypto
,
605 &ed
.encryptedContentInfo
.encryptedContent
);
607 hx509_set_error_string(context
, 0, ret
,
608 "Failed to encrypt EnvelopedData content");
613 AlgorithmIdentifier
*enc_alg
;
614 enc_alg
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
615 ret
= der_copy_oid(encryption_type
, &enc_alg
->algorithm
);
617 hx509_set_error_string(context
, 0, ret
,
618 "Failed to set crypto oid "
619 "for EnvelopedData");
622 ALLOC(enc_alg
->parameters
, 1);
623 if (enc_alg
->parameters
== NULL
) {
625 hx509_set_error_string(context
, 0, ret
,
626 "Failed to allocate crypto paramaters "
627 "for EnvelopedData");
631 ret
= hx509_crypto_get_params(context
,
634 enc_alg
->parameters
);
640 ALLOC_SEQ(&ed
.recipientInfos
, 1);
641 if (ed
.recipientInfos
.val
== NULL
) {
643 hx509_set_error_string(context
, 0, ret
,
644 "Failed to allocate recipients info "
645 "for EnvelopedData");
649 ri
= &ed
.recipientInfos
.val
[0];
652 ret
= fill_CMSIdentifier(cert
, CMS_ID_SKI
, &ri
->rid
);
654 hx509_set_error_string(context
, 0, ret
,
655 "Failed to set CMS identifier info "
656 "for EnvelopedData");
660 ret
= _hx509_cert_public_encrypt(context
,
662 &ri
->keyEncryptionAlgorithm
.algorithm
,
665 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
666 "Failed to encrypt transport key for "
676 ed
.originatorInfo
= NULL
;
678 ret
= der_copy_oid(contentType
, &ed
.encryptedContentInfo
.contentType
);
680 hx509_set_error_string(context
, 0, ret
,
681 "Failed to copy content oid for "
686 ed
.unprotectedAttrs
= NULL
;
688 ASN1_MALLOC_ENCODE(EnvelopedData
, content
->data
, content
->length
,
691 hx509_set_error_string(context
, 0, ret
,
692 "Failed to encode EnvelopedData");
695 if (size
!= content
->length
)
696 _hx509_abort("internal ASN.1 encoder error");
700 hx509_crypto_destroy(crypto
);
702 der_free_octet_string(content
);
703 der_free_octet_string(&key
);
704 der_free_octet_string(&ivec
);
705 free_EnvelopedData(&ed
);
711 any_to_certs(hx509_context context
, const SignedData
*sd
, hx509_certs certs
)
715 if (sd
->certificates
== NULL
)
718 for (i
= 0; i
< sd
->certificates
->len
; i
++) {
721 ret
= hx509_cert_init_data(context
,
722 sd
->certificates
->val
[i
].data
,
723 sd
->certificates
->val
[i
].length
,
727 ret
= hx509_certs_add(context
, certs
, c
);
736 static const Attribute
*
737 find_attribute(const CMSAttributes
*attr
, const heim_oid
*oid
)
740 for (i
= 0; i
< attr
->len
; i
++)
741 if (der_heim_oid_cmp(&attr
->val
[i
].type
, oid
) == 0)
742 return &attr
->val
[i
];
747 * Decode SignedData and verify that the signature is correct.
749 * @param context A hx509 context.
750 * @param ctx a hx509 verify context.
751 * @param flags to control the behaivor of the function.
752 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
753 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
754 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
755 * @param data pointer to CMS SignedData encoded data.
756 * @param length length of the data that data point to.
757 * @param signedContent external data used for signature.
758 * @param pool certificate pool to build certificates paths.
759 * @param contentType free with der_free_oid().
760 * @param content the output of the function, free with
761 * der_free_octet_string().
762 * @param signer_certs list of the cerficates used to sign this
763 * request, free with hx509_certs_free().
769 hx509_cms_verify_signed(hx509_context context
,
770 hx509_verify_ctx ctx
,
774 const heim_octet_string
*signedContent
,
776 heim_oid
*contentType
,
777 heim_octet_string
*content
,
778 hx509_certs
*signer_certs
)
780 SignerInfo
*signer_info
;
781 hx509_cert cert
= NULL
;
782 hx509_certs certs
= NULL
;
785 int ret
, i
, found_valid_sig
;
787 *signer_certs
= NULL
;
788 content
->data
= NULL
;
790 contentType
->length
= 0;
791 contentType
->components
= NULL
;
793 memset(&sd
, 0, sizeof(sd
));
795 ret
= decode_SignedData(data
, length
, &sd
, &size
);
797 hx509_set_error_string(context
, 0, ret
,
798 "Failed to decode SignedData");
802 if (sd
.encapContentInfo
.eContent
== NULL
&& signedContent
== NULL
) {
803 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
804 hx509_set_error_string(context
, 0, ret
,
805 "No content data in SignedData");
808 if (sd
.encapContentInfo
.eContent
&& signedContent
) {
809 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
810 hx509_set_error_string(context
, 0, ret
,
811 "Both external and internal SignedData");
815 if (sd
.encapContentInfo
.eContent
)
816 ret
= der_copy_octet_string(sd
.encapContentInfo
.eContent
, content
);
818 ret
= der_copy_octet_string(signedContent
, content
);
820 hx509_set_error_string(context
, 0, ret
, "malloc: out of memory");
824 ret
= hx509_certs_init(context
, "MEMORY:cms-cert-buffer",
829 ret
= hx509_certs_init(context
, "MEMORY:cms-signer-certs",
830 0, NULL
, signer_certs
);
834 /* XXX Check CMS version */
836 ret
= any_to_certs(context
, &sd
, certs
);
841 ret
= hx509_certs_merge(context
, certs
, pool
);
846 for (found_valid_sig
= 0, i
= 0; i
< sd
.signerInfos
.len
; i
++) {
847 heim_octet_string signed_data
;
848 const heim_oid
*match_oid
;
851 signer_info
= &sd
.signerInfos
.val
[i
];
854 if (signer_info
->signature
.length
== 0) {
855 ret
= HX509_CMS_MISSING_SIGNER_DATA
;
856 hx509_set_error_string(context
, 0, ret
,
857 "SignerInfo %d in SignedData "
858 "missing sigature", i
);
862 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
863 _hx509_verify_get_time(ctx
), &cert
,
864 HX509_QUERY_KU_DIGITALSIGNATURE
);
867 * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
868 * search for matching certificates by not considering
869 * KeyUsage bits on the certificates.
871 if ((flags
& HX509_CMS_VS_NO_KU_CHECK
) == 0)
874 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
875 _hx509_verify_get_time(ctx
), &cert
,
882 if (signer_info
->signedAttrs
) {
883 const Attribute
*attr
;
886 heim_octet_string os
;
888 sa
.val
= signer_info
->signedAttrs
->val
;
889 sa
.len
= signer_info
->signedAttrs
->len
;
891 /* verify that sigature exists */
892 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_messageDigest
);
894 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
895 hx509_set_error_string(context
, 0, ret
,
896 "SignerInfo have signed attributes "
897 "but messageDigest (signature) "
901 if (attr
->value
.len
!= 1) {
902 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
903 hx509_set_error_string(context
, 0, ret
,
904 "SignerInfo have more then one "
905 "messageDigest (signature)");
909 ret
= decode_MessageDigest(attr
->value
.val
[0].data
,
910 attr
->value
.val
[0].length
,
914 hx509_set_error_string(context
, 0, ret
,
916 "messageDigest (signature)");
920 ret
= _hx509_verify_signature(context
,
922 &signer_info
->digestAlgorithm
,
925 der_free_octet_string(&os
);
927 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
928 "Failed to verify messageDigest");
933 * Fetch content oid inside signedAttrs or set it to
936 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_contentType
);
938 match_oid
= &asn1_oid_id_pkcs7_data
;
940 if (attr
->value
.len
!= 1) {
941 ret
= HX509_CMS_DATA_OID_MISMATCH
;
942 hx509_set_error_string(context
, 0, ret
,
943 "More then one oid in signedAttrs");
947 ret
= decode_ContentType(attr
->value
.val
[0].data
,
948 attr
->value
.val
[0].length
,
952 hx509_set_error_string(context
, 0, ret
,
954 "oid in signedAttrs");
957 match_oid
= &decode_oid
;
960 ASN1_MALLOC_ENCODE(CMSAttributes
,
966 if (match_oid
== &decode_oid
)
967 der_free_oid(&decode_oid
);
968 hx509_clear_error_string(context
);
971 if (size
!= signed_data
.length
)
972 _hx509_abort("internal ASN.1 encoder error");
975 signed_data
.data
= content
->data
;
976 signed_data
.length
= content
->length
;
977 match_oid
= &asn1_oid_id_pkcs7_data
;
981 * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
982 * encapContentInfo mismatch with the oid in signedAttributes
983 * (or if no signedAttributes where use, pkcs7-data oid).
984 * This is only needed to work with broken CMS implementations
985 * that doesn't follow CMS signedAttributes rules.
988 if (der_heim_oid_cmp(match_oid
, &sd
.encapContentInfo
.eContentType
) &&
989 (flags
& HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH
) == 0) {
990 ret
= HX509_CMS_DATA_OID_MISMATCH
;
991 hx509_set_error_string(context
, 0, ret
,
992 "Oid in message mismatch from the expected");
994 if (match_oid
== &decode_oid
)
995 der_free_oid(&decode_oid
);
998 ret
= hx509_verify_signature(context
,
1000 &signer_info
->signatureAlgorithm
,
1002 &signer_info
->signature
);
1004 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
1005 "Failed to verify signature in "
1008 if (signer_info
->signedAttrs
)
1009 free(signed_data
.data
);
1014 * If HX509_CMS_VS_NO_VALIDATE flags is set, do not verify the
1015 * signing certificates and leave that up to the caller.
1018 if ((flags
& HX509_CMS_VS_NO_VALIDATE
) == 0) {
1019 ret
= hx509_verify_path(context
, ctx
, cert
, certs
);
1024 ret
= hx509_certs_add(context
, *signer_certs
, cert
);
1032 hx509_cert_free(cert
);
1036 * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
1037 * SignerInfo (no signatures). If SignedData have no signatures,
1038 * the function will return 0 with signer_certs set to NULL. Zero
1039 * signers is allowed by the standard, but since its only useful
1040 * in corner cases, it make into a flag that the caller have to
1043 if (sd
.signerInfos
.len
== 0 && (flags
& HX509_CMS_VS_ALLOW_ZERO_SIGNER
)) {
1045 hx509_certs_free(signer_certs
);
1046 } else if (found_valid_sig
== 0) {
1048 ret
= HX509_CMS_SIGNER_NOT_FOUND
;
1049 hx509_set_error_string(context
, 0, ret
,
1050 "No signers where found");
1055 ret
= der_copy_oid(&sd
.encapContentInfo
.eContentType
, contentType
);
1057 hx509_clear_error_string(context
);
1062 free_SignedData(&sd
);
1064 hx509_certs_free(&certs
);
1067 der_free_octet_string(content
);
1069 hx509_certs_free(signer_certs
);
1070 der_free_oid(contentType
);
1071 der_free_octet_string(content
);
1078 add_one_attribute(Attribute
**attr
,
1080 const heim_oid
*oid
,
1081 heim_octet_string
*data
)
1086 d
= realloc(*attr
, sizeof((*attr
)[0]) * (*len
+ 1));
1091 ret
= der_copy_oid(oid
, &(*attr
)[*len
].type
);
1095 ALLOC_SEQ(&(*attr
)[*len
].value
, 1);
1096 if ((*attr
)[*len
].value
.val
== NULL
) {
1097 der_free_oid(&(*attr
)[*len
].type
);
1101 (*attr
)[*len
].value
.val
[0].data
= data
->data
;
1102 (*attr
)[*len
].value
.val
[0].length
= data
->length
;
1110 * Decode SignedData and verify that the signature is correct.
1112 * @param context A hx509 context.
1114 * @param eContentType the type of the data.
1115 * @param data data to sign
1116 * @param length length of the data that data point to.
1117 * @param digest_alg digest algorithm to use, use NULL to get the
1118 * default or the peer determined algorithm.
1119 * @param cert certificate to use for sign the data.
1120 * @param peer info about the peer the message to send the message to,
1121 * like what digest algorithm to use.
1122 * @param anchors trust anchors that the client will use, used to
1123 * polulate the certificates included in the message
1124 * @param pool certificates to use in try to build the path to the
1126 * @param signed_data the output of the function, free with
1127 * der_free_octet_string().
1129 * @ingroup hx509_cms
1133 hx509_cms_create_signed_1(hx509_context context
,
1135 const heim_oid
*eContentType
,
1136 const void *data
, size_t length
,
1137 const AlgorithmIdentifier
*digest_alg
,
1139 hx509_peer_info peer
,
1140 hx509_certs anchors
,
1142 heim_octet_string
*signed_data
)
1147 signed_data
->data
= NULL
;
1148 signed_data
->length
= 0;
1150 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &certs
);
1153 ret
= hx509_certs_add(context
, certs
, cert
);
1157 ret
= hx509_cms_create_signed(context
, flags
, eContentType
, data
, length
,
1158 digest_alg
, certs
, peer
, anchors
, pool
,
1162 hx509_certs_free(&certs
);
1168 const AlgorithmIdentifier
*digest_alg
;
1169 const heim_oid
*eContentType
;
1170 heim_octet_string content
;
1171 hx509_peer_info peer
;
1175 hx509_certs anchors
;
1180 sig_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1182 struct sigctx
*sigctx
= ctx
;
1183 heim_octet_string buf
, sigdata
= { 0, NULL
};
1184 SignerInfo
*signer_info
= NULL
;
1185 AlgorithmIdentifier digest
;
1189 SignedData
*sd
= &sigctx
->sd
;
1192 memset(&digest
, 0, sizeof(digest
));
1193 memset(&path
, 0, sizeof(path
));
1195 if (_hx509_cert_private_key(cert
) == NULL
) {
1196 hx509_set_error_string(context
, 0, HX509_PRIVATE_KEY_MISSING
,
1197 "Private key missing for signing");
1198 return HX509_PRIVATE_KEY_MISSING
;
1201 if (sigctx
->digest_alg
) {
1202 ret
= copy_AlgorithmIdentifier(sigctx
->digest_alg
, &digest
);
1204 hx509_clear_error_string(context
);
1206 ret
= hx509_crypto_select(context
, HX509_SELECT_DIGEST
,
1207 _hx509_cert_private_key(cert
),
1208 sigctx
->peer
, &digest
);
1214 * Allocate on more signerInfo and do the signature processing
1217 ptr
= realloc(sd
->signerInfos
.val
,
1218 (sd
->signerInfos
.len
+ 1) * sizeof(sd
->signerInfos
.val
[0]));
1223 sd
->signerInfos
.val
= ptr
;
1225 signer_info
= &sd
->signerInfos
.val
[sd
->signerInfos
.len
];
1227 memset(signer_info
, 0, sizeof(*signer_info
));
1229 signer_info
->version
= 1;
1231 ret
= fill_CMSIdentifier(cert
, sigctx
->cmsidflag
, &signer_info
->sid
);
1233 hx509_clear_error_string(context
);
1237 signer_info
->signedAttrs
= NULL
;
1238 signer_info
->unsignedAttrs
= NULL
;
1240 ret
= copy_AlgorithmIdentifier(&digest
, &signer_info
->digestAlgorithm
);
1242 hx509_clear_error_string(context
);
1247 * If it isn't pkcs7-data send signedAttributes
1250 if (der_heim_oid_cmp(sigctx
->eContentType
, &asn1_oid_id_pkcs7_data
) != 0) {
1252 heim_octet_string sig
;
1254 ALLOC(signer_info
->signedAttrs
, 1);
1255 if (signer_info
->signedAttrs
== NULL
) {
1260 ret
= _hx509_create_signature(context
,
1269 ASN1_MALLOC_ENCODE(MessageDigest
,
1275 der_free_octet_string(&sig
);
1277 hx509_clear_error_string(context
);
1280 if (size
!= buf
.length
)
1281 _hx509_abort("internal ASN.1 encoder error");
1283 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1284 &signer_info
->signedAttrs
->len
,
1285 &asn1_oid_id_pkcs9_messageDigest
,
1289 hx509_clear_error_string(context
);
1294 ASN1_MALLOC_ENCODE(ContentType
,
1297 sigctx
->eContentType
,
1302 if (size
!= buf
.length
)
1303 _hx509_abort("internal ASN.1 encoder error");
1305 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1306 &signer_info
->signedAttrs
->len
,
1307 &asn1_oid_id_pkcs9_contentType
,
1311 hx509_clear_error_string(context
);
1315 sa
.val
= signer_info
->signedAttrs
->val
;
1316 sa
.len
= signer_info
->signedAttrs
->len
;
1318 ASN1_MALLOC_ENCODE(CMSAttributes
,
1325 hx509_clear_error_string(context
);
1328 if (size
!= sigdata
.length
)
1329 _hx509_abort("internal ASN.1 encoder error");
1331 sigdata
.data
= sigctx
->content
.data
;
1332 sigdata
.length
= sigctx
->content
.length
;
1336 AlgorithmIdentifier sigalg
;
1338 ret
= hx509_crypto_select(context
, HX509_SELECT_PUBLIC_SIG
,
1339 _hx509_cert_private_key(cert
), sigctx
->peer
,
1344 ret
= _hx509_create_signature(context
,
1345 _hx509_cert_private_key(cert
),
1348 &signer_info
->signatureAlgorithm
,
1349 &signer_info
->signature
);
1350 free_AlgorithmIdentifier(&sigalg
);
1355 sigctx
->sd
.signerInfos
.len
++;
1359 * Provide best effort path
1361 if (sigctx
->certs
) {
1364 if (sigctx
->pool
&& sigctx
->leafonly
== 0) {
1365 _hx509_calculate_path(context
,
1366 HX509_CALCULATE_PATH_NO_ANCHOR
,
1374 _hx509_path_append(context
, &path
, cert
);
1376 for (i
= 0; i
< path
.len
; i
++) {
1377 /* XXX remove dups */
1378 ret
= hx509_certs_add(context
, sigctx
->certs
, path
.val
[i
]);
1380 hx509_clear_error_string(context
);
1388 free_SignerInfo(signer_info
);
1389 if (sigdata
.data
!= sigctx
->content
.data
)
1390 der_free_octet_string(&sigdata
);
1391 _hx509_path_free(&path
);
1392 free_AlgorithmIdentifier(&digest
);
1398 cert_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1400 struct sigctx
*sigctx
= ctx
;
1401 const unsigned int i
= sigctx
->sd
.certificates
->len
;
1405 ptr
= realloc(sigctx
->sd
.certificates
->val
,
1406 (i
+ 1) * sizeof(sigctx
->sd
.certificates
->val
[0]));
1409 sigctx
->sd
.certificates
->val
= ptr
;
1411 ret
= hx509_cert_binary(context
, cert
,
1412 &sigctx
->sd
.certificates
->val
[i
]);
1414 sigctx
->sd
.certificates
->len
++;
1420 cmp_AlgorithmIdentifier(const AlgorithmIdentifier
*p
, const AlgorithmIdentifier
*q
)
1422 return der_heim_oid_cmp(&p
->algorithm
, &q
->algorithm
);
1426 hx509_cms_create_signed(hx509_context context
,
1428 const heim_oid
*eContentType
,
1429 const void *data
, size_t length
,
1430 const AlgorithmIdentifier
*digest_alg
,
1432 hx509_peer_info peer
,
1433 hx509_certs anchors
,
1435 heim_octet_string
*signed_data
)
1441 struct sigctx sigctx
;
1443 memset(&sigctx
, 0, sizeof(sigctx
));
1444 memset(&name
, 0, sizeof(name
));
1446 if (eContentType
== NULL
)
1447 eContentType
= &asn1_oid_id_pkcs7_data
;
1449 sigctx
.digest_alg
= digest_alg
;
1450 sigctx
.content
.data
= rk_UNCONST(data
);
1451 sigctx
.content
.length
= length
;
1452 sigctx
.eContentType
= eContentType
;
1455 * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name
1456 * and serial number if possible. Otherwise subject key identifier
1459 if (flags
& HX509_CMS_SIGNATURE_ID_NAME
)
1460 sigctx
.cmsidflag
= CMS_ID_NAME
;
1462 sigctx
.cmsidflag
= CMS_ID_SKI
;
1465 * Use HX509_CMS_SIGNATURE_LEAF_ONLY to only request leaf
1466 * certificates to be added to the SignedData.
1468 sigctx
.leafonly
= (flags
& HX509_CMS_SIGNATURE_LEAF_ONLY
) ? 1 : 0;
1471 * Use HX509_CMS_NO_CERTS to make the SignedData contain no
1472 * certificates, overrides HX509_CMS_SIGNATURE_LEAF_ONLY.
1475 if ((flags
& HX509_CMS_SIGNATURE_NO_CERTS
) == 0) {
1476 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &sigctx
.certs
);
1481 sigctx
.anchors
= anchors
;
1484 sigctx
.sd
.version
= CMSVersion_v3
;
1486 der_copy_oid(eContentType
, &sigctx
.sd
.encapContentInfo
.eContentType
);
1489 * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
1491 if ((flags
& HX509_CMS_SIGNATURE_DETACHED
) == 0) {
1492 ALLOC(sigctx
.sd
.encapContentInfo
.eContent
, 1);
1493 if (sigctx
.sd
.encapContentInfo
.eContent
== NULL
) {
1494 hx509_clear_error_string(context
);
1499 sigctx
.sd
.encapContentInfo
.eContent
->data
= malloc(length
);
1500 if (sigctx
.sd
.encapContentInfo
.eContent
->data
== NULL
) {
1501 hx509_clear_error_string(context
);
1505 memcpy(sigctx
.sd
.encapContentInfo
.eContent
->data
, data
, length
);
1506 sigctx
.sd
.encapContentInfo
.eContent
->length
= length
;
1510 * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
1513 if ((flags
& HX509_CMS_SIGNATURE_NO_SIGNER
) == 0) {
1514 ret
= hx509_certs_iter_f(context
, certs
, sig_process
, &sigctx
);
1519 if (sigctx
.sd
.signerInfos
.len
) {
1520 for (i
= 0; i
< sigctx
.sd
.signerInfos
.len
; i
++) {
1521 AlgorithmIdentifier
*di
=
1522 &sigctx
.sd
.signerInfos
.val
[i
].digestAlgorithm
;
1524 for (j
= 0; j
< sigctx
.sd
.digestAlgorithms
.len
; j
++)
1525 if (cmp_AlgorithmIdentifier(di
, &sigctx
.sd
.digestAlgorithms
.val
[j
]) == 0)
1527 if (j
< sigctx
.sd
.digestAlgorithms
.len
) {
1528 ret
= add_DigestAlgorithmIdentifiers(&sigctx
.sd
.digestAlgorithms
, di
);
1530 hx509_clear_error_string(context
);
1538 ALLOC(sigctx
.sd
.certificates
, 1);
1539 if (sigctx
.sd
.certificates
== NULL
) {
1540 hx509_clear_error_string(context
);
1545 ret
= hx509_certs_iter_f(context
, sigctx
.certs
, cert_process
, &sigctx
);
1550 ASN1_MALLOC_ENCODE(SignedData
,
1551 signed_data
->data
, signed_data
->length
,
1552 &sigctx
.sd
, &size
, ret
);
1554 hx509_clear_error_string(context
);
1557 if (signed_data
->length
!= size
)
1558 _hx509_abort("internal ASN.1 encoder error");
1561 hx509_certs_free(&sigctx
.certs
);
1562 free_SignedData(&sigctx
.sd
);
1568 hx509_cms_decrypt_encrypted(hx509_context context
,
1572 heim_oid
*contentType
,
1573 heim_octet_string
*content
)
1575 heim_octet_string cont
;
1576 CMSEncryptedData ed
;
1577 AlgorithmIdentifier
*ai
;
1580 memset(content
, 0, sizeof(*content
));
1581 memset(&cont
, 0, sizeof(cont
));
1583 ret
= decode_CMSEncryptedData(data
, length
, &ed
, NULL
);
1585 hx509_set_error_string(context
, 0, ret
,
1586 "Failed to decode CMSEncryptedData");
1590 if (ed
.encryptedContentInfo
.encryptedContent
== NULL
) {
1591 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
1592 hx509_set_error_string(context
, 0, ret
,
1593 "No content in EncryptedData");
1597 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
1599 hx509_clear_error_string(context
);
1603 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
1604 if (ai
->parameters
== NULL
) {
1605 ret
= HX509_ALG_NOT_SUPP
;
1606 hx509_clear_error_string(context
);
1610 ret
= _hx509_pbe_decrypt(context
,
1613 ed
.encryptedContentInfo
.encryptedContent
,
1625 free_CMSEncryptedData(&ed
);