alg1485.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  1. /* alg1485.c - implementation of RFCs 1485, 1779 and 2253.
  2. *
  3. * This Source Code Form is subject to the terms of the Mozilla Public
  4. * License, v. 2.0. If a copy of the MPL was not distributed with this
  5. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6. #include "prprf.h"
  7. #include "cert.h"
  8. #include "certi.h"
  9. #include "xconst.h"
  10. #include "genname.h"
  11. #include "secitem.h"
  12. #include "secerr.h"
  13. typedef struct NameToKindStr {
  14. const char* name;
  15. unsigned int maxLen; /* max bytes in UTF8 encoded string value */
  16. SECOidTag kind;
  17. int valueType;
  18. } NameToKind;
  19. /* local type for directory string--could be printable_string or utf8 */
  20. #define SEC_ASN1_DS SEC_ASN1_HIGH_TAG_NUMBER
  21. /* clang-format off */
  22. /* Add new entries to this table, and maybe to function ParseRFC1485AVA */
  23. static const NameToKind name2kinds[] = {
  24. /* IANA registered type names
  25. * (See: http://www.iana.org/assignments/ldap-parameters)
  26. */
  27. /* RFC 3280, 4630 MUST SUPPORT */
  28. { "CN", 640, SEC_OID_AVA_COMMON_NAME, SEC_ASN1_DS},
  29. { "ST", 128, SEC_OID_AVA_STATE_OR_PROVINCE,
  30. SEC_ASN1_DS},
  31. { "O", 128, SEC_OID_AVA_ORGANIZATION_NAME,
  32. SEC_ASN1_DS},
  33. { "OU", 128, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME,
  34. SEC_ASN1_DS},
  35. { "dnQualifier", 32767, SEC_OID_AVA_DN_QUALIFIER, SEC_ASN1_PRINTABLE_STRING},
  36. { "C", 2, SEC_OID_AVA_COUNTRY_NAME, SEC_ASN1_PRINTABLE_STRING},
  37. { "serialNumber", 64, SEC_OID_AVA_SERIAL_NUMBER,SEC_ASN1_PRINTABLE_STRING},
  38. /* RFC 3280, 4630 SHOULD SUPPORT */
  39. { "L", 128, SEC_OID_AVA_LOCALITY, SEC_ASN1_DS},
  40. { "title", 64, SEC_OID_AVA_TITLE, SEC_ASN1_DS},
  41. { "SN", 64, SEC_OID_AVA_SURNAME, SEC_ASN1_DS},
  42. { "givenName", 64, SEC_OID_AVA_GIVEN_NAME, SEC_ASN1_DS},
  43. { "initials", 64, SEC_OID_AVA_INITIALS, SEC_ASN1_DS},
  44. { "generationQualifier",
  45. 64, SEC_OID_AVA_GENERATION_QUALIFIER,
  46. SEC_ASN1_DS},
  47. /* RFC 3280, 4630 MAY SUPPORT */
  48. { "DC", 128, SEC_OID_AVA_DC, SEC_ASN1_IA5_STRING},
  49. { "MAIL", 256, SEC_OID_RFC1274_MAIL, SEC_ASN1_IA5_STRING},
  50. { "UID", 256, SEC_OID_RFC1274_UID, SEC_ASN1_DS},
  51. /* ------------------ "strict" boundary ---------------------------------
  52. * In strict mode, cert_NameToAscii does not encode any of the attributes
  53. * below this line. The first SECOidTag below this line must be used to
  54. * conditionally define the "endKind" in function AppendAVA() below.
  55. * Most new attribute names should be added below this line.
  56. * Maybe this line should be up higher? Say, after the 3280 MUSTs and
  57. * before the 3280 SHOULDs?
  58. */
  59. /* values from draft-ietf-ldapbis-user-schema-05 (not in RFC 3280) */
  60. { "postalAddress", 128, SEC_OID_AVA_POSTAL_ADDRESS, SEC_ASN1_DS},
  61. { "postalCode", 40, SEC_OID_AVA_POSTAL_CODE, SEC_ASN1_DS},
  62. { "postOfficeBox", 40, SEC_OID_AVA_POST_OFFICE_BOX,SEC_ASN1_DS},
  63. { "houseIdentifier",64, SEC_OID_AVA_HOUSE_IDENTIFIER,SEC_ASN1_DS},
  64. /* end of IANA registered type names */
  65. /* legacy keywords */
  66. { "E", 128, SEC_OID_PKCS9_EMAIL_ADDRESS,SEC_ASN1_IA5_STRING},
  67. { "STREET", 128, SEC_OID_AVA_STREET_ADDRESS, SEC_ASN1_DS},
  68. { "pseudonym", 64, SEC_OID_AVA_PSEUDONYM, SEC_ASN1_DS},
  69. /* values defined by the CAB Forum for EV */
  70. { "incorporationLocality", 128, SEC_OID_EV_INCORPORATION_LOCALITY,
  71. SEC_ASN1_DS},
  72. { "incorporationState", 128, SEC_OID_EV_INCORPORATION_STATE,
  73. SEC_ASN1_DS},
  74. { "incorporationCountry", 2, SEC_OID_EV_INCORPORATION_COUNTRY,
  75. SEC_ASN1_PRINTABLE_STRING},
  76. { "businessCategory", 64, SEC_OID_BUSINESS_CATEGORY, SEC_ASN1_DS},
  77. /* values defined in X.520 */
  78. { "name", 64, SEC_OID_AVA_NAME, SEC_ASN1_DS},
  79. { 0, 256, SEC_OID_UNKNOWN, 0},
  80. };
  81. /* Table facilitates conversion of ASCII hex to binary. */
  82. static const PRInt16 x2b[256] = {
  83. /* #0x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  84. /* #1x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  85. /* #2x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  86. /* #3x */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  87. /* #4x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  88. /* #5x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  89. /* #6x */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  90. /* #7x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  91. /* #8x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  92. /* #9x */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  93. /* #ax */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  94. /* #bx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  95. /* #cx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  96. /* #dx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  97. /* #ex */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  98. /* #fx */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
  99. };
  100. #define IS_HEX(c) (x2b[(PRUint8)(c)] >= 0)
  101. #define C_DOUBLE_QUOTE '\042'
  102. #define C_BACKSLASH '\134'
  103. #define C_EQUAL '='
  104. #define OPTIONAL_SPACE(c) \
  105. (((c) == ' ') || ((c) == '\r') || ((c) == '\n'))
  106. #define SPECIAL_CHAR(c) \
  107. (((c) == ',') || ((c) == '=') || ((c) == C_DOUBLE_QUOTE) || \
  108. ((c) == '\r') || ((c) == '\n') || ((c) == '+') || \
  109. ((c) == '<') || ((c) == '>') || ((c) == '#') || \
  110. ((c) == ';') || ((c) == C_BACKSLASH))
  111. #define IS_PRINTABLE(c) \
  112. ((((c) >= 'a') && ((c) <= 'z')) || \
  113. (((c) >= 'A') && ((c) <= 'Z')) || \
  114. (((c) >= '0') && ((c) <= '9')) || \
  115. ((c) == ' ') || \
  116. ((c) == '\'') || \
  117. ((c) == '\050') || /* ( */ \
  118. ((c) == '\051') || /* ) */ \
  119. (((c) >= '+') && ((c) <= '/')) || /* + , - . / */ \
  120. ((c) == ':') || \
  121. ((c) == '=') || \
  122. ((c) == '?'))
  123. /* clang-format on */
  124. /* RFC 2253 says we must escape ",+\"\\<>;=" EXCEPT inside a quoted string.
  125. * Inside a quoted string, we only need to escape " and \
  126. * We choose to quote strings containing any of those special characters,
  127. * so we only need to escape " and \
  128. */
  129. #define NEEDS_ESCAPE(c) (c == C_DOUBLE_QUOTE || c == C_BACKSLASH)
  130. #define NEEDS_HEX_ESCAPE(c) ((PRUint8)c < 0x20 || c == 0x7f)
  131. int
  132. cert_AVAOidTagToMaxLen(SECOidTag tag)
  133. {
  134. const NameToKind* n2k = name2kinds;
  135. while (n2k->kind != tag && n2k->kind != SEC_OID_UNKNOWN) {
  136. ++n2k;
  137. }
  138. return (n2k->kind != SEC_OID_UNKNOWN) ? n2k->maxLen : -1;
  139. }
  140. static PRBool
  141. IsPrintable(unsigned char* data, unsigned len)
  142. {
  143. unsigned char ch, *end;
  144. end = data + len;
  145. while (data < end) {
  146. ch = *data++;
  147. if (!IS_PRINTABLE(ch)) {
  148. return PR_FALSE;
  149. }
  150. }
  151. return PR_TRUE;
  152. }
  153. static void
  154. skipSpace(const char** pbp, const char* endptr)
  155. {
  156. const char* bp = *pbp;
  157. while (bp < endptr && OPTIONAL_SPACE(*bp)) {
  158. bp++;
  159. }
  160. *pbp = bp;
  161. }
  162. static SECStatus
  163. scanTag(const char** pbp, const char* endptr, char* tagBuf, int tagBufSize)
  164. {
  165. const char* bp;
  166. char* tagBufp;
  167. int taglen;
  168. PORT_Assert(tagBufSize > 0);
  169. /* skip optional leading space */
  170. skipSpace(pbp, endptr);
  171. if (*pbp == endptr) {
  172. /* nothing left */
  173. return SECFailure;
  174. }
  175. /* fill tagBuf */
  176. taglen = 0;
  177. bp = *pbp;
  178. tagBufp = tagBuf;
  179. while (bp < endptr && !OPTIONAL_SPACE(*bp) && (*bp != C_EQUAL)) {
  180. if (++taglen >= tagBufSize) {
  181. *pbp = bp;
  182. return SECFailure;
  183. }
  184. *tagBufp++ = *bp++;
  185. }
  186. /* null-terminate tagBuf -- guaranteed at least one space left */
  187. *tagBufp++ = 0;
  188. *pbp = bp;
  189. /* skip trailing spaces till we hit something - should be an equal sign */
  190. skipSpace(pbp, endptr);
  191. if (*pbp == endptr) {
  192. /* nothing left */
  193. return SECFailure;
  194. }
  195. if (**pbp != C_EQUAL) {
  196. /* should be an equal sign */
  197. return SECFailure;
  198. }
  199. /* skip over the equal sign */
  200. (*pbp)++;
  201. return SECSuccess;
  202. }
  203. /* Returns the number of bytes in the value. 0 means failure. */
  204. static int
  205. scanVal(const char** pbp, const char* endptr, char* valBuf, int valBufSize)
  206. {
  207. const char* bp;
  208. char* valBufp;
  209. int vallen = 0;
  210. PRBool isQuoted;
  211. PORT_Assert(valBufSize > 0);
  212. /* skip optional leading space */
  213. skipSpace(pbp, endptr);
  214. if (*pbp == endptr) {
  215. /* nothing left */
  216. return 0;
  217. }
  218. bp = *pbp;
  219. /* quoted? */
  220. if (*bp == C_DOUBLE_QUOTE) {
  221. isQuoted = PR_TRUE;
  222. /* skip over it */
  223. bp++;
  224. } else {
  225. isQuoted = PR_FALSE;
  226. }
  227. valBufp = valBuf;
  228. while (bp < endptr) {
  229. char c = *bp;
  230. if (c == C_BACKSLASH) {
  231. /* escape character */
  232. bp++;
  233. if (bp >= endptr) {
  234. /* escape charater must appear with paired char */
  235. *pbp = bp;
  236. return 0;
  237. }
  238. c = *bp;
  239. if (IS_HEX(c) && (endptr - bp) >= 2 && IS_HEX(bp[1])) {
  240. bp++;
  241. c = (char)((x2b[(PRUint8)c] << 4) | x2b[(PRUint8)*bp]);
  242. }
  243. } else if (c == '#' && bp == *pbp) {
  244. /* ignore leading #, quotation not required for it. */
  245. } else if (!isQuoted && SPECIAL_CHAR(c)) {
  246. /* unescaped special and not within quoted value */
  247. break;
  248. } else if (c == C_DOUBLE_QUOTE) {
  249. /* reached unescaped double quote */
  250. break;
  251. }
  252. /* append character */
  253. vallen++;
  254. if (vallen >= valBufSize) {
  255. *pbp = bp;
  256. return 0;
  257. }
  258. *valBufp++ = c;
  259. bp++;
  260. }
  261. /* strip trailing spaces from unquoted values */
  262. if (!isQuoted) {
  263. while (valBufp > valBuf) {
  264. char c = valBufp[-1];
  265. if (!OPTIONAL_SPACE(c))
  266. break;
  267. --valBufp;
  268. }
  269. vallen = valBufp - valBuf;
  270. }
  271. if (isQuoted) {
  272. /* insist that we stopped on a double quote */
  273. if (*bp != C_DOUBLE_QUOTE) {
  274. *pbp = bp;
  275. return 0;
  276. }
  277. /* skip over the quote and skip optional space */
  278. bp++;
  279. skipSpace(&bp, endptr);
  280. }
  281. *pbp = bp;
  282. /* null-terminate valBuf -- guaranteed at least one space left */
  283. *valBufp = 0;
  284. return vallen;
  285. }
  286. /* Caller must set error code upon failure */
  287. static SECStatus
  288. hexToBin(PLArenaPool* pool, SECItem* destItem, const char* src, int len)
  289. {
  290. PRUint8* dest;
  291. destItem->data = NULL;
  292. if (len <= 0 || (len & 1)) {
  293. goto loser;
  294. }
  295. len >>= 1;
  296. if (!SECITEM_AllocItem(pool, destItem, len)) {
  297. goto loser;
  298. }
  299. dest = destItem->data;
  300. for (; len > 0; len--, src += 2) {
  301. PRUint16 bin = ((PRUint16)x2b[(PRUint8)src[0]] << 4);
  302. bin |= (PRUint16)x2b[(PRUint8)src[1]];
  303. if (bin >> 15) { /* is negative */
  304. goto loser;
  305. }
  306. *dest++ = (PRUint8)bin;
  307. }
  308. return SECSuccess;
  309. loser:
  310. if (!pool)
  311. SECITEM_FreeItem(destItem, PR_FALSE);
  312. return SECFailure;
  313. }
  314. /* Parses one AVA, starting at *pbp. Stops at endptr.
  315. * Advances *pbp past parsed AVA and trailing separator (if present).
  316. * On any error, returns NULL and *pbp is undefined.
  317. * On success, returns CERTAVA allocated from arena, and (*pbp)[-1] was
  318. * the last character parsed. *pbp is either equal to endptr or
  319. * points to first character after separator.
  320. */
  321. static CERTAVA*
  322. ParseRFC1485AVA(PLArenaPool* arena, const char** pbp, const char* endptr)
  323. {
  324. CERTAVA* a;
  325. const NameToKind* n2k;
  326. const char* bp;
  327. int vt = -1;
  328. int valLen;
  329. PRBool isDottedOid = PR_FALSE;
  330. SECOidTag kind = SEC_OID_UNKNOWN;
  331. SECStatus rv = SECFailure;
  332. SECItem derOid = { 0, NULL, 0 };
  333. SECItem derVal = { 0, NULL, 0 };
  334. char sep = 0;
  335. char tagBuf[32];
  336. char valBuf[1024];
  337. PORT_Assert(arena);
  338. if (SECSuccess != scanTag(pbp, endptr, tagBuf, sizeof tagBuf) ||
  339. !(valLen = scanVal(pbp, endptr, valBuf, sizeof valBuf))) {
  340. goto loser;
  341. }
  342. bp = *pbp;
  343. if (bp < endptr) {
  344. sep = *bp++; /* skip over separator */
  345. }
  346. *pbp = bp;
  347. /* if we haven't finished, insist that we've stopped on a separator */
  348. if (sep && sep != ',' && sep != ';' && sep != '+') {
  349. goto loser;
  350. }
  351. /* is this a dotted decimal OID attribute type ? */
  352. if (!PL_strncasecmp("oid.", tagBuf, 4) || isdigit(tagBuf[0])) {
  353. rv = SEC_StringToOID(arena, &derOid, tagBuf, strlen(tagBuf));
  354. isDottedOid = (PRBool)(rv == SECSuccess);
  355. } else {
  356. for (n2k = name2kinds; n2k->name; n2k++) {
  357. SECOidData* oidrec;
  358. if (PORT_Strcasecmp(n2k->name, tagBuf) == 0) {
  359. kind = n2k->kind;
  360. vt = n2k->valueType;
  361. oidrec = SECOID_FindOIDByTag(kind);
  362. if (oidrec == NULL)
  363. goto loser;
  364. derOid = oidrec->oid;
  365. break;
  366. }
  367. }
  368. }
  369. if (kind == SEC_OID_UNKNOWN && rv != SECSuccess)
  370. goto loser;
  371. /* Is this a hex encoding of a DER attribute value ? */
  372. if ('#' == valBuf[0]) {
  373. /* convert attribute value from hex to binary */
  374. rv = hexToBin(arena, &derVal, valBuf + 1, valLen - 1);
  375. if (rv)
  376. goto loser;
  377. a = CERT_CreateAVAFromRaw(arena, &derOid, &derVal);
  378. } else {
  379. if (kind == SEC_OID_AVA_COUNTRY_NAME && valLen != 2)
  380. goto loser;
  381. if (vt == SEC_ASN1_PRINTABLE_STRING &&
  382. !IsPrintable((unsigned char*)valBuf, valLen))
  383. goto loser;
  384. if (vt == SEC_ASN1_DS) {
  385. /* RFC 4630: choose PrintableString or UTF8String */
  386. if (IsPrintable((unsigned char*)valBuf, valLen))
  387. vt = SEC_ASN1_PRINTABLE_STRING;
  388. else
  389. vt = SEC_ASN1_UTF8_STRING;
  390. }
  391. derVal.data = (unsigned char*)valBuf;
  392. derVal.len = valLen;
  393. if (kind == SEC_OID_UNKNOWN && isDottedOid) {
  394. a = CERT_CreateAVAFromRaw(arena, &derOid, &derVal);
  395. } else {
  396. a = CERT_CreateAVAFromSECItem(arena, kind, vt, &derVal);
  397. }
  398. }
  399. return a;
  400. loser:
  401. /* matched no kind -- invalid tag */
  402. PORT_SetError(SEC_ERROR_INVALID_AVA);
  403. return 0;
  404. }
  405. static CERTName*
  406. ParseRFC1485Name(const char* buf, int len)
  407. {
  408. SECStatus rv;
  409. CERTName* name;
  410. const char *bp, *e;
  411. CERTAVA* ava;
  412. CERTRDN* rdn = NULL;
  413. name = CERT_CreateName(NULL);
  414. if (name == NULL) {
  415. return NULL;
  416. }
  417. e = buf + len;
  418. bp = buf;
  419. while (bp < e) {
  420. ava = ParseRFC1485AVA(name->arena, &bp, e);
  421. if (ava == 0)
  422. goto loser;
  423. if (!rdn) {
  424. rdn = CERT_CreateRDN(name->arena, ava, (CERTAVA*)0);
  425. if (rdn == 0)
  426. goto loser;
  427. rv = CERT_AddRDN(name, rdn);
  428. } else {
  429. rv = CERT_AddAVA(name->arena, rdn, ava);
  430. }
  431. if (rv)
  432. goto loser;
  433. if (bp[-1] != '+')
  434. rdn = NULL; /* done with this RDN */
  435. skipSpace(&bp, e);
  436. }
  437. if (name->rdns[0] == 0) {
  438. /* empty name -- illegal */
  439. goto loser;
  440. }
  441. /* Reverse order of RDNS to comply with RFC */
  442. {
  443. CERTRDN** firstRdn;
  444. CERTRDN** lastRdn;
  445. CERTRDN* tmp;
  446. /* get first one */
  447. firstRdn = name->rdns;
  448. /* find last one */
  449. lastRdn = name->rdns;
  450. while (*lastRdn)
  451. lastRdn++;
  452. lastRdn--;
  453. /* reverse list */
  454. for (; firstRdn < lastRdn; firstRdn++, lastRdn--) {
  455. tmp = *firstRdn;
  456. *firstRdn = *lastRdn;
  457. *lastRdn = tmp;
  458. }
  459. }
  460. /* return result */
  461. return name;
  462. loser:
  463. CERT_DestroyName(name);
  464. return NULL;
  465. }
  466. CERTName*
  467. CERT_AsciiToName(const char* string)
  468. {
  469. CERTName* name;
  470. name = ParseRFC1485Name(string, PORT_Strlen(string));
  471. return name;
  472. }
  473. /************************************************************************/
  474. typedef struct stringBufStr {
  475. char* buffer;
  476. unsigned offset;
  477. unsigned size;
  478. } stringBuf;
  479. #define DEFAULT_BUFFER_SIZE 200
  480. static SECStatus
  481. AppendStr(stringBuf* bufp, char* str)
  482. {
  483. char* buf;
  484. unsigned bufLen, bufSize, len;
  485. int size = 0;
  486. /* Figure out how much to grow buf by (add in the '\0') */
  487. buf = bufp->buffer;
  488. bufLen = bufp->offset;
  489. len = PORT_Strlen(str);
  490. bufSize = bufLen + len;
  491. if (!buf) {
  492. bufSize++;
  493. size = PR_MAX(DEFAULT_BUFFER_SIZE, bufSize * 2);
  494. buf = (char*)PORT_Alloc(size);
  495. bufp->size = size;
  496. } else if (bufp->size < bufSize) {
  497. size = bufSize * 2;
  498. buf = (char*)PORT_Realloc(buf, size);
  499. bufp->size = size;
  500. }
  501. if (!buf) {
  502. PORT_SetError(SEC_ERROR_NO_MEMORY);
  503. return SECFailure;
  504. }
  505. bufp->buffer = buf;
  506. bufp->offset = bufSize;
  507. /* Concatenate str onto buf */
  508. buf = buf + bufLen;
  509. if (bufLen)
  510. buf--; /* stomp on old '\0' */
  511. PORT_Memcpy(buf, str, len + 1); /* put in new null */
  512. return SECSuccess;
  513. }
  514. typedef enum {
  515. minimalEscape = 0, /* only hex escapes, and " and \ */
  516. minimalEscapeAndQuote, /* as above, plus quoting */
  517. fullEscape /* no quoting, full escaping */
  518. } EQMode;
  519. /* Some characters must be escaped as a hex string, e.g. c -> \nn .
  520. * Others must be escaped by preceding with a '\', e.g. c -> \c , but
  521. * there are certain "special characters" that may be handled by either
  522. * escaping them, or by enclosing the entire attribute value in quotes.
  523. * A NULL value for pEQMode implies selecting minimalEscape mode.
  524. * Some callers will do quoting when needed, others will not.
  525. * If a caller selects minimalEscapeAndQuote, and the string does not
  526. * need quoting, then this function changes it to minimalEscape.
  527. */
  528. static int
  529. cert_RFC1485_GetRequiredLen(const char* src, int srclen, EQMode* pEQMode)
  530. {
  531. int i, reqLen = 0;
  532. EQMode mode = pEQMode ? *pEQMode : minimalEscape;
  533. PRBool needsQuoting = PR_FALSE;
  534. char lastC = 0;
  535. /* need to make an initial pass to determine if quoting is needed */
  536. for (i = 0; i < srclen; i++) {
  537. char c = src[i];
  538. reqLen++;
  539. if (NEEDS_HEX_ESCAPE(c)) { /* c -> \xx */
  540. reqLen += 2;
  541. } else if (NEEDS_ESCAPE(c)) { /* c -> \c */
  542. reqLen++;
  543. } else if (SPECIAL_CHAR(c)) {
  544. if (mode == minimalEscapeAndQuote) /* quoting is allowed */
  545. needsQuoting = PR_TRUE; /* entirety will need quoting */
  546. else if (mode == fullEscape)
  547. reqLen++; /* MAY escape this character */
  548. } else if (OPTIONAL_SPACE(c) && OPTIONAL_SPACE(lastC)) {
  549. if (mode == minimalEscapeAndQuote) /* quoting is allowed */
  550. needsQuoting = PR_TRUE; /* entirety will need quoting */
  551. }
  552. lastC = c;
  553. }
  554. /* if it begins or ends in optional space it needs quoting */
  555. if (!needsQuoting && srclen > 0 && mode == minimalEscapeAndQuote &&
  556. (OPTIONAL_SPACE(src[srclen - 1]) || OPTIONAL_SPACE(src[0]))) {
  557. needsQuoting = PR_TRUE;
  558. }
  559. if (needsQuoting)
  560. reqLen += 2;
  561. if (pEQMode && mode == minimalEscapeAndQuote && !needsQuoting)
  562. *pEQMode = minimalEscape;
  563. return reqLen;
  564. }
  565. static const char hexChars[16] = { "0123456789abcdef" };
  566. static SECStatus
  567. escapeAndQuote(char* dst, int dstlen, char* src, int srclen, EQMode* pEQMode)
  568. {
  569. int i, reqLen = 0;
  570. EQMode mode = pEQMode ? *pEQMode : minimalEscape;
  571. /* space for terminal null */
  572. reqLen = cert_RFC1485_GetRequiredLen(src, srclen, &mode) + 1;
  573. if (reqLen > dstlen) {
  574. PORT_SetError(SEC_ERROR_OUTPUT_LEN);
  575. return SECFailure;
  576. }
  577. if (mode == minimalEscapeAndQuote)
  578. *dst++ = C_DOUBLE_QUOTE;
  579. for (i = 0; i < srclen; i++) {
  580. char c = src[i];
  581. if (NEEDS_HEX_ESCAPE(c)) {
  582. *dst++ = C_BACKSLASH;
  583. *dst++ = hexChars[(c >> 4) & 0x0f];
  584. *dst++ = hexChars[c & 0x0f];
  585. } else {
  586. if (NEEDS_ESCAPE(c) || (SPECIAL_CHAR(c) && mode == fullEscape)) {
  587. *dst++ = C_BACKSLASH;
  588. }
  589. *dst++ = c;
  590. }
  591. }
  592. if (mode == minimalEscapeAndQuote)
  593. *dst++ = C_DOUBLE_QUOTE;
  594. *dst++ = 0;
  595. if (pEQMode)
  596. *pEQMode = mode;
  597. return SECSuccess;
  598. }
  599. SECStatus
  600. CERT_RFC1485_EscapeAndQuote(char* dst, int dstlen, char* src, int srclen)
  601. {
  602. EQMode mode = minimalEscapeAndQuote;
  603. return escapeAndQuote(dst, dstlen, src, srclen, &mode);
  604. }
  605. /* convert an OID to dotted-decimal representation */
  606. /* Returns a string that must be freed with PR_smprintf_free(), */
  607. char*
  608. CERT_GetOidString(const SECItem* oid)
  609. {
  610. PRUint8* stop; /* points to first byte after OID string */
  611. PRUint8* first; /* byte of an OID component integer */
  612. PRUint8* last; /* byte of an OID component integer */
  613. char* rvString = NULL;
  614. char* prefix = NULL;
  615. #define MAX_OID_LEN 1024 /* bytes */
  616. if (oid->len > MAX_OID_LEN) {
  617. PORT_SetError(SEC_ERROR_INPUT_LEN);
  618. return NULL;
  619. }
  620. /* If the OID has length 1, we bail. */
  621. if (oid->len < 2) {
  622. return NULL;
  623. }
  624. /* first will point to the next sequence of bytes to decode */
  625. first = (PRUint8*)oid->data;
  626. /* stop points to one past the legitimate data */
  627. stop = &first[oid->len];
  628. /*
  629. * Check for our pseudo-encoded single-digit OIDs
  630. */
  631. if ((*first == 0x80) && (2 == oid->len)) {
  632. /* Funky encoding. The second byte is the number */
  633. rvString = PR_smprintf("%lu", (PRUint32)first[1]);
  634. if (!rvString) {
  635. PORT_SetError(SEC_ERROR_NO_MEMORY);
  636. }
  637. return rvString;
  638. }
  639. for (; first < stop; first = last + 1) {
  640. unsigned int bytesBeforeLast;
  641. for (last = first; last < stop; last++) {
  642. if (0 == (*last & 0x80)) {
  643. break;
  644. }
  645. }
  646. /* There's no first bit set, so this isn't valid. Bail.*/
  647. if (last == stop) {
  648. goto unsupported;
  649. }
  650. bytesBeforeLast = (unsigned int)(last - first);
  651. if (bytesBeforeLast <= 3U) { /* 0-28 bit number */
  652. PRUint32 n = 0;
  653. PRUint32 c;
  654. #define CGET(i, m) \
  655. c = last[-i] & m; \
  656. n |= c << (7 * i)
  657. #define CASE(i, m) \
  658. case i: \
  659. CGET(i, m); \
  660. if (!n) \
  661. goto unsupported /* fall-through */
  662. switch (bytesBeforeLast) {
  663. CASE(3, 0x7f);
  664. CASE(2, 0x7f);
  665. CASE(1, 0x7f);
  666. case 0:
  667. n |= last[0] & 0x7f;
  668. break;
  669. }
  670. if (last[0] & 0x80) {
  671. goto unsupported;
  672. }
  673. if (!rvString) {
  674. /* This is the first number.. decompose it */
  675. PRUint32 one = PR_MIN(n / 40, 2); /* never > 2 */
  676. PRUint32 two = n - (one * 40);
  677. rvString = PR_smprintf("OID.%lu.%lu", one, two);
  678. } else {
  679. prefix = rvString;
  680. rvString = PR_smprintf("%s.%lu", prefix, n);
  681. }
  682. } else if (bytesBeforeLast <= 9U) { /* 29-64 bit number */
  683. PRUint64 n = 0;
  684. PRUint64 c;
  685. switch (bytesBeforeLast) {
  686. CASE(9, 0x01);
  687. CASE(8, 0x7f);
  688. CASE(7, 0x7f);
  689. CASE(6, 0x7f);
  690. CASE(5, 0x7f);
  691. CASE(4, 0x7f);
  692. CGET(3, 0x7f);
  693. CGET(2, 0x7f);
  694. CGET(1, 0x7f);
  695. CGET(0, 0x7f);
  696. break;
  697. }
  698. if (last[0] & 0x80)
  699. goto unsupported;
  700. if (!rvString) {
  701. /* This is the first number.. decompose it */
  702. PRUint64 one = PR_MIN(n / 40, 2); /* never > 2 */
  703. PRUint64 two = n - (one * 40);
  704. rvString = PR_smprintf("OID.%llu.%llu", one, two);
  705. } else {
  706. prefix = rvString;
  707. rvString = PR_smprintf("%s.%llu", prefix, n);
  708. }
  709. } else {
  710. /* More than a 64-bit number, or not minimal encoding. */
  711. unsupported:
  712. if (!rvString)
  713. rvString = PR_smprintf("OID.UNSUPPORTED");
  714. else {
  715. prefix = rvString;
  716. rvString = PR_smprintf("%s.UNSUPPORTED", prefix);
  717. }
  718. }
  719. if (prefix) {
  720. PR_smprintf_free(prefix);
  721. prefix = NULL;
  722. }
  723. if (!rvString) {
  724. PORT_SetError(SEC_ERROR_NO_MEMORY);
  725. break;
  726. }
  727. }
  728. return rvString;
  729. }
  730. /* convert DER-encoded hex to a string */
  731. static SECItem*
  732. get_hex_string(SECItem* data)
  733. {
  734. SECItem* rv;
  735. unsigned int i, j;
  736. static const char hex[] = { "0123456789ABCDEF" };
  737. /* '#' + 2 chars per octet + terminator */
  738. rv = SECITEM_AllocItem(NULL, NULL, data->len * 2 + 2);
  739. if (!rv) {
  740. return NULL;
  741. }
  742. rv->data[0] = '#';
  743. rv->len = 1 + 2 * data->len;
  744. for (i = 0; i < data->len; i++) {
  745. j = data->data[i];
  746. rv->data[2 * i + 1] = hex[j >> 4];
  747. rv->data[2 * i + 2] = hex[j & 15];
  748. }
  749. rv->data[rv->len] = 0;
  750. return rv;
  751. }
  752. /* For compliance with RFC 2253, RFC 3280 and RFC 4630, we choose to
  753. * use the NAME=STRING form, rather than the OID.N.N=#hexXXXX form,
  754. * when both of these conditions are met:
  755. * 1) The attribute name OID (kind) has a known name string that is
  756. * defined in one of those RFCs, or in RFCs that they cite, AND
  757. * 2) The attribute's value encoding is RFC compliant for the kind
  758. * (e.g., the value's encoding tag is correct for the kind, and
  759. * the value's length is in the range allowed for the kind, and
  760. * the value's contents are appropriate for the encoding tag).
  761. * Otherwise, we use the OID.N.N=#hexXXXX form.
  762. *
  763. * If the caller prefers maximum human readability to RFC compliance,
  764. * then
  765. * - We print the kind in NAME= string form if we know the name
  766. * string for the attribute type OID, regardless of whether the
  767. * value is correctly encoded or not. else we use the OID.N.N= form.
  768. * - We use the non-hex STRING form for the attribute value if the
  769. * value can be represented in such a form. Otherwise, we use
  770. * the hex string form.
  771. * This implies that, for maximum human readability, in addition to
  772. * the two forms allowed by the RFC, we allow two other forms of output:
  773. * - the OID.N.N=STRING form, and
  774. * - the NAME=#hexXXXX form
  775. * When the caller prefers maximum human readability, we do not allow
  776. * the value of any attribute to exceed the length allowed by the RFC.
  777. * If the attribute value exceeds the allowed length, we truncate it to
  778. * the allowed length and append "...".
  779. * Also in this case, we arbitrarily impose a limit on the length of the
  780. * entire AVA encoding, regardless of the form, of 384 bytes per AVA.
  781. * This limit includes the trailing NULL character. If the encoded
  782. * AVA length exceeds that limit, this function reports failure to encode
  783. * the AVA.
  784. *
  785. * An ASCII representation of an AVA is said to be "invertible" if
  786. * conversion back to DER reproduces the original DER encoding exactly.
  787. * The RFC 2253 rules do not ensure that all ASCII AVAs derived according
  788. * to its rules are invertible. That is because the RFCs allow some
  789. * attribute values to be encoded in any of a number of encodings,
  790. * and the encoding type information is lost in the non-hex STRING form.
  791. * This is particularly true of attributes of type DirectoryString.
  792. * The encoding type information is always preserved in the hex string
  793. * form, because the hex includes the entire DER encoding of the value.
  794. *
  795. * So, when the caller perfers maximum invertibility, we apply the
  796. * RFC compliance rules stated above, and add a third required
  797. * condition on the use of the NAME=STRING form.
  798. * 3) The attribute's kind is not is allowed to be encoded in any of
  799. * several different encodings, such as DirectoryStrings.
  800. *
  801. * The chief difference between CERT_N2A_STRICT and CERT_N2A_INVERTIBLE
  802. * is that the latter forces DirectoryStrings to be hex encoded.
  803. *
  804. * As a simplification, we assume the value is correctly encoded for
  805. * its encoding type. That is, we do not test that all the characters
  806. * in a string encoded type are allowed by that type. We assume it.
  807. */
  808. static SECStatus
  809. AppendAVA(stringBuf* bufp, CERTAVA* ava, CertStrictnessLevel strict)
  810. {
  811. #define TMPBUF_LEN 2048
  812. const NameToKind* pn2k = name2kinds;
  813. SECItem* avaValue = NULL;
  814. char* unknownTag = NULL;
  815. char* encodedAVA = NULL;
  816. PRBool useHex = PR_FALSE; /* use =#hexXXXX form */
  817. PRBool truncateName = PR_FALSE;
  818. PRBool truncateValue = PR_FALSE;
  819. SECOidTag endKind;
  820. SECStatus rv;
  821. unsigned int len;
  822. unsigned int nameLen, valueLen;
  823. unsigned int maxName, maxValue;
  824. EQMode mode = minimalEscapeAndQuote;
  825. NameToKind n2k = { NULL, 32767, SEC_OID_UNKNOWN, SEC_ASN1_DS };
  826. char tmpBuf[TMPBUF_LEN];
  827. #define tagName n2k.name /* non-NULL means use NAME= form */
  828. #define maxBytes n2k.maxLen
  829. #define tag n2k.kind
  830. #define vt n2k.valueType
  831. /* READABLE mode recognizes more names from the name2kinds table
  832. * than do STRICT or INVERTIBLE modes. This assignment chooses the
  833. * point in the table where the attribute type name scanning stops.
  834. */
  835. endKind = (strict == CERT_N2A_READABLE) ? SEC_OID_UNKNOWN
  836. : SEC_OID_AVA_POSTAL_ADDRESS;
  837. tag = CERT_GetAVATag(ava);
  838. while (pn2k->kind != tag && pn2k->kind != endKind) {
  839. ++pn2k;
  840. }
  841. if (pn2k->kind != endKind) {
  842. n2k = *pn2k;
  843. } else if (strict != CERT_N2A_READABLE) {
  844. useHex = PR_TRUE;
  845. }
  846. /* For invertable form, force Directory Strings to use hex form. */
  847. if (strict == CERT_N2A_INVERTIBLE && vt == SEC_ASN1_DS) {
  848. tagName = NULL; /* must use OID.N form */
  849. useHex = PR_TRUE; /* must use hex string */
  850. }
  851. if (!useHex) {
  852. avaValue = CERT_DecodeAVAValue(&ava->value);
  853. if (!avaValue) {
  854. useHex = PR_TRUE;
  855. if (strict != CERT_N2A_READABLE) {
  856. tagName = NULL; /* must use OID.N form */
  857. }
  858. }
  859. }
  860. if (!tagName) {
  861. /* handle unknown attribute types per RFC 2253 */
  862. tagName = unknownTag = CERT_GetOidString(&ava->type);
  863. if (!tagName) {
  864. if (avaValue)
  865. SECITEM_FreeItem(avaValue, PR_TRUE);
  866. return SECFailure;
  867. }
  868. }
  869. if (useHex) {
  870. avaValue = get_hex_string(&ava->value);
  871. if (!avaValue) {
  872. if (unknownTag)
  873. PR_smprintf_free(unknownTag);
  874. return SECFailure;
  875. }
  876. }
  877. nameLen = strlen(tagName);
  878. valueLen =
  879. (useHex ? avaValue->len : cert_RFC1485_GetRequiredLen(
  880. (char*)avaValue->data, avaValue->len, &mode));
  881. len = nameLen + valueLen + 2; /* Add 2 for '=' and trailing NUL */
  882. maxName = nameLen;
  883. maxValue = valueLen;
  884. if (len <= sizeof(tmpBuf)) {
  885. encodedAVA = tmpBuf;
  886. } else if (strict != CERT_N2A_READABLE) {
  887. encodedAVA = PORT_Alloc(len);
  888. if (!encodedAVA) {
  889. SECITEM_FreeItem(avaValue, PR_TRUE);
  890. if (unknownTag)
  891. PR_smprintf_free(unknownTag);
  892. return SECFailure;
  893. }
  894. } else {
  895. /* Must make output fit in tmpbuf */
  896. unsigned int fair = (sizeof tmpBuf) / 2 - 1; /* for = and \0 */
  897. if (nameLen < fair) {
  898. /* just truncate the value */
  899. maxValue = (sizeof tmpBuf) - (nameLen + 6); /* for "=...\0",
  900. and possibly '"' */
  901. } else if (valueLen < fair) {
  902. /* just truncate the name */
  903. maxName = (sizeof tmpBuf) - (valueLen + 5); /* for "=...\0" */
  904. } else {
  905. /* truncate both */
  906. maxName = maxValue = fair - 3; /* for "..." */
  907. }
  908. if (nameLen > maxName) {
  909. PORT_Assert(unknownTag && unknownTag == tagName);
  910. truncateName = PR_TRUE;
  911. nameLen = maxName;
  912. }
  913. encodedAVA = tmpBuf;
  914. }
  915. memcpy(encodedAVA, tagName, nameLen);
  916. if (truncateName) {
  917. /* If tag name is too long, we know it is an OID form that was
  918. * allocated from the heap, so we can modify it in place
  919. */
  920. encodedAVA[nameLen - 1] = '.';
  921. encodedAVA[nameLen - 2] = '.';
  922. encodedAVA[nameLen - 3] = '.';
  923. }
  924. encodedAVA[nameLen++] = '=';
  925. if (unknownTag)
  926. PR_smprintf_free(unknownTag);
  927. if (strict == CERT_N2A_READABLE && maxValue > maxBytes)
  928. maxValue = maxBytes;
  929. if (valueLen > maxValue) {
  930. valueLen = maxValue;
  931. truncateValue = PR_TRUE;
  932. }
  933. /* escape and quote as necessary - don't quote hex strings */
  934. if (useHex) {
  935. char* end = encodedAVA + nameLen + valueLen;
  936. memcpy(encodedAVA + nameLen, (char*)avaValue->data, valueLen);
  937. end[0] = '\0';
  938. if (truncateValue) {
  939. end[-1] = '.';
  940. end[-2] = '.';
  941. end[-3] = '.';
  942. }
  943. rv = SECSuccess;
  944. } else if (!truncateValue) {
  945. rv = escapeAndQuote(encodedAVA + nameLen, len - nameLen,
  946. (char*)avaValue->data, avaValue->len, &mode);
  947. } else {
  948. /* must truncate the escaped and quoted value */
  949. char bigTmpBuf[TMPBUF_LEN * 3 + 3];
  950. PORT_Assert(valueLen < sizeof tmpBuf);
  951. rv = escapeAndQuote(bigTmpBuf, sizeof bigTmpBuf, (char*)avaValue->data,
  952. PR_MIN(avaValue->len, valueLen), &mode);
  953. bigTmpBuf[valueLen--] = '\0'; /* hard stop here */
  954. /* See if we're in the middle of a multi-byte UTF8 character */
  955. while (((bigTmpBuf[valueLen] & 0xc0) == 0x80) && valueLen > 0) {
  956. bigTmpBuf[valueLen--] = '\0';
  957. }
  958. /* add ellipsis to signify truncation. */
  959. bigTmpBuf[++valueLen] = '.';
  960. bigTmpBuf[++valueLen] = '.';
  961. bigTmpBuf[++valueLen] = '.';
  962. if (bigTmpBuf[0] == '"')
  963. bigTmpBuf[++valueLen] = '"';
  964. bigTmpBuf[++valueLen] = '\0';
  965. PORT_Assert(nameLen + valueLen <= (sizeof tmpBuf) - 1);
  966. memcpy(encodedAVA + nameLen, bigTmpBuf, valueLen + 1);
  967. }
  968. SECITEM_FreeItem(avaValue, PR_TRUE);
  969. if (rv == SECSuccess)
  970. rv = AppendStr(bufp, encodedAVA);
  971. if (encodedAVA != tmpBuf)
  972. PORT_Free(encodedAVA);
  973. return rv;
  974. }
  975. #undef tagName
  976. #undef maxBytes
  977. #undef tag
  978. #undef vt
  979. char*
  980. CERT_NameToAsciiInvertible(CERTName* name, CertStrictnessLevel strict)
  981. {
  982. CERTRDN** rdns;
  983. CERTRDN** lastRdn;
  984. CERTRDN** rdn;
  985. PRBool first = PR_TRUE;
  986. stringBuf strBuf = { NULL, 0, 0 };
  987. rdns = name->rdns;
  988. if (rdns == NULL) {
  989. return NULL;
  990. }
  991. /* find last RDN */
  992. lastRdn = rdns;
  993. while (*lastRdn)
  994. lastRdn++;
  995. lastRdn--;
  996. /*
  997. * Loop over name contents in _reverse_ RDN order appending to string
  998. */
  999. for (rdn = lastRdn; rdn >= rdns; rdn--) {
  1000. CERTAVA** avas = (*rdn)->avas;
  1001. CERTAVA* ava;
  1002. PRBool newRDN = PR_TRUE;
  1003. /*
  1004. * XXX Do we need to traverse the AVAs in reverse order, too?
  1005. */
  1006. while (avas && (ava = *avas++) != NULL) {
  1007. SECStatus rv;
  1008. /* Put in comma or plus separator */
  1009. if (!first) {
  1010. /* Use of spaces is deprecated in RFC 2253. */
  1011. rv = AppendStr(&strBuf, newRDN ? "," : "+");
  1012. if (rv)
  1013. goto loser;
  1014. } else {
  1015. first = PR_FALSE;
  1016. }
  1017. /* Add in tag type plus value into strBuf */
  1018. rv = AppendAVA(&strBuf, ava, strict);
  1019. if (rv)
  1020. goto loser;
  1021. newRDN = PR_FALSE;
  1022. }
  1023. }
  1024. return strBuf.buffer;
  1025. loser:
  1026. if (strBuf.buffer) {
  1027. PORT_Free(strBuf.buffer);
  1028. }
  1029. return NULL;
  1030. }
  1031. char*
  1032. CERT_NameToAscii(CERTName* name)
  1033. {
  1034. return CERT_NameToAsciiInvertible(name, CERT_N2A_READABLE);
  1035. }
  1036. /*
  1037. * Return the string representation of a DER encoded distinguished name
  1038. * "dername" - The DER encoded name to convert
  1039. */
  1040. char*
  1041. CERT_DerNameToAscii(SECItem* dername)
  1042. {
  1043. int rv;
  1044. PLArenaPool* arena = NULL;
  1045. CERTName name;
  1046. char* retstr = NULL;
  1047. arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  1048. if (arena == NULL) {
  1049. goto loser;
  1050. }
  1051. rv = SEC_QuickDERDecodeItem(arena, &name, CERT_NameTemplate, dername);
  1052. if (rv != SECSuccess) {
  1053. goto loser;
  1054. }
  1055. retstr = CERT_NameToAscii(&name);
  1056. loser:
  1057. if (arena != NULL) {
  1058. PORT_FreeArena(arena, PR_FALSE);
  1059. }
  1060. return (retstr);
  1061. }
  1062. static char*
  1063. avaToString(PLArenaPool* arena, CERTAVA* ava)
  1064. {
  1065. char* buf = NULL;
  1066. SECItem* avaValue;
  1067. int valueLen;
  1068. avaValue = CERT_DecodeAVAValue(&ava->value);
  1069. if (!avaValue) {
  1070. return buf;
  1071. }
  1072. valueLen =
  1073. cert_RFC1485_GetRequiredLen((char*)avaValue->data, avaValue->len, NULL) + 1;
  1074. if (arena) {
  1075. buf = (char*)PORT_ArenaZAlloc(arena, valueLen);
  1076. } else {
  1077. buf = (char*)PORT_ZAlloc(valueLen);
  1078. }
  1079. if (buf) {
  1080. SECStatus rv =
  1081. escapeAndQuote(buf, valueLen, (char*)avaValue->data, avaValue->len, NULL);
  1082. if (rv != SECSuccess) {
  1083. if (!arena)
  1084. PORT_Free(buf);
  1085. buf = NULL;
  1086. }
  1087. }
  1088. SECITEM_FreeItem(avaValue, PR_TRUE);
  1089. return buf;
  1090. }
  1091. /* RDNs are sorted from most general to most specific.
  1092. * This code returns the FIRST one found, the most general one found.
  1093. */
  1094. static char*
  1095. CERT_GetNameElement(PLArenaPool* arena, const CERTName* name, int wantedTag)
  1096. {
  1097. CERTRDN** rdns = name->rdns;
  1098. CERTRDN* rdn;
  1099. CERTAVA* ava = NULL;
  1100. while (rdns && (rdn = *rdns++) != 0) {
  1101. CERTAVA** avas = rdn->avas;
  1102. while (avas && (ava = *avas++) != 0) {
  1103. int tag = CERT_GetAVATag(ava);
  1104. if (tag == wantedTag) {
  1105. avas = NULL;
  1106. rdns = NULL; /* break out of all loops */
  1107. }
  1108. }
  1109. }
  1110. return ava ? avaToString(arena, ava) : NULL;
  1111. }
  1112. /* RDNs are sorted from most general to most specific.
  1113. * This code returns the LAST one found, the most specific one found.
  1114. * This is particularly appropriate for Common Name. See RFC 2818.
  1115. */
  1116. static char*
  1117. CERT_GetLastNameElement(PLArenaPool* arena, const CERTName* name, int wantedTag)
  1118. {
  1119. CERTRDN** rdns = name->rdns;
  1120. CERTRDN* rdn;
  1121. CERTAVA* lastAva = NULL;
  1122. while (rdns && (rdn = *rdns++) != 0) {
  1123. CERTAVA** avas = rdn->avas;
  1124. CERTAVA* ava;
  1125. while (avas && (ava = *avas++) != 0) {
  1126. int tag = CERT_GetAVATag(ava);
  1127. if (tag == wantedTag) {
  1128. lastAva = ava;
  1129. }
  1130. }
  1131. }
  1132. return lastAva ? avaToString(arena, lastAva) : NULL;
  1133. }
  1134. char*
  1135. CERT_GetCertificateEmailAddress(CERTCertificate* cert)
  1136. {
  1137. char* rawEmailAddr = NULL;
  1138. SECItem subAltName;
  1139. SECStatus rv;
  1140. CERTGeneralName* nameList = NULL;
  1141. CERTGeneralName* current;
  1142. PLArenaPool* arena = NULL;
  1143. int i;
  1144. subAltName.data = NULL;
  1145. rawEmailAddr = CERT_GetNameElement(cert->arena, &(cert->subject),
  1146. SEC_OID_PKCS9_EMAIL_ADDRESS);
  1147. if (rawEmailAddr == NULL) {
  1148. rawEmailAddr =
  1149. CERT_GetNameElement(cert->arena, &(cert->subject), SEC_OID_RFC1274_MAIL);
  1150. }
  1151. if (rawEmailAddr == NULL) {
  1152. rv =
  1153. CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, &subAltName);
  1154. if (rv != SECSuccess) {
  1155. goto finish;
  1156. }
  1157. arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  1158. if (!arena) {
  1159. goto finish;
  1160. }
  1161. nameList = current = CERT_DecodeAltNameExtension(arena, &subAltName);
  1162. if (!nameList) {
  1163. goto finish;
  1164. }
  1165. if (nameList != NULL) {
  1166. do {
  1167. if (current->type == certDirectoryName) {
  1168. rawEmailAddr =
  1169. CERT_GetNameElement(cert->arena, &(current->name.directoryName),
  1170. SEC_OID_PKCS9_EMAIL_ADDRESS);
  1171. if (rawEmailAddr ==
  1172. NULL) {
  1173. rawEmailAddr =
  1174. CERT_GetNameElement(cert->arena, &(current->name.directoryName),
  1175. SEC_OID_RFC1274_MAIL);
  1176. }
  1177. } else if (current->type == certRFC822Name) {
  1178. rawEmailAddr =
  1179. (char*)PORT_ArenaZAlloc(cert->arena, current->name.other.len + 1);
  1180. if (!rawEmailAddr) {
  1181. goto finish;
  1182. }
  1183. PORT_Memcpy(rawEmailAddr, current->name.other.data,
  1184. current->name.other.len);
  1185. rawEmailAddr[current->name.other.len] =
  1186. '\0';
  1187. }
  1188. if (rawEmailAddr) {
  1189. break;
  1190. }
  1191. current = CERT_GetNextGeneralName(current);
  1192. } while (current != nameList);
  1193. }
  1194. }
  1195. if (rawEmailAddr) {
  1196. for (i = 0; i <= (int)PORT_Strlen(rawEmailAddr); i++) {
  1197. rawEmailAddr[i] = tolower(rawEmailAddr[i]);
  1198. }
  1199. }
  1200. finish:
  1201. /* Don't free nameList, it's part of the arena. */
  1202. if (arena) {
  1203. PORT_FreeArena(arena, PR_FALSE);
  1204. }
  1205. if (subAltName.data) {
  1206. SECITEM_FreeItem(&subAltName, PR_FALSE);
  1207. }
  1208. return (rawEmailAddr);
  1209. }
  1210. static char*
  1211. appendStringToBuf(char* dest, char* src, PRUint32* pRemaining)
  1212. {
  1213. PRUint32 len;
  1214. if (dest && src && src[0] && *pRemaining > (len = PL_strlen(src))) {
  1215. PRUint32 i;
  1216. for (i = 0; i < len; ++i)
  1217. dest[i] = tolower(src[i]);
  1218. dest[len] = 0;
  1219. dest += len + 1;
  1220. *pRemaining -= len + 1;
  1221. }
  1222. return dest;
  1223. }
  1224. #undef NEEDS_HEX_ESCAPE
  1225. #define NEEDS_HEX_ESCAPE(c) (c < 0x20)
  1226. static char*
  1227. appendItemToBuf(char* dest, SECItem* src, PRUint32* pRemaining)
  1228. {
  1229. if (dest && src && src->data && src->len && src->data[0]) {
  1230. PRUint32 len = src->len;
  1231. PRUint32 i;
  1232. PRUint32 reqLen = len + 1;
  1233. /* are there any embedded control characters ? */
  1234. for (i = 0; i < len; i++) {
  1235. if (NEEDS_HEX_ESCAPE(src->data[i]))
  1236. reqLen += 2;
  1237. }
  1238. if (*pRemaining > reqLen) {
  1239. for (i = 0; i < len; ++i) {
  1240. PRUint8 c = src->data[i];
  1241. if (NEEDS_HEX_ESCAPE(c)) {
  1242. *dest++ =
  1243. C_BACKSLASH;
  1244. *dest++ =
  1245. hexChars[(c >> 4) & 0x0f];
  1246. *dest++ =
  1247. hexChars[c & 0x0f];
  1248. } else {
  1249. *dest++ =
  1250. tolower(c);
  1251. }
  1252. }
  1253. *dest++ = '\0';
  1254. *pRemaining -= reqLen;
  1255. }
  1256. }
  1257. return dest;
  1258. }
  1259. /* Returns a pointer to an environment-like string, a series of
  1260. ** null-terminated strings, terminated by a zero-length string.
  1261. ** This function is intended to be internal to NSS.
  1262. */
  1263. char*
  1264. cert_GetCertificateEmailAddresses(CERTCertificate* cert)
  1265. {
  1266. char* rawEmailAddr = NULL;
  1267. char* addrBuf = NULL;
  1268. char* pBuf = NULL;
  1269. PORTCheapArenaPool tmpArena;
  1270. PRUint32 maxLen = 0;
  1271. PRInt32 finalLen = 0;
  1272. SECStatus rv;
  1273. SECItem subAltName;
  1274. PORT_InitCheapArena(&tmpArena, DER_DEFAULT_CHUNKSIZE);
  1275. subAltName.data = NULL;
  1276. maxLen = cert->derCert.len;
  1277. PORT_Assert(maxLen);
  1278. if (!maxLen)
  1279. maxLen = 2000; /* a guess, should never happen */
  1280. pBuf = addrBuf = (char*)PORT_ArenaZAlloc(&tmpArena.arena, maxLen + 1);
  1281. if (!addrBuf)
  1282. goto loser;
  1283. rawEmailAddr = CERT_GetNameElement(&tmpArena.arena, &cert->subject,
  1284. SEC_OID_PKCS9_EMAIL_ADDRESS);
  1285. pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
  1286. rawEmailAddr = CERT_GetNameElement(&tmpArena.arena, &cert->subject,
  1287. SEC_OID_RFC1274_MAIL);
  1288. pBuf = appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
  1289. rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, &subAltName);
  1290. if (rv == SECSuccess && subAltName.data) {
  1291. CERTGeneralName* nameList = NULL;
  1292. if (!!(nameList = CERT_DecodeAltNameExtension(&tmpArena.arena, &subAltName))) {
  1293. CERTGeneralName* current = nameList;
  1294. do {
  1295. if (current->type == certDirectoryName) {
  1296. rawEmailAddr =
  1297. CERT_GetNameElement(&tmpArena.arena,
  1298. &current->name.directoryName,
  1299. SEC_OID_PKCS9_EMAIL_ADDRESS);
  1300. pBuf =
  1301. appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
  1302. rawEmailAddr =
  1303. CERT_GetNameElement(&tmpArena.arena,
  1304. &current->name.directoryName,
  1305. SEC_OID_RFC1274_MAIL);
  1306. pBuf =
  1307. appendStringToBuf(pBuf, rawEmailAddr, &maxLen);
  1308. } else if (current->type == certRFC822Name) {
  1309. pBuf =
  1310. appendItemToBuf(pBuf, &current->name.other, &maxLen);
  1311. }
  1312. current = CERT_GetNextGeneralName(current);
  1313. } while (current != nameList);
  1314. }
  1315. SECITEM_FreeItem(&subAltName, PR_FALSE);
  1316. /* Don't free nameList, it's part of the tmpArena. */
  1317. }
  1318. /* now copy superstring to cert's arena */
  1319. finalLen = (pBuf - addrBuf) + 1;
  1320. pBuf = NULL;
  1321. if (finalLen > 1) {
  1322. pBuf = PORT_ArenaAlloc(cert->arena, finalLen);
  1323. if (pBuf) {
  1324. PORT_Memcpy(pBuf, addrBuf, finalLen);
  1325. }
  1326. }
  1327. loser:
  1328. PORT_DestroyCheapArena(&tmpArena);
  1329. return pBuf;
  1330. }
  1331. /* returns pointer to storage in cert's arena. Storage remains valid
  1332. ** as long as cert's reference count doesn't go to zero.
  1333. ** Caller should strdup or otherwise copy.
  1334. */
  1335. const char* /* const so caller won't muck with it. */
  1336. CERT_GetFirstEmailAddress(CERTCertificate* cert)
  1337. {
  1338. if (cert && cert->emailAddr && cert->emailAddr[0])
  1339. return (const char*)cert->emailAddr;
  1340. return NULL;
  1341. }
  1342. /* returns pointer to storage in cert's arena. Storage remains valid
  1343. ** as long as cert's reference count doesn't go to zero.
  1344. ** Caller should strdup or otherwise copy.
  1345. */
  1346. const char* /* const so caller won't muck with it. */
  1347. CERT_GetNextEmailAddress(CERTCertificate* cert, const char* prev)
  1348. {
  1349. if (cert && prev && prev[0]) {
  1350. PRUint32 len = PL_strlen(prev);
  1351. prev += len + 1;
  1352. if (prev && prev[0])
  1353. return prev;
  1354. }
  1355. return NULL;
  1356. }
  1357. /* This is seriously bogus, now that certs store their email addresses in
  1358. ** subject Alternative Name extensions.
  1359. ** Returns a string allocated by PORT_StrDup, which the caller must free.
  1360. */
  1361. char*
  1362. CERT_GetCertEmailAddress(const CERTName* name)
  1363. {
  1364. char* rawEmailAddr;
  1365. char* emailAddr;
  1366. rawEmailAddr = CERT_GetNameElement(NULL, name, SEC_OID_PKCS9_EMAIL_ADDRESS);
  1367. if (rawEmailAddr == NULL) {
  1368. rawEmailAddr = CERT_GetNameElement(NULL, name, SEC_OID_RFC1274_MAIL);
  1369. }
  1370. emailAddr = CERT_FixupEmailAddr(rawEmailAddr);
  1371. if (rawEmailAddr) {
  1372. PORT_Free(rawEmailAddr);
  1373. }
  1374. return (emailAddr);
  1375. }
  1376. /* The return value must be freed with PORT_Free. */
  1377. char*
  1378. CERT_GetCommonName(const CERTName* name)
  1379. {
  1380. return (CERT_GetLastNameElement(NULL, name, SEC_OID_AVA_COMMON_NAME));
  1381. }
  1382. char*
  1383. CERT_GetCountryName(const CERTName* name)
  1384. {
  1385. return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_COUNTRY_NAME));
  1386. }
  1387. char*
  1388. CERT_GetLocalityName(const CERTName* name)
  1389. {
  1390. return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_LOCALITY));
  1391. }
  1392. char*
  1393. CERT_GetStateName(const CERTName* name)
  1394. {
  1395. return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_STATE_OR_PROVINCE));
  1396. }
  1397. char*
  1398. CERT_GetOrgName(const CERTName* name)
  1399. {
  1400. return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_ORGANIZATION_NAME));
  1401. }
  1402. char*
  1403. CERT_GetDomainComponentName(const CERTName* name)
  1404. {
  1405. return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_DC));
  1406. }
  1407. char*
  1408. CERT_GetOrgUnitName(const CERTName* name)
  1409. {
  1410. return (
  1411. CERT_GetNameElement(NULL, name, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME));
  1412. }
  1413. char*
  1414. CERT_GetDnQualifier(const CERTName* name)
  1415. {
  1416. return (CERT_GetNameElement(NULL, name, SEC_OID_AVA_DN_QUALIFIER));
  1417. }
  1418. char*
  1419. CERT_GetCertUid(const CERTName* name)
  1420. {
  1421. return (CERT_GetNameElement(NULL, name, SEC_OID_RFC1274_UID));
  1422. }