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 ret
= 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 ret
= asprintf(str
, "certificate with id %s", keyid
);
250 ret
= asprintf(str
, "certificate have unknown CMSidentifier type");
254 * In the following if, we check ret and *str which should be returned/set
255 * by asprintf(3) in every branch of the switch statement.
257 if (ret
== -1 || *str
== NULL
)
263 find_CMSIdentifier(hx509_context context
,
264 CMSIdentifier
*client
,
267 hx509_cert
*signer_cert
,
275 memset(&c
, 0, sizeof(c
));
276 _hx509_query_clear(&q
);
280 switch (client
->element
) {
281 case choice_CMSIdentifier_issuerAndSerialNumber
:
282 q
.serial
= &client
->u
.issuerAndSerialNumber
.serialNumber
;
283 q
.issuer_name
= &client
->u
.issuerAndSerialNumber
.issuer
;
284 q
.match
= HX509_QUERY_MATCH_SERIALNUMBER
|HX509_QUERY_MATCH_ISSUER_NAME
;
286 case choice_CMSIdentifier_subjectKeyIdentifier
:
287 q
.subject_id
= &client
->u
.subjectKeyIdentifier
;
288 q
.match
= HX509_QUERY_MATCH_SUBJECT_KEY_ID
;
291 hx509_set_error_string(context
, 0, HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
292 "unknown CMS identifier element");
293 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
298 q
.match
|= HX509_QUERY_MATCH_TIME
;
300 q
.timenow
= time_now
;
302 q
.timenow
= time(NULL
);
304 ret
= hx509_certs_find(context
, certs
, &q
, &cert
);
305 if (ret
== HX509_CERT_NOT_FOUND
) {
308 ret
= unparse_CMSIdentifier(context
, client
, &str
);
310 hx509_set_error_string(context
, 0,
311 HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
312 "Failed to find %s", str
);
314 hx509_clear_error_string(context
);
315 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
317 hx509_set_error_string(context
, HX509_ERROR_APPEND
,
318 HX509_CMS_NO_RECIPIENT_CERTIFICATE
,
319 "Failed to find CMS id in cert store");
320 return HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
329 * Decode and unencrypt EnvelopedData.
331 * Extract data and parameteres from from the EnvelopedData. Also
332 * supports using detached EnvelopedData.
334 * @param context A hx509 context.
335 * @param certs Certificate that can decrypt the EnvelopedData
337 * @param flags HX509_CMS_UE flags to control the behavior.
338 * @param data pointer the structure the contains the DER/BER encoded
339 * EnvelopedData stucture.
340 * @param length length of the data that data point to.
341 * @param encryptedContent in case of detached signature, this
342 * contains the actual encrypted data, othersize its should be NULL.
343 * @param time_now set the current time, if zero the library uses now as the date.
344 * @param contentType output type oid, should be freed with der_free_oid().
345 * @param content the data, free with der_free_octet_string().
351 hx509_cms_unenvelope(hx509_context context
,
356 const heim_octet_string
*encryptedContent
,
358 heim_oid
*contentType
,
359 heim_octet_string
*content
)
361 heim_octet_string key
;
364 AlgorithmIdentifier
*ai
;
365 const heim_octet_string
*enccontent
;
366 heim_octet_string
*params
, params_data
;
367 heim_octet_string ivec
;
369 int ret
, matched
= 0, findflags
= 0;
373 memset(&key
, 0, sizeof(key
));
374 memset(&ed
, 0, sizeof(ed
));
375 memset(&ivec
, 0, sizeof(ivec
));
376 memset(content
, 0, sizeof(*content
));
377 memset(contentType
, 0, sizeof(*contentType
));
379 if ((flags
& HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT
) == 0)
380 findflags
|= HX509_QUERY_KU_ENCIPHERMENT
;
382 ret
= decode_EnvelopedData(data
, length
, &ed
, &size
);
384 hx509_set_error_string(context
, 0, ret
,
385 "Failed to decode EnvelopedData");
389 if (ed
.recipientInfos
.len
== 0) {
390 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
391 hx509_set_error_string(context
, 0, ret
,
392 "No recipient info in enveloped data");
396 enccontent
= ed
.encryptedContentInfo
.encryptedContent
;
397 if (enccontent
== NULL
) {
398 if (encryptedContent
== NULL
) {
399 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
400 hx509_set_error_string(context
, 0, ret
,
401 "Content missing from encrypted data");
404 enccontent
= encryptedContent
;
405 } else if (encryptedContent
!= NULL
) {
406 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
407 hx509_set_error_string(context
, 0, ret
,
408 "Both internal and external encrypted data");
413 for (i
= 0; i
< ed
.recipientInfos
.len
; i
++) {
414 KeyTransRecipientInfo
*ri
;
418 ri
= &ed
.recipientInfos
.val
[i
];
420 ret
= find_CMSIdentifier(context
, &ri
->rid
, certs
,
422 HX509_QUERY_PRIVATE_KEY
|findflags
);
426 matched
= 1; /* found a matching certificate, let decrypt */
428 ret
= _hx509_cert_private_decrypt(context
,
430 &ri
->keyEncryptionAlgorithm
.algorithm
,
433 hx509_cert_free(cert
);
435 break; /* succuessfully decrypted cert */
437 ret2
= unparse_CMSIdentifier(context
, &ri
->rid
, &str
);
439 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
440 "Failed to decrypt with %s", str
);
446 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
447 hx509_set_error_string(context
, 0, ret
,
448 "No private key matched any certificate");
453 ret
= HX509_CMS_NO_RECIPIENT_CERTIFICATE
;
454 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
455 "No private key decrypted the transfer key");
459 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
461 hx509_set_error_string(context
, 0, ret
,
462 "Failed to copy EnvelopedData content oid");
466 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
467 if (ai
->parameters
) {
468 params_data
.data
= ai
->parameters
->data
;
469 params_data
.length
= ai
->parameters
->length
;
470 params
= ¶ms_data
;
477 ret
= hx509_crypto_init(context
, NULL
, &ai
->algorithm
, &crypto
);
481 if (flags
& HX509_CMS_UE_ALLOW_WEAK
)
482 hx509_crypto_allow_weak(crypto
);
485 ret
= hx509_crypto_set_params(context
, crypto
, params
, &ivec
);
487 hx509_crypto_destroy(crypto
);
492 ret
= hx509_crypto_set_key_data(crypto
, key
.data
, key
.length
);
494 hx509_crypto_destroy(crypto
);
495 hx509_set_error_string(context
, 0, ret
,
496 "Failed to set key for decryption "
501 ret
= hx509_crypto_decrypt(crypto
,
504 ivec
.length
? &ivec
: NULL
,
506 hx509_crypto_destroy(crypto
);
508 hx509_set_error_string(context
, 0, ret
,
509 "Failed to decrypt EnvelopedData");
516 free_EnvelopedData(&ed
);
517 der_free_octet_string(&key
);
519 der_free_octet_string(&ivec
);
521 der_free_oid(contentType
);
522 der_free_octet_string(content
);
529 * Encrypt end encode EnvelopedData.
531 * Encrypt and encode EnvelopedData. The data is encrypted with a
532 * random key and the the random key is encrypted with the
533 * certificates private key. This limits what private key type can be
536 * @param context A hx509 context.
537 * @param flags flags to control the behavior.
538 * - HX509_CMS_EV_NO_KU_CHECK - Dont check KU on certificate
539 * - HX509_CMS_EV_ALLOW_WEAK - Allow weak crytpo
540 * - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number
541 * @param cert Certificate to encrypt the EnvelopedData encryption key
543 * @param data pointer the data to encrypt.
544 * @param length length of the data that data point to.
545 * @param encryption_type Encryption cipher to use for the bulk data,
546 * use NULL to get default.
547 * @param contentType type of the data that is encrypted
548 * @param content the output of the function,
549 * free with der_free_octet_string().
555 hx509_cms_envelope_1(hx509_context context
,
560 const heim_oid
*encryption_type
,
561 const heim_oid
*contentType
,
562 heim_octet_string
*content
)
564 KeyTransRecipientInfo
*ri
;
565 heim_octet_string ivec
;
566 heim_octet_string key
;
567 hx509_crypto crypto
= NULL
;
572 memset(&ivec
, 0, sizeof(ivec
));
573 memset(&key
, 0, sizeof(key
));
574 memset(&ed
, 0, sizeof(ed
));
575 memset(content
, 0, sizeof(*content
));
577 if (encryption_type
== NULL
)
578 encryption_type
= &asn1_oid_id_aes_256_cbc
;
580 if ((flags
& HX509_CMS_EV_NO_KU_CHECK
) == 0) {
581 ret
= _hx509_check_key_usage(context
, cert
, 1 << 2, TRUE
);
586 ret
= hx509_crypto_init(context
, NULL
, encryption_type
, &crypto
);
590 if (flags
& HX509_CMS_EV_ALLOW_WEAK
)
591 hx509_crypto_allow_weak(crypto
);
593 ret
= hx509_crypto_set_random_key(crypto
, &key
);
595 hx509_set_error_string(context
, 0, ret
,
596 "Create random key for EnvelopedData content");
600 ret
= hx509_crypto_random_iv(crypto
, &ivec
);
602 hx509_set_error_string(context
, 0, ret
,
603 "Failed to create a random iv");
607 ret
= hx509_crypto_encrypt(crypto
,
611 &ed
.encryptedContentInfo
.encryptedContent
);
613 hx509_set_error_string(context
, 0, ret
,
614 "Failed to encrypt EnvelopedData content");
619 AlgorithmIdentifier
*enc_alg
;
620 enc_alg
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
621 ret
= der_copy_oid(encryption_type
, &enc_alg
->algorithm
);
623 hx509_set_error_string(context
, 0, ret
,
624 "Failed to set crypto oid "
625 "for EnvelopedData");
628 ALLOC(enc_alg
->parameters
, 1);
629 if (enc_alg
->parameters
== NULL
) {
631 hx509_set_error_string(context
, 0, ret
,
632 "Failed to allocate crypto paramaters "
633 "for EnvelopedData");
637 ret
= hx509_crypto_get_params(context
,
640 enc_alg
->parameters
);
646 ALLOC_SEQ(&ed
.recipientInfos
, 1);
647 if (ed
.recipientInfos
.val
== NULL
) {
649 hx509_set_error_string(context
, 0, ret
,
650 "Failed to allocate recipients info "
651 "for EnvelopedData");
655 ri
= &ed
.recipientInfos
.val
[0];
657 if (flags
& HX509_CMS_EV_ID_NAME
) {
659 cmsidflag
= CMS_ID_NAME
;
662 cmsidflag
= CMS_ID_SKI
;
665 ret
= fill_CMSIdentifier(cert
, cmsidflag
, &ri
->rid
);
667 hx509_set_error_string(context
, 0, ret
,
668 "Failed to set CMS identifier info "
669 "for EnvelopedData");
673 ret
= hx509_cert_public_encrypt(context
,
675 &ri
->keyEncryptionAlgorithm
.algorithm
,
678 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
679 "Failed to encrypt transport key for "
689 ed
.originatorInfo
= NULL
;
691 ret
= der_copy_oid(contentType
, &ed
.encryptedContentInfo
.contentType
);
693 hx509_set_error_string(context
, 0, ret
,
694 "Failed to copy content oid for "
699 ed
.unprotectedAttrs
= NULL
;
701 ASN1_MALLOC_ENCODE(EnvelopedData
, content
->data
, content
->length
,
704 hx509_set_error_string(context
, 0, ret
,
705 "Failed to encode EnvelopedData");
708 if (size
!= content
->length
)
709 _hx509_abort("internal ASN.1 encoder error");
713 hx509_crypto_destroy(crypto
);
715 der_free_octet_string(content
);
716 der_free_octet_string(&key
);
717 der_free_octet_string(&ivec
);
718 free_EnvelopedData(&ed
);
724 any_to_certs(hx509_context context
, const SignedData
*sd
, hx509_certs certs
)
729 if (sd
->certificates
== NULL
)
732 for (i
= 0; i
< sd
->certificates
->len
; i
++) {
736 c
= hx509_cert_init_data(context
,
737 sd
->certificates
->val
[i
].data
,
738 sd
->certificates
->val
[i
].length
,
741 ret
= heim_error_get_code(error
);
745 ret
= hx509_certs_add(context
, certs
, c
);
754 static const Attribute
*
755 find_attribute(const CMSAttributes
*attr
, const heim_oid
*oid
)
758 for (i
= 0; i
< attr
->len
; i
++)
759 if (der_heim_oid_cmp(&attr
->val
[i
].type
, oid
) == 0)
760 return &attr
->val
[i
];
765 * Decode SignedData and verify that the signature is correct.
767 * @param context A hx509 context.
768 * @param ctx a hx509 verify context.
769 * @param flags to control the behaivor of the function.
770 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
771 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
772 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
773 * @param data pointer to CMS SignedData encoded data.
774 * @param length length of the data that data point to.
775 * @param signedContent external data used for signature.
776 * @param pool certificate pool to build certificates paths.
777 * @param contentType free with der_free_oid().
778 * @param content the output of the function, free with
779 * der_free_octet_string().
780 * @param signer_certs list of the cerficates used to sign this
781 * request, free with hx509_certs_free().
787 hx509_cms_verify_signed(hx509_context context
,
788 hx509_verify_ctx ctx
,
792 const heim_octet_string
*signedContent
,
794 heim_oid
*contentType
,
795 heim_octet_string
*content
,
796 hx509_certs
*signer_certs
)
798 SignerInfo
*signer_info
;
799 hx509_cert cert
= NULL
;
800 hx509_certs certs
= NULL
;
803 int ret
, found_valid_sig
;
806 *signer_certs
= NULL
;
807 content
->data
= NULL
;
809 contentType
->length
= 0;
810 contentType
->components
= NULL
;
812 memset(&sd
, 0, sizeof(sd
));
814 ret
= decode_SignedData(data
, length
, &sd
, &size
);
816 hx509_set_error_string(context
, 0, ret
,
817 "Failed to decode SignedData");
821 if (sd
.encapContentInfo
.eContent
== NULL
&& signedContent
== NULL
) {
822 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
823 hx509_set_error_string(context
, 0, ret
,
824 "No content data in SignedData");
827 if (sd
.encapContentInfo
.eContent
&& signedContent
) {
828 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
829 hx509_set_error_string(context
, 0, ret
,
830 "Both external and internal SignedData");
834 if (sd
.encapContentInfo
.eContent
)
835 ret
= der_copy_octet_string(sd
.encapContentInfo
.eContent
, content
);
837 ret
= der_copy_octet_string(signedContent
, content
);
839 hx509_set_error_string(context
, 0, ret
, "malloc: out of memory");
843 ret
= hx509_certs_init(context
, "MEMORY:cms-cert-buffer",
848 ret
= hx509_certs_init(context
, "MEMORY:cms-signer-certs",
849 0, NULL
, signer_certs
);
853 /* XXX Check CMS version */
855 ret
= any_to_certs(context
, &sd
, certs
);
860 ret
= hx509_certs_merge(context
, certs
, pool
);
865 for (found_valid_sig
= 0, i
= 0; i
< sd
.signerInfos
.len
; i
++) {
866 heim_octet_string signed_data
;
867 const heim_oid
*match_oid
;
870 signer_info
= &sd
.signerInfos
.val
[i
];
873 if (signer_info
->signature
.length
== 0) {
874 ret
= HX509_CMS_MISSING_SIGNER_DATA
;
875 hx509_set_error_string(context
, 0, ret
,
876 "SignerInfo %d in SignedData "
877 "missing sigature", i
);
881 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
882 _hx509_verify_get_time(ctx
), &cert
,
883 HX509_QUERY_KU_DIGITALSIGNATURE
);
886 * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
887 * search for matching certificates by not considering
888 * KeyUsage bits on the certificates.
890 if ((flags
& HX509_CMS_VS_NO_KU_CHECK
) == 0)
893 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
894 _hx509_verify_get_time(ctx
), &cert
,
901 if (signer_info
->signedAttrs
) {
902 const Attribute
*attr
;
905 heim_octet_string os
;
907 sa
.val
= signer_info
->signedAttrs
->val
;
908 sa
.len
= signer_info
->signedAttrs
->len
;
910 /* verify that sigature exists */
911 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_messageDigest
);
913 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
914 hx509_set_error_string(context
, 0, ret
,
915 "SignerInfo have signed attributes "
916 "but messageDigest (signature) "
920 if (attr
->value
.len
!= 1) {
921 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
922 hx509_set_error_string(context
, 0, ret
,
923 "SignerInfo have more then one "
924 "messageDigest (signature)");
928 ret
= decode_MessageDigest(attr
->value
.val
[0].data
,
929 attr
->value
.val
[0].length
,
933 hx509_set_error_string(context
, 0, ret
,
935 "messageDigest (signature)");
939 ret
= _hx509_verify_signature(context
,
941 &signer_info
->digestAlgorithm
,
944 der_free_octet_string(&os
);
946 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
947 "Failed to verify messageDigest");
952 * Fetch content oid inside signedAttrs or set it to
955 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_contentType
);
957 match_oid
= &asn1_oid_id_pkcs7_data
;
959 if (attr
->value
.len
!= 1) {
960 ret
= HX509_CMS_DATA_OID_MISMATCH
;
961 hx509_set_error_string(context
, 0, ret
,
962 "More then one oid in signedAttrs");
966 ret
= decode_ContentType(attr
->value
.val
[0].data
,
967 attr
->value
.val
[0].length
,
971 hx509_set_error_string(context
, 0, ret
,
973 "oid in signedAttrs");
976 match_oid
= &decode_oid
;
979 ASN1_MALLOC_ENCODE(CMSAttributes
,
985 if (match_oid
== &decode_oid
)
986 der_free_oid(&decode_oid
);
987 hx509_clear_error_string(context
);
990 if (size
!= signed_data
.length
)
991 _hx509_abort("internal ASN.1 encoder error");
994 signed_data
.data
= content
->data
;
995 signed_data
.length
= content
->length
;
996 match_oid
= &asn1_oid_id_pkcs7_data
;
1000 * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
1001 * encapContentInfo mismatch with the oid in signedAttributes
1002 * (or if no signedAttributes where use, pkcs7-data oid).
1003 * This is only needed to work with broken CMS implementations
1004 * that doesn't follow CMS signedAttributes rules.
1007 if (der_heim_oid_cmp(match_oid
, &sd
.encapContentInfo
.eContentType
) &&
1008 (flags
& HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH
) == 0) {
1009 ret
= HX509_CMS_DATA_OID_MISMATCH
;
1010 hx509_set_error_string(context
, 0, ret
,
1011 "Oid in message mismatch from the expected");
1013 if (match_oid
== &decode_oid
)
1014 der_free_oid(&decode_oid
);
1017 ret
= hx509_verify_signature(context
,
1019 &signer_info
->signatureAlgorithm
,
1021 &signer_info
->signature
);
1023 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
1024 "Failed to verify signature in "
1027 if (signer_info
->signedAttrs
)
1028 free(signed_data
.data
);
1033 * If HX509_CMS_VS_NO_VALIDATE flags is set, do not verify the
1034 * signing certificates and leave that up to the caller.
1037 if ((flags
& HX509_CMS_VS_NO_VALIDATE
) == 0) {
1038 ret
= hx509_verify_path(context
, ctx
, cert
, certs
);
1043 ret
= hx509_certs_add(context
, *signer_certs
, cert
);
1051 hx509_cert_free(cert
);
1055 * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
1056 * SignerInfo (no signatures). If SignedData have no signatures,
1057 * the function will return 0 with signer_certs set to NULL. Zero
1058 * signers is allowed by the standard, but since its only useful
1059 * in corner cases, it make into a flag that the caller have to
1062 if (sd
.signerInfos
.len
== 0 && (flags
& HX509_CMS_VS_ALLOW_ZERO_SIGNER
)) {
1064 hx509_certs_free(signer_certs
);
1065 } else if (found_valid_sig
== 0) {
1067 ret
= HX509_CMS_SIGNER_NOT_FOUND
;
1068 hx509_set_error_string(context
, 0, ret
,
1069 "No signers where found");
1074 ret
= der_copy_oid(&sd
.encapContentInfo
.eContentType
, contentType
);
1076 hx509_clear_error_string(context
);
1081 free_SignedData(&sd
);
1083 hx509_certs_free(&certs
);
1086 der_free_octet_string(content
);
1088 hx509_certs_free(signer_certs
);
1089 der_free_oid(contentType
);
1090 der_free_octet_string(content
);
1097 add_one_attribute(Attribute
**attr
,
1099 const heim_oid
*oid
,
1100 heim_octet_string
*data
)
1105 d
= realloc(*attr
, sizeof((*attr
)[0]) * (*len
+ 1));
1110 ret
= der_copy_oid(oid
, &(*attr
)[*len
].type
);
1114 ALLOC_SEQ(&(*attr
)[*len
].value
, 1);
1115 if ((*attr
)[*len
].value
.val
== NULL
) {
1116 der_free_oid(&(*attr
)[*len
].type
);
1120 (*attr
)[*len
].value
.val
[0].data
= data
->data
;
1121 (*attr
)[*len
].value
.val
[0].length
= data
->length
;
1129 * Decode SignedData and verify that the signature is correct.
1131 * @param context A hx509 context.
1133 * @param eContentType the type of the data.
1134 * @param data data to sign
1135 * @param length length of the data that data point to.
1136 * @param digest_alg digest algorithm to use, use NULL to get the
1137 * default or the peer determined algorithm.
1138 * @param cert certificate to use for sign the data.
1139 * @param peer info about the peer the message to send the message to,
1140 * like what digest algorithm to use.
1141 * @param anchors trust anchors that the client will use, used to
1142 * polulate the certificates included in the message
1143 * @param pool certificates to use in try to build the path to the
1145 * @param signed_data the output of the function, free with
1146 * der_free_octet_string().
1148 * @ingroup hx509_cms
1152 hx509_cms_create_signed_1(hx509_context context
,
1154 const heim_oid
*eContentType
,
1155 const void *data
, size_t length
,
1156 const AlgorithmIdentifier
*digest_alg
,
1158 hx509_peer_info peer
,
1159 hx509_certs anchors
,
1161 heim_octet_string
*signed_data
)
1166 signed_data
->data
= NULL
;
1167 signed_data
->length
= 0;
1169 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &certs
);
1172 ret
= hx509_certs_add(context
, certs
, cert
);
1176 ret
= hx509_cms_create_signed(context
, flags
, eContentType
, data
, length
,
1177 digest_alg
, certs
, peer
, anchors
, pool
,
1181 hx509_certs_free(&certs
);
1187 const AlgorithmIdentifier
*digest_alg
;
1188 const heim_oid
*eContentType
;
1189 heim_octet_string content
;
1190 hx509_peer_info peer
;
1194 hx509_certs anchors
;
1199 sig_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1201 struct sigctx
*sigctx
= ctx
;
1202 heim_octet_string buf
, sigdata
= { 0, NULL
};
1203 SignerInfo
*signer_info
= NULL
;
1204 AlgorithmIdentifier digest
;
1208 SignedData
*sd
= &sigctx
->sd
;
1211 memset(&digest
, 0, sizeof(digest
));
1212 memset(&path
, 0, sizeof(path
));
1214 if (_hx509_cert_private_key(cert
) == NULL
) {
1215 hx509_set_error_string(context
, 0, HX509_PRIVATE_KEY_MISSING
,
1216 "Private key missing for signing");
1217 return HX509_PRIVATE_KEY_MISSING
;
1220 if (sigctx
->digest_alg
) {
1221 ret
= copy_AlgorithmIdentifier(sigctx
->digest_alg
, &digest
);
1223 hx509_clear_error_string(context
);
1225 ret
= hx509_crypto_select(context
, HX509_SELECT_DIGEST
,
1226 _hx509_cert_private_key(cert
),
1227 sigctx
->peer
, &digest
);
1233 * Allocate on more signerInfo and do the signature processing
1236 ptr
= realloc(sd
->signerInfos
.val
,
1237 (sd
->signerInfos
.len
+ 1) * sizeof(sd
->signerInfos
.val
[0]));
1242 sd
->signerInfos
.val
= ptr
;
1244 signer_info
= &sd
->signerInfos
.val
[sd
->signerInfos
.len
];
1246 memset(signer_info
, 0, sizeof(*signer_info
));
1248 signer_info
->version
= 1;
1250 ret
= fill_CMSIdentifier(cert
, sigctx
->cmsidflag
, &signer_info
->sid
);
1252 hx509_clear_error_string(context
);
1256 signer_info
->signedAttrs
= NULL
;
1257 signer_info
->unsignedAttrs
= NULL
;
1259 ret
= copy_AlgorithmIdentifier(&digest
, &signer_info
->digestAlgorithm
);
1261 hx509_clear_error_string(context
);
1266 * If it isn't pkcs7-data send signedAttributes
1269 if (der_heim_oid_cmp(sigctx
->eContentType
, &asn1_oid_id_pkcs7_data
) != 0) {
1271 heim_octet_string sig
;
1273 ALLOC(signer_info
->signedAttrs
, 1);
1274 if (signer_info
->signedAttrs
== NULL
) {
1279 ret
= _hx509_create_signature(context
,
1288 ASN1_MALLOC_ENCODE(MessageDigest
,
1294 der_free_octet_string(&sig
);
1296 hx509_clear_error_string(context
);
1299 if (size
!= buf
.length
)
1300 _hx509_abort("internal ASN.1 encoder error");
1302 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1303 &signer_info
->signedAttrs
->len
,
1304 &asn1_oid_id_pkcs9_messageDigest
,
1308 hx509_clear_error_string(context
);
1313 ASN1_MALLOC_ENCODE(ContentType
,
1316 sigctx
->eContentType
,
1321 if (size
!= buf
.length
)
1322 _hx509_abort("internal ASN.1 encoder error");
1324 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1325 &signer_info
->signedAttrs
->len
,
1326 &asn1_oid_id_pkcs9_contentType
,
1330 hx509_clear_error_string(context
);
1334 sa
.val
= signer_info
->signedAttrs
->val
;
1335 sa
.len
= signer_info
->signedAttrs
->len
;
1337 ASN1_MALLOC_ENCODE(CMSAttributes
,
1344 hx509_clear_error_string(context
);
1347 if (size
!= sigdata
.length
)
1348 _hx509_abort("internal ASN.1 encoder error");
1350 sigdata
.data
= sigctx
->content
.data
;
1351 sigdata
.length
= sigctx
->content
.length
;
1355 AlgorithmIdentifier sigalg
;
1357 ret
= hx509_crypto_select(context
, HX509_SELECT_PUBLIC_SIG
,
1358 _hx509_cert_private_key(cert
), sigctx
->peer
,
1363 ret
= _hx509_create_signature(context
,
1364 _hx509_cert_private_key(cert
),
1367 &signer_info
->signatureAlgorithm
,
1368 &signer_info
->signature
);
1369 free_AlgorithmIdentifier(&sigalg
);
1374 sigctx
->sd
.signerInfos
.len
++;
1378 * Provide best effort path
1380 if (sigctx
->certs
) {
1383 if (sigctx
->pool
&& sigctx
->leafonly
== 0) {
1384 _hx509_calculate_path(context
,
1385 HX509_CALCULATE_PATH_NO_ANCHOR
,
1393 _hx509_path_append(context
, &path
, cert
);
1395 for (i
= 0; i
< path
.len
; i
++) {
1396 /* XXX remove dups */
1397 ret
= hx509_certs_add(context
, sigctx
->certs
, path
.val
[i
]);
1399 hx509_clear_error_string(context
);
1407 free_SignerInfo(signer_info
);
1408 if (sigdata
.data
!= sigctx
->content
.data
)
1409 der_free_octet_string(&sigdata
);
1410 _hx509_path_free(&path
);
1411 free_AlgorithmIdentifier(&digest
);
1417 cert_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1419 struct sigctx
*sigctx
= ctx
;
1420 const unsigned int i
= sigctx
->sd
.certificates
->len
;
1424 ptr
= realloc(sigctx
->sd
.certificates
->val
,
1425 (i
+ 1) * sizeof(sigctx
->sd
.certificates
->val
[0]));
1428 sigctx
->sd
.certificates
->val
= ptr
;
1430 ret
= hx509_cert_binary(context
, cert
,
1431 &sigctx
->sd
.certificates
->val
[i
]);
1433 sigctx
->sd
.certificates
->len
++;
1439 cmp_AlgorithmIdentifier(const AlgorithmIdentifier
*p
, const AlgorithmIdentifier
*q
)
1441 return der_heim_oid_cmp(&p
->algorithm
, &q
->algorithm
);
1445 hx509_cms_create_signed(hx509_context context
,
1447 const heim_oid
*eContentType
,
1448 const void *data
, size_t length
,
1449 const AlgorithmIdentifier
*digest_alg
,
1451 hx509_peer_info peer
,
1452 hx509_certs anchors
,
1454 heim_octet_string
*signed_data
)
1460 struct sigctx sigctx
;
1462 memset(&sigctx
, 0, sizeof(sigctx
));
1463 memset(&name
, 0, sizeof(name
));
1465 if (eContentType
== NULL
)
1466 eContentType
= &asn1_oid_id_pkcs7_data
;
1468 sigctx
.digest_alg
= digest_alg
;
1469 sigctx
.content
.data
= rk_UNCONST(data
);
1470 sigctx
.content
.length
= length
;
1471 sigctx
.eContentType
= eContentType
;
1474 * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name
1475 * and serial number if possible. Otherwise subject key identifier
1478 if (flags
& HX509_CMS_SIGNATURE_ID_NAME
)
1479 sigctx
.cmsidflag
= CMS_ID_NAME
;
1481 sigctx
.cmsidflag
= CMS_ID_SKI
;
1484 * Use HX509_CMS_SIGNATURE_LEAF_ONLY to only request leaf
1485 * certificates to be added to the SignedData.
1487 sigctx
.leafonly
= (flags
& HX509_CMS_SIGNATURE_LEAF_ONLY
) ? 1 : 0;
1490 * Use HX509_CMS_NO_CERTS to make the SignedData contain no
1491 * certificates, overrides HX509_CMS_SIGNATURE_LEAF_ONLY.
1494 if ((flags
& HX509_CMS_SIGNATURE_NO_CERTS
) == 0) {
1495 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &sigctx
.certs
);
1500 sigctx
.anchors
= anchors
;
1503 sigctx
.sd
.version
= CMSVersion_v3
;
1505 der_copy_oid(eContentType
, &sigctx
.sd
.encapContentInfo
.eContentType
);
1508 * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
1510 if ((flags
& HX509_CMS_SIGNATURE_DETACHED
) == 0) {
1511 ALLOC(sigctx
.sd
.encapContentInfo
.eContent
, 1);
1512 if (sigctx
.sd
.encapContentInfo
.eContent
== NULL
) {
1513 hx509_clear_error_string(context
);
1518 sigctx
.sd
.encapContentInfo
.eContent
->data
= malloc(length
);
1519 if (sigctx
.sd
.encapContentInfo
.eContent
->data
== NULL
) {
1520 hx509_clear_error_string(context
);
1524 memcpy(sigctx
.sd
.encapContentInfo
.eContent
->data
, data
, length
);
1525 sigctx
.sd
.encapContentInfo
.eContent
->length
= length
;
1529 * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
1532 if ((flags
& HX509_CMS_SIGNATURE_NO_SIGNER
) == 0) {
1533 ret
= hx509_certs_iter_f(context
, certs
, sig_process
, &sigctx
);
1538 if (sigctx
.sd
.signerInfos
.len
) {
1541 * For each signerInfo, collect all different digest types.
1543 for (i
= 0; i
< sigctx
.sd
.signerInfos
.len
; i
++) {
1544 AlgorithmIdentifier
*di
=
1545 &sigctx
.sd
.signerInfos
.val
[i
].digestAlgorithm
;
1547 for (j
= 0; j
< sigctx
.sd
.digestAlgorithms
.len
; j
++)
1548 if (cmp_AlgorithmIdentifier(di
, &sigctx
.sd
.digestAlgorithms
.val
[j
]) == 0)
1550 if (j
== sigctx
.sd
.digestAlgorithms
.len
) {
1551 ret
= add_DigestAlgorithmIdentifiers(&sigctx
.sd
.digestAlgorithms
, di
);
1553 hx509_clear_error_string(context
);
1561 * Add certs we think are needed, build as part of sig_process
1564 ALLOC(sigctx
.sd
.certificates
, 1);
1565 if (sigctx
.sd
.certificates
== NULL
) {
1566 hx509_clear_error_string(context
);
1571 ret
= hx509_certs_iter_f(context
, sigctx
.certs
, cert_process
, &sigctx
);
1576 ASN1_MALLOC_ENCODE(SignedData
,
1577 signed_data
->data
, signed_data
->length
,
1578 &sigctx
.sd
, &size
, ret
);
1580 hx509_clear_error_string(context
);
1583 if (signed_data
->length
!= size
)
1584 _hx509_abort("internal ASN.1 encoder error");
1587 hx509_certs_free(&sigctx
.certs
);
1588 free_SignedData(&sigctx
.sd
);
1594 hx509_cms_decrypt_encrypted(hx509_context context
,
1598 heim_oid
*contentType
,
1599 heim_octet_string
*content
)
1601 heim_octet_string cont
;
1602 CMSEncryptedData ed
;
1603 AlgorithmIdentifier
*ai
;
1606 memset(content
, 0, sizeof(*content
));
1607 memset(&cont
, 0, sizeof(cont
));
1609 ret
= decode_CMSEncryptedData(data
, length
, &ed
, NULL
);
1611 hx509_set_error_string(context
, 0, ret
,
1612 "Failed to decode CMSEncryptedData");
1616 if (ed
.encryptedContentInfo
.encryptedContent
== NULL
) {
1617 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
1618 hx509_set_error_string(context
, 0, ret
,
1619 "No content in EncryptedData");
1623 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
1625 hx509_clear_error_string(context
);
1629 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
1630 if (ai
->parameters
== NULL
) {
1631 ret
= HX509_ALG_NOT_SUPP
;
1632 hx509_clear_error_string(context
);
1636 ret
= _hx509_pbe_decrypt(context
,
1639 ed
.encryptedContentInfo
.encryptedContent
,
1651 free_CMSEncryptedData(&ed
);