lib/hx509: hx509_request_get_san handle strpool on error
[heimdal.git] / lib / hx509 / req.c
blob64eb543a11b53775b7b4e3c16bb1c0fe8e278fa7
1 /*
2 * Copyright (c) 2006 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
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
31 * SUCH DAMAGE.
34 #include "hx_locl.h"
35 #include <pkcs10_asn1.h>
37 typedef struct abitstring_s {
38 unsigned char *feats;
39 size_t feat_bytes;
40 } *abitstring;
42 struct hx509_request_data {
43 hx509_context context;
44 hx509_name name;
45 SubjectPublicKeyInfo key;
46 KeyUsage ku;
47 ExtKeyUsage eku;
48 GeneralNames san;
49 struct abitstring_s authorized_EKUs;
50 struct abitstring_s authorized_SANs;
51 uint32_t nunsupported; /* Count of unsupported features requested */
52 uint32_t nauthorized; /* Count of supported features authorized */
53 uint32_t ku_are_authorized:1;
56 /**
57 * Allocate and initialize an hx509_request structure representing a PKCS#10
58 * certificate signing request.
60 * @param context An hx509 context.
61 * @param req Where to put the new hx509_request object.
63 * @return An hx509 error code, see hx509_get_error_string().
65 * @ingroup hx509_request
67 HX509_LIB_FUNCTION int HX509_LIB_CALL
68 hx509_request_init(hx509_context context, hx509_request *req)
70 *req = calloc(1, sizeof(**req));
71 if (*req == NULL)
72 return ENOMEM;
74 (*req)->context = context;
75 return 0;
78 /**
79 * Free a certificate signing request object.
81 * @param req A pointer to the hx509_request to free.
83 * @ingroup hx509_request
85 HX509_LIB_FUNCTION void HX509_LIB_CALL
86 hx509_request_free(hx509_request *reqp)
88 hx509_request req = *reqp;
90 *reqp = NULL;
91 if (req == NULL)
92 return;
93 if (req->name)
94 hx509_name_free(&req->name);
95 free(req->authorized_EKUs.feats);
96 free(req->authorized_SANs.feats);
97 free_SubjectPublicKeyInfo(&req->key);
98 free_ExtKeyUsage(&req->eku);
99 free_GeneralNames(&req->san);
100 memset(req, 0, sizeof(*req));
101 free(req);
105 * Set the subjectName of the CSR.
107 * @param context An hx509 context.
108 * @param req The hx509_request to alter.
109 * @param name The subjectName.
111 * @return An hx509 error code, see hx509_get_error_string().
113 * @ingroup hx509_request
115 HX509_LIB_FUNCTION int HX509_LIB_CALL
116 hx509_request_set_name(hx509_context context,
117 hx509_request req,
118 hx509_name name)
120 if (req->name)
121 hx509_name_free(&req->name);
122 if (name) {
123 int ret = hx509_name_copy(context, name, &req->name);
124 if (ret)
125 return ret;
127 return 0;
131 * Get the subject name requested by a CSR.
133 * @param context An hx509 context.
134 * @param req The hx509_request object.
135 * @param name Where to put the name.
137 * @return An hx509 error code, see hx509_get_error_string().
139 * @ingroup hx509_request
141 HX509_LIB_FUNCTION int HX509_LIB_CALL
142 hx509_request_get_name(hx509_context context,
143 hx509_request req,
144 hx509_name *name)
146 if (req->name == NULL) {
147 hx509_set_error_string(context, 0, EINVAL, "Request have no name");
148 return EINVAL;
150 return hx509_name_copy(context, req->name, name);
154 * Set the subject public key requested by a CSR.
156 * @param context An hx509 context.
157 * @param req The hx509_request object.
158 * @param key The public key.
160 * @return An hx509 error code, see hx509_get_error_string().
162 * @ingroup hx509_request
164 HX509_LIB_FUNCTION int HX509_LIB_CALL
165 hx509_request_set_SubjectPublicKeyInfo(hx509_context context,
166 hx509_request req,
167 const SubjectPublicKeyInfo *key)
169 free_SubjectPublicKeyInfo(&req->key);
170 return copy_SubjectPublicKeyInfo(key, &req->key);
174 * Get the subject public key requested by a CSR.
176 * @param context An hx509 context.
177 * @param req The hx509_request object.
178 * @param key Where to put the key.
180 * @return An hx509 error code, see hx509_get_error_string().
182 * @ingroup hx509_request
184 HX509_LIB_FUNCTION int HX509_LIB_CALL
185 hx509_request_get_SubjectPublicKeyInfo(hx509_context context,
186 hx509_request req,
187 SubjectPublicKeyInfo *key)
189 return copy_SubjectPublicKeyInfo(&req->key, key);
193 * Set the key usage requested by a CSR.
195 * @param context An hx509 context.
196 * @param req The hx509_request object.
197 * @param ku The key usage.
199 * @return An hx509 error code, see hx509_get_error_string().
201 * @ingroup hx509_request
203 HX509_LIB_FUNCTION int HX509_LIB_CALL
204 hx509_request_set_ku(hx509_context context, hx509_request req, KeyUsage ku)
206 uint64_t n = KeyUsage2int(ku);
208 if ((KeyUsage2int(req->ku) & n) != n)
209 req->ku_are_authorized = 0;
210 req->ku = ku;
211 return 0;
215 * Get the key usage requested by a CSR.
217 * @param context An hx509 context.
218 * @param req The hx509_request object.
219 * @param ku Where to put the key usage.
221 * @return An hx509 error code, see hx509_get_error_string().
223 * @ingroup hx509_request
225 HX509_LIB_FUNCTION int HX509_LIB_CALL
226 hx509_request_get_ku(hx509_context context, hx509_request req, KeyUsage *ku)
228 *ku = req->ku;
229 return 0;
233 * Add an extended key usage OID to a CSR.
235 * @param context An hx509 context.
236 * @param req The hx509_request object.
237 * @param oid The EKU OID.
239 * @return An hx509 error code, see hx509_get_error_string().
241 * @ingroup hx509_request
243 HX509_LIB_FUNCTION int HX509_LIB_CALL
244 hx509_request_add_eku(hx509_context context,
245 hx509_request req,
246 const heim_oid *oid)
248 void *val;
249 int ret;
251 val = realloc(req->eku.val, sizeof(req->eku.val[0]) * (req->eku.len + 1));
252 if (val == NULL)
253 return ENOMEM;
254 req->eku.val = val;
256 ret = der_copy_oid(oid, &req->eku.val[req->eku.len]);
257 if (ret)
258 return ret;
260 req->eku.len += 1;
262 return 0;
266 * Add a GeneralName (Jabber ID) subject alternative name to a CSR.
268 * XXX Make this take a heim_octet_string, not a GeneralName*.
270 * @param context An hx509 context.
271 * @param req The hx509_request object.
272 * @param gn The GeneralName object.
274 * @return An hx509 error code, see hx509_get_error_string().
276 * @ingroup hx509_request
278 HX509_LIB_FUNCTION int HX509_LIB_CALL
279 hx509_request_add_GeneralName(hx509_context context,
280 hx509_request req,
281 const GeneralName *gn)
283 return add_GeneralNames(&req->san, gn);
286 static int
287 add_utf8_other_san(hx509_context context,
288 GeneralNames *gns,
289 const heim_oid *oid,
290 const char *s)
292 const PKIXXmppAddr us = (const PKIXXmppAddr)(uintptr_t)s;
293 GeneralName gn;
294 size_t size;
295 int ret;
297 gn.element = choice_GeneralName_otherName;
298 gn.u.otherName.type_id.length = 0;
299 gn.u.otherName.type_id.components = 0;
300 gn.u.otherName.value.data = NULL;
301 gn.u.otherName.value.length = 0;
302 ret = der_copy_oid(oid, &gn.u.otherName.type_id);
303 if (ret == 0)
304 ASN1_MALLOC_ENCODE(PKIXXmppAddr, gn.u.otherName.value.data,
305 gn.u.otherName.value.length, &us, &size, ret);
306 if (ret == 0 && size != gn.u.otherName.value.length)
307 _hx509_abort("internal ASN.1 encoder error");
308 if (ret == 0)
309 ret = add_GeneralNames(gns, &gn);
310 free_GeneralName(&gn);
311 if (ret)
312 hx509_set_error_string(context, 0, ret, "Out of memory");
313 return ret;
317 * Add an xmppAddr (Jabber ID) subject alternative name to a CSR.
319 * @param context An hx509 context.
320 * @param req The hx509_request object.
321 * @param jid The XMPP address.
323 * @return An hx509 error code, see hx509_get_error_string().
325 * @ingroup hx509_request
327 HX509_LIB_FUNCTION int HX509_LIB_CALL
328 hx509_request_add_xmpp_name(hx509_context context,
329 hx509_request req,
330 const char *jid)
332 return add_utf8_other_san(context, &req->san,
333 &asn1_oid_id_pkix_on_xmppAddr, jid);
337 * Add a Microsoft UPN subject alternative name to a CSR.
339 * @param context An hx509 context.
340 * @param req The hx509_request object.
341 * @param hostname The XMPP address.
343 * @return An hx509 error code, see hx509_get_error_string().
345 * @ingroup hx509_request
347 HX509_LIB_FUNCTION int HX509_LIB_CALL
348 hx509_request_add_ms_upn_name(hx509_context context,
349 hx509_request req,
350 const char *upn)
352 return add_utf8_other_san(context, &req->san, &asn1_oid_id_pkinit_ms_san,
353 upn);
357 * Add a dNSName (hostname) subject alternative name to a CSR.
359 * @param context An hx509 context.
360 * @param req The hx509_request object.
361 * @param hostname The fully-qualified hostname.
363 * @return An hx509 error code, see hx509_get_error_string().
365 * @ingroup hx509_request
367 HX509_LIB_FUNCTION int HX509_LIB_CALL
368 hx509_request_add_dns_name(hx509_context context,
369 hx509_request req,
370 const char *hostname)
372 GeneralName name;
374 memset(&name, 0, sizeof(name));
375 name.element = choice_GeneralName_dNSName;
376 name.u.dNSName.data = rk_UNCONST(hostname);
377 name.u.dNSName.length = strlen(hostname);
379 return add_GeneralNames(&req->san, &name);
383 * Add a dnsSRV (_service.hostname) subject alternative name to a CSR.
385 * @param context An hx509 context.
386 * @param req The hx509_request object.
387 * @param dnssrv The DNS SRV name.
389 * @return An hx509 error code, see hx509_get_error_string().
391 * @ingroup hx509_request
393 HX509_LIB_FUNCTION int HX509_LIB_CALL
394 hx509_request_add_dns_srv(hx509_context context,
395 hx509_request req,
396 const char *dnssrv)
398 GeneralName gn;
399 SRVName n;
400 size_t size;
401 int ret;
403 memset(&n, 0, sizeof(n));
404 memset(&gn, 0, sizeof(gn));
405 gn.element = choice_GeneralName_otherName;
406 gn.u.otherName.type_id.length = 0;
407 gn.u.otherName.type_id.components = 0;
408 gn.u.otherName.value.data = NULL;
409 gn.u.otherName.value.length = 0;
410 n.length = strlen(dnssrv);
411 n.data = (void *)(uintptr_t)dnssrv;
412 ASN1_MALLOC_ENCODE(SRVName,
413 gn.u.otherName.value.data,
414 gn.u.otherName.value.length, &n, &size, ret);
415 if (ret == 0)
416 ret = der_copy_oid(&asn1_oid_id_pkix_on_dnsSRV, &gn.u.otherName.type_id);
417 if (ret == 0)
418 ret = add_GeneralNames(&req->san, &gn);
419 free_GeneralName(&gn);
420 return ret;
424 * Add an rfc822Name (e-mail address) subject alternative name to a CSR.
426 * @param context An hx509 context.
427 * @param req The hx509_request object.
428 * @param email The e-mail address.
430 * @return An hx509 error code, see hx509_get_error_string().
432 * @ingroup hx509_request
434 HX509_LIB_FUNCTION int HX509_LIB_CALL
435 hx509_request_add_email(hx509_context context,
436 hx509_request req,
437 const char *email)
439 GeneralName name;
441 memset(&name, 0, sizeof(name));
442 name.element = choice_GeneralName_rfc822Name;
443 name.u.rfc822Name.data = rk_UNCONST(email);
444 name.u.rfc822Name.length = strlen(email);
446 return add_GeneralNames(&req->san, &name);
450 * Add a registeredID (OID) subject alternative name to a CSR.
452 * @param context An hx509 context.
453 * @param req The hx509_request object.
454 * @param oid The OID.
456 * @return An hx509 error code, see hx509_get_error_string().
458 * @ingroup hx509_request
460 HX509_LIB_FUNCTION int HX509_LIB_CALL
461 hx509_request_add_registered(hx509_context context,
462 hx509_request req,
463 heim_oid *oid)
465 GeneralName name;
466 int ret;
468 memset(&name, 0, sizeof(name));
469 name.element = choice_GeneralName_registeredID;
470 ret = der_copy_oid(oid, &name.u.registeredID);
471 if (ret)
472 return ret;
473 ret = add_GeneralNames(&req->san, &name);
474 free_GeneralName(&name);
475 return ret;
479 * Add a Kerberos V5 principal subject alternative name to a CSR.
481 * @param context An hx509 context.
482 * @param req The hx509_request object.
483 * @param princ The Kerberos principal name.
485 * @return An hx509 error code, see hx509_get_error_string().
487 * @ingroup hx509_request
489 HX509_LIB_FUNCTION int HX509_LIB_CALL
490 hx509_request_add_pkinit(hx509_context context,
491 hx509_request req,
492 const char *princ)
494 KRB5PrincipalName kn;
495 GeneralName gn;
496 int ret;
498 memset(&kn, 0, sizeof(kn));
499 memset(&gn, 0, sizeof(gn));
500 gn.element = choice_GeneralName_otherName;
501 gn.u.otherName.type_id.length = 0;
502 gn.u.otherName.type_id.components = 0;
503 gn.u.otherName.value.data = NULL;
504 gn.u.otherName.value.length = 0;
505 ret = der_copy_oid(&asn1_oid_id_pkinit_san, &gn.u.otherName.type_id);
506 if (ret == 0)
507 ret = _hx509_make_pkinit_san(context, princ, &gn.u.otherName.value);
508 if (ret == 0)
509 ret = add_GeneralNames(&req->san, &gn);
510 free_GeneralName(&gn);
511 return ret;
514 /* XXX Add DNSSRV and other SANs */
516 static int
517 get_exts(hx509_context context,
518 const hx509_request req,
519 Extensions *exts)
521 size_t size;
522 int ret = 0;
524 exts->val = NULL;
525 exts->len = 0;
527 if (KeyUsage2int(req->ku)) {
528 Extension e;
530 memset(&e, 0, sizeof(e));
531 /* The critical field needs to be made DEFAULT FALSE... */
532 e.critical = 1;
533 if (ret == 0)
534 ASN1_MALLOC_ENCODE(KeyUsage, e.extnValue.data, e.extnValue.length,
535 &req->ku, &size, ret);
536 if (ret == 0)
537 ret = der_copy_oid(&asn1_oid_id_x509_ce_keyUsage, &e.extnID);
538 if (ret == 0)
539 ret = add_Extensions(exts, &e);
540 free_Extension(&e);
542 if (ret == 0 && req->eku.len) {
543 Extension e;
545 memset(&e, 0, sizeof(e));
546 e.critical = 1;
547 if (ret == 0)
548 ASN1_MALLOC_ENCODE(ExtKeyUsage,
549 e.extnValue.data, e.extnValue.length,
550 &req->eku, &size, ret);
551 if (ret == 0)
552 ret = der_copy_oid(&asn1_oid_id_x509_ce_extKeyUsage, &e.extnID);
553 if (ret == 0)
554 ret = add_Extensions(exts, &e);
555 free_Extension(&e);
557 if (ret == 0 && req->san.len) {
558 Extension e;
560 memset(&e, 0, sizeof(e));
562 * SANs are critical when the subject Name is empty.
564 * The empty DN check could probably stand to be a function we export.
566 e.critical = FALSE;
567 if (req->name &&
568 req->name->der_name.element == choice_Name_rdnSequence &&
569 req->name->der_name.u.rdnSequence.len == 0)
570 e.critical = 1;
571 if (ret == 0)
572 ASN1_MALLOC_ENCODE(GeneralNames,
573 e.extnValue.data, e.extnValue.length,
574 &req->san,
575 &size, ret);
576 if (ret == 0)
577 ret = der_copy_oid(&asn1_oid_id_x509_ce_subjectAltName, &e.extnID);
578 if (ret == 0)
579 ret = add_Extensions(exts, &e);
580 free_Extension(&e);
583 return ret;
587 * Get the KU/EKUs/SANs set on a request as a DER-encoding of Extensions.
589 * @param context An hx509 context.
590 * @param req The hx509_request object.
591 * @param exts_der Where to put the DER-encoded Extensions.
593 * @return An hx509 error code, see hx509_get_error_string().
595 * @ingroup hx509_request
597 HX509_LIB_FUNCTION int HX509_LIB_CALL
598 hx509_request_get_exts(hx509_context context,
599 const hx509_request req,
600 heim_octet_string *exts_der)
602 Extensions exts;
603 size_t size;
604 int ret;
606 exts_der->data = NULL;
607 exts_der->length = 0;
608 ret = get_exts(context, req, &exts);
609 if (ret == 0 && exts.len /* Extensions has a min size constraint of 1 */)
610 ASN1_MALLOC_ENCODE(Extensions, exts_der->data, exts_der->length,
611 &exts, &size, ret);
612 free_Extensions(&exts);
613 return ret;
616 /* XXX Add PEM */
619 * Encode a CSR.
621 * @param context An hx509 context.
622 * @param req The hx509_request object.
623 * @param signer The private key corresponding to the CSR's subject public key.
624 * @param request Where to put the DER-encoded CSR.
626 * @return An hx509 error code, see hx509_get_error_string().
628 * @ingroup hx509_request
630 HX509_LIB_FUNCTION int HX509_LIB_CALL
631 hx509_request_to_pkcs10(hx509_context context,
632 const hx509_request req,
633 const hx509_private_key signer,
634 heim_octet_string *request)
636 CertificationRequest r;
637 Extensions exts;
638 heim_octet_string data;
639 size_t size;
640 int ret;
642 request->data = NULL;
643 request->length = 0;
645 data.length = 0;
646 data.data = NULL;
648 if (req->name == NULL) {
649 hx509_set_error_string(context, 0, EINVAL,
650 "PKCS10 needs to have a subject");
651 return EINVAL;
654 memset(&r, 0, sizeof(r));
656 /* Setup CSR */
657 r.certificationRequestInfo.version = pkcs10_v1;
658 ret = copy_Name(&req->name->der_name,
659 &r.certificationRequestInfo.subject);
660 if (ret == 0)
661 ret = copy_SubjectPublicKeyInfo(&req->key,
662 &r.certificationRequestInfo.subjectPKInfo);
664 /* Encode extReq attribute with requested Certificate Extensions */
666 if (ret == 0)
667 ret = get_exts(context, req, &exts);
668 if (ret == 0 && exts.len) {
669 Attribute *a = NULL; /* Quiet VC */
670 heim_any extns;
672 r.certificationRequestInfo.attributes =
673 calloc(1, sizeof(r.certificationRequestInfo.attributes[0]));
674 if (r.certificationRequestInfo.attributes == NULL)
675 ret = ENOMEM;
676 if (ret == 0) {
677 r.certificationRequestInfo.attributes[0].len = 1;
678 r.certificationRequestInfo.attributes[0].val =
679 calloc(1, sizeof(r.certificationRequestInfo.attributes[0].val[0]));
680 if (r.certificationRequestInfo.attributes[0].val == NULL)
681 ret = ENOMEM;
682 if (ret == 0)
683 a = r.certificationRequestInfo.attributes[0].val;
685 if (ret == 0)
686 ASN1_MALLOC_ENCODE(Extensions, extns.data, extns.length,
687 &exts, &size, ret);
688 if (ret == 0 && a)
689 ret = der_copy_oid(&asn1_oid_id_pkcs9_extReq, &a->type);
690 if (ret == 0)
691 ret = add_AttributeValues(&a->value, &extns);
692 free_heim_any(&extns);
695 /* Encode CSR body for signing */
696 if (ret == 0)
697 ASN1_MALLOC_ENCODE(CertificationRequestInfo, data.data, data.length,
698 &r.certificationRequestInfo, &size, ret);
699 if (ret == 0 && data.length != size)
700 abort();
702 /* Self-sign CSR body */
703 if (ret == 0) {
704 ret = _hx509_create_signature_bitstring(context, signer,
705 _hx509_crypto_default_sig_alg,
706 &data,
707 &r.signatureAlgorithm,
708 &r.signature);
710 free(data.data);
712 /* Encode CSR */
713 if (ret == 0)
714 ASN1_MALLOC_ENCODE(CertificationRequest, request->data, request->length,
715 &r, &size, ret);
716 if (ret == 0 && request->length != size)
717 abort();
719 free_CertificationRequest(&r);
720 free_Extensions(&exts);
721 return ret;
725 * Parse an encoded CSR and verify its self-signature.
727 * @param context An hx509 context.
728 * @param der The DER-encoded CSR.
729 * @param req Where to put request object.
731 * @return An hx509 error code, see hx509_get_error_string().
733 * @ingroup hx509_request
735 HX509_LIB_FUNCTION int HX509_LIB_CALL
736 hx509_request_parse_der(hx509_context context,
737 heim_octet_string *der,
738 hx509_request *req)
740 CertificationRequestInfo *rinfo = NULL;
741 CertificationRequest r;
742 hx509_cert signer = NULL;
743 Extensions exts;
744 size_t i, size;
745 int ret;
747 memset(&exts, 0, sizeof(exts));
749 /* Initial setup and decoding of CSR */
750 ret = hx509_request_init(context, req);
751 if (ret)
752 return ret;
753 ret = decode_CertificationRequest(der->data, der->length, &r, &size);
754 if (ret) {
755 hx509_set_error_string(context, 0, ret, "Failed to decode CSR");
756 free(*req);
757 *req = NULL;
758 return ret;
760 rinfo = &r.certificationRequestInfo;
763 * Setup a 'signer' for verifying the self-signature for proof of
764 * possession.
766 * Sadly we need a "certificate" here because _hx509_verify_signature_*()
767 * functions want one as a signer even though all the verification
768 * functions that use the signer argument only ever use the spki of the
769 * signer certificate.
771 * FIXME Change struct signature_alg's verify_signature's prototype to use
772 * an spki instead of an hx509_cert as the signer! The we won't have
773 * to do this.
775 if (ret == 0) {
776 Certificate c;
777 memset(&c, 0, sizeof(c));
778 c.tbsCertificate.subjectPublicKeyInfo = rinfo->subjectPKInfo;
779 if ((signer = hx509_cert_init(context, &c, NULL)) == NULL)
780 ret = ENOMEM;
783 /* Verify the signature */
784 if (ret == 0)
785 ret = _hx509_verify_signature_bitstring(context, signer,
786 &r.signatureAlgorithm,
787 &rinfo->_save,
788 &r.signature);
789 if (ret)
790 hx509_set_error_string(context, 0, ret,
791 "CSR signature verification failed");
792 hx509_cert_free(signer);
794 /* Populate the hx509_request */
795 if (ret == 0)
796 ret = hx509_request_set_SubjectPublicKeyInfo(context, *req,
797 &rinfo->subjectPKInfo);
798 if (ret == 0)
799 ret = _hx509_name_from_Name(&rinfo->subject, &(*req)->name);
801 /* Extract KUs, EKUs, and SANs from the CSR's attributes */
802 if (ret || !rinfo->attributes || !rinfo->attributes[0].len)
803 goto out;
805 for (i = 0; ret == 0 && i < rinfo->attributes[0].len; i++) {
806 Attribute *a = &rinfo->attributes[0].val[i];
807 heim_any *av = NULL;
809 /* We only support Extensions request attributes */
810 if (der_heim_oid_cmp(&a->type, &asn1_oid_id_pkcs9_extReq) != 0) {
811 char *oidstr = NULL;
814 * We need an HX509_TRACE facility for this sort of warning.
816 * We'd put the warning in the context and then allow the caller to
817 * extract and reset the warning.
819 * FIXME
821 der_print_heim_oid(&a->type, '.', &oidstr);
822 warnx("Unknown or unsupported CSR attribute %s",
823 oidstr ? oidstr : "<error decoding OID>");
824 free(oidstr);
825 continue;
827 if (!a->value.val)
828 continue;
830 av = a->value.val;
831 ret = decode_Extensions(av->data, av->length, &exts, NULL);
832 if (ret) {
833 hx509_set_error_string(context, 0, ret,
834 "CSR signature verification failed "
835 "due to invalid extReq attribute");
836 goto out;
839 for (i = 0; ret == 0 && i < exts.len; i++) {
840 const char *what = "";
841 Extension *e = &exts.val[i];
843 if (der_heim_oid_cmp(&e->extnID,
844 &asn1_oid_id_x509_ce_keyUsage) == 0) {
845 ret = decode_KeyUsage(e->extnValue.data, e->extnValue.length,
846 &(*req)->ku, NULL);
847 what = "keyUsage";
849 * Count all KUs as one requested extension to be authorized,
850 * though the caller will have to check the KU values individually.
852 if (KeyUsage2int((*req)->ku) & ~KeyUsage2int(int2KeyUsage(~0)))
853 (*req)->nunsupported++;
854 } else if (der_heim_oid_cmp(&e->extnID,
855 &asn1_oid_id_x509_ce_extKeyUsage) == 0) {
856 ret = decode_ExtKeyUsage(e->extnValue.data, e->extnValue.length,
857 &(*req)->eku, NULL);
858 what = "extKeyUsage";
861 * Count each EKU as a separate requested extension to be
862 * authorized.
864 } else if (der_heim_oid_cmp(&e->extnID,
865 &asn1_oid_id_x509_ce_subjectAltName) == 0) {
866 ret = decode_GeneralNames(e->extnValue.data, e->extnValue.length,
867 &(*req)->san, NULL);
868 what = "subjectAlternativeName";
871 * Count each SAN as a separate requested extension to be
872 * authorized.
874 } else {
875 char *oidstr = NULL;
877 (*req)->nunsupported++;
880 * We need an HX509_TRACE facility for this sort of warning.
882 * We'd put the warning in the context and then allow the caller to
883 * extract and reset the warning.
885 * FIXME
887 der_print_heim_oid(&e->extnID, '.', &oidstr);
888 warnx("Unknown or unsupported CSR extension request %s",
889 oidstr ? oidstr : "<error decoding OID>");
890 free(oidstr);
892 if (ret) {
893 hx509_set_error_string(context, 0, ret,
894 "CSR signature verification failed "
895 "due to invalid %s extension", what);
896 break;
900 out:
901 free_CertificationRequest(&r);
902 free_Extensions(&exts);
903 if (ret)
904 hx509_request_free(req);
905 return ret;
909 * Parse an encoded CSR and verify its self-signature.
911 * @param context An hx509 context.
912 * @param csr The name of a store containing the CSR ("PKCS10:/path/to/file")
913 * @param req Where to put request object.
915 * @return An hx509 error code, see hx509_get_error_string().
917 * @ingroup hx509_request
919 HX509_LIB_FUNCTION int HX509_LIB_CALL
920 hx509_request_parse(hx509_context context,
921 const char *csr,
922 hx509_request *req)
924 heim_octet_string d;
925 int ret;
927 /* XXX Add support for PEM */
928 if (strncmp(csr, "PKCS10:", 7) != 0) {
929 hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION,
930 "CSR location does not start with \"PKCS10:\": %s",
931 csr);
932 return HX509_UNSUPPORTED_OPERATION;
935 ret = rk_undumpdata(csr + 7, &d.data, &d.length);
936 if (ret) {
937 hx509_set_error_string(context, 0, ret, "Could not read %s", csr);
938 return ret;
941 ret = hx509_request_parse_der(context, &d, req);
942 free(d.data);
943 if (ret)
944 hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
945 " (while parsing CSR from %s)", csr);
946 return ret;
950 * Get some EKU from a CSR. Usable as an iterator.
952 * @param context An hx509 context.
953 * @param req The hx509_request object.
954 * @param idx The index of the EKU (0 for the first) to return
955 * @param out A pointer to a char * variable where the OID will be placed
956 * (caller must free with free())
958 * @return Zero on success, HX509_NO_ITEM if no such item exists (denoting
959 * iteration end), or an error.
961 * @ingroup hx509_request
963 HX509_LIB_FUNCTION int HX509_LIB_CALL
964 hx509_request_get_eku(hx509_request req,
965 size_t idx,
966 char **out)
968 *out = NULL;
969 if (idx >= req->eku.len)
970 return HX509_NO_ITEM;
971 return der_print_heim_oid(&req->eku.val[idx], '.', out);
974 static int
975 abitstring_check(abitstring a, size_t n, int idx)
977 size_t bytes;
979 if (idx >= n)
980 return EINVAL;
982 bytes = (idx + 1) / CHAR_BIT + (((idx + 1) % CHAR_BIT) ? 1 : 0);
983 if (a->feat_bytes < bytes)
984 return 0;
986 return !!(a->feats[idx / CHAR_BIT] & (1UL<<(idx % CHAR_BIT)));
990 * Sets and returns 0 if not already set, -1 if already set. Positive return
991 * values are system errors.
993 static int
994 abitstring_set(abitstring a, size_t n, int idx)
996 size_t bytes;
998 if (idx >= n)
999 return EINVAL;
1001 bytes = n / CHAR_BIT + ((n % CHAR_BIT) ? 1 : 0);
1002 if (a->feat_bytes < bytes) {
1003 unsigned char *tmp;
1005 if ((tmp = realloc(a->feats, bytes)) == NULL)
1006 return ENOMEM;
1007 memset(tmp + a->feat_bytes, 0, bytes - a->feat_bytes);
1008 a->feats = tmp;
1009 a->feat_bytes = bytes;
1012 if (!(a->feats[idx / CHAR_BIT] & (1UL<<(idx % CHAR_BIT)))) {
1013 a->feats[idx / CHAR_BIT] |= 1UL<<(idx % CHAR_BIT);
1014 return 0;
1016 return -1;
1020 * Resets and returns 0 if not already reset, -1 if already reset. Positive
1021 * return values are system errors.
1023 static int
1024 abitstring_reset(abitstring a, size_t n, int idx)
1026 size_t bytes;
1028 if (idx >= n)
1029 return EINVAL;
1031 bytes = (idx + 1) / CHAR_BIT + (((idx + 1) % CHAR_BIT) ? 1 : 0);
1032 if (a->feat_bytes >= bytes &&
1033 (a->feats[idx / CHAR_BIT] & (1UL<<(idx % CHAR_BIT)))) {
1034 a->feats[idx / CHAR_BIT] &= ~(1UL<<(idx % CHAR_BIT));
1035 return 0;
1037 return -1;
1040 static int
1041 authorize_feat(hx509_request req, abitstring a, size_t n, int idx)
1043 int ret;
1045 ret = abitstring_set(a, n, idx);
1046 switch (ret) {
1047 case 0:
1048 req->nauthorized++;
1049 /*fallthrough*/
1050 case -1:
1051 return 0;
1052 default:
1053 return ret;
1057 static int
1058 reject_feat(hx509_request req, abitstring a, size_t n, int idx)
1060 int ret;
1062 ret = abitstring_reset(a, n, idx);
1063 switch (ret) {
1064 case 0:
1065 req->nauthorized--;
1066 /*fallthrough*/
1067 case -1:
1068 return 0;
1069 default:
1070 return ret;
1075 * Filter the requested KeyUsage and mark it authorized.
1077 * @param req The hx509_request object.
1078 * @param ku Permitted KeyUsage
1080 * @ingroup hx509_request
1082 HX509_LIB_FUNCTION void HX509_LIB_CALL
1083 hx509_request_authorize_ku(hx509_request req, KeyUsage ku)
1085 (void) hx509_request_set_ku(NULL, req, ku);
1086 req->ku = int2KeyUsage(KeyUsage2int(req->ku) & KeyUsage2int(ku));
1087 if (KeyUsage2int(ku))
1088 req->ku_are_authorized = 1;
1092 * Mark a requested EKU as authorized.
1094 * @param req The hx509_request object.
1095 * @param idx The index of an EKU that can be fetched with
1096 * hx509_request_get_eku()
1098 * @return Zero on success, an error otherwise.
1100 * @ingroup hx509_request
1102 HX509_LIB_FUNCTION int HX509_LIB_CALL
1103 hx509_request_authorize_eku(hx509_request req, size_t idx)
1105 return authorize_feat(req, &req->authorized_EKUs, req->eku.len, idx);
1109 * Mark a requested EKU as not authorized.
1111 * @param req The hx509_request object.
1112 * @param idx The index of an EKU that can be fetched with
1113 * hx509_request_get_eku()
1115 * @return Zero on success, an error otherwise.
1117 * @ingroup hx509_request
1119 HX509_LIB_FUNCTION int HX509_LIB_CALL
1120 hx509_request_reject_eku(hx509_request req, size_t idx)
1122 return reject_feat(req, &req->authorized_EKUs, req->eku.len, idx);
1126 * Check if an EKU has been marked authorized.
1128 * @param req The hx509_request object.
1129 * @param idx The index of an EKU that can be fetched with
1130 * hx509_request_get_eku()
1132 * @return Non-zero if authorized, zero if not.
1134 * @ingroup hx509_request
1136 HX509_LIB_FUNCTION int HX509_LIB_CALL
1137 hx509_request_eku_authorized_p(hx509_request req, size_t idx)
1139 return abitstring_check(&req->authorized_EKUs, req->eku.len, idx);
1143 * Mark a requested SAN as authorized.
1145 * @param req The hx509_request object.
1146 * @param idx The cursor as modified by a SAN iterator.
1148 * @return Zero on success, an error otherwise.
1150 * @ingroup hx509_request
1152 HX509_LIB_FUNCTION int HX509_LIB_CALL
1153 hx509_request_authorize_san(hx509_request req, size_t idx)
1155 return authorize_feat(req, &req->authorized_SANs, req->san.len, idx);
1159 * Mark a requested SAN as not authorized.
1161 * @param req The hx509_request object.
1162 * @param idx The cursor as modified by a SAN iterator.
1164 * @return Zero on success, an error otherwise.
1166 * @ingroup hx509_request
1168 HX509_LIB_FUNCTION int HX509_LIB_CALL
1169 hx509_request_reject_san(hx509_request req, size_t idx)
1171 return reject_feat(req, &req->authorized_SANs, req->san.len, idx);
1175 * Check if a SAN has been marked authorized.
1177 * @param req The hx509_request object.
1178 * @param idx The index of a SAN that can be fetched with
1179 * hx509_request_get_san()
1181 * @return Non-zero if authorized, zero if not.
1183 * @ingroup hx509_request
1185 HX509_LIB_FUNCTION int HX509_LIB_CALL
1186 hx509_request_san_authorized_p(hx509_request req, size_t idx)
1188 return abitstring_check(&req->authorized_SANs, req->san.len, idx);
1192 * Return the count of unsupported requested certificate extensions.
1194 * @param req The hx509_request object.
1195 * @return The number of unsupported certificate extensions requested.
1197 * @ingroup hx509_request
1199 HX509_LIB_FUNCTION size_t HX509_LIB_CALL
1200 hx509_request_count_unsupported(hx509_request req)
1202 return req->nunsupported;
1206 * Return the count of as-yet unauthorized certificate extensions requested.
1208 * @param req The hx509_request object.
1209 * @return The number of as-yet unauthorized certificate extensions requested.
1211 * @ingroup hx509_request
1213 HX509_LIB_FUNCTION size_t HX509_LIB_CALL
1214 hx509_request_count_unauthorized(hx509_request req)
1216 size_t nrequested = req->eku.len + req->san.len +
1217 (KeyUsage2int(req->ku) ? 1 : 0) + req->nunsupported;
1219 return nrequested - (req->nauthorized + req->ku_are_authorized);
1222 static hx509_san_type
1223 san_map_type(GeneralName *san)
1225 static const struct {
1226 const heim_oid *oid;
1227 hx509_san_type type;
1228 } map[] = {
1229 { &asn1_oid_id_pkix_on_dnsSRV, HX509_SAN_TYPE_DNSSRV },
1230 { &asn1_oid_id_pkinit_san, HX509_SAN_TYPE_PKINIT },
1231 { &asn1_oid_id_pkix_on_xmppAddr, HX509_SAN_TYPE_XMPP },
1232 { &asn1_oid_id_pkinit_ms_san, HX509_SAN_TYPE_MS_UPN },
1233 { &asn1_oid_id_pkix_on_permanentIdentifier, HX509_SAN_TYPE_PERMANENT_ID },
1234 { &asn1_oid_id_on_hardwareModuleName, HX509_SAN_TYPE_HW_MODULE },
1236 size_t i;
1238 switch (san->element) {
1239 case choice_GeneralName_rfc822Name: return HX509_SAN_TYPE_EMAIL;
1240 case choice_GeneralName_dNSName: return HX509_SAN_TYPE_DNSNAME;
1241 case choice_GeneralName_directoryName: return HX509_SAN_TYPE_DN;
1242 case choice_GeneralName_registeredID: return HX509_SAN_TYPE_REGISTERED_ID;
1243 case choice_GeneralName_otherName: {
1244 for (i = 0; i < sizeof(map)/sizeof(map[0]); i++)
1245 if (der_heim_oid_cmp(&san->u.otherName.type_id, map[i].oid) == 0)
1246 return map[i].type;
1248 /*fallthrough*/
1249 default: return HX509_SAN_TYPE_UNSUPPORTED;
1254 * Return the count of as-yet unauthorized certificate extensions requested.
1256 * @param req The hx509_request object.
1258 * @ingroup hx509_request
1260 HX509_LIB_FUNCTION size_t HX509_LIB_CALL
1261 hx509_request_get_san(hx509_request req,
1262 size_t idx,
1263 hx509_san_type *type,
1264 char **out)
1266 struct rk_strpool *pool = NULL;
1267 GeneralName *san;
1269 *out = NULL;
1270 if (idx >= req->san.len)
1271 return HX509_NO_ITEM;
1273 san = &req->san.val[idx];
1274 switch ((*type = san_map_type(san))) {
1275 case HX509_SAN_TYPE_UNSUPPORTED: return 0;
1276 case HX509_SAN_TYPE_EMAIL:
1277 *out = strndup(san->u.rfc822Name.data,
1278 san->u.rfc822Name.length);
1279 break;
1280 case HX509_SAN_TYPE_DNSNAME:
1281 *out = strndup(san->u.dNSName.data,
1282 san->u.dNSName.length);
1283 break;
1284 case HX509_SAN_TYPE_DNSSRV: {
1285 SRVName name;
1286 size_t size;
1287 int ret;
1289 ret = decode_SRVName(san->u.otherName.value.data,
1290 san->u.otherName.value.length, &name, &size);
1291 if (ret)
1292 return ret;
1293 *out = strndup(name.data, name.length);
1294 break;
1296 case HX509_SAN_TYPE_PERMANENT_ID: {
1297 PermanentIdentifier pi;
1298 size_t size;
1299 char *s = NULL;
1300 int ret;
1302 ret = decode_PermanentIdentifier(san->u.otherName.value.data,
1303 san->u.otherName.value.length,
1304 &pi, &size);
1305 if (ret == 0 && pi.assigner) {
1306 ret = der_print_heim_oid(pi.assigner, '.', &s);
1307 if (ret == 0 &&
1308 (pool = rk_strpoolprintf(NULL, "%s", s)) == NULL)
1309 ret = ENOMEM;
1310 } else if (ret == 0) {
1311 pool = rk_strpoolprintf(NULL, "-");
1313 if (ret == 0 &&
1314 (pool = rk_strpoolprintf(pool, "%s%s",
1315 *pi.identifierValue ? " " : "",
1316 *pi.identifierValue ? *pi.identifierValue : "")) == NULL)
1317 ret = ENOMEM;
1318 if (ret == 0 && (*out = rk_strpoolcollect(pool)) == NULL)
1319 ret = ENOMEM;
1320 free_PermanentIdentifier(&pi);
1321 free(s);
1322 return ret;
1324 case HX509_SAN_TYPE_HW_MODULE: {
1325 HardwareModuleName hn;
1326 size_t size;
1327 char *s = NULL;
1328 int ret;
1330 ret = decode_HardwareModuleName(san->u.otherName.value.data,
1331 san->u.otherName.value.length,
1332 &hn, &size);
1333 if (ret == 0 && hn.hwSerialNum.length > 256)
1334 hn.hwSerialNum.length = 256;
1335 if (ret == 0)
1336 ret = der_print_heim_oid(&hn.hwType, '.', &s);
1337 if (ret == 0)
1338 pool = rk_strpoolprintf(NULL, "%s", s);
1339 if (ret == 0 && pool)
1340 pool = rk_strpoolprintf(pool, " %.*s",
1341 (int)hn.hwSerialNum.length,
1342 (char *)hn.hwSerialNum.data);
1343 if (ret == 0 &&
1344 (pool == NULL || (*out = rk_strpoolcollect(pool)) == NULL))
1345 ret = ENOMEM;
1346 free_HardwareModuleName(&hn);
1347 return ret;
1349 case HX509_SAN_TYPE_DN: {
1350 Name name;
1352 if (san->u.directoryName.element == choice_Name_rdnSequence) {
1353 name.element = choice_Name_rdnSequence;
1354 name.u.rdnSequence = san->u.directoryName.u.rdnSequence;
1355 return _hx509_Name_to_string(&name, out);
1357 *type = HX509_SAN_TYPE_UNSUPPORTED;
1358 return 0;
1360 case HX509_SAN_TYPE_REGISTERED_ID:
1361 return der_print_heim_oid(&san->u.registeredID, '.', out);
1362 case HX509_SAN_TYPE_XMPP:
1363 /*fallthrough*/
1364 case HX509_SAN_TYPE_MS_UPN: {
1365 int ret;
1367 ret = _hx509_unparse_utf8_string_name(req->context, &pool,
1368 &san->u.otherName.value);
1369 if ((*out = rk_strpoolcollect(pool)) == NULL)
1370 return hx509_enomem(req->context);
1371 return ret;
1373 case HX509_SAN_TYPE_PKINIT: {
1374 int ret;
1376 ret = _hx509_unparse_KRB5PrincipalName(req->context, &pool,
1377 &san->u.otherName.value);
1378 if ((*out = rk_strpoolcollect(pool)) == NULL)
1379 return hx509_enomem(req->context);
1380 return 0;
1382 default:
1383 *type = HX509_SAN_TYPE_UNSUPPORTED;
1384 return 0;
1386 if (*out == NULL)
1387 return ENOMEM;
1388 return 0;
1392 * Display a CSR.
1394 * @param context An hx509 context.
1395 * @param req The hx509_request object.
1396 * @param f A FILE * to print the CSR to.
1398 * @return An hx509 error code, see hx509_get_error_string().
1400 * @ingroup hx509_request
1402 HX509_LIB_FUNCTION int HX509_LIB_CALL
1403 hx509_request_print(hx509_context context, hx509_request req, FILE *f)
1405 uint64_t ku_num;
1406 size_t i;
1407 char *s = NULL;
1408 int ret = 0;
1411 * It's really unformatunate that we can't reuse more of the
1412 * lib/hx509/print.c infrastructure here, as it's too focused on
1413 * Certificates.
1415 * For that matter, it's really annoying that CSRs don't more resemble
1416 * Certificates. Indeed, an ideal CSR would look like this:
1418 * CSRInfo ::= {
1419 * desiredTbsCertificate TBSCertificate,
1420 * attributes [1] SEQUENCE OF Attribute OPTIONAL,
1422 * CSR :: = {
1423 * csrInfo CSRInfo,
1424 * sigAlg AlgorithmIdentifier,
1425 * signature BIT STRING
1428 * with everything related to the desired certificate in
1429 * desiredTbsCertificate and anything not related to the CSR's contents in
1430 * the 'attributes' field.
1432 * That wouldn't allow one to have optional desired TBSCertificate
1433 * features, but hey. One could express "gimme all or gimme nothing" as an
1434 * attribute, or "gimme what you can", then check what one got.
1436 fprintf(f, "PKCS#10 CertificationRequest:\n");
1438 if (req->name) {
1439 char *subject;
1440 ret = hx509_name_to_string(req->name, &subject);
1441 if (ret) {
1442 hx509_set_error_string(context, 0, ret, "Failed to print name");
1443 return ret;
1445 fprintf(f, " name: %s\n", subject);
1446 free(subject);
1448 /* XXX Use hx509_request_get_ku() accessor */
1449 if ((ku_num = KeyUsage2int(req->ku))) {
1450 const struct units *u;
1451 const char *first = " ";
1453 fprintf(f, " key usage:");
1454 for (u = asn1_KeyUsage_units(); u->name; ++u) {
1455 if ((ku_num & u->mult)) {
1456 fprintf(f, "%s%s", first, u->name);
1457 first = ", ";
1458 ku_num &= ~u->mult;
1461 if (ku_num)
1462 fprintf(f, "%s<unknown-KeyUsage-value(s)>", first);
1463 fprintf(f, "\n");
1465 if (req->eku.len) {
1466 const char *first = " ";
1468 fprintf(f, " eku:");
1469 for (i = 0; ret == 0; i++) {
1470 free(s); s = NULL;
1471 ret = hx509_request_get_eku(req, i, &s);
1472 if (ret)
1473 break;
1474 fprintf(f, "%s{%s}", first, s);
1475 first = ", ";
1477 fprintf(f, "\n");
1479 free(s); s = NULL;
1480 if (ret == HX509_NO_ITEM)
1481 ret = 0;
1482 for (i = 0; ret == 0; i++) {
1483 hx509_san_type san_type;
1485 free(s); s = NULL;
1486 ret = hx509_request_get_san(req, i, &san_type, &s);
1487 if (ret)
1488 break;
1489 switch (san_type) {
1490 case HX509_SAN_TYPE_EMAIL:
1491 fprintf(f, " san: rfc822Name: %s\n", s);
1492 break;
1493 case HX509_SAN_TYPE_DNSNAME:
1494 fprintf(f, " san: dNSName: %s\n", s);
1495 break;
1496 case HX509_SAN_TYPE_DN:
1497 fprintf(f, " san: dn: %s\n", s);
1498 break;
1499 case HX509_SAN_TYPE_REGISTERED_ID:
1500 fprintf(f, " san: registeredID: %s\n", s);
1501 break;
1502 case HX509_SAN_TYPE_XMPP:
1503 fprintf(f, " san: xmpp: %s\n", s);
1504 break;
1505 case HX509_SAN_TYPE_PKINIT:
1506 fprintf(f, " san: pkinit: %s\n", s);
1507 break;
1508 case HX509_SAN_TYPE_MS_UPN:
1509 fprintf(f, " san: ms-upn: %s\n", s);
1510 break;
1511 default:
1512 fprintf(f, " san: <SAN type not supported>\n");
1513 break;
1516 free(s); s = NULL;
1517 if (ret == HX509_NO_ITEM)
1518 ret = 0;
1519 return ret;