Provide the correct principal name to verify_flags() for user2user tickets
[heimdal.git] / lib / hx509 / name.c
blobd90580183dbc0da3641172d421bf9e337c324b55
1 /*
2 * Copyright (c) 2004 - 2009 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 <wind.h>
36 #include "char_map.h"
38 /**
39 * @page page_name PKIX/X.509 Names
41 * There are several names in PKIX/X.509, GeneralName and Name.
43 * A Name consists of an ordered list of Relative Distinguished Names
44 * (RDN). Each RDN consists of an unordered list of typed strings. The
45 * types are defined by OID and have long and short description. For
46 * example id-at-commonName (2.5.4.3) have the long name CommonName
47 * and short name CN. The string itself can be of several encoding,
48 * UTF8, UTF16, Teltex string, etc. The type limit what encoding
49 * should be used.
51 * GeneralName is a broader nametype that can contains al kind of
52 * stuff like Name, IP addresses, partial Name, etc.
54 * Name is mapped into a hx509_name object.
56 * Parse and string name into a hx509_name object with hx509_parse_name(),
57 * make it back into string representation with hx509_name_to_string().
59 * Name string are defined rfc2253, rfc1779 and X.501.
61 * See the library functions here: @ref hx509_name
64 static const struct {
65 const char *n;
66 const heim_oid *o;
67 wind_profile_flags flags;
69 * RFC52380 imposes maximum lengths for some strings in Names. These are
70 * ASN.1 size limits. We should implement these in our copy of the PKIX
71 * ASN.1 module. For now we treat them as maximum byte counts rather than
72 * maximum character counts, and we encode and enforce them here.
74 * 0 -> no max
76 size_t max_bytes;
77 } no[] = {
78 { "C", &asn1_oid_id_at_countryName, 0, 2 },
79 { "CN", &asn1_oid_id_at_commonName, 0, ub_common_name },
80 { "DC", &asn1_oid_id_domainComponent, 0, 63 }, /* DNS label */
81 { "L", &asn1_oid_id_at_localityName, 0, ub_locality_name },
82 { "O", &asn1_oid_id_at_organizationName, 0, ub_organization_name },
83 { "OU", &asn1_oid_id_at_organizationalUnitName, 0, ub_organizational_unit_name },
84 { "S", &asn1_oid_id_at_stateOrProvinceName, 0, ub_state_name },
85 { "STREET", &asn1_oid_id_at_streetAddress, 0, 0 }, /* ENOTSUP */
86 { "UID", &asn1_oid_id_Userid, 0, ub_numeric_user_id_length },
87 { "emailAddress", &asn1_oid_id_pkcs9_emailAddress, 0, ub_emailaddress_length },
88 /* This is for DevID certificates and maybe others */
89 { "serialNumber", &asn1_oid_id_at_serialNumber, 0, ub_serial_number },
90 /* These are for TPM 2.0 Endorsement Key Certificates (EKCerts) */
91 { "TPMManufacturer", &asn1_oid_tcg_at_tpmManufacturer, 0, ub_emailaddress_length },
92 { "TPMModel", &asn1_oid_tcg_at_tpmModel, 0, ub_emailaddress_length },
93 { "TPMVersion", &asn1_oid_tcg_at_tpmVersion, 0, ub_emailaddress_length },
96 static char *
97 quote_string(const char *f, size_t len, int flags, size_t *rlen)
99 size_t i, j, tolen;
100 const unsigned char *from = (const unsigned char *)f;
101 unsigned char *to;
103 tolen = len * 3 + 1;
104 to = malloc(tolen);
105 if (to == NULL)
106 return NULL;
108 for (i = 0, j = 0; i < len; i++) {
109 unsigned char map = char_map[from[i]] & flags;
110 if (i == 0 && (map & Q_RFC2253_QUOTE_FIRST)) {
111 to[j++] = '\\';
112 to[j++] = from[i];
113 } else if ((i + 1) == len && (map & Q_RFC2253_QUOTE_LAST)) {
115 to[j++] = '\\';
116 to[j++] = from[i];
117 } else if (map & Q_RFC2253_QUOTE) {
118 to[j++] = '\\';
119 to[j++] = from[i];
120 } else if (map & Q_RFC2253_HEX) {
121 int l = snprintf((char *)&to[j], tolen - j - 1,
122 "#%02x", (unsigned char)from[i]);
123 j += l;
124 } else {
125 to[j++] = from[i];
128 to[j] = '\0';
129 assert(j < tolen);
130 *rlen = j;
131 return (char *)to;
135 static int
136 append_string(char **str, size_t *total_len, const char *ss,
137 size_t len, int quote)
139 char *s, *qs;
141 if (quote)
142 qs = quote_string(ss, len, Q_RFC2253, &len);
143 else
144 qs = rk_UNCONST(ss);
146 s = realloc(*str, len + *total_len + 1);
147 if (s == NULL)
148 _hx509_abort("allocation failure"); /* XXX */
149 memcpy(s + *total_len, qs, len);
150 if (qs != ss)
151 free(qs);
152 s[*total_len + len] = '\0';
153 *str = s;
154 *total_len += len;
155 return 0;
158 static char *
159 oidtostring(const heim_oid *type)
161 char *s;
162 size_t i;
164 for (i = 0; i < sizeof(no)/sizeof(no[0]); i++) {
165 if (der_heim_oid_cmp(no[i].o, type) == 0)
166 return strdup(no[i].n);
168 if (der_print_heim_oid(type, '.', &s) != 0)
169 return NULL;
170 return s;
173 static size_t
174 oidtomaxlen(const heim_oid *type)
176 size_t i;
178 for (i = 0; i < sizeof(no)/sizeof(no[0]); i++) {
179 if (der_heim_oid_cmp(no[i].o, type) == 0)
180 return no[i].max_bytes;
182 return 0;
185 static int
186 stringtooid(const char *name, size_t len, heim_oid *oid)
188 int ret;
189 size_t i;
190 char *s;
192 memset(oid, 0, sizeof(*oid));
194 for (i = 0; i < sizeof(no)/sizeof(no[0]); i++) {
195 if (strncasecmp(no[i].n, name, len) == 0)
196 return der_copy_oid(no[i].o, oid);
198 s = malloc(len + 1);
199 if (s == NULL)
200 return ENOMEM;
201 memcpy(s, name, len);
202 s[len] = '\0';
203 ret = der_parse_heim_oid(s, ".", oid);
204 free(s);
205 return ret;
209 * Convert the hx509 name object into a printable string.
210 * The resulting string should be freed with free().
212 * @param name name to print
213 * @param str the string to return
215 * @return An hx509 error code, see hx509_get_error_string().
217 * @ingroup hx509_name
220 HX509_LIB_FUNCTION int HX509_LIB_CALL
221 hx509_name_to_string(const hx509_name name, char **str)
223 return _hx509_Name_to_string(&name->der_name, str);
226 HX509_LIB_FUNCTION int HX509_LIB_CALL
227 _hx509_Name_to_string(const Name *n, char **str)
229 size_t total_len = 0;
230 size_t i, j, m;
231 int ret;
233 *str = strdup("");
234 if (*str == NULL)
235 return ENOMEM;
237 for (m = n->u.rdnSequence.len; m > 0; m--) {
238 size_t len;
239 i = m - 1;
241 for (j = 0; j < n->u.rdnSequence.val[i].len; j++) {
242 DirectoryString *ds = &n->u.rdnSequence.val[i].val[j].value;
243 char *oidname;
244 char *ss;
246 oidname = oidtostring(&n->u.rdnSequence.val[i].val[j].type);
248 switch(ds->element) {
249 case choice_DirectoryString_ia5String:
250 ss = ds->u.ia5String.data;
251 len = ds->u.ia5String.length;
252 break;
253 case choice_DirectoryString_printableString:
254 ss = ds->u.printableString.data;
255 len = ds->u.printableString.length;
256 break;
257 case choice_DirectoryString_utf8String:
258 ss = ds->u.utf8String;
259 len = strlen(ss);
260 break;
261 case choice_DirectoryString_bmpString: {
262 const uint16_t *bmp = ds->u.bmpString.data;
263 size_t bmplen = ds->u.bmpString.length;
264 size_t k;
266 ret = wind_ucs2utf8_length(bmp, bmplen, &k);
267 if (ret) {
268 free(oidname);
269 free(*str);
270 *str = NULL;
271 return ret;
274 ss = malloc(k + 1);
275 if (ss == NULL)
276 _hx509_abort("allocation failure"); /* XXX */
277 ret = wind_ucs2utf8(bmp, bmplen, ss, NULL);
278 if (ret) {
279 free(oidname);
280 free(ss);
281 free(*str);
282 *str = NULL;
283 return ret;
285 ss[k] = '\0';
286 len = k;
287 break;
289 case choice_DirectoryString_teletexString:
290 ss = ds->u.teletexString;
291 len = strlen(ss);
292 break;
293 case choice_DirectoryString_universalString: {
294 const uint32_t *uni = ds->u.universalString.data;
295 size_t unilen = ds->u.universalString.length;
296 size_t k;
298 ret = wind_ucs4utf8_length(uni, unilen, &k);
299 if (ret) {
300 free(oidname);
301 free(*str);
302 *str = NULL;
303 return ret;
306 ss = malloc(k + 1);
307 if (ss == NULL)
308 _hx509_abort("allocation failure"); /* XXX */
309 ret = wind_ucs4utf8(uni, unilen, ss, NULL);
310 if (ret) {
311 free(ss);
312 free(oidname);
313 free(*str);
314 *str = NULL;
315 return ret;
317 ss[k] = '\0';
318 len = k;
319 break;
321 default:
322 _hx509_abort("unknown directory type: %d", ds->element);
323 exit(1);
325 append_string(str, &total_len, oidname, strlen(oidname), 0);
326 free(oidname);
327 append_string(str, &total_len, "=", 1, 0);
328 append_string(str, &total_len, ss, len, 1);
329 if (ds->element == choice_DirectoryString_bmpString ||
330 ds->element == choice_DirectoryString_universalString)
332 free(ss);
334 if (j + 1 < n->u.rdnSequence.val[i].len)
335 append_string(str, &total_len, "+", 1, 0);
338 if (i > 0)
339 append_string(str, &total_len, ",", 1, 0);
341 return 0;
344 #define COPYCHARARRAY(_ds,_el,_l,_n) \
345 (_l) = strlen(_ds->u._el); \
346 (_n) = malloc((_l) * sizeof((_n)[0])); \
347 if ((_n) == NULL) \
348 return ENOMEM; \
349 for (i = 0; i < (_l); i++) \
350 (_n)[i] = _ds->u._el[i]
353 #define COPYVALARRAY(_ds,_el,_l,_n) \
354 (_l) = _ds->u._el.length; \
355 (_n) = malloc((_l) * sizeof((_n)[0])); \
356 if ((_n) == NULL) \
357 return ENOMEM; \
358 for (i = 0; i < (_l); i++) \
359 (_n)[i] = _ds->u._el.data[i]
361 #define COPYVOIDARRAY(_ds,_el,_l,_n) \
362 (_l) = _ds->u._el.length; \
363 (_n) = malloc((_l) * sizeof((_n)[0])); \
364 if ((_n) == NULL) \
365 return ENOMEM; \
366 for (i = 0; i < (_l); i++) \
367 (_n)[i] = ((unsigned char *)_ds->u._el.data)[i]
371 static int
372 dsstringprep(const DirectoryString *ds, uint32_t **rname, size_t *rlen)
374 wind_profile_flags flags;
375 size_t i, len;
376 int ret = 0;
377 uint32_t *name;
379 *rname = NULL;
380 *rlen = 0;
382 switch(ds->element) {
383 case choice_DirectoryString_ia5String:
384 flags = WIND_PROFILE_LDAP;
385 COPYVOIDARRAY(ds, ia5String, len, name);
386 break;
387 case choice_DirectoryString_printableString:
388 flags = WIND_PROFILE_LDAP;
389 flags |= WIND_PROFILE_LDAP_CASE_EXACT_ATTRIBUTE;
390 COPYVOIDARRAY(ds, printableString, len, name);
391 break;
392 case choice_DirectoryString_teletexString:
393 flags = WIND_PROFILE_LDAP_CASE;
394 COPYCHARARRAY(ds, teletexString, len, name);
395 break;
396 case choice_DirectoryString_bmpString:
397 flags = WIND_PROFILE_LDAP;
398 COPYVALARRAY(ds, bmpString, len, name);
399 break;
400 case choice_DirectoryString_universalString:
401 flags = WIND_PROFILE_LDAP;
402 COPYVALARRAY(ds, universalString, len, name);
403 break;
404 case choice_DirectoryString_utf8String:
405 flags = WIND_PROFILE_LDAP;
406 ret = wind_utf8ucs4_length(ds->u.utf8String, &len);
407 if (ret)
408 return ret;
409 name = malloc(len * sizeof(name[0]));
410 if (name == NULL)
411 return ENOMEM;
412 ret = wind_utf8ucs4(ds->u.utf8String, name, &len);
413 if (ret) {
414 free(name);
415 return ret;
417 break;
418 default:
419 _hx509_abort("unknown directory type: %d", ds->element);
422 *rlen = len;
423 /* try a couple of times to get the length right, XXX gross */
424 for (i = 0; i < 4; i++) {
425 *rlen = *rlen * 2;
426 if ((*rname = malloc(*rlen * sizeof((*rname)[0]))) == NULL) {
427 ret = ENOMEM;
428 break;
431 ret = wind_stringprep(name, len, *rname, rlen, flags);
432 if (ret == WIND_ERR_OVERRUN) {
433 free(*rname);
434 *rname = NULL;
435 continue;
436 } else
437 break;
439 free(name);
440 if (ret) {
441 if (*rname)
442 free(*rname);
443 *rname = NULL;
444 *rlen = 0;
445 return ret;
448 return 0;
451 HX509_LIB_FUNCTION int HX509_LIB_CALL
452 _hx509_name_ds_cmp(const DirectoryString *ds1,
453 const DirectoryString *ds2,
454 int *diff)
456 uint32_t *ds1lp, *ds2lp;
457 size_t ds1len, ds2len, i;
458 int ret;
460 ret = dsstringprep(ds1, &ds1lp, &ds1len);
461 if (ret)
462 return ret;
463 ret = dsstringprep(ds2, &ds2lp, &ds2len);
464 if (ret) {
465 free(ds1lp);
466 return ret;
469 if (ds1len != ds2len)
470 *diff = ds1len - ds2len;
471 else {
472 for (i = 0; i < ds1len; i++) {
473 *diff = ds1lp[i] - ds2lp[i];
474 if (*diff)
475 break;
478 free(ds1lp);
479 free(ds2lp);
481 return 0;
484 HX509_LIB_FUNCTION int HX509_LIB_CALL
485 _hx509_name_cmp(const Name *n1, const Name *n2, int *c)
487 int ret;
488 size_t i, j;
490 *c = n1->u.rdnSequence.len - n2->u.rdnSequence.len;
491 if (*c)
492 return 0;
494 for (i = 0 ; i < n1->u.rdnSequence.len; i++) {
495 *c = n1->u.rdnSequence.val[i].len - n2->u.rdnSequence.val[i].len;
496 if (*c)
497 return 0;
499 for (j = 0; j < n1->u.rdnSequence.val[i].len; j++) {
500 *c = der_heim_oid_cmp(&n1->u.rdnSequence.val[i].val[j].type,
501 &n1->u.rdnSequence.val[i].val[j].type);
502 if (*c)
503 return 0;
505 ret = _hx509_name_ds_cmp(&n1->u.rdnSequence.val[i].val[j].value,
506 &n2->u.rdnSequence.val[i].val[j].value,
508 if (ret)
509 return ret;
510 if (*c)
511 return 0;
514 *c = 0;
515 return 0;
519 * Compare to hx509 name object, useful for sorting.
521 * @param n1 a hx509 name object.
522 * @param n2 a hx509 name object.
524 * @return 0 the objects are the same, returns > 0 is n2 is "larger"
525 * then n2, < 0 if n1 is "smaller" then n2.
527 * @ingroup hx509_name
530 HX509_LIB_FUNCTION int HX509_LIB_CALL
531 hx509_name_cmp(hx509_name n1, hx509_name n2)
533 int ret, diff;
534 ret = _hx509_name_cmp(&n1->der_name, &n2->der_name, &diff);
535 if (ret)
536 return ret;
537 return diff;
541 HX509_LIB_FUNCTION int HX509_LIB_CALL
542 _hx509_name_from_Name(const Name *n, hx509_name *name)
544 int ret;
545 *name = calloc(1, sizeof(**name));
546 if (*name == NULL)
547 return ENOMEM;
548 ret = copy_Name(n, &(*name)->der_name);
549 if (ret) {
550 free(*name);
551 *name = NULL;
553 return ret;
556 HX509_LIB_FUNCTION int HX509_LIB_CALL
557 _hx509_name_modify(hx509_context context,
558 Name *name,
559 int append,
560 const heim_oid *oid,
561 const char *str)
563 RelativeDistinguishedName rdn;
564 size_t max_len = oidtomaxlen(oid);
565 int ret;
568 * Check string length upper bounds.
570 * Because we don't have these bounds in our copy of the PKIX ASN.1 module,
571 * and because we might like to catch these early anyways, we enforce them
572 * here.
574 if (max_len && strlen(str) > max_len) {
575 const char *a = oidtostring(oid);
577 ret = HX509_PARSING_NAME_FAILED;
578 hx509_set_error_string(context, 0, ret, "RDN attribute %s value too "
579 "long (max %llu): %s", a ? a : "<unknown>",
580 max_len, str);
581 return ret;
584 memset(&rdn, 0, sizeof(rdn));
585 if ((rdn.val = malloc(sizeof(rdn.val[0]))) == NULL) {
586 hx509_set_error_string(context, 0, ENOMEM, "Out of memory");
587 return ENOMEM;
589 rdn.len = 1;
590 rdn.val[0].value.element = choice_DirectoryString_utf8String;
591 if ((rdn.val[0].value.u.utf8String = strdup(str)) == NULL ||
592 (ret = der_copy_oid(oid, &rdn.val[0].type))) {
593 hx509_set_error_string(context, 0, ENOMEM, "Out of memory");
594 free(rdn.val[0].value.u.utf8String);
595 free(rdn.val);
596 return ENOMEM;
599 /* Append RDN. If the caller wanted to prepend instead, we'll rotate. */
600 ret = add_RDNSequence(&name->u.rdnSequence, &rdn);
601 free_RelativeDistinguishedName(&rdn);
603 if (ret || append || name->u.rdnSequence.len < 2)
604 return ret;
606 /* Rotate */
607 rdn = name->u.rdnSequence.val[name->u.rdnSequence.len - 1];
608 memmove(&name->u.rdnSequence.val[1],
609 &name->u.rdnSequence.val[0],
610 (name->u.rdnSequence.len - 1) *
611 sizeof(name->u.rdnSequence.val[0]));
612 name->u.rdnSequence.val[0] = rdn;
613 return 0;
616 HX509_LIB_FUNCTION int HX509_LIB_CALL
617 hx509_empty_name(hx509_context context, hx509_name *name)
619 if ((*name = calloc(1, sizeof(**name))) == NULL) {
620 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
621 return ENOMEM;
623 (*name)->der_name.element = choice_Name_rdnSequence;
624 (*name)->der_name.u.rdnSequence.val = 0;
625 (*name)->der_name.u.rdnSequence.len = 0;
626 return 0;
630 * Parse a string into a hx509 name object.
632 * @param context A hx509 context.
633 * @param str a string to parse.
634 * @param name the resulting object, NULL in case of error.
636 * @return An hx509 error code, see hx509_get_error_string().
638 * @ingroup hx509_name
641 HX509_LIB_FUNCTION int HX509_LIB_CALL
642 hx509_parse_name(hx509_context context, const char *str, hx509_name *name)
644 const char *p, *q;
645 size_t len;
646 hx509_name n;
647 int ret;
649 *name = NULL;
651 n = calloc(1, sizeof(*n));
652 if (n == NULL) {
653 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
654 return ENOMEM;
657 n->der_name.element = choice_Name_rdnSequence;
659 p = str;
661 while (p != NULL && *p != '\0') {
662 heim_oid oid;
663 int last;
665 q = strchr(p, ',');
666 if (q) {
667 len = (q - p);
668 last = 1;
669 } else {
670 len = strlen(p);
671 last = 0;
674 q = strchr(p, '=');
675 if (q == NULL) {
676 ret = HX509_PARSING_NAME_FAILED;
677 hx509_set_error_string(context, 0, ret, "missing = in %s", p);
678 goto out;
680 if (q == p) {
681 ret = HX509_PARSING_NAME_FAILED;
682 hx509_set_error_string(context, 0, ret,
683 "missing name before = in %s", p);
684 goto out;
687 if ((size_t)(q - p) > len) {
688 ret = HX509_PARSING_NAME_FAILED;
689 hx509_set_error_string(context, 0, ret, " = after , in %s", p);
690 goto out;
693 ret = stringtooid(p, q - p, &oid);
694 if (ret) {
695 ret = HX509_PARSING_NAME_FAILED;
696 hx509_set_error_string(context, 0, ret,
697 "unknown type: %.*s", (int)(q - p), p);
698 goto out;
702 size_t pstr_len = len - (q - p) - 1;
703 const char *pstr = p + (q - p) + 1;
704 char *r;
706 r = malloc(pstr_len + 1);
707 if (r == NULL) {
708 der_free_oid(&oid);
709 ret = ENOMEM;
710 hx509_set_error_string(context, 0, ret, "out of memory");
711 goto out;
713 memcpy(r, pstr, pstr_len);
714 r[pstr_len] = '\0';
716 ret = _hx509_name_modify(context, &n->der_name, 0, &oid, r);
717 free(r);
718 der_free_oid(&oid);
719 if(ret)
720 goto out;
722 p += len + last;
725 *name = n;
727 return 0;
728 out:
729 hx509_name_free(&n);
730 return HX509_NAME_MALFORMED;
734 * Copy a hx509 name object.
736 * @param context A hx509 cotext.
737 * @param from the name to copy from
738 * @param to the name to copy to
740 * @return An hx509 error code, see hx509_get_error_string().
742 * @ingroup hx509_name
745 HX509_LIB_FUNCTION int HX509_LIB_CALL
746 hx509_name_copy(hx509_context context, const hx509_name from, hx509_name *to)
748 int ret;
750 *to = calloc(1, sizeof(**to));
751 if (*to == NULL)
752 return ENOMEM;
753 ret = copy_Name(&from->der_name, &(*to)->der_name);
754 if (ret) {
755 free(*to);
756 *to = NULL;
757 return ENOMEM;
759 return 0;
763 * Convert a hx509_name into a Name.
765 * @param from the name to copy from
766 * @param to the name to copy to
768 * @return An hx509 error code, see hx509_get_error_string().
770 * @ingroup hx509_name
773 HX509_LIB_FUNCTION int HX509_LIB_CALL
774 hx509_name_to_Name(const hx509_name from, Name *to)
776 return copy_Name(&from->der_name, to);
779 HX509_LIB_FUNCTION int HX509_LIB_CALL
780 hx509_name_normalize(hx509_context context, hx509_name name)
782 return 0;
786 * Expands variables in the name using env. Variables are on the form
787 * ${name}. Useful when dealing with certificate templates.
789 * @param context A hx509 cotext.
790 * @param name the name to expand.
791 * @param env environment variable to expand.
793 * @return An hx509 error code, see hx509_get_error_string().
795 * @ingroup hx509_name
798 HX509_LIB_FUNCTION int HX509_LIB_CALL
799 hx509_name_expand(hx509_context context,
800 hx509_name name,
801 hx509_env env)
803 Name *n = &name->der_name;
804 size_t i, j;
805 int bounds_check = 1;
807 if (env == NULL)
808 return 0;
810 if (n->element != choice_Name_rdnSequence) {
811 hx509_set_error_string(context, 0, EINVAL, "RDN not of supported type");
812 return EINVAL;
815 for (i = 0 ; i < n->u.rdnSequence.len; i++) {
816 for (j = 0; j < n->u.rdnSequence.val[i].len; j++) {
817 /** Only UTF8String rdnSequence names are allowed */
819 THIS SHOULD REALLY BE:
820 COMP = n->u.rdnSequence.val[i].val[j];
821 normalize COMP to utf8
822 check if there are variables
823 expand variables
824 convert back to orignal format, store in COMP
825 free normalized utf8 string
827 DirectoryString *ds = &n->u.rdnSequence.val[i].val[j].value;
828 heim_oid *type = &n->u.rdnSequence.val[i].val[j].type;
829 char *p, *p2;
830 struct rk_strpool *strpool = NULL;
832 if (ds->element != choice_DirectoryString_utf8String) {
833 hx509_set_error_string(context, 0, EINVAL, "unsupported type");
834 return EINVAL;
836 p = strstr(ds->u.utf8String, "${");
837 if (p) {
838 strpool = rk_strpoolprintf(strpool, "%.*s",
839 (int)(p - ds->u.utf8String),
840 ds->u.utf8String);
841 if (strpool == NULL) {
842 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
843 return ENOMEM;
846 while (p != NULL) {
847 /* expand variables */
848 const char *value;
849 p2 = strchr(p, '}');
850 if (p2 == NULL) {
851 hx509_set_error_string(context, 0, EINVAL, "missing }");
852 rk_strpoolfree(strpool);
853 return EINVAL;
855 p += 2;
856 value = hx509_env_lfind(context, env, p, p2 - p);
857 if (value == NULL) {
858 hx509_set_error_string(context, 0, EINVAL,
859 "variable %.*s missing",
860 (int)(p2 - p), p);
861 rk_strpoolfree(strpool);
862 return EINVAL;
864 strpool = rk_strpoolprintf(strpool, "%s", value);
865 if (strpool == NULL) {
866 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
867 return ENOMEM;
869 p2++;
871 p = strstr(p2, "${");
872 if (p)
873 strpool = rk_strpoolprintf(strpool, "%.*s",
874 (int)(p - p2), p2);
875 else
876 strpool = rk_strpoolprintf(strpool, "%s", p2);
877 if (strpool == NULL) {
878 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
879 return ENOMEM;
882 if (strpool) {
883 size_t max_bytes;
885 free(ds->u.utf8String);
886 ds->u.utf8String = rk_strpoolcollect(strpool);
887 if (ds->u.utf8String == NULL) {
888 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
889 return ENOMEM;
892 /* Check upper bounds! */
893 if ((max_bytes = oidtomaxlen(type)) &&
894 strlen(ds->u.utf8String) > max_bytes)
895 bounds_check = 0;
900 if (!bounds_check) {
901 hx509_set_error_string(context, 0, HX509_PARSING_NAME_FAILED,
902 "some expanded RDNs are too long");
903 return HX509_PARSING_NAME_FAILED;
905 return 0;
909 * Free a hx509 name object, upond return *name will be NULL.
911 * @param name a hx509 name object to be freed.
913 * @ingroup hx509_name
916 HX509_LIB_FUNCTION void HX509_LIB_CALL
917 hx509_name_free(hx509_name *name)
919 free_Name(&(*name)->der_name);
920 memset(*name, 0, sizeof(**name));
921 free(*name);
922 *name = NULL;
926 * Convert a DER encoded name info a string.
928 * @param data data to a DER/BER encoded name
929 * @param length length of data
930 * @param str the resulting string, is NULL on failure.
932 * @return An hx509 error code, see hx509_get_error_string().
934 * @ingroup hx509_name
937 HX509_LIB_FUNCTION int HX509_LIB_CALL
938 hx509_unparse_der_name(const void *data, size_t length, char **str)
940 Name name;
941 int ret;
943 *str = NULL;
945 ret = decode_Name(data, length, &name, NULL);
946 if (ret)
947 return ret;
948 ret = _hx509_Name_to_string(&name, str);
949 free_Name(&name);
950 return ret;
954 * Convert a hx509_name object to DER encoded name.
956 * @param name name to concert
957 * @param os data to a DER encoded name, free the resulting octet
958 * string with hx509_xfree(os->data).
960 * @return An hx509 error code, see hx509_get_error_string().
962 * @ingroup hx509_name
965 HX509_LIB_FUNCTION int HX509_LIB_CALL
966 hx509_name_binary(const hx509_name name, heim_octet_string *os)
968 size_t size;
969 int ret;
971 ASN1_MALLOC_ENCODE(Name, os->data, os->length, &name->der_name, &size, ret);
972 if (ret)
973 return ret;
974 if (os->length != size)
975 _hx509_abort("internal ASN.1 encoder error");
977 return 0;
980 HX509_LIB_FUNCTION int HX509_LIB_CALL
981 _hx509_unparse_Name(const Name *aname, char **str)
983 hx509_name name;
984 int ret;
986 ret = _hx509_name_from_Name(aname, &name);
987 if (ret)
988 return ret;
990 ret = hx509_name_to_string(name, str);
991 hx509_name_free(&name);
992 return ret;
996 * Check if a name is empty.
998 * @param name the name to check if its empty/null.
1000 * @return non zero if the name is empty/null.
1002 * @ingroup hx509_name
1005 HX509_LIB_FUNCTION int HX509_LIB_CALL
1006 hx509_name_is_null_p(const hx509_name name)
1008 return name->der_name.element == choice_Name_rdnSequence &&
1009 name->der_name.u.rdnSequence.len == 0;
1013 _hx509_unparse_PermanentIdentifier(hx509_context context,
1014 struct rk_strpool **strpool,
1015 heim_any *value)
1017 PermanentIdentifier pi;
1018 size_t len;
1019 const char *pid = "";
1020 char *s = NULL;
1021 int ret;
1023 ret = decode_PermanentIdentifier(value->data, value->length, &pi, &len);
1024 if (ret == 0 && pi.assigner &&
1025 der_print_heim_oid(pi.assigner, '.', &s) != 0)
1026 ret = hx509_enomem(context);
1027 if (pi.identifierValue && *pi.identifierValue)
1028 pid = *pi.identifierValue;
1029 if (ret == 0 &&
1030 (*strpool = rk_strpoolprintf(*strpool, "%s:%s", s ? s : "", pid)) == NULL)
1031 ret = hx509_enomem(context);
1032 free_PermanentIdentifier(&pi);
1033 free(s);
1034 if (ret) {
1035 rk_strpoolfree(*strpool);
1036 *strpool = rk_strpoolprintf(NULL,
1037 "<error-decoding-PermanentIdentifier");
1038 hx509_set_error_string(context, 0, ret,
1039 "Failed to decode PermanentIdentifier");
1041 return ret;
1045 _hx509_unparse_HardwareModuleName(hx509_context context,
1046 struct rk_strpool **strpool,
1047 heim_any *value)
1049 HardwareModuleName hm;
1050 size_t len;
1051 char *s = NULL;
1052 int ret;
1054 ret = decode_HardwareModuleName(value->data, value->length, &hm, &len);
1055 if (ret == 0 && hm.hwSerialNum.length > 256)
1056 hm.hwSerialNum.length = 256;
1057 if (ret == 0)
1058 ret = der_print_heim_oid(&hm.hwType, '.', &s);
1059 if (ret == 0) {
1060 *strpool = rk_strpoolprintf(*strpool, "%s:%.*s%s", s,
1061 (int)hm.hwSerialNum.length,
1062 (char *)hm.hwSerialNum.data,
1063 value->length == len ? "" : ", <garbage>");
1064 if (*strpool == NULL)
1065 ret = hx509_enomem(context);
1067 free_HardwareModuleName(&hm);
1068 free(s);
1069 if (ret) {
1070 rk_strpoolfree(*strpool);
1071 *strpool = rk_strpoolprintf(NULL,
1072 "<error-decoding-HardwareModuleName");
1073 hx509_set_error_string(context, 0, ret,
1074 "Failed to decode HardwareModuleName");
1076 return ret;
1080 * This necessarily duplicates code from libkrb5, and has to unless we move
1081 * common code here or to lib/roken for it. We do have slightly different
1082 * needs (e.g., we want space quoted, and we want to indicate whether we saw
1083 * trailing garbage, we have no need for flags, no special realm treatment,
1084 * etc) than the corresponding code in libkrb5, so for now we duplicate this
1085 * code.
1087 * The relevant RFCs here are RFC1964 for the string representation of Kerberos
1088 * principal names, and RFC4556 for the KRB5PrincipalName ASN.1 type (Kerberos
1089 * lacks such a type because on the wire the name and realm are sent
1090 * separately as a form of cheap compression).
1092 * Note that we cannot handle embedded NULs because of Heimdal's representation
1093 * of ASN.1 strings as C strings.
1096 _hx509_unparse_KRB5PrincipalName(hx509_context context,
1097 struct rk_strpool **strpool,
1098 heim_any *value)
1100 KRB5PrincipalName kn;
1101 size_t len;
1102 int ret;
1104 ret = decode_KRB5PrincipalName(value->data, value->length, &kn, &len);
1105 if (ret == 0 &&
1106 (*strpool = _hx509_unparse_kerberos_name(*strpool, &kn)) == NULL)
1107 ret = hx509_enomem(context);
1108 free_KRB5PrincipalName(&kn);
1109 if (ret == 0 && (value->length != len) &&
1110 (*strpool = rk_strpoolprintf(*strpool, " <garbage>")) == NULL)
1111 ret = hx509_enomem(context);
1112 if (ret) {
1113 rk_strpoolfree(*strpool);
1114 *strpool = rk_strpoolprintf(NULL,
1115 "<error-decoding-PrincipalName");
1116 hx509_set_error_string(context, 0, ret,
1117 "Failed to decode PermanentIdentifier");
1119 return ret;
1122 struct rk_strpool *
1123 _hx509_unparse_kerberos_name(struct rk_strpool *strpool, KRB5PrincipalName *kn)
1125 static const char comp_quotable_chars[] = " \n\t\b\\/@";
1126 static const char realm_quotable_chars[] = " \n\t\b\\@";
1127 const char *s;
1128 size_t i, k, len, plen;
1129 int need_slash = 0;
1131 for (i = 0; i < kn->principalName.name_string.len; i++) {
1132 s = kn->principalName.name_string.val[i];
1133 len = strlen(s);
1135 if (need_slash)
1136 strpool = rk_strpoolprintf(strpool, "/");
1137 need_slash = 1;
1139 for (k = 0; k < len; s += plen, k += plen) {
1140 char c;
1142 plen = strcspn(s, comp_quotable_chars);
1143 if (plen)
1144 strpool = rk_strpoolprintf(strpool, "%.*s", (int)plen, s);
1145 if (k + plen >= len)
1146 continue;
1147 switch ((c = s[plen++])) {
1148 case '\n': strpool = rk_strpoolprintf(strpool, "\\n"); break;
1149 case '\t': strpool = rk_strpoolprintf(strpool, "\\t"); break;
1150 case '\b': strpool = rk_strpoolprintf(strpool, "\\b"); break;
1151 /* default -> '@', ' ', '\\', or '/' */
1152 default: strpool = rk_strpoolprintf(strpool, "\\%c", c); break;
1156 if (!kn->realm)
1157 return strpool;
1158 strpool = rk_strpoolprintf(strpool, "@");
1160 s = kn->realm;
1161 len = strlen(kn->realm);
1162 for (k = 0; k < len; s += plen, k += plen) {
1163 char c;
1165 plen = strcspn(s, realm_quotable_chars);
1166 if (plen)
1167 strpool = rk_strpoolprintf(strpool, "%.*s", (int)plen, s);
1168 if (k + plen >= len)
1169 continue;
1170 switch ((c = s[plen++])) {
1171 case '\n': strpool = rk_strpoolprintf(strpool, "\\n"); break;
1172 case '\t': strpool = rk_strpoolprintf(strpool, "\\t"); break;
1173 case '\b': strpool = rk_strpoolprintf(strpool, "\\b"); break;
1174 /* default -> '@', ' ', or '\\' */
1175 default: strpool = rk_strpoolprintf(strpool, "\\%c", c); break;
1178 return strpool;
1182 _hx509_unparse_utf8_string_name(hx509_context context,
1183 struct rk_strpool **strpool,
1184 heim_any *value)
1186 PKIXXmppAddr us;
1187 size_t size;
1188 int ret;
1190 ret = decode_PKIXXmppAddr(value->data, value->length, &us, &size);
1191 if (ret == 0 &&
1192 (*strpool = rk_strpoolprintf(*strpool, "%s", us)) == NULL)
1193 ret = hx509_enomem(context);
1194 if (ret) {
1195 rk_strpoolfree(*strpool);
1196 *strpool = rk_strpoolprintf(NULL,
1197 "<error-decoding-UTF8String-SAN>");
1198 hx509_set_error_string(context, 0, ret,
1199 "Failed to decode UTF8String SAN");
1201 free_PKIXXmppAddr(&us);
1202 return ret;
1206 _hx509_unparse_ia5_string_name(hx509_context context,
1207 struct rk_strpool **strpool,
1208 heim_any *value)
1210 SRVName us;
1211 size_t size;
1212 int ret;
1214 ret = decode_SRVName(value->data, value->length, &us, &size);
1215 if (ret == 0) {
1216 rk_strpoolfree(*strpool);
1217 *strpool = rk_strpoolprintf(NULL,
1218 "<error-decoding-IA5String-SAN>");
1219 hx509_set_error_string(context, 0, ret,
1220 "Failed to decode UTF8String SAN");
1221 return ret;
1223 *strpool = rk_strpoolprintf(*strpool, "%.*s",
1224 (int)us.length, (char *)us.data);
1225 free_SRVName(&us);
1226 return ret;
1229 typedef int (*other_unparser_f)(hx509_context,
1230 struct rk_strpool **,
1231 heim_any *);
1233 struct {
1234 const heim_oid *oid;
1235 const char *friendly_name;
1236 other_unparser_f f;
1237 } o_unparsers[] = {
1238 { &asn1_oid_id_pkinit_san,
1239 "KerberosPrincipalName",
1240 _hx509_unparse_KRB5PrincipalName },
1241 { &asn1_oid_id_pkix_on_permanentIdentifier,
1242 "PermanentIdentifier",
1243 _hx509_unparse_PermanentIdentifier },
1244 { &asn1_oid_id_on_hardwareModuleName,
1245 "HardwareModuleName",
1246 _hx509_unparse_HardwareModuleName },
1247 { &asn1_oid_id_pkix_on_xmppAddr,
1248 "XMPPName",
1249 _hx509_unparse_utf8_string_name },
1250 { &asn1_oid_id_pkinit_ms_san,
1251 "MSFTKerberosPrincipalName",
1252 _hx509_unparse_utf8_string_name },
1253 { &asn1_oid_id_pkix_on_dnsSRV,
1254 "SRVName",
1255 _hx509_unparse_ia5_string_name },
1259 * Unparse the hx509 name in name into a string.
1261 * @param name the name to print
1262 * @param str an allocated string returns the name in string form
1264 * @return An hx509 error code, see hx509_get_error_string().
1266 * @ingroup hx509_name
1269 HX509_LIB_FUNCTION int HX509_LIB_CALL
1270 hx509_general_name_unparse(GeneralName *name, char **str)
1272 hx509_context context;
1273 int ret;
1275 if ((ret = hx509_context_init(&context)))
1276 return ret;
1277 return hx509_general_name_unparse2(context, name, str);
1281 * Unparse the hx509 name in name into a string.
1283 * @param context hx509 library context
1284 * @param name the name to print
1285 * @param str an allocated string returns the name in string form
1287 * @return An hx509 error code, see hx509_get_error_string().
1289 * @ingroup hx509_name
1292 HX509_LIB_FUNCTION int HX509_LIB_CALL
1293 hx509_general_name_unparse2(hx509_context context,
1294 GeneralName *name,
1295 char **str)
1297 struct rk_strpool *strpool = NULL;
1298 int ret = 0;
1300 *str = NULL;
1302 switch (name->element) {
1303 case choice_GeneralName_otherName: {
1304 size_t i;
1305 char *oid;
1307 ret = hx509_oid_sprint(&name->u.otherName.type_id, &oid);
1308 if (ret == 0)
1309 strpool = rk_strpoolprintf(strpool, "otherName: %s ", oid);
1310 if (strpool == NULL)
1311 ret = ENOMEM;
1313 for (i = 0; ret == 0 && i < sizeof(o_unparsers)/sizeof(o_unparsers[0]); i++) {
1314 if (der_heim_oid_cmp(&name->u.otherName.type_id,
1315 o_unparsers[i].oid))
1316 continue;
1317 strpool = rk_strpoolprintf(strpool, "%s ",o_unparsers[i].friendly_name);
1318 if (strpool == NULL)
1319 ret = ENOMEM;
1320 if (ret == 0)
1321 ret = o_unparsers[i].f(context, &strpool, &name->u.otherName.value);
1322 break;
1324 if (ret == 0 && i == sizeof(o_unparsers)/sizeof(o_unparsers[0])) {
1325 strpool = rk_strpoolprintf(strpool, "<unknown-other-name-type>");
1326 ret = ENOTSUP;
1328 free(oid);
1329 break;
1331 case choice_GeneralName_rfc822Name:
1332 strpool = rk_strpoolprintf(strpool, "rfc822Name: %.*s",
1333 (int)name->u.rfc822Name.length,
1334 (char *)name->u.rfc822Name.data);
1335 break;
1336 case choice_GeneralName_dNSName:
1337 strpool = rk_strpoolprintf(strpool, "dNSName: %.*s",
1338 (int)name->u.dNSName.length,
1339 (char *)name->u.dNSName.data);
1340 break;
1341 case choice_GeneralName_directoryName: {
1342 Name dir;
1343 char *s;
1344 memset(&dir, 0, sizeof(dir));
1345 dir.element = (enum Name_enum)name->u.directoryName.element;
1346 dir.u.rdnSequence = name->u.directoryName.u.rdnSequence;
1347 ret = _hx509_unparse_Name(&dir, &s);
1348 if (ret)
1349 return ret;
1350 strpool = rk_strpoolprintf(strpool, "directoryName: %s", s);
1351 free(s);
1352 break;
1354 case choice_GeneralName_uniformResourceIdentifier:
1355 strpool = rk_strpoolprintf(strpool, "URI: %.*s",
1356 (int)name->u.uniformResourceIdentifier.length,
1357 (char *)name->u.uniformResourceIdentifier.data);
1358 break;
1359 case choice_GeneralName_iPAddress: {
1360 unsigned char *a = name->u.iPAddress.data;
1362 strpool = rk_strpoolprintf(strpool, "IPAddress: ");
1363 if (strpool == NULL)
1364 break;
1365 if (name->u.iPAddress.length == 4)
1366 strpool = rk_strpoolprintf(strpool, "%d.%d.%d.%d",
1367 a[0], a[1], a[2], a[3]);
1368 else if (name->u.iPAddress.length == 16)
1369 strpool = rk_strpoolprintf(strpool,
1370 "%02X:%02X:%02X:%02X:"
1371 "%02X:%02X:%02X:%02X:"
1372 "%02X:%02X:%02X:%02X:"
1373 "%02X:%02X:%02X:%02X",
1374 a[0], a[1], a[2], a[3],
1375 a[4], a[5], a[6], a[7],
1376 a[8], a[9], a[10], a[11],
1377 a[12], a[13], a[14], a[15]);
1378 else
1379 strpool = rk_strpoolprintf(strpool,
1380 "unknown IP address of length %lu",
1381 (unsigned long)name->u.iPAddress.length);
1382 break;
1384 case choice_GeneralName_registeredID: {
1385 char *oid;
1386 hx509_oid_sprint(&name->u.registeredID, &oid);
1387 if (oid == NULL)
1388 return ENOMEM;
1389 strpool = rk_strpoolprintf(strpool, "registeredID: %s", oid);
1390 free(oid);
1391 break;
1393 default:
1394 return EINVAL;
1396 if (strpool == NULL ||
1397 (*str = rk_strpoolcollect(strpool)) == NULL)
1398 return ENOMEM;
1399 return 0;