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
++) {
735 ret
= hx509_cert_init_data(context
,
736 sd
->certificates
->val
[i
].data
,
737 sd
->certificates
->val
[i
].length
,
741 ret
= hx509_certs_add(context
, certs
, c
);
750 static const Attribute
*
751 find_attribute(const CMSAttributes
*attr
, const heim_oid
*oid
)
754 for (i
= 0; i
< attr
->len
; i
++)
755 if (der_heim_oid_cmp(&attr
->val
[i
].type
, oid
) == 0)
756 return &attr
->val
[i
];
761 * Decode SignedData and verify that the signature is correct.
763 * @param context A hx509 context.
764 * @param ctx a hx509 verify context.
765 * @param flags to control the behaivor of the function.
766 * - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
767 * - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
768 * - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
769 * @param data pointer to CMS SignedData encoded data.
770 * @param length length of the data that data point to.
771 * @param signedContent external data used for signature.
772 * @param pool certificate pool to build certificates paths.
773 * @param contentType free with der_free_oid().
774 * @param content the output of the function, free with
775 * der_free_octet_string().
776 * @param signer_certs list of the cerficates used to sign this
777 * request, free with hx509_certs_free().
783 hx509_cms_verify_signed(hx509_context context
,
784 hx509_verify_ctx ctx
,
788 const heim_octet_string
*signedContent
,
790 heim_oid
*contentType
,
791 heim_octet_string
*content
,
792 hx509_certs
*signer_certs
)
794 SignerInfo
*signer_info
;
795 hx509_cert cert
= NULL
;
796 hx509_certs certs
= NULL
;
799 int ret
, found_valid_sig
;
802 *signer_certs
= NULL
;
803 content
->data
= NULL
;
805 contentType
->length
= 0;
806 contentType
->components
= NULL
;
808 memset(&sd
, 0, sizeof(sd
));
810 ret
= decode_SignedData(data
, length
, &sd
, &size
);
812 hx509_set_error_string(context
, 0, ret
,
813 "Failed to decode SignedData");
817 if (sd
.encapContentInfo
.eContent
== NULL
&& signedContent
== NULL
) {
818 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
819 hx509_set_error_string(context
, 0, ret
,
820 "No content data in SignedData");
823 if (sd
.encapContentInfo
.eContent
&& signedContent
) {
824 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
825 hx509_set_error_string(context
, 0, ret
,
826 "Both external and internal SignedData");
830 if (sd
.encapContentInfo
.eContent
)
831 ret
= der_copy_octet_string(sd
.encapContentInfo
.eContent
, content
);
833 ret
= der_copy_octet_string(signedContent
, content
);
835 hx509_set_error_string(context
, 0, ret
, "malloc: out of memory");
839 ret
= hx509_certs_init(context
, "MEMORY:cms-cert-buffer",
844 ret
= hx509_certs_init(context
, "MEMORY:cms-signer-certs",
845 0, NULL
, signer_certs
);
849 /* XXX Check CMS version */
851 ret
= any_to_certs(context
, &sd
, certs
);
856 ret
= hx509_certs_merge(context
, certs
, pool
);
861 for (found_valid_sig
= 0, i
= 0; i
< sd
.signerInfos
.len
; i
++) {
862 heim_octet_string signed_data
;
863 const heim_oid
*match_oid
;
866 signer_info
= &sd
.signerInfos
.val
[i
];
869 if (signer_info
->signature
.length
== 0) {
870 ret
= HX509_CMS_MISSING_SIGNER_DATA
;
871 hx509_set_error_string(context
, 0, ret
,
872 "SignerInfo %d in SignedData "
873 "missing sigature", i
);
877 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
878 _hx509_verify_get_time(ctx
), &cert
,
879 HX509_QUERY_KU_DIGITALSIGNATURE
);
882 * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
883 * search for matching certificates by not considering
884 * KeyUsage bits on the certificates.
886 if ((flags
& HX509_CMS_VS_NO_KU_CHECK
) == 0)
889 ret
= find_CMSIdentifier(context
, &signer_info
->sid
, certs
,
890 _hx509_verify_get_time(ctx
), &cert
,
897 if (signer_info
->signedAttrs
) {
898 const Attribute
*attr
;
901 heim_octet_string os
;
903 sa
.val
= signer_info
->signedAttrs
->val
;
904 sa
.len
= signer_info
->signedAttrs
->len
;
906 /* verify that sigature exists */
907 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_messageDigest
);
909 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
910 hx509_set_error_string(context
, 0, ret
,
911 "SignerInfo have signed attributes "
912 "but messageDigest (signature) "
916 if (attr
->value
.len
!= 1) {
917 ret
= HX509_CRYPTO_SIGNATURE_MISSING
;
918 hx509_set_error_string(context
, 0, ret
,
919 "SignerInfo have more then one "
920 "messageDigest (signature)");
924 ret
= decode_MessageDigest(attr
->value
.val
[0].data
,
925 attr
->value
.val
[0].length
,
929 hx509_set_error_string(context
, 0, ret
,
931 "messageDigest (signature)");
935 ret
= _hx509_verify_signature(context
,
937 &signer_info
->digestAlgorithm
,
940 der_free_octet_string(&os
);
942 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
943 "Failed to verify messageDigest");
948 * Fetch content oid inside signedAttrs or set it to
951 attr
= find_attribute(&sa
, &asn1_oid_id_pkcs9_contentType
);
953 match_oid
= &asn1_oid_id_pkcs7_data
;
955 if (attr
->value
.len
!= 1) {
956 ret
= HX509_CMS_DATA_OID_MISMATCH
;
957 hx509_set_error_string(context
, 0, ret
,
958 "More then one oid in signedAttrs");
962 ret
= decode_ContentType(attr
->value
.val
[0].data
,
963 attr
->value
.val
[0].length
,
967 hx509_set_error_string(context
, 0, ret
,
969 "oid in signedAttrs");
972 match_oid
= &decode_oid
;
975 ASN1_MALLOC_ENCODE(CMSAttributes
,
981 if (match_oid
== &decode_oid
)
982 der_free_oid(&decode_oid
);
983 hx509_clear_error_string(context
);
986 if (size
!= signed_data
.length
)
987 _hx509_abort("internal ASN.1 encoder error");
990 signed_data
.data
= content
->data
;
991 signed_data
.length
= content
->length
;
992 match_oid
= &asn1_oid_id_pkcs7_data
;
996 * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
997 * encapContentInfo mismatch with the oid in signedAttributes
998 * (or if no signedAttributes where use, pkcs7-data oid).
999 * This is only needed to work with broken CMS implementations
1000 * that doesn't follow CMS signedAttributes rules.
1003 if (der_heim_oid_cmp(match_oid
, &sd
.encapContentInfo
.eContentType
) &&
1004 (flags
& HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH
) == 0) {
1005 ret
= HX509_CMS_DATA_OID_MISMATCH
;
1006 hx509_set_error_string(context
, 0, ret
,
1007 "Oid in message mismatch from the expected");
1009 if (match_oid
== &decode_oid
)
1010 der_free_oid(&decode_oid
);
1013 ret
= hx509_verify_signature(context
,
1015 &signer_info
->signatureAlgorithm
,
1017 &signer_info
->signature
);
1019 hx509_set_error_string(context
, HX509_ERROR_APPEND
, ret
,
1020 "Failed to verify signature in "
1023 if (signer_info
->signedAttrs
)
1024 free(signed_data
.data
);
1029 * If HX509_CMS_VS_NO_VALIDATE flags is set, do not verify the
1030 * signing certificates and leave that up to the caller.
1033 if ((flags
& HX509_CMS_VS_NO_VALIDATE
) == 0) {
1034 ret
= hx509_verify_path(context
, ctx
, cert
, certs
);
1039 ret
= hx509_certs_add(context
, *signer_certs
, cert
);
1047 hx509_cert_free(cert
);
1051 * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
1052 * SignerInfo (no signatures). If SignedData have no signatures,
1053 * the function will return 0 with signer_certs set to NULL. Zero
1054 * signers is allowed by the standard, but since its only useful
1055 * in corner cases, it make into a flag that the caller have to
1058 if (sd
.signerInfos
.len
== 0 && (flags
& HX509_CMS_VS_ALLOW_ZERO_SIGNER
)) {
1060 hx509_certs_free(signer_certs
);
1061 } else if (found_valid_sig
== 0) {
1063 ret
= HX509_CMS_SIGNER_NOT_FOUND
;
1064 hx509_set_error_string(context
, 0, ret
,
1065 "No signers where found");
1070 ret
= der_copy_oid(&sd
.encapContentInfo
.eContentType
, contentType
);
1072 hx509_clear_error_string(context
);
1077 free_SignedData(&sd
);
1079 hx509_certs_free(&certs
);
1082 der_free_octet_string(content
);
1084 hx509_certs_free(signer_certs
);
1085 der_free_oid(contentType
);
1086 der_free_octet_string(content
);
1093 add_one_attribute(Attribute
**attr
,
1095 const heim_oid
*oid
,
1096 heim_octet_string
*data
)
1101 d
= realloc(*attr
, sizeof((*attr
)[0]) * (*len
+ 1));
1106 ret
= der_copy_oid(oid
, &(*attr
)[*len
].type
);
1110 ALLOC_SEQ(&(*attr
)[*len
].value
, 1);
1111 if ((*attr
)[*len
].value
.val
== NULL
) {
1112 der_free_oid(&(*attr
)[*len
].type
);
1116 (*attr
)[*len
].value
.val
[0].data
= data
->data
;
1117 (*attr
)[*len
].value
.val
[0].length
= data
->length
;
1125 * Decode SignedData and verify that the signature is correct.
1127 * @param context A hx509 context.
1129 * @param eContentType the type of the data.
1130 * @param data data to sign
1131 * @param length length of the data that data point to.
1132 * @param digest_alg digest algorithm to use, use NULL to get the
1133 * default or the peer determined algorithm.
1134 * @param cert certificate to use for sign the data.
1135 * @param peer info about the peer the message to send the message to,
1136 * like what digest algorithm to use.
1137 * @param anchors trust anchors that the client will use, used to
1138 * polulate the certificates included in the message
1139 * @param pool certificates to use in try to build the path to the
1141 * @param signed_data the output of the function, free with
1142 * der_free_octet_string().
1144 * @ingroup hx509_cms
1148 hx509_cms_create_signed_1(hx509_context context
,
1150 const heim_oid
*eContentType
,
1151 const void *data
, size_t length
,
1152 const AlgorithmIdentifier
*digest_alg
,
1154 hx509_peer_info peer
,
1155 hx509_certs anchors
,
1157 heim_octet_string
*signed_data
)
1162 signed_data
->data
= NULL
;
1163 signed_data
->length
= 0;
1165 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &certs
);
1168 ret
= hx509_certs_add(context
, certs
, cert
);
1172 ret
= hx509_cms_create_signed(context
, flags
, eContentType
, data
, length
,
1173 digest_alg
, certs
, peer
, anchors
, pool
,
1177 hx509_certs_free(&certs
);
1183 const AlgorithmIdentifier
*digest_alg
;
1184 const heim_oid
*eContentType
;
1185 heim_octet_string content
;
1186 hx509_peer_info peer
;
1190 hx509_certs anchors
;
1195 sig_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1197 struct sigctx
*sigctx
= ctx
;
1198 heim_octet_string buf
, sigdata
= { 0, NULL
};
1199 SignerInfo
*signer_info
= NULL
;
1200 AlgorithmIdentifier digest
;
1204 SignedData
*sd
= &sigctx
->sd
;
1207 memset(&digest
, 0, sizeof(digest
));
1208 memset(&path
, 0, sizeof(path
));
1210 if (_hx509_cert_private_key(cert
) == NULL
) {
1211 hx509_set_error_string(context
, 0, HX509_PRIVATE_KEY_MISSING
,
1212 "Private key missing for signing");
1213 return HX509_PRIVATE_KEY_MISSING
;
1216 if (sigctx
->digest_alg
) {
1217 ret
= copy_AlgorithmIdentifier(sigctx
->digest_alg
, &digest
);
1219 hx509_clear_error_string(context
);
1221 ret
= hx509_crypto_select(context
, HX509_SELECT_DIGEST
,
1222 _hx509_cert_private_key(cert
),
1223 sigctx
->peer
, &digest
);
1229 * Allocate on more signerInfo and do the signature processing
1232 ptr
= realloc(sd
->signerInfos
.val
,
1233 (sd
->signerInfos
.len
+ 1) * sizeof(sd
->signerInfos
.val
[0]));
1238 sd
->signerInfos
.val
= ptr
;
1240 signer_info
= &sd
->signerInfos
.val
[sd
->signerInfos
.len
];
1242 memset(signer_info
, 0, sizeof(*signer_info
));
1244 signer_info
->version
= 1;
1246 ret
= fill_CMSIdentifier(cert
, sigctx
->cmsidflag
, &signer_info
->sid
);
1248 hx509_clear_error_string(context
);
1252 signer_info
->signedAttrs
= NULL
;
1253 signer_info
->unsignedAttrs
= NULL
;
1255 ret
= copy_AlgorithmIdentifier(&digest
, &signer_info
->digestAlgorithm
);
1257 hx509_clear_error_string(context
);
1262 * If it isn't pkcs7-data send signedAttributes
1265 if (der_heim_oid_cmp(sigctx
->eContentType
, &asn1_oid_id_pkcs7_data
) != 0) {
1267 heim_octet_string sig
;
1269 ALLOC(signer_info
->signedAttrs
, 1);
1270 if (signer_info
->signedAttrs
== NULL
) {
1275 ret
= _hx509_create_signature(context
,
1284 ASN1_MALLOC_ENCODE(MessageDigest
,
1290 der_free_octet_string(&sig
);
1292 hx509_clear_error_string(context
);
1295 if (size
!= buf
.length
)
1296 _hx509_abort("internal ASN.1 encoder error");
1298 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1299 &signer_info
->signedAttrs
->len
,
1300 &asn1_oid_id_pkcs9_messageDigest
,
1304 hx509_clear_error_string(context
);
1309 ASN1_MALLOC_ENCODE(ContentType
,
1312 sigctx
->eContentType
,
1317 if (size
!= buf
.length
)
1318 _hx509_abort("internal ASN.1 encoder error");
1320 ret
= add_one_attribute(&signer_info
->signedAttrs
->val
,
1321 &signer_info
->signedAttrs
->len
,
1322 &asn1_oid_id_pkcs9_contentType
,
1326 hx509_clear_error_string(context
);
1330 sa
.val
= signer_info
->signedAttrs
->val
;
1331 sa
.len
= signer_info
->signedAttrs
->len
;
1333 ASN1_MALLOC_ENCODE(CMSAttributes
,
1340 hx509_clear_error_string(context
);
1343 if (size
!= sigdata
.length
)
1344 _hx509_abort("internal ASN.1 encoder error");
1346 sigdata
.data
= sigctx
->content
.data
;
1347 sigdata
.length
= sigctx
->content
.length
;
1351 AlgorithmIdentifier sigalg
;
1353 ret
= hx509_crypto_select(context
, HX509_SELECT_PUBLIC_SIG
,
1354 _hx509_cert_private_key(cert
), sigctx
->peer
,
1359 ret
= _hx509_create_signature(context
,
1360 _hx509_cert_private_key(cert
),
1363 &signer_info
->signatureAlgorithm
,
1364 &signer_info
->signature
);
1365 free_AlgorithmIdentifier(&sigalg
);
1370 sigctx
->sd
.signerInfos
.len
++;
1374 * Provide best effort path
1376 if (sigctx
->certs
) {
1379 if (sigctx
->pool
&& sigctx
->leafonly
== 0) {
1380 _hx509_calculate_path(context
,
1381 HX509_CALCULATE_PATH_NO_ANCHOR
,
1389 _hx509_path_append(context
, &path
, cert
);
1391 for (i
= 0; i
< path
.len
; i
++) {
1392 /* XXX remove dups */
1393 ret
= hx509_certs_add(context
, sigctx
->certs
, path
.val
[i
]);
1395 hx509_clear_error_string(context
);
1403 free_SignerInfo(signer_info
);
1404 if (sigdata
.data
!= sigctx
->content
.data
)
1405 der_free_octet_string(&sigdata
);
1406 _hx509_path_free(&path
);
1407 free_AlgorithmIdentifier(&digest
);
1413 cert_process(hx509_context context
, void *ctx
, hx509_cert cert
)
1415 struct sigctx
*sigctx
= ctx
;
1416 const unsigned int i
= sigctx
->sd
.certificates
->len
;
1420 ptr
= realloc(sigctx
->sd
.certificates
->val
,
1421 (i
+ 1) * sizeof(sigctx
->sd
.certificates
->val
[0]));
1424 sigctx
->sd
.certificates
->val
= ptr
;
1426 ret
= hx509_cert_binary(context
, cert
,
1427 &sigctx
->sd
.certificates
->val
[i
]);
1429 sigctx
->sd
.certificates
->len
++;
1435 cmp_AlgorithmIdentifier(const AlgorithmIdentifier
*p
, const AlgorithmIdentifier
*q
)
1437 return der_heim_oid_cmp(&p
->algorithm
, &q
->algorithm
);
1441 hx509_cms_create_signed(hx509_context context
,
1443 const heim_oid
*eContentType
,
1444 const void *data
, size_t length
,
1445 const AlgorithmIdentifier
*digest_alg
,
1447 hx509_peer_info peer
,
1448 hx509_certs anchors
,
1450 heim_octet_string
*signed_data
)
1456 struct sigctx sigctx
;
1458 memset(&sigctx
, 0, sizeof(sigctx
));
1459 memset(&name
, 0, sizeof(name
));
1461 if (eContentType
== NULL
)
1462 eContentType
= &asn1_oid_id_pkcs7_data
;
1464 sigctx
.digest_alg
= digest_alg
;
1465 sigctx
.content
.data
= rk_UNCONST(data
);
1466 sigctx
.content
.length
= length
;
1467 sigctx
.eContentType
= eContentType
;
1470 * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name
1471 * and serial number if possible. Otherwise subject key identifier
1474 if (flags
& HX509_CMS_SIGNATURE_ID_NAME
)
1475 sigctx
.cmsidflag
= CMS_ID_NAME
;
1477 sigctx
.cmsidflag
= CMS_ID_SKI
;
1480 * Use HX509_CMS_SIGNATURE_LEAF_ONLY to only request leaf
1481 * certificates to be added to the SignedData.
1483 sigctx
.leafonly
= (flags
& HX509_CMS_SIGNATURE_LEAF_ONLY
) ? 1 : 0;
1486 * Use HX509_CMS_NO_CERTS to make the SignedData contain no
1487 * certificates, overrides HX509_CMS_SIGNATURE_LEAF_ONLY.
1490 if ((flags
& HX509_CMS_SIGNATURE_NO_CERTS
) == 0) {
1491 ret
= hx509_certs_init(context
, "MEMORY:certs", 0, NULL
, &sigctx
.certs
);
1496 sigctx
.anchors
= anchors
;
1499 sigctx
.sd
.version
= CMSVersion_v3
;
1501 der_copy_oid(eContentType
, &sigctx
.sd
.encapContentInfo
.eContentType
);
1504 * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
1506 if ((flags
& HX509_CMS_SIGNATURE_DETACHED
) == 0) {
1507 ALLOC(sigctx
.sd
.encapContentInfo
.eContent
, 1);
1508 if (sigctx
.sd
.encapContentInfo
.eContent
== NULL
) {
1509 hx509_clear_error_string(context
);
1514 sigctx
.sd
.encapContentInfo
.eContent
->data
= malloc(length
);
1515 if (sigctx
.sd
.encapContentInfo
.eContent
->data
== NULL
) {
1516 hx509_clear_error_string(context
);
1520 memcpy(sigctx
.sd
.encapContentInfo
.eContent
->data
, data
, length
);
1521 sigctx
.sd
.encapContentInfo
.eContent
->length
= length
;
1525 * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
1528 if ((flags
& HX509_CMS_SIGNATURE_NO_SIGNER
) == 0) {
1529 ret
= hx509_certs_iter_f(context
, certs
, sig_process
, &sigctx
);
1534 if (sigctx
.sd
.signerInfos
.len
) {
1537 * For each signerInfo, collect all different digest types.
1539 for (i
= 0; i
< sigctx
.sd
.signerInfos
.len
; i
++) {
1540 AlgorithmIdentifier
*di
=
1541 &sigctx
.sd
.signerInfos
.val
[i
].digestAlgorithm
;
1543 for (j
= 0; j
< sigctx
.sd
.digestAlgorithms
.len
; j
++)
1544 if (cmp_AlgorithmIdentifier(di
, &sigctx
.sd
.digestAlgorithms
.val
[j
]) == 0)
1546 if (j
== sigctx
.sd
.digestAlgorithms
.len
) {
1547 ret
= add_DigestAlgorithmIdentifiers(&sigctx
.sd
.digestAlgorithms
, di
);
1549 hx509_clear_error_string(context
);
1557 * Add certs we think are needed, build as part of sig_process
1560 ALLOC(sigctx
.sd
.certificates
, 1);
1561 if (sigctx
.sd
.certificates
== NULL
) {
1562 hx509_clear_error_string(context
);
1567 ret
= hx509_certs_iter_f(context
, sigctx
.certs
, cert_process
, &sigctx
);
1572 ASN1_MALLOC_ENCODE(SignedData
,
1573 signed_data
->data
, signed_data
->length
,
1574 &sigctx
.sd
, &size
, ret
);
1576 hx509_clear_error_string(context
);
1579 if (signed_data
->length
!= size
)
1580 _hx509_abort("internal ASN.1 encoder error");
1583 hx509_certs_free(&sigctx
.certs
);
1584 free_SignedData(&sigctx
.sd
);
1590 hx509_cms_decrypt_encrypted(hx509_context context
,
1594 heim_oid
*contentType
,
1595 heim_octet_string
*content
)
1597 heim_octet_string cont
;
1598 CMSEncryptedData ed
;
1599 AlgorithmIdentifier
*ai
;
1602 memset(content
, 0, sizeof(*content
));
1603 memset(&cont
, 0, sizeof(cont
));
1605 ret
= decode_CMSEncryptedData(data
, length
, &ed
, NULL
);
1607 hx509_set_error_string(context
, 0, ret
,
1608 "Failed to decode CMSEncryptedData");
1612 if (ed
.encryptedContentInfo
.encryptedContent
== NULL
) {
1613 ret
= HX509_CMS_NO_DATA_AVAILABLE
;
1614 hx509_set_error_string(context
, 0, ret
,
1615 "No content in EncryptedData");
1619 ret
= der_copy_oid(&ed
.encryptedContentInfo
.contentType
, contentType
);
1621 hx509_clear_error_string(context
);
1625 ai
= &ed
.encryptedContentInfo
.contentEncryptionAlgorithm
;
1626 if (ai
->parameters
== NULL
) {
1627 ret
= HX509_ALG_NOT_SUPP
;
1628 hx509_clear_error_string(context
);
1632 ret
= _hx509_pbe_decrypt(context
,
1635 ed
.encryptedContentInfo
.encryptedContent
,
1647 free_CMSEncryptedData(&ed
);