1 /* alg1485.c - implementation of RFCs 1485, 1779 and 2253.
3 * ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
16 * The Original Code is the Netscape security libraries.
18 * The Initial Developer of the Original Code is
19 * Netscape Communications Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 1994-2000
21 * the Initial Developer. All Rights Reserved.
25 * Alternatively, the contents of this file may be used under the terms of
26 * either the GNU General Public License Version 2 or later (the "GPL"), or
27 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
37 * ***** END LICENSE BLOCK ***** */
47 typedef struct NameToKindStr {
49 unsigned int maxLen; /* max bytes in UTF8 encoded string value */
54 /* local type for directory string--could be printable_string or utf8 */
55 #define SEC_ASN1_DS SEC_ASN1_HIGH_TAG_NUMBER
57 /* Add new entries to this table, and maybe to function ParseRFC1485AVA */
58 static const NameToKind name2kinds[] = {
59 /* IANA registered type names
60 * (See: http://www.iana.org/assignments/ldap-parameters)
62 /* RFC 3280, 4630 MUST SUPPORT */
63 { "CN", 64, SEC_OID_AVA_COMMON_NAME, SEC_ASN1_DS},
64 { "ST", 128, SEC_OID_AVA_STATE_OR_PROVINCE,
66 { "O", 64, SEC_OID_AVA_ORGANIZATION_NAME,
68 { "OU", 64, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME,
70 { "dnQualifier", 32767, SEC_OID_AVA_DN_QUALIFIER, SEC_ASN1_PRINTABLE_STRING},
71 { "C", 2, SEC_OID_AVA_COUNTRY_NAME, SEC_ASN1_PRINTABLE_STRING},
72 { "serialNumber", 64, SEC_OID_AVA_SERIAL_NUMBER,SEC_ASN1_PRINTABLE_STRING},
74 /* RFC 3280, 4630 SHOULD SUPPORT */
75 { "L", 128, SEC_OID_AVA_LOCALITY, SEC_ASN1_DS},
76 { "title", 64, SEC_OID_AVA_TITLE, SEC_ASN1_DS},
77 { "SN", 64, SEC_OID_AVA_SURNAME, SEC_ASN1_DS},
78 { "givenName", 64, SEC_OID_AVA_GIVEN_NAME, SEC_ASN1_DS},
79 { "initials", 64, SEC_OID_AVA_INITIALS, SEC_ASN1_DS},
80 { "generationQualifier",
81 64, SEC_OID_AVA_GENERATION_QUALIFIER,
83 /* RFC 3280, 4630 MAY SUPPORT */
84 { "DC", 128, SEC_OID_AVA_DC, SEC_ASN1_IA5_STRING},
85 { "MAIL", 256, SEC_OID_RFC1274_MAIL, SEC_ASN1_IA5_STRING},
86 { "UID", 256, SEC_OID_RFC1274_UID, SEC_ASN1_DS},
88 /* ------------------ "strict" boundary ---------------------------------
89 * In strict mode, cert_NameToAscii does not encode any of the attributes
90 * below this line. The first SECOidTag below this line must be used to
91 * conditionally define the "endKind" in function AppendAVA() below.
92 * Most new attribute names should be added below this line.
93 * Maybe this line should be up higher? Say, after the 3280 MUSTs and
94 * before the 3280 SHOULDs?
97 /* values from draft-ietf-ldapbis-user-schema-05 (not in RFC 3280) */
98 { "postalAddress", 128, SEC_OID_AVA_POSTAL_ADDRESS, SEC_ASN1_DS},
99 { "postalCode", 40, SEC_OID_AVA_POSTAL_CODE, SEC_ASN1_DS},
100 { "postOfficeBox", 40, SEC_OID_AVA_POST_OFFICE_BOX,SEC_ASN1_DS},
101 { "houseIdentifier",64, SEC_OID_AVA_HOUSE_IDENTIFIER,SEC_ASN1_DS},
102 /* end of IANA registered type names */
104 /* legacy keywords */
105 { "E", 128, SEC_OID_PKCS9_EMAIL_ADDRESS,SEC_ASN1_IA5_STRING},
106 { "STREET", 128, SEC_OID_AVA_STREET_ADDRESS, SEC_ASN1_DS},
107 { "pseudonym", 64, SEC_OID_AVA_PSEUDONYM, SEC_ASN1_DS},
109 /* values defined by the CAB Forum for EV */
110 { "incorporationLocality", 128, SEC_OID_EV_INCORPORATION_LOCALITY,
112 { "incorporationState", 128, SEC_OID_EV_INCORPORATION_STATE,
114 { "incorporationCountry", 2, SEC_OID_EV_INCORPORATION_COUNTRY,
115 SEC_ASN1_PRINTABLE_STRING},
116 { "businessCategory", 64, SEC_OID_BUSINESS_CATEGORY, SEC_ASN1_DS},
118 { 0, 256, SEC_OID_UNKNOWN, 0},
121 /* Table facilitates conversion of ASCII hex to binary. */
122 static const PRInt16 x2b[256] = {
123 /* #0x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
124 /* #1x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
125 /* #2x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
126 /* #3x */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
127 /* #4x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
128 /* #5x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
129 /* #6x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
130 /* #7x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
131 /* #8x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
132 /* #9x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
133 /* #ax */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
134 /* #bx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
135 /* #cx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
136 /* #dx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
137 /* #ex */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
138 /* #fx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
141 #define IS_HEX(c) (x2b[(PRUint8)(c)] >= 0)
143 #define C_DOUBLE_QUOTE '\042'
145 #define C_BACKSLASH '\134'
149 #define OPTIONAL_SPACE(c) \
150 (((c) == ' ') || ((c) == '\r') || ((c) == '\n'))
152 #define SPECIAL_CHAR(c) \
153 (((c) == ',') || ((c) == '=') || ((c) == C_DOUBLE_QUOTE) || \
154 ((c) == '\r') || ((c) == '\n') || ((c) == '+') || \
155 ((c) == '<') || ((c) == '>') || ((c) == '#') || \
156 ((c) == ';') || ((c) == C_BACKSLASH))
159 #define IS_PRINTABLE(c) \
160 ((((c) >= 'a') && ((c) <= 'z')) || \
161 (((c) >= 'A') && ((c) <= 'Z')) || \
162 (((c) >= '0') && ((c) <= '9')) || \
165 ((c) == '\050') || /* ( */ \
166 ((c) == '\051') || /* ) */ \
167 (((c) >= '+') && ((c) <= '/')) || /* + , - . / */ \
172 /* RFC 2253 says we must escape ",+\"\\<>;=" EXCEPT inside a quoted string.
173 * Inside a quoted string, we only need to escape " and \
174 * We choose to quote strings containing any of those special characters,
175 * so we only need to escape " and \
177 #define NEEDS_ESCAPE(c) \
178 (c == C_DOUBLE_QUOTE || c == C_BACKSLASH)
180 #define NEEDS_HEX_ESCAPE(c) \
181 ((PRUint8)c < 0x20 || c == 0x7f)
184 cert_AVAOidTagToMaxLen(SECOidTag tag)
186 const NameToKind *n2k = name2kinds;
188 while (n2k->kind != tag && n2k->kind != SEC_OID_UNKNOWN) {
191 return (n2k->kind != SEC_OID_UNKNOWN) ? n2k->maxLen : -1;
195 IsPrintable(unsigned char *data, unsigned len)
197 unsigned char ch, *end;
202 if (!IS_PRINTABLE(ch)) {
210 skipSpace(char **pbp, char *endptr)
213 while (bp < endptr && OPTIONAL_SPACE(*bp)) {
220 scanTag(char **pbp, char *endptr, char *tagBuf, int tagBufSize)
225 PORT_Assert(tagBufSize > 0);
227 /* skip optional leading space */
228 skipSpace(pbp, endptr);
229 if (*pbp == endptr) {
238 while (bp < endptr && !OPTIONAL_SPACE(*bp) && (*bp != C_EQUAL)) {
239 if (++taglen >= tagBufSize) {
245 /* null-terminate tagBuf -- guaranteed at least one space left */
249 /* skip trailing spaces till we hit something - should be an equal sign */
250 skipSpace(pbp, endptr);
251 if (*pbp == endptr) {
255 if (**pbp != C_EQUAL) {
256 /* should be an equal sign */
259 /* skip over the equal sign */
265 /* Returns the number of bytes in the value. 0 means failure. */
267 scanVal(char **pbp, char *endptr, char *valBuf, int valBufSize)
273 PORT_Assert(valBufSize > 0);
275 /* skip optional leading space */
276 skipSpace(pbp, endptr);
285 if (*bp == C_DOUBLE_QUOTE) {
294 while (bp < endptr) {
296 if (c == C_BACKSLASH) {
297 /* escape character */
300 /* escape charater must appear with paired char */
305 if (IS_HEX(c) && (endptr - bp) >= 2 && IS_HEX(bp[1])) {
307 c = (char)((x2b[(PRUint8)c] << 4) | x2b[(PRUint8)*bp]);
309 } else if (c == '#' && bp == *pbp) {
310 /* ignore leading #, quotation not required for it. */
311 } else if (!isQuoted && SPECIAL_CHAR(c)) {
312 /* unescaped special and not within quoted value */
314 } else if (c == C_DOUBLE_QUOTE) {
315 /* reached unescaped double quote */
318 /* append character */
320 if (vallen >= valBufSize) {
328 /* strip trailing spaces from unquoted values */
330 while (valBufp > valBuf) {
331 char c = valBufp[-1];
332 if (! OPTIONAL_SPACE(c))
336 vallen = valBufp - valBuf;
340 /* insist that we stopped on a double quote */
341 if (*bp != C_DOUBLE_QUOTE) {
345 /* skip over the quote and skip optional space */
347 skipSpace(&bp, endptr);
352 /* null-terminate valBuf -- guaranteed at least one space left */
358 /* Caller must set error code upon failure */
360 hexToBin(PLArenaPool *pool, SECItem * destItem, const char * src, int len)
364 destItem->data = NULL;
365 if (len <= 0 || (len & 1)) {
369 if (!SECITEM_AllocItem(pool, destItem, len))
371 dest = destItem->data;
372 for (; len > 0; len--, src += 2) {
373 PRInt16 bin = (x2b[(PRUint8)src[0]] << 4) | x2b[(PRUint8)src[1]];
376 *dest++ = (PRUint8)bin;
381 SECITEM_FreeItem(destItem, PR_FALSE);
385 /* Parses one AVA, starting at *pbp. Stops at endptr.
386 * Advances *pbp past parsed AVA and trailing separator (if present).
387 * On any error, returns NULL and *pbp is undefined.
388 * On success, returns CERTAVA allocated from arena, and (*pbp)[-1] was
389 * the last character parsed. *pbp is either equal to endptr or
390 * points to first character after separator.
393 ParseRFC1485AVA(PRArenaPool *arena, char **pbp, char *endptr)
396 const NameToKind *n2k;
400 SECOidTag kind = SEC_OID_UNKNOWN;
401 SECStatus rv = SECFailure;
402 SECItem derOid = { 0, NULL, 0 };
403 SECItem derVal = { 0, NULL, 0};
410 if (SECSuccess != scanTag(pbp, endptr, tagBuf, sizeof tagBuf) ||
411 !(valLen = scanVal(pbp, endptr, valBuf, sizeof valBuf))) {
417 sep = *bp++; /* skip over separator */
420 /* if we haven't finished, insist that we've stopped on a separator */
421 if (sep && sep != ',' && sep != ';' && sep != '+') {
425 /* is this a dotted decimal OID attribute type ? */
426 if (!PL_strncasecmp("oid.", tagBuf, 4)) {
427 rv = SEC_StringToOID(arena, &derOid, tagBuf, strlen(tagBuf));
429 for (n2k = name2kinds; n2k->name; n2k++) {
431 if (PORT_Strcasecmp(n2k->name, tagBuf) == 0) {
434 oidrec = SECOID_FindOIDByTag(kind);
437 derOid = oidrec->oid;
442 if (kind == SEC_OID_UNKNOWN && rv != SECSuccess)
445 /* Is this a hex encoding of a DER attribute value ? */
446 if ('#' == valBuf[0]) {
447 /* convert attribute value from hex to binary */
448 rv = hexToBin(arena, &derVal, valBuf + 1, valLen - 1);
451 a = CERT_CreateAVAFromRaw(arena, &derOid, &derVal);
453 if (kind == SEC_OID_UNKNOWN)
455 if (kind == SEC_OID_AVA_COUNTRY_NAME && valLen != 2)
457 if (vt == SEC_ASN1_PRINTABLE_STRING &&
458 !IsPrintable((unsigned char*) valBuf, valLen))
460 if (vt == SEC_ASN1_DS) {
461 /* RFC 4630: choose PrintableString or UTF8String */
462 if (IsPrintable((unsigned char*) valBuf, valLen))
463 vt = SEC_ASN1_PRINTABLE_STRING;
465 vt = SEC_ASN1_UTF8_STRING;
468 derVal.data = (unsigned char*) valBuf;
470 a = CERT_CreateAVAFromSECItem(arena, kind, vt, &derVal);
475 /* matched no kind -- invalid tag */
476 PORT_SetError(SEC_ERROR_INVALID_AVA);
481 ParseRFC1485Name(char *buf, int len)
489 name = CERT_CreateName(NULL);
497 ava = ParseRFC1485AVA(name->arena, &bp, e);
501 rdn = CERT_CreateRDN(name->arena, ava, (CERTAVA *)0);
504 rv = CERT_AddRDN(name, rdn);
506 rv = CERT_AddAVA(name->arena, rdn, ava);
511 rdn = NULL; /* done with this RDN */
515 if (name->rdns[0] == 0) {
516 /* empty name -- illegal */
520 /* Reverse order of RDNS to comply with RFC */
527 firstRdn = name->rdns;
530 lastRdn = name->rdns;
531 while (*lastRdn) lastRdn++;
535 for ( ; firstRdn < lastRdn; firstRdn++, lastRdn--) {
537 *firstRdn = *lastRdn;
546 CERT_DestroyName(name);
551 CERT_AsciiToName(char *string)
554 name = ParseRFC1485Name(string, PORT_Strlen(string));
558 /************************************************************************/
560 typedef struct stringBufStr {
566 #define DEFAULT_BUFFER_SIZE 200
569 AppendStr(stringBuf *bufp, char *str)
572 unsigned bufLen, bufSize, len;
575 /* Figure out how much to grow buf by (add in the '\0') */
577 bufLen = bufp->offset;
578 len = PORT_Strlen(str);
579 bufSize = bufLen + len;
582 size = PR_MAX(DEFAULT_BUFFER_SIZE,bufSize*2);
583 buf = (char *) PORT_Alloc(size);
585 } else if (bufp->size < bufSize) {
587 buf =(char *) PORT_Realloc(buf,size);
591 PORT_SetError(SEC_ERROR_NO_MEMORY);
595 bufp->offset = bufSize;
597 /* Concatenate str onto buf */
599 if (bufLen) buf--; /* stomp on old '\0' */
600 PORT_Memcpy(buf, str, len+1); /* put in new null */
605 minimalEscape = 0, /* only hex escapes, and " and \ */
606 minimalEscapeAndQuote, /* as above, plus quoting */
607 fullEscape /* no quoting, full escaping */
610 /* Some characters must be escaped as a hex string, e.g. c -> \nn .
611 * Others must be escaped by preceding with a '\', e.g. c -> \c , but
612 * there are certain "special characters" that may be handled by either
613 * escaping them, or by enclosing the entire attribute value in quotes.
614 * A NULL value for pEQMode implies selecting minimalEscape mode.
615 * Some callers will do quoting when needed, others will not.
616 * If a caller selects minimalEscapeAndQuote, and the string does not
617 * need quoting, then this function changes it to minimalEscape.
620 cert_RFC1485_GetRequiredLen(const char *src, int srclen, EQMode *pEQMode)
623 EQMode mode = pEQMode ? *pEQMode : minimalEscape;
624 PRBool needsQuoting = PR_FALSE;
627 /* need to make an initial pass to determine if quoting is needed */
628 for (i = 0; i < srclen; i++) {
631 if (NEEDS_HEX_ESCAPE(c)) { /* c -> \xx */
633 } else if (NEEDS_ESCAPE(c)) { /* c -> \c */
635 } else if (SPECIAL_CHAR(c)) {
636 if (mode == minimalEscapeAndQuote) /* quoting is allowed */
637 needsQuoting = PR_TRUE; /* entirety will need quoting */
638 else if (mode == fullEscape)
639 reqLen++; /* MAY escape this character */
640 } else if (OPTIONAL_SPACE(c) && OPTIONAL_SPACE(lastC)) {
641 if (mode == minimalEscapeAndQuote) /* quoting is allowed */
642 needsQuoting = PR_TRUE; /* entirety will need quoting */
646 /* if it begins or ends in optional space it needs quoting */
647 if (!needsQuoting && srclen > 0 && mode == minimalEscapeAndQuote &&
648 (OPTIONAL_SPACE(src[srclen-1]) || OPTIONAL_SPACE(src[0]))) {
649 needsQuoting = PR_TRUE;
654 if (pEQMode && mode == minimalEscapeAndQuote && !needsQuoting)
655 *pEQMode = minimalEscape;
659 static const char hexChars[16] = { "0123456789abcdef" };
662 escapeAndQuote(char *dst, int dstlen, char *src, int srclen, EQMode *pEQMode)
665 EQMode mode = pEQMode ? *pEQMode : minimalEscape;
667 /* space for terminal null */
668 reqLen = cert_RFC1485_GetRequiredLen(src, srclen, &mode) + 1;
669 if (reqLen > dstlen) {
670 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
674 if (mode == minimalEscapeAndQuote)
675 *dst++ = C_DOUBLE_QUOTE;
676 for (i = 0; i < srclen; i++) {
678 if (NEEDS_HEX_ESCAPE(c)) {
679 *dst++ = C_BACKSLASH;
680 *dst++ = hexChars[ (c >> 4) & 0x0f ];
681 *dst++ = hexChars[ c & 0x0f ];
683 if (NEEDS_ESCAPE(c) || (SPECIAL_CHAR(c) && mode == fullEscape)) {
684 *dst++ = C_BACKSLASH;
689 if (mode == minimalEscapeAndQuote)
690 *dst++ = C_DOUBLE_QUOTE;
698 CERT_RFC1485_EscapeAndQuote(char *dst, int dstlen, char *src, int srclen)
700 EQMode mode = minimalEscapeAndQuote;
701 return escapeAndQuote(dst, dstlen, src, srclen, &mode);
705 /* convert an OID to dotted-decimal representation */
706 /* Returns a string that must be freed with PR_smprintf_free(), */
708 CERT_GetOidString(const SECItem *oid)
710 PRUint8 *stop; /* points to first byte after OID string */
711 PRUint8 *first; /* byte of an OID component integer */
712 PRUint8 *last; /* byte of an OID component integer */
713 char *rvString = NULL;
716 #define MAX_OID_LEN 1024 /* bytes */
718 if (oid->len > MAX_OID_LEN) {
719 PORT_SetError(SEC_ERROR_INPUT_LEN);
723 /* first will point to the next sequence of bytes to decode */
724 first = (PRUint8 *)oid->data;
725 /* stop points to one past the legitimate data */
726 stop = &first[ oid->len ];
729 * Check for our pseudo-encoded single-digit OIDs
731 if ((*first == 0x80) && (2 == oid->len)) {
732 /* Funky encoding. The second byte is the number */
733 rvString = PR_smprintf("%lu", (PRUint32)first[1]);
735 PORT_SetError(SEC_ERROR_NO_MEMORY);
740 for (; first < stop; first = last + 1) {
741 unsigned int bytesBeforeLast;
743 for (last = first; last < stop; last++) {
744 if (0 == (*last & 0x80)) {
748 bytesBeforeLast = (unsigned int)(last - first);
749 if (bytesBeforeLast <= 3U) { /* 0-28 bit number */
760 if (!n) goto unsupported \
763 switch (bytesBeforeLast) {
767 case 0: n |= last[0] & 0x7f;
774 /* This is the first number.. decompose it */
775 PRUint32 one = PR_MIN(n/40, 2); /* never > 2 */
776 PRUint32 two = n - (one * 40);
778 rvString = PR_smprintf("OID.%lu.%lu", one, two);
781 rvString = PR_smprintf("%s.%lu", prefix, n);
783 } else if (bytesBeforeLast <= 9U) { /* 29-64 bit number */
787 switch (bytesBeforeLast) {
804 /* This is the first number.. decompose it */
805 PRUint64 one = PR_MIN(n/40, 2); /* never > 2 */
806 PRUint64 two = n - (one * 40);
808 rvString = PR_smprintf("OID.%llu.%llu", one, two);
811 rvString = PR_smprintf("%s.%llu", prefix, n);
814 /* More than a 64-bit number, or not minimal encoding. */
817 rvString = PR_smprintf("OID.UNSUPPORTED");
820 rvString = PR_smprintf("%s.UNSUPPORTED", prefix);
825 PR_smprintf_free(prefix);
829 PORT_SetError(SEC_ERROR_NO_MEMORY);
836 /* convert DER-encoded hex to a string */
838 get_hex_string(SECItem *data)
842 static const char hex[] = { "0123456789ABCDEF" };
844 /* '#' + 2 chars per octet + terminator */
845 rv = SECITEM_AllocItem(NULL, NULL, data->len*2 + 2);
850 rv->len = 1 + 2 * data->len;
851 for (i=0; i<data->len; i++) {
853 rv->data[2*i+1] = hex[j >> 4];
854 rv->data[2*i+2] = hex[j & 15];
856 rv->data[rv->len] = 0;
860 /* For compliance with RFC 2253, RFC 3280 and RFC 4630, we choose to
861 * use the NAME=STRING form, rather than the OID.N.N=#hexXXXX form,
862 * when both of these conditions are met:
863 * 1) The attribute name OID (kind) has a known name string that is
864 * defined in one of those RFCs, or in RFCs that they cite, AND
865 * 2) The attribute's value encoding is RFC compliant for the kind
866 * (e.g., the value's encoding tag is correct for the kind, and
867 * the value's length is in the range allowed for the kind, and
868 * the value's contents are appropriate for the encoding tag).
869 * Otherwise, we use the OID.N.N=#hexXXXX form.
871 * If the caller prefers maximum human readability to RFC compliance,
873 * - We print the kind in NAME= string form if we know the name
874 * string for the attribute type OID, regardless of whether the
875 * value is correctly encoded or not. else we use the OID.N.N= form.
876 * - We use the non-hex STRING form for the attribute value if the
877 * value can be represented in such a form. Otherwise, we use
878 * the hex string form.
879 * This implies that, for maximum human readability, in addition to
880 * the two forms allowed by the RFC, we allow two other forms of output:
881 * - the OID.N.N=STRING form, and
882 * - the NAME=#hexXXXX form
883 * When the caller prefers maximum human readability, we do not allow
884 * the value of any attribute to exceed the length allowed by the RFC.
885 * If the attribute value exceeds the allowed length, we truncate it to
886 * the allowed length and append "...".
887 * Also in this case, we arbitrarily impose a limit on the length of the
888 * entire AVA encoding, regardless of the form, of 384 bytes per AVA.
889 * This limit includes the trailing NULL character. If the encoded
890 * AVA length exceeds that limit, this function reports failure to encode
893 * An ASCII representation of an AVA is said to be "invertible" if
894 * conversion back to DER reproduces the original DER encoding exactly.
895 * The RFC 2253 rules do not ensure that all ASCII AVAs derived according
896 * to its rules are invertible. That is because the RFCs allow some
897 * attribute values to be encoded in any of a number of encodings,
898 * and the encoding type information is lost in the non-hex STRING form.
899 * This is particularly true of attributes of type DirectoryString.
900 * The encoding type information is always preserved in the hex string
901 * form, because the hex includes the entire DER encoding of the value.
903 * So, when the caller perfers maximum invertibility, we apply the
904 * RFC compliance rules stated above, and add a third required
905 * condition on the use of the NAME=STRING form.
906 * 3) The attribute's kind is not is allowed to be encoded in any of
907 * several different encodings, such as DirectoryStrings.
909 * The chief difference between CERT_N2A_STRICT and CERT_N2A_INVERTIBLE
910 * is that the latter forces DirectoryStrings to be hex encoded.
912 * As a simplification, we assume the value is correctly encoded for
913 * its encoding type. That is, we do not test that all the characters
914 * in a string encoded type are allowed by that type. We assume it.
917 AppendAVA(stringBuf *bufp, CERTAVA *ava, CertStrictnessLevel strict)
919 #define TMPBUF_LEN 384
920 const NameToKind *pn2k = name2kinds;
921 SECItem *avaValue = NULL;
922 char *unknownTag = NULL;
923 char *encodedAVA = NULL;
924 PRBool useHex = PR_FALSE; /* use =#hexXXXX form */
925 PRBool truncateName = PR_FALSE;
926 PRBool truncateValue = PR_FALSE;
930 unsigned int nameLen, valueLen;
931 unsigned int maxName, maxValue;
932 EQMode mode = minimalEscapeAndQuote;
933 NameToKind n2k = { NULL, 32767, SEC_OID_UNKNOWN, SEC_ASN1_DS };
934 char tmpBuf[TMPBUF_LEN];
936 #define tagName n2k.name /* non-NULL means use NAME= form */
937 #define maxBytes n2k.maxLen
939 #define vt n2k.valueType
941 /* READABLE mode recognizes more names from the name2kinds table
942 * than do STRICT or INVERTIBLE modes. This assignment chooses the
943 * point in the table where the attribute type name scanning stops.
945 endKind = (strict == CERT_N2A_READABLE) ? SEC_OID_UNKNOWN
946 : SEC_OID_AVA_POSTAL_ADDRESS;
947 tag = CERT_GetAVATag(ava);
948 while (pn2k->kind != tag && pn2k->kind != endKind) {
952 if (pn2k->kind != endKind ) {
954 } else if (strict != CERT_N2A_READABLE) {
957 /* For invertable form, force Directory Strings to use hex form. */
958 if (strict == CERT_N2A_INVERTIBLE && vt == SEC_ASN1_DS) {
959 tagName = NULL; /* must use OID.N form */
960 useHex = PR_TRUE; /* must use hex string */
963 avaValue = CERT_DecodeAVAValue(&ava->value);
966 if (strict != CERT_N2A_READABLE) {
967 tagName = NULL; /* must use OID.N form */
972 /* handle unknown attribute types per RFC 2253 */
973 tagName = unknownTag = CERT_GetOidString(&ava->type);
976 SECITEM_FreeItem(avaValue, PR_TRUE);
981 avaValue = get_hex_string(&ava->value);
984 PR_smprintf_free(unknownTag);
989 nameLen = strlen(tagName);
990 valueLen = (useHex ? avaValue->len :
991 cert_RFC1485_GetRequiredLen((char *)avaValue->data, avaValue->len,
993 len = nameLen + valueLen + 2; /* Add 2 for '=' and trailing NUL */
997 if (len <= sizeof(tmpBuf)) {
999 } else if (strict != CERT_N2A_READABLE) {
1000 encodedAVA = PORT_Alloc(len);
1002 SECITEM_FreeItem(avaValue, PR_TRUE);
1004 PR_smprintf_free(unknownTag);
1008 /* Must make output fit in tmpbuf */
1009 unsigned int fair = (sizeof tmpBuf)/2 - 1; /* for = and \0 */
1011 if (nameLen < fair) {
1012 /* just truncate the value */
1013 maxValue = (sizeof tmpBuf) - (nameLen + 6); /* for "=...\0",
1015 } else if (valueLen < fair) {
1016 /* just truncate the name */
1017 maxName = (sizeof tmpBuf) - (valueLen + 5); /* for "=...\0" */
1020 maxName = maxValue = fair - 3; /* for "..." */
1022 if (nameLen > maxName) {
1023 PORT_Assert(unknownTag && unknownTag == tagName);
1024 truncateName = PR_TRUE;
1027 encodedAVA = tmpBuf;
1030 memcpy(encodedAVA, tagName, nameLen);
1032 /* If tag name is too long, we know it is an OID form that was
1033 * allocated from the heap, so we can modify it in place
1035 encodedAVA[nameLen-1] = '.';
1036 encodedAVA[nameLen-2] = '.';
1037 encodedAVA[nameLen-3] = '.';
1039 encodedAVA[nameLen++] = '=';
1041 PR_smprintf_free(unknownTag);
1043 if (strict == CERT_N2A_READABLE && maxValue > maxBytes)
1044 maxValue = maxBytes;
1045 if (valueLen > maxValue) {
1046 valueLen = maxValue;
1047 truncateValue = PR_TRUE;
1049 /* escape and quote as necessary - don't quote hex strings */
1051 char * end = encodedAVA + nameLen + valueLen;
1052 memcpy(encodedAVA + nameLen, (char *)avaValue->data, valueLen);
1054 if (truncateValue) {
1060 } else if (!truncateValue) {
1061 rv = escapeAndQuote(encodedAVA + nameLen, len - nameLen,
1062 (char *)avaValue->data, avaValue->len, &mode);
1064 /* must truncate the escaped and quoted value */
1065 char bigTmpBuf[TMPBUF_LEN * 3 + 3];
1066 rv = escapeAndQuote(bigTmpBuf, sizeof bigTmpBuf,
1067 (char *)avaValue->data, valueLen, &mode);
1069 bigTmpBuf[valueLen--] = '\0'; /* hard stop here */
1070 /* See if we're in the middle of a multi-byte UTF8 character */
1071 while (((bigTmpBuf[valueLen] & 0xc0) == 0x80) && valueLen > 0) {
1072 bigTmpBuf[valueLen--] = '\0';
1074 /* add ellipsis to signify truncation. */
1075 bigTmpBuf[++valueLen] = '.';
1076 bigTmpBuf[++valueLen] = '.';
1077 bigTmpBuf[++valueLen] = '.';
1078 if (bigTmpBuf[0] == '"')
1079 bigTmpBuf[++valueLen] = '"';
1080 bigTmpBuf[++valueLen] = '\0';
1081 PORT_Assert(nameLen + valueLen <= (sizeof tmpBuf) - 1);
1082 memcpy(encodedAVA + nameLen, bigTmpBuf, valueLen+1);
1085 SECITEM_FreeItem(avaValue, PR_TRUE);
1086 if (rv == SECSuccess)
1087 rv = AppendStr(bufp, encodedAVA);
1088 if (encodedAVA != tmpBuf)
1089 PORT_Free(encodedAVA);
1099 CERT_NameToAsciiInvertible(CERTName *name, CertStrictnessLevel strict)
1104 PRBool first = PR_TRUE;
1105 stringBuf strBuf = { NULL, 0, 0 };
1114 while (*lastRdn) lastRdn++;
1118 * Loop over name contents in _reverse_ RDN order appending to string
1120 for (rdn = lastRdn; rdn >= rdns; rdn--) {
1121 CERTAVA** avas = (*rdn)->avas;
1123 PRBool newRDN = PR_TRUE;
1126 * XXX Do we need to traverse the AVAs in reverse order, too?
1128 while (avas && (ava = *avas++) != NULL) {
1130 /* Put in comma or plus separator */
1132 /* Use of spaces is deprecated in RFC 2253. */
1133 rv = AppendStr(&strBuf, newRDN ? "," : "+");
1139 /* Add in tag type plus value into strBuf */
1140 rv = AppendAVA(&strBuf, ava, strict);
1145 return strBuf.buffer;
1147 if (strBuf.buffer) {
1148 PORT_Free(strBuf.buffer);
1154 CERT_NameToAscii(CERTName *name)
1156 return CERT_NameToAsciiInvertible(name, CERT_N2A_READABLE);
1160 * Return the string representation of a DER encoded distinguished name
1161 * "dername" - The DER encoded name to convert
1164 CERT_DerNameToAscii(SECItem *dername)
1167 PRArenaPool *arena = NULL;
1169 char *retstr = NULL;
1171 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1173 if ( arena == NULL) {
1177 rv = SEC_QuickDERDecodeItem(arena, &name, CERT_NameTemplate, dername);
1179 if ( rv != SECSuccess ) {
1183 retstr = CERT_NameToAscii(&name);
1186 if ( arena != NULL ) {
1187 PORT_FreeArena(arena, PR_FALSE);
1194 avaToString(PRArenaPool *arena, CERTAVA *ava)
1200 avaValue = CERT_DecodeAVAValue(&ava->value);
1204 valueLen = cert_RFC1485_GetRequiredLen((char *)avaValue->data,
1205 avaValue->len, NULL) + 1;
1207 buf = (char *)PORT_ArenaZAlloc(arena, valueLen);
1209 buf = (char *)PORT_ZAlloc(valueLen);
1212 SECStatus rv = escapeAndQuote(buf, valueLen, (char *)avaValue->data,
1213 avaValue->len, NULL);
1214 if (rv != SECSuccess) {
1220 SECITEM_FreeItem(avaValue, PR_TRUE);
1224 /* RDNs are sorted from most general to most specific.
1225 * This code returns the FIRST one found, the most general one found.
1228 CERT_GetNameElement(PRArenaPool *arena, CERTName *name, int wantedTag)
1230 CERTRDN** rdns = name->rdns;
1232 CERTAVA* ava = NULL;
1234 while (rdns && (rdn = *rdns++) != 0) {
1235 CERTAVA** avas = rdn->avas;
1236 while (avas && (ava = *avas++) != 0) {
1237 int tag = CERT_GetAVATag(ava);
1238 if ( tag == wantedTag ) {
1240 rdns = NULL; /* break out of all loops */
1244 return ava ? avaToString(arena, ava) : NULL;
1247 /* RDNs are sorted from most general to most specific.
1248 * This code returns the LAST one found, the most specific one found.
1249 * This is particularly appropriate for Common Name. See RFC 2818.
1252 CERT_GetLastNameElement(PRArenaPool *arena, CERTName *name, int wantedTag)
1254 CERTRDN** rdns = name->rdns;
1256 CERTAVA* lastAva = NULL;
1258 while (rdns && (rdn = *rdns++) != 0) {
1259 CERTAVA** avas = rdn->avas;
1261 while (avas && (ava = *avas++) != 0) {
1262 int tag = CERT_GetAVATag(ava);
1263 if ( tag == wantedTag ) {
1268 return lastAva ? avaToString(arena, lastAva) : NULL;
1272 CERT_GetCertificateEmailAddress(CERTCertificate *cert)
1274 char *rawEmailAddr = NULL;
1277 CERTGeneralName *nameList = NULL;
1278 CERTGeneralName *current;
1279 PRArenaPool *arena = NULL;
1282 subAltName.data = NULL;
1284 rawEmailAddr = CERT_GetNameElement(cert->arena, &(cert->subject),
1285 SEC_OID_PKCS9_EMAIL_ADDRESS);
1286 if ( rawEmailAddr == NULL ) {
1287 rawEmailAddr = CERT_GetNameElement(cert->arena, &(cert->subject),
1288 SEC_OID_RFC1274_MAIL);
1290 if ( rawEmailAddr == NULL) {
1292 rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME,
1294 if (rv != SECSuccess) {
1297 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1301 nameList = current = CERT_DecodeAltNameExtension(arena, &subAltName);
1305 if (nameList != NULL) {
1307 if (current->type == certDirectoryName) {
1308 rawEmailAddr = CERT_GetNameElement(cert->arena,
1309 &(current->name.directoryName),
1310 SEC_OID_PKCS9_EMAIL_ADDRESS);
1311 if ( rawEmailAddr == NULL ) {
1312 rawEmailAddr = CERT_GetNameElement(cert->arena,
1313 &(current->name.directoryName), SEC_OID_RFC1274_MAIL);
1315 } else if (current->type == certRFC822Name) {
1316 rawEmailAddr = (char*)PORT_ArenaZAlloc(cert->arena,
1317 current->name.other.len + 1);
1318 if (!rawEmailAddr) {
1321 PORT_Memcpy(rawEmailAddr, current->name.other.data,
1322 current->name.other.len);
1323 rawEmailAddr[current->name.other.len] = '\0';
1328 current = CERT_GetNextGeneralName(current);
1329 } while (current != nameList);
1333 for (i = 0; i <= (int) PORT_Strlen(rawEmailAddr); i++) {
1334 rawEmailAddr[i] = tolower(rawEmailAddr[i]);
1340 /* Don't free nameList, it's part of the arena. */
1343 PORT_FreeArena(arena, PR_FALSE);
1346 if ( subAltName.data ) {
1347 SECITEM_FreeItem(&subAltName, PR_FALSE);
1350 return(rawEmailAddr);
1354 appendStringToBuf(char *dest, char *src, PRUint32 *pRemaining)
1357 if (dest && src && src[0] && *pRemaining > (len = PL_strlen(src))) {
1359 for (i = 0; i < len; ++i)
1360 dest[i] = tolower(src[i]);
1363 *pRemaining -= len + 1;
1368 #undef NEEDS_HEX_ESCAPE
1369 #define NEEDS_HEX_ESCAPE(c) (c < 0x20)
1372 appendItemToBuf(char *dest, SECItem *src, PRUint32 *pRemaining)
1374 if (dest && src && src->data && src->len && src->data[0]) {
1375 PRUint32 len = src->len;
1377 PRUint32 reqLen = len + 1;
1378 /* are there any embedded control characters ? */
1379 for (i = 0; i < len; i++) {
1380 if (NEEDS_HEX_ESCAPE(src->data[i]))
1383 if (*pRemaining > reqLen) {
1384 for (i = 0; i < len; ++i) {
1385 PRUint8 c = src->data[i];
1386 if (NEEDS_HEX_ESCAPE(c)) {
1387 *dest++ = C_BACKSLASH;
1388 *dest++ = hexChars[ (c >> 4) & 0x0f ];
1389 *dest++ = hexChars[ c & 0x0f ];
1391 *dest++ = tolower(c);
1395 *pRemaining -= reqLen;
1401 /* Returns a pointer to an environment-like string, a series of
1402 ** null-terminated strings, terminated by a zero-length string.
1403 ** This function is intended to be internal to NSS.
1406 cert_GetCertificateEmailAddresses(CERTCertificate *cert)
1408 char * rawEmailAddr = NULL;
1409 char * addrBuf = NULL;
1411 PRArenaPool * tmpArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1412 PRUint32 maxLen = 0;
1413 PRInt32 finalLen = 0;
1420 subAltName.data = NULL;
1421 maxLen = cert->derCert.len;
1422 PORT_Assert(maxLen);
1424 maxLen = 2000; /* a guess, should never happen */
1426 pBuf = addrBuf = (char *)PORT_ArenaZAlloc(tmpArena, maxLen + 1);
1430 rawEmailAddr = CERT_GetNameElement(tmpArena, &cert->subject,
1431 SEC_OID_PKCS9_EMAIL_ADDRESS);
1432 pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
1434 rawEmailAddr = CERT_GetNameElement(tmpArena, &cert->subject,
1435 SEC_OID_RFC1274_MAIL);
1436 pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
1438 rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME,
1440 if (rv == SECSuccess && subAltName.data) {
1441 CERTGeneralName *nameList = NULL;
1443 if (!!(nameList = CERT_DecodeAltNameExtension(tmpArena, &subAltName))) {
1444 CERTGeneralName *current = nameList;
1446 if (current->type == certDirectoryName) {
1447 rawEmailAddr = CERT_GetNameElement(tmpArena,
1448 ¤t->name.directoryName,
1449 SEC_OID_PKCS9_EMAIL_ADDRESS);
1450 pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
1452 rawEmailAddr = CERT_GetNameElement(tmpArena,
1453 ¤t->name.directoryName,
1454 SEC_OID_RFC1274_MAIL);
1455 pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
1456 } else if (current->type == certRFC822Name) {
1457 pBuf = appendItemToBuf(pBuf, ¤t->name.other, &maxLen);
1459 current = CERT_GetNextGeneralName(current);
1460 } while (current != nameList);
1462 SECITEM_FreeItem(&subAltName, PR_FALSE);
1463 /* Don't free nameList, it's part of the tmpArena. */
1465 /* now copy superstring to cert's arena */
1466 finalLen = (pBuf - addrBuf) + 1;
1469 pBuf = PORT_ArenaAlloc(cert->arena, finalLen);
1471 PORT_Memcpy(pBuf, addrBuf, finalLen);
1476 PORT_FreeArena(tmpArena, PR_FALSE);
1481 /* returns pointer to storage in cert's arena. Storage remains valid
1482 ** as long as cert's reference count doesn't go to zero.
1483 ** Caller should strdup or otherwise copy.
1485 const char * /* const so caller won't muck with it. */
1486 CERT_GetFirstEmailAddress(CERTCertificate * cert)
1488 if (cert && cert->emailAddr && cert->emailAddr[0])
1489 return (const char *)cert->emailAddr;
1493 /* returns pointer to storage in cert's arena. Storage remains valid
1494 ** as long as cert's reference count doesn't go to zero.
1495 ** Caller should strdup or otherwise copy.
1497 const char * /* const so caller won't muck with it. */
1498 CERT_GetNextEmailAddress(CERTCertificate * cert, const char * prev)
1500 if (cert && prev && prev[0]) {
1501 PRUint32 len = PL_strlen(prev);
1503 if (prev && prev[0])
1509 /* This is seriously bogus, now that certs store their email addresses in
1510 ** subject Alternative Name extensions.
1511 ** Returns a string allocated by PORT_StrDup, which the caller must free.
1514 CERT_GetCertEmailAddress(CERTName *name)
1520 rawEmailAddr = CERT_GetNameElement(NULL, name, SEC_OID_PKCS9_EMAIL_ADDRESS);
1521 if ( rawEmailAddr == NULL ) {
1522 rawEmailAddr = CERT_GetNameElement(NULL, name, SEC_OID_RFC1274_MAIL);
1524 emailAddr = CERT_FixupEmailAddr(rawEmailAddr);
1525 if ( rawEmailAddr ) {
1526 PORT_Free(rawEmailAddr);
1531 /* The return value must be freed with PORT_Free. */
1533 CERT_GetCommonName(CERTName *name)
1535 return(CERT_GetLastNameElement(NULL, name, SEC_OID_AVA_COMMON_NAME));
1539 CERT_GetCountryName(CERTName *name)
1541 return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_COUNTRY_NAME));
1545 CERT_GetLocalityName(CERTName *name)
1547 return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_LOCALITY));
1551 CERT_GetStateName(CERTName *name)
1553 return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_STATE_OR_PROVINCE));
1557 CERT_GetOrgName(CERTName *name)
1559 return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_ORGANIZATION_NAME));
1563 CERT_GetDomainComponentName(CERTName *name)
1565 return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_DC));
1569 CERT_GetOrgUnitName(CERTName *name)
1571 return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME));
1575 CERT_GetDnQualifier(CERTName *name)
1577 return(CERT_GetNameElement(NULL, name, SEC_OID_AVA_DN_QUALIFIER));
1581 CERT_GetCertUid(CERTName *name)
1583 return(CERT_GetNameElement(NULL, name, SEC_OID_RFC1274_UID));