2 * Copyright (c) 2004 - 2009 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
38 * @page page_name PKIX/X.509 Names
40 * There are several names in PKIX/X.509, GeneralName and Name.
42 * A Name consists of an ordered list of Relative Distinguished Names
43 * (RDN). Each RDN consists of an unordered list of typed strings. The
44 * types are defined by OID and have long and short description. For
45 * example id-at-commonName (2.5.4.3) have the long name CommonName
46 * and short name CN. The string itself can be of serveral encoding,
47 * UTF8, UTF16, Teltex string, etc. The type limit what encoding
50 * GeneralName is a broader nametype that can contains al kind of
51 * stuff like Name, IP addresses, partial Name, etc.
53 * Name is mapped into a hx509_name object.
55 * Parse and string name into a hx509_name object with hx509_parse_name(),
56 * make it back into string representation with hx509_name_to_string().
58 * Name string are defined rfc2253, rfc1779 and X.501.
60 * See the library functions here: @ref hx509_name
66 wind_profile_flags flags;
68 { "C", &asn1_oid_id_at_countryName },
69 { "CN", &asn1_oid_id_at_commonName },
70 { "DC", &asn1_oid_id_domainComponent },
71 { "L", &asn1_oid_id_at_localityName },
72 { "O", &asn1_oid_id_at_organizationName },
73 { "OU", &asn1_oid_id_at_organizationalUnitName },
74 { "S", &asn1_oid_id_at_stateOrProvinceName },
75 { "STREET", &asn1_oid_id_at_streetAddress },
76 { "UID", &asn1_oid_id_Userid },
77 { "emailAddress", &asn1_oid_id_pkcs9_emailAddress },
78 { "serialNumber", &asn1_oid_id_at_serialNumber }
82 quote_string(const char *f, size_t len, size_t *rlen)
93 for (i = 0, j = 0; i < len; i++) {
94 if (from[i] == ' ' && i + 1 < len)
96 else if (from[i] == ',' || from[i] == '=' || from[i] == '+' ||
97 from[i] == '<' || from[i] == '>' || from[i] == '#' ||
98 from[i] == ';' || from[i] == ' ')
102 } else if (((unsigned char)from[i]) >= 32 && ((unsigned char)from[i]) <= 127) {
105 int l = snprintf(&to[j], tolen - j - 1,
106 "#%02x", (unsigned char)from[i]);
118 append_string(char **str, size_t *total_len, const char *ss,
119 size_t len, int quote)
124 qs = quote_string(ss, len, &len);
128 s = realloc(*str, len + *total_len + 1);
130 _hx509_abort("allocation failure"); /* XXX */
131 memcpy(s + *total_len, qs, len);
134 s[*total_len + len] = '\0';
141 oidtostring(const heim_oid *type)
146 for (i = 0; i < sizeof(no)/sizeof(no[0]); i++) {
147 if (der_heim_oid_cmp(no[i].o, type) == 0)
148 return strdup(no[i].n);
150 if (der_print_heim_oid(type, '.', &s) != 0)
156 stringtooid(const char *name, size_t len, heim_oid *oid)
161 memset(oid, 0, sizeof(*oid));
163 for (i = 0; i < sizeof(no)/sizeof(no[0]); i++) {
164 if (strncasecmp(no[i].n, name, len) == 0)
165 return der_copy_oid(no[i].o, oid);
170 memcpy(s, name, len);
172 ret = der_parse_heim_oid(s, ".", oid);
178 * Convert the hx509 name object into a printable string.
179 * The resulting string should be freed with free().
181 * @param name name to print
182 * @param str the string to return
184 * @return An hx509 error code, see hx509_get_error_string().
186 * @ingroup hx509_name
190 hx509_name_to_string(const hx509_name name, char **str)
192 return _hx509_Name_to_string(&name->der_name, str);
196 _hx509_Name_to_string(const Name *n, char **str)
198 size_t total_len = 0;
205 for (i = n->u.rdnSequence.len - 1 ; i >= 0 ; i--) {
208 for (j = 0; j < n->u.rdnSequence.val[i].len; j++) {
209 DirectoryString *ds = &n->u.rdnSequence.val[i].val[j].value;
213 oidname = oidtostring(&n->u.rdnSequence.val[i].val[j].type);
215 switch(ds->element) {
216 case choice_DirectoryString_ia5String:
217 ss = ds->u.ia5String;
219 case choice_DirectoryString_printableString:
220 ss = ds->u.printableString;
222 case choice_DirectoryString_utf8String:
223 ss = ds->u.utf8String;
225 case choice_DirectoryString_bmpString: {
226 const uint16_t *bmp = ds->u.bmpString.data;
227 size_t bmplen = ds->u.bmpString.length;
230 ret = wind_ucs2utf8_length(bmp, bmplen, &k);
236 _hx509_abort("allocation failure"); /* XXX */
237 ret = wind_ucs2utf8(bmp, bmplen, ss, NULL);
245 case choice_DirectoryString_teletexString:
246 ss = malloc(ds->u.teletexString.length + 1);
248 _hx509_abort("allocation failure"); /* XXX */
249 memcpy(ss, ds->u.teletexString.data, ds->u.teletexString.length);
250 ss[ds->u.teletexString.length] = '\0';
252 case choice_DirectoryString_universalString: {
253 const uint32_t *uni = ds->u.universalString.data;
254 size_t unilen = ds->u.universalString.length;
257 ret = wind_ucs4utf8_length(uni, unilen, &k);
263 _hx509_abort("allocation failure"); /* XXX */
264 ret = wind_ucs4utf8(uni, unilen, ss, NULL);
273 _hx509_abort("unknown directory type: %d", ds->element);
276 append_string(str, &total_len, oidname, strlen(oidname), 0);
278 append_string(str, &total_len, "=", 1, 0);
280 append_string(str, &total_len, ss, len, 1);
281 if (ds->element == choice_DirectoryString_universalString ||
282 ds->element == choice_DirectoryString_bmpString ||
283 ds->element == choice_DirectoryString_teletexString)
287 if (j + 1 < n->u.rdnSequence.val[i].len)
288 append_string(str, &total_len, "+", 1, 0);
292 append_string(str, &total_len, ",", 1, 0);
297 #define COPYCHARARRAY(_ds,_el,_l,_n) \
298 (_l) = strlen(_ds->u._el); \
299 (_n) = malloc((_l) * sizeof((_n)[0])); \
302 for (i = 0; i < (_l); i++) \
303 (_n)[i] = _ds->u._el[i]
306 #define COPYVALARRAY(_ds,_el,_l,_n) \
307 (_l) = _ds->u._el.length; \
308 (_n) = malloc((_l) * sizeof((_n)[0])); \
311 for (i = 0; i < (_l); i++) \
312 (_n)[i] = _ds->u._el.data[i]
314 #define COPYVOIDARRAY(_ds,_el,_l,_n) \
315 (_l) = _ds->u._el.length; \
316 (_n) = malloc((_l) * sizeof((_n)[0])); \
319 for (i = 0; i < (_l); i++) \
320 (_n)[i] = ((unsigned char *)_ds->u._el.data)[i]
325 dsstringprep(const DirectoryString *ds, uint32_t **rname, size_t *rlen)
327 wind_profile_flags flags = 0;
335 switch(ds->element) {
336 case choice_DirectoryString_ia5String:
337 COPYCHARARRAY(ds, ia5String, len, name);
339 case choice_DirectoryString_printableString:
340 flags = WIND_PROFILE_LDAP_CASE_EXACT_ATTRIBUTE;
341 COPYCHARARRAY(ds, printableString, len, name);
343 case choice_DirectoryString_teletexString:
344 COPYVOIDARRAY(ds, teletexString, len, name);
346 case choice_DirectoryString_bmpString:
347 COPYVALARRAY(ds, bmpString, len, name);
349 case choice_DirectoryString_universalString:
350 COPYVALARRAY(ds, universalString, len, name);
352 case choice_DirectoryString_utf8String:
353 ret = wind_utf8ucs4_length(ds->u.utf8String, &len);
356 name = malloc(len * sizeof(name[0]));
359 ret = wind_utf8ucs4(ds->u.utf8String, name, &len);
366 _hx509_abort("unknown directory type: %d", ds->element);
370 /* try a couple of times to get the length right, XXX gross */
371 for (i = 0; i < 4; i++) {
373 *rname = malloc(*rlen * sizeof((*rname)[0]));
375 ret = wind_stringprep(name, len, *rname, rlen,
376 WIND_PROFILE_LDAP|flags);
377 if (ret == WIND_ERR_OVERRUN) {
397 _hx509_name_ds_cmp(const DirectoryString *ds1,
398 const DirectoryString *ds2,
401 uint32_t *ds1lp, *ds2lp;
402 size_t ds1len, ds2len;
405 ret = dsstringprep(ds1, &ds1lp, &ds1len);
408 ret = dsstringprep(ds2, &ds2lp, &ds2len);
414 if (ds1len != ds2len)
415 *diff = ds1len - ds2len;
417 *diff = memcmp(ds1lp, ds2lp, ds1len * sizeof(ds1lp[0]));
426 _hx509_name_cmp(const Name *n1, const Name *n2, int *c)
430 *c = n1->u.rdnSequence.len - n2->u.rdnSequence.len;
434 for (i = 0 ; i < n1->u.rdnSequence.len; i++) {
435 *c = n1->u.rdnSequence.val[i].len - n2->u.rdnSequence.val[i].len;
439 for (j = 0; j < n1->u.rdnSequence.val[i].len; j++) {
440 *c = der_heim_oid_cmp(&n1->u.rdnSequence.val[i].val[j].type,
441 &n1->u.rdnSequence.val[i].val[j].type);
445 ret = _hx509_name_ds_cmp(&n1->u.rdnSequence.val[i].val[j].value,
446 &n2->u.rdnSequence.val[i].val[j].value,
459 * Compare to hx509 name object, useful for sorting.
461 * @param n1 a hx509 name object.
462 * @param n2 a hx509 name object.
464 * @return 0 the objects are the same, returns > 0 is n2 is "larger"
465 * then n2, < 0 if n1 is "smaller" then n2.
467 * @ingroup hx509_name
471 hx509_name_cmp(hx509_name n1, hx509_name n2)
474 ret = _hx509_name_cmp(&n1->der_name, &n2->der_name, &diff);
482 _hx509_name_from_Name(const Name *n, hx509_name *name)
485 *name = calloc(1, sizeof(**name));
488 ret = copy_Name(n, &(*name)->der_name);
497 _hx509_name_modify(hx509_context context,
503 RelativeDistinguishedName *rdn;
507 ptr = realloc(name->u.rdnSequence.val,
508 sizeof(name->u.rdnSequence.val[0]) *
509 (name->u.rdnSequence.len + 1));
511 hx509_set_error_string(context, 0, ENOMEM, "Out of memory");
514 name->u.rdnSequence.val = ptr;
517 rdn = &name->u.rdnSequence.val[name->u.rdnSequence.len];
519 memmove(&name->u.rdnSequence.val[1],
520 &name->u.rdnSequence.val[0],
521 name->u.rdnSequence.len *
522 sizeof(name->u.rdnSequence.val[0]));
524 rdn = &name->u.rdnSequence.val[0];
526 rdn->val = malloc(sizeof(rdn->val[0]));
527 if (rdn->val == NULL)
530 ret = der_copy_oid(oid, &rdn->val[0].type);
533 rdn->val[0].value.element = choice_DirectoryString_utf8String;
534 rdn->val[0].value.u.utf8String = strdup(str);
535 if (rdn->val[0].value.u.utf8String == NULL)
537 name->u.rdnSequence.len += 1;
543 * Parse a string into a hx509 name object.
545 * @param context A hx509 context.
546 * @param str a string to parse.
547 * @param name the resulting object, NULL in case of error.
549 * @return An hx509 error code, see hx509_get_error_string().
551 * @ingroup hx509_name
555 hx509_parse_name(hx509_context context, const char *str, hx509_name *name)
564 n = calloc(1, sizeof(*n));
566 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
570 n->der_name.element = choice_Name_rdnSequence;
574 while (p != NULL && *p != '\0') {
589 ret = HX509_PARSING_NAME_FAILED;
590 hx509_set_error_string(context, 0, ret, "missing = in %s", p);
594 ret = HX509_PARSING_NAME_FAILED;
595 hx509_set_error_string(context, 0, ret,
596 "missing name before = in %s", p);
601 ret = HX509_PARSING_NAME_FAILED;
602 hx509_set_error_string(context, 0, ret, " = after , in %s", p);
606 ret = stringtooid(p, q - p, &oid);
608 ret = HX509_PARSING_NAME_FAILED;
609 hx509_set_error_string(context, 0, ret,
610 "unknown type: %.*s", (int)(q - p), p);
615 size_t pstr_len = len - (q - p) - 1;
616 const char *pstr = p + (q - p) + 1;
619 r = malloc(pstr_len + 1);
623 hx509_set_error_string(context, 0, ret, "out of memory");
626 memcpy(r, pstr, pstr_len);
629 ret = _hx509_name_modify(context, &n->der_name, 0, &oid, r);
643 return HX509_NAME_MALFORMED;
647 * Copy a hx509 name object.
649 * @param context A hx509 cotext.
650 * @param from the name to copy from
651 * @param to the name to copy to
653 * @return An hx509 error code, see hx509_get_error_string().
655 * @ingroup hx509_name
659 hx509_name_copy(hx509_context context, const hx509_name from, hx509_name *to)
663 *to = calloc(1, sizeof(**to));
666 ret = copy_Name(&from->der_name, &(*to)->der_name);
676 * Convert a hx509_name into a Name.
678 * @param from the name to copy from
679 * @param to the name to copy to
681 * @return An hx509 error code, see hx509_get_error_string().
683 * @ingroup hx509_name
687 hx509_name_to_Name(const hx509_name from, Name *to)
689 return copy_Name(&from->der_name, to);
693 hx509_name_normalize(hx509_context context, hx509_name name)
699 * Expands variables in the name using env. Variables are on the form
700 * ${name}. Useful when dealing with certificate templates.
702 * @param context A hx509 cotext.
703 * @param name the name to expand.
704 * @param env environment variable to expand.
706 * @return An hx509 error code, see hx509_get_error_string().
708 * @ingroup hx509_name
712 hx509_name_expand(hx509_context context,
716 Name *n = &name->der_name;
722 if (n->element != choice_Name_rdnSequence) {
723 hx509_set_error_string(context, 0, EINVAL, "RDN not of supported type");
727 for (i = 0 ; i < n->u.rdnSequence.len; i++) {
728 for (j = 0; j < n->u.rdnSequence.val[i].len; j++) {
729 /** Only UTF8String rdnSequence names are allowed */
731 THIS SHOULD REALLY BE:
732 COMP = n->u.rdnSequence.val[i].val[j];
733 normalize COMP to utf8
734 check if there are variables
736 convert back to orignal format, store in COMP
737 free normalized utf8 string
739 DirectoryString *ds = &n->u.rdnSequence.val[i].val[j].value;
741 struct rk_strpool *strpool = NULL;
743 if (ds->element != choice_DirectoryString_utf8String) {
744 hx509_set_error_string(context, 0, EINVAL, "unsupported type");
747 p = strstr(ds->u.utf8String, "${");
749 strpool = rk_strpoolprintf(strpool, "%.*s",
750 (int)(p - ds->u.utf8String),
752 if (strpool == NULL) {
753 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
758 /* expand variables */
762 hx509_set_error_string(context, 0, EINVAL, "missing }");
763 rk_strpoolfree(strpool);
767 value = hx509_env_lfind(context, env, p, p2 - p);
769 hx509_set_error_string(context, 0, EINVAL,
770 "variable %.*s missing",
772 rk_strpoolfree(strpool);
775 strpool = rk_strpoolprintf(strpool, "%s", value);
776 if (strpool == NULL) {
777 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
782 p = strstr(p2, "${");
784 strpool = rk_strpoolprintf(strpool, "%.*s",
787 strpool = rk_strpoolprintf(strpool, "%s", p2);
788 if (strpool == NULL) {
789 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
794 free(ds->u.utf8String);
795 ds->u.utf8String = rk_strpoolcollect(strpool);
796 if (ds->u.utf8String == NULL) {
797 hx509_set_error_string(context, 0, ENOMEM, "out of memory");
807 * Free a hx509 name object, upond return *name will be NULL.
809 * @param name a hx509 name object to be freed.
811 * @ingroup hx509_name
815 hx509_name_free(hx509_name *name)
817 free_Name(&(*name)->der_name);
818 memset(*name, 0, sizeof(**name));
824 * Convert a DER encoded name info a string.
826 * @param data data to a DER/BER encoded name
827 * @param length length of data
828 * @param str the resulting string, is NULL on failure.
830 * @return An hx509 error code, see hx509_get_error_string().
832 * @ingroup hx509_name
836 hx509_unparse_der_name(const void *data, size_t length, char **str)
843 ret = decode_Name(data, length, &name, NULL);
846 ret = _hx509_Name_to_string(&name, str);
852 * Convert a hx509_name object to DER encoded name.
854 * @param name name to concert
855 * @param os data to a DER encoded name, free the resulting octet
856 * string with hx509_xfree(os->data).
858 * @return An hx509 error code, see hx509_get_error_string().
860 * @ingroup hx509_name
864 hx509_name_binary(const hx509_name name, heim_octet_string *os)
869 ASN1_MALLOC_ENCODE(Name, os->data, os->length, &name->der_name, &size, ret);
872 if (os->length != size)
873 _hx509_abort("internal ASN.1 encoder error");
879 _hx509_unparse_Name(const Name *aname, char **str)
884 ret = _hx509_name_from_Name(aname, &name);
888 ret = hx509_name_to_string(name, str);
889 hx509_name_free(&name);
894 * Unparse the hx509 name in name into a string.
896 * @param name the name to check if its empty/null.
898 * @return non zero if the name is empty/null.
900 * @ingroup hx509_name
904 hx509_name_is_null_p(const hx509_name name)
906 return name->der_name.u.rdnSequence.len == 0;
910 * Unparse the hx509 name in name into a string.
912 * @param name the name to print
913 * @param str an allocated string returns the name in string form
915 * @return An hx509 error code, see hx509_get_error_string().
917 * @ingroup hx509_name
921 hx509_general_name_unparse(GeneralName *name, char **str)
923 struct rk_strpool *strpool = NULL;
927 switch (name->element) {
928 case choice_GeneralName_otherName: {
930 hx509_oid_sprint(&name->u.otherName.type_id, &str);
933 strpool = rk_strpoolprintf(strpool, "otherName: %s", str);
937 case choice_GeneralName_rfc822Name:
938 strpool = rk_strpoolprintf(strpool, "rfc822Name: %s\n",
941 case choice_GeneralName_dNSName:
942 strpool = rk_strpoolprintf(strpool, "dNSName: %s\n",
945 case choice_GeneralName_directoryName: {
949 memset(&dir, 0, sizeof(dir));
950 dir.element = name->u.directoryName.element;
951 dir.u.rdnSequence = name->u.directoryName.u.rdnSequence;
952 ret = _hx509_unparse_Name(&dir, &s);
955 strpool = rk_strpoolprintf(strpool, "directoryName: %s", s);
959 case choice_GeneralName_uniformResourceIdentifier:
960 strpool = rk_strpoolprintf(strpool, "URI: %s",
961 name->u.uniformResourceIdentifier);
963 case choice_GeneralName_iPAddress: {
964 unsigned char *a = name->u.iPAddress.data;
966 strpool = rk_strpoolprintf(strpool, "IPAddress: ");
969 if (name->u.iPAddress.length == 4)
970 strpool = rk_strpoolprintf(strpool, "%d.%d.%d.%d",
971 a[0], a[1], a[2], a[3]);
972 else if (name->u.iPAddress.length == 16)
973 strpool = rk_strpoolprintf(strpool,
974 "%02X:%02X:%02X:%02X:"
975 "%02X:%02X:%02X:%02X:"
976 "%02X:%02X:%02X:%02X:"
977 "%02X:%02X:%02X:%02X",
978 a[0], a[1], a[2], a[3],
979 a[4], a[5], a[6], a[7],
980 a[8], a[9], a[10], a[11],
981 a[12], a[13], a[14], a[15]);
983 strpool = rk_strpoolprintf(strpool,
984 "unknown IP address of length %lu",
985 (unsigned long)name->u.iPAddress.length);
988 case choice_GeneralName_registeredID: {
990 hx509_oid_sprint(&name->u.registeredID, &str);
993 strpool = rk_strpoolprintf(strpool, "registeredID: %s", str);
1000 if (strpool == NULL)
1003 *str = rk_strpoolcollect(strpool);