File Coverage

inc/matrixssl-3-9-3-open/crypto/keyformat/x509.c
Criterion Covered Total %
statement 1026 2577 39.8
branch 516 1872 27.5
condition n/a
subroutine n/a
pod n/a
total 1542 4449 34.6


line stmt bran cond sub pod time code
1             /**
2             * @file x509.c
3             * @version 950bba4 (HEAD -> master)
4             *
5             * X.509 Parser.
6             */
7             /*
8             * Copyright (c) 2013-2017 INSIDE Secure Corporation
9             * Copyright (c) PeerSec Networks, 2002-2011
10             * All Rights Reserved
11             *
12             * The latest version of this code is available at http://www.matrixssl.org
13             *
14             * This software is open source; you can redistribute it and/or modify
15             * it under the terms of the GNU General Public License as published by
16             * the Free Software Foundation; either version 2 of the License, or
17             * (at your option) any later version.
18             *
19             * This General Public License does NOT permit incorporating this software
20             * into proprietary programs. If you are unable to comply with the GPL, a
21             * commercial license for this software may be purchased from INSIDE at
22             * http://www.insidesecure.com/
23             *
24             * This program is distributed in WITHOUT ANY WARRANTY; without even the
25             * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
26             * See the GNU General Public License for more details.
27             *
28             * You should have received a copy of the GNU General Public License
29             * along with this program; if not, write to the Free Software
30             * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31             * http://www.gnu.org/copyleft/gpl.html
32             */
33             /******************************************************************************/
34              
35             #include "../cryptoImpl.h"
36              
37             #ifdef USE_X509
38              
39             /******************************************************************************/
40              
41             # ifdef POSIX
42             # include
43             # endif
44              
45             /******************************************************************************/
46              
47             # define MAX_CERTS_PER_FILE 16
48              
49             /* Maximum time length accepted.
50             Allows RFC 5280 format time + nanosecond fractional time + non-Zulu time. */
51             # define MAX_TIME_LEN 32
52              
53             # ifdef USE_CERT_PARSE
54             /*
55             Certificate extensions
56             */
57             # define IMPLICIT_ISSUER_ID 1
58             # define IMPLICIT_SUBJECT_ID 2
59             # define EXPLICIT_EXTENSION 3
60              
61             /*
62             Distinguished Name attributes
63             */
64             # define ATTRIB_COMMON_NAME 3
65             # define ATTRIB_SURNAME 4
66             # define ATTRIB_SERIALNUMBER 5
67             # define ATTRIB_COUNTRY_NAME 6
68             # define ATTRIB_LOCALITY 7
69             # define ATTRIB_STATE_PROVINCE 8
70             # define ATTRIB_STREET_ADDRESS 9
71             # define ATTRIB_ORGANIZATION 10
72             # define ATTRIB_ORG_UNIT 11
73             # define ATTRIB_TITLE 12
74             # define ATTRIB_POSTAL_ADDRESS 16
75             # define ATTRIB_TELEPHONE_NUMBER 20
76             # define ATTRIB_NAME 41
77             # define ATTRIB_GIVEN_NAME 42
78             # define ATTRIB_INITIALS 43
79             # define ATTRIB_GEN_QUALIFIER 44
80             # define ATTRIB_DN_QUALIFIER 46
81             # define ATTRIB_PSEUDONYM 65
82              
83             # define ATTRIB_DOMAIN_COMPONENT 25
84             # define ATTRIB_UID 26
85             # define ATTRIB_EMAIL 27
86              
87             /** Enumerate X.509 milestones for issuedBefore() api */
88             typedef enum
89             {
90             RFC_6818, /* January 2013 X.509 Updates Below */
91             RFC_5280, /* May 2008 X.509 Obsoletes Below */
92             RFC_3280, /* April 2002 X.509 Obsoletes Below */
93             RFC_2459, /* January 1999 X.509 First RFC */
94             X509_V3, /* 1996 X.509v3 Pre-RFC */
95             X509_V2, /* 1993 X.509v2 Pre-RFC */
96             X509_V1, /* 1988 X.509v1 Pre-RFC */
97             } rfc_e;
98              
99             # ifdef USE_CRYPTO_TRACE
100             # define OID_LIST(A, B) { { A, B }, #B, oid_ ## B }
101             # else
102             # define OID_LIST(A, B) { { A, B }, oid_ ## B }
103             # endif
104             static const struct
105             {
106             uint16_t oid[MAX_OID_LEN];
107             # ifdef USE_CRYPTO_TRACE
108             char name[32];
109             # endif
110             int id;
111             } oid_list[] = {
112             /* X.509 certificate extensions */
113             OID_LIST(id_ce, id_ce_authorityKeyIdentifier),
114             OID_LIST(id_ce, id_ce_subjectKeyIdentifier),
115             OID_LIST(id_ce, id_ce_keyUsage),
116             OID_LIST(id_ce, id_ce_certificatePolicies),
117             OID_LIST(id_ce, id_ce_policyMappings),
118             OID_LIST(id_ce, id_ce_subjectAltName),
119             OID_LIST(id_ce, id_ce_issuerAltName),
120             OID_LIST(id_ce, id_ce_subjectDirectoryAttributes),
121             OID_LIST(id_ce, id_ce_basicConstraints),
122             OID_LIST(id_ce, id_ce_nameConstraints),
123             OID_LIST(id_ce, id_ce_policyConstraints),
124             OID_LIST(id_ce, id_ce_extKeyUsage),
125             OID_LIST(id_ce, id_ce_cRLDistributionPoints),
126             OID_LIST(id_ce, id_ce_cRLNumber),
127             OID_LIST(id_ce, id_ce_issuingDistributionPoint),
128             OID_LIST(id_ce, id_ce_inhibitAnyPolicy),
129             OID_LIST(id_ce, id_ce_freshestCRL),
130             OID_LIST(id_pe, id_pe_authorityInfoAccess),
131             OID_LIST(id_pe, id_pe_subjectInfoAccess),
132             /* Extended Key Usage */
133             OID_LIST(id_ce_eku, id_ce_eku_anyExtendedKeyUsage),
134             OID_LIST(id_kp, id_kp_serverAuth),
135             OID_LIST(id_kp, id_kp_clientAuth),
136             OID_LIST(id_kp, id_kp_codeSigning),
137             OID_LIST(id_kp, id_kp_emailProtection),
138             OID_LIST(id_kp, id_kp_timeStamping),
139             OID_LIST(id_kp, id_kp_OCSPSigning),
140             /* policyIdentifiers */
141             OID_LIST(id_qt, id_qt_cps),
142             OID_LIST(id_qt, id_qt_unotice),
143             /* accessDescriptors */
144             OID_LIST(id_ad, id_ad_caIssuers),
145             OID_LIST(id_ad, id_ad_ocsp),
146             /* List terminator */
147             OID_LIST(0, 0),
148             };
149              
150             /*
151             Hybrid ASN.1/X.509 cert parsing helpers
152             */
153             static int32_t getExplicitVersion(const unsigned char **pp, psSize_t len,
154             int32_t expVal, int32_t *val);
155             static int32_t getTimeValidity(psPool_t *pool, const unsigned char **pp,
156             psSize_t len,
157             int32_t *notBeforeTimeType, int32_t *notAfterTimeType,
158             char **notBefore, char **notAfter);
159             static int32_t getImplicitBitString(psPool_t *pool, const unsigned char **pp,
160             psSize_t len, int32_t impVal, unsigned char **bitString,
161             psSize_t *bitLen);
162             static int32_t validateDateRange(psX509Cert_t *cert);
163             static int32_t issuedBefore(rfc_e rfc, const psX509Cert_t *cert);
164              
165             # ifdef USE_RSA
166             static int32_t x509ConfirmSignature(const unsigned char *sigHash,
167             const unsigned char *sigOut, psSize_t sigLen);
168             # endif
169              
170             # endif /* USE_CERT_PARSE */
171              
172             /******************************************************************************/
173             # ifdef MATRIX_USE_FILE_SYSTEM
174             /******************************************************************************/
175              
176             static int32_t pemCertFileBufToX509(psPool_t *pool, const unsigned char *fileBuf,
177             psSize_t fileBufLen, psList_t **x509certList);
178              
179             /******************************************************************************/
180             /*
181             Open a PEM X.509 certificate file and parse it
182              
183             Memory info:
184             Caller must free outcert with psX509FreeCert on function success
185             Caller does not have to free outcert on function failure
186             */
187 777           int32 psX509ParseCertFile(psPool_t *pool, char *fileName,
188             psX509Cert_t **outcert, int32 flags)
189             {
190             int32 fileBufLen, err;
191             unsigned char *fileBuf;
192             psList_t *fileList, *currentFile, *x509list, *frontX509;
193             psX509Cert_t *currentCert, *firstCert, *prevCert;
194 777           int32 numParsed = 0;
195              
196 777           *outcert = NULL;
197             /*
198             First test to see if there are multiple files being passed in.
199             Looking for a semi-colon delimiter
200             */
201 777 50         if ((err = psParseList(pool, fileName, ';', &fileList)) < 0)
202             {
203 0           return err;
204             }
205 777           currentFile = fileList;
206 777           firstCert = prevCert = NULL;
207              
208             /* Recurse each individual file */
209 1552 100         while (currentFile)
210             {
211 777 100         if ((err = psGetFileBuf(pool, (char *) currentFile->item, &fileBuf,
212             &fileBufLen)) < PS_SUCCESS)
213             {
214 1           psFreeList(fileList, pool);
215 1 50         if (firstCert)
216             {
217 0           psX509FreeCert(firstCert);
218             }
219 1           return err;
220             }
221              
222 776 100         if ((err = pemCertFileBufToX509(pool, fileBuf, fileBufLen, &x509list))
223             < PS_SUCCESS)
224             {
225 1           psFreeList(fileList, pool);
226 1           psFree(fileBuf, pool);
227 1 50         if (firstCert)
228             {
229 0           psX509FreeCert(firstCert);
230             }
231 1           return err;
232             }
233 775           psFree(fileBuf, pool);
234              
235 775           frontX509 = x509list;
236             /*
237             Recurse each individual cert buffer from within the file
238              
239             If partial parse of cert bundles is not allowed, the failure
240             to load any of the certificates causes the whole function
241             call to fail. If partial parse of cert bundles is allowed,
242             parse as many as we can and return the number of parsed certs.
243             */
244 2270 100         while (x509list != NULL)
245             {
246 1495           err = psX509ParseCert(pool, x509list->item, x509list->len,
247             ¤tCert, flags);
248 1495 50         if (err < 0)
249             {
250 0 0         if (!(flags & CERT_ALLOW_BUNDLE_PARTIAL_PARSE))
251             {
252 0           psX509FreeCert(currentCert);
253 0           psFreeList(fileList, pool);
254 0           psFreeList(frontX509, pool);
255 0 0         if (firstCert)
256             {
257 0           psX509FreeCert(firstCert);
258             }
259 0           return err;
260             }
261             }
262             else
263             {
264 1495           numParsed++;
265             }
266              
267 1495           x509list = x509list->next;
268 1495 100         if (firstCert == NULL)
269             {
270 775           firstCert = currentCert;
271             }
272             else
273             {
274 720           prevCert->next = currentCert;
275             }
276 1495           prevCert = currentCert;
277 1495           currentCert = currentCert->next;
278             }
279 775           currentFile = currentFile->next;
280 775           psFreeList(frontX509, pool);
281             }
282 775           psFreeList(fileList, pool);
283              
284 775           *outcert = firstCert;
285              
286 777           return numParsed;
287             }
288              
289             /******************************************************************************/
290             /*
291             */
292 776           static int32_t pemCertFileBufToX509(psPool_t *pool, const unsigned char *fileBuf,
293             psSize_t fileBufLen, psList_t **x509certList)
294             {
295             psList_t *front, *prev, *current;
296             unsigned char *start, *end, *endTmp;
297             const unsigned char *chFileBuf;
298             unsigned char l;
299              
300 776           *x509certList = NULL;
301 776           prev = NULL;
302 776 50         if (fileBuf == NULL)
303             {
304             psTraceCrypto("Bad parameters to pemCertFileBufToX509\n");
305 0           return PS_ARG_FAIL;
306             }
307 776           front = current = psMalloc(pool, sizeof(psList_t));
308 776 50         if (current == NULL)
309             {
310 0           psError("Memory allocation error first pemCertFileBufToX509\n");
311 0           return PS_MEM_FAIL;
312             }
313 776           l = strlen("CERTIFICATE-----");
314 776           memset(current, 0x0, sizeof(psList_t));
315 776           chFileBuf = fileBuf;
316 2271 100         while (fileBufLen > 0)
317             {
318 2991 100         if (
319 1495 50         ((start = (unsigned char *) strstr((char *) chFileBuf, "-----BEGIN")) != NULL) &&
320 1495 50         ((start = (unsigned char *) strstr((char *) chFileBuf, "CERTIFICATE-----")) != NULL) &&
321 1495 50         ((end = (unsigned char *) strstr((char *) start, "-----END")) != NULL) &&
322             ((endTmp = (unsigned char *) strstr((char *) end, "CERTIFICATE-----")) != NULL)
323             )
324             {
325 1495           start += l;
326 1495 100         if (current == NULL)
327             {
328 720           current = psMalloc(pool, sizeof(psList_t));
329 720 50         if (current == NULL)
330             {
331 0           psFreeList(front, pool);
332 0           psError("Memory allocation error: pemCertFileBufToX509\n");
333 0           return PS_MEM_FAIL;
334             }
335 720           memset(current, 0x0, sizeof(psList_t));
336 720           prev->next = current;
337             }
338 1495           current->len = (uint16_t) (end - start);
339 1495           end = endTmp + l;
340 2990 50         while (*end == '\x0d' || *end == '\x0a' || *end == '\x09'
    100          
    50          
341 1495 50         || *end == ' ')
342             {
343 1495           end++;
344             }
345             }
346             else
347             {
348 1           psFreeList(front, pool);
349             psTraceCrypto("File buffer does not look to be X.509 PEM format\n");
350 1           return PS_PARSE_FAIL;
351             }
352 1495           current->item = psMalloc(pool, current->len);
353 1495 50         if (current->item == NULL)
354             {
355 0           psFreeList(front, pool);
356 0           psError("Memory allocation error: pemCertFileBufToX509\n");
357 0           return PS_MEM_FAIL;
358             }
359 1495           memset(current->item, '\0', current->len);
360              
361 1495           fileBufLen -= (uint16_t) (end - fileBuf);
362 1495           fileBuf = end;
363              
364 1495 50         if (psBase64decode(start, current->len, current->item, ¤t->len) != 0)
365             {
366 0           psFreeList(front, pool);
367             psTraceCrypto("Unable to base64 decode certificate\n");
368 0           return PS_PARSE_FAIL;
369             }
370 1495           prev = current;
371 1495           current = current->next;
372 1495           chFileBuf = fileBuf;
373             }
374 775           *x509certList = front;
375 775           return PS_SUCCESS;
376             }
377             # endif /* MATRIX_USE_FILE_SYSTEM */
378             /******************************************************************************/
379              
380              
381             # ifdef USE_PKCS1_PSS
382             /*
383             RSASSA-PSS-params ::= SEQUENCE {
384             hashAlgorithm [0] HashAlgorithm DEFAULT sha1,
385             maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1,
386             saltLength [2] INTEGER DEFAULT 20,
387             trailerField [3] TrailerField DEFAULT 1
388             }
389             Note, each of these is sequential, but optional.
390             */
391 0           static int32 getRsaPssParams(const unsigned char **pp, int32 size,
392             psX509Cert_t *cert, int32 secondPass)
393             {
394             const unsigned char *p, *end;
395             int32 oi, second, asnint;
396             psSize_t plen;
397              
398 0           p = *pp;
399             /* SEQUENCE has already been pulled off into size */
400 0           end = p + size;
401              
402             /* The signature algorithm appears twice in an X.509 cert and must be
403             identical. If secondPass is set we check for that */
404              
405 0 0         if ((uint32) (end - p) < 1)
406             {
407 0           goto L_PSS_DONE_OPTIONAL_PARAMS;
408             }
409 0 0         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
410             {
411 0           p++;
412 0 0         if (getAsnLength(&p, (uint32) (end - p), &plen) < 0 ||
    0          
413 0           (end - p) < plen)
414             {
415             psTraceCrypto("Error parsing rsapss hash alg len\n");
416 0           return PS_PARSE_FAIL;
417             }
418             /* hashAlgorithm is OID */
419 0 0         if (getAsnAlgorithmIdentifier(&p, (uint32) (end - p), &oi, &plen) < 0)
420             {
421             psTraceCrypto("Error parsing rsapss hash alg\n");
422 0           return PS_PARSE_FAIL;
423             }
424 0 0         if (secondPass)
425             {
426 0 0         if (oi != cert->pssHash)
427             {
428             psTraceCrypto("rsapss hash alg doesn't repeat\n");
429 0           return PS_PARSE_FAIL;
430             }
431             /* Convert to PKCS1_ ID for pssDecode on second pass */
432 0 0         if (oi == OID_SHA1_ALG)
433             {
434 0           second = PKCS1_SHA1_ID;
435             }
436 0 0         else if (oi == OID_SHA256_ALG)
437             {
438 0           second = PKCS1_SHA256_ID;
439             }
440 0 0         else if (oi == OID_MD5_ALG)
441             {
442 0           second = PKCS1_MD5_ID;
443             # ifdef USE_SHA384
444             }
445 0 0         else if (oi == OID_SHA384_ALG)
446             {
447 0           second = PKCS1_SHA384_ID;
448             # endif
449             # ifdef USE_SHA512
450             }
451 0 0         else if (oi == OID_SHA512_ALG)
452             {
453 0           second = PKCS1_SHA512_ID;
454             # endif
455             }
456             else
457             {
458             psTraceCrypto("Unsupported rsapss hash alg\n");
459 0           return PS_UNSUPPORTED_FAIL;
460             }
461 0           cert->pssHash = second;
462             }
463             else
464             {
465             /* first time, save the OID for compare */
466 0           cert->pssHash = oi;
467             }
468             }
469 0 0         if ((uint32) (end - p) < 1)
470             {
471 0           goto L_PSS_DONE_OPTIONAL_PARAMS;
472             }
473 0 0         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
474             {
475             /* maskGenAlgorthm is OID */
476 0           p++;
477 0 0         if (getAsnLength(&p, (uint32) (end - p), &plen) < 0 ||
    0          
478 0           (end - p) < plen)
479             {
480             psTraceCrypto("Error parsing mask gen alg len\n");
481 0           return PS_PARSE_FAIL;
482             }
483 0 0         if (getAsnAlgorithmIdentifier(&p, (uint32) (end - p), &oi, &plen) < 0)
484             {
485             psTraceCrypto("Error parsing mask gen alg\n");
486 0           return PS_PARSE_FAIL;
487             }
488 0 0         if (secondPass)
489             {
490 0 0         if (oi != cert->maskGen)
491             {
492             psTraceCrypto("rsapss mask gen alg doesn't repeat\n");
493 0           return PS_PARSE_FAIL;
494             }
495             }
496 0           cert->maskGen = oi;
497 0 0         if (cert->maskGen != OID_ID_MGF1)
498             {
499             psTraceCrypto("Unsupported RSASSA-PSS maskGenAlgorithm\n");
500 0           return PS_UNSUPPORTED_FAIL;
501             }
502             /* MaskGenAlgorithm ::= AlgorithmIdentifier {
503             {PKCS1MGFAlgorithms}
504             }
505             PKCS1MGFAlgorithms ALGORITHM-IDENTIFIER ::= {
506             { OID id-mgf1 PARAMETERS HashAlgorithm },
507             ... -- Allows for future expansion --
508             }
509              
510             The default mask generation function is MGF1 with SHA-1:
511              
512             mgf1SHA1 MaskGenAlgorithm ::= {
513             algorithm id-mgf1,
514             parameters HashAlgorithm : sha1
515             }
516             */
517 0 0         if (getAsnAlgorithmIdentifier(&p, (uint32) (end - p), &oi, &plen) < 0)
518             {
519             psTraceCrypto("Error parsing mask hash alg\n");
520 0           return PS_PARSE_FAIL;
521             }
522 0 0         if (secondPass)
523             {
524 0 0         if (oi != cert->maskHash)
525             {
526             psTraceCrypto("rsapss mask hash alg doesn't repeat\n");
527 0           return PS_PARSE_FAIL;
528             }
529             }
530 0           cert->maskHash = oi;
531             }
532 0 0         if ((uint32) (end - p) < 1)
533             {
534 0           goto L_PSS_DONE_OPTIONAL_PARAMS;
535             }
536 0 0         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2))
537             {
538             /* saltLen */
539 0           p++;
540 0 0         if (getAsnLength(&p, (uint32) (end - p), &plen) < 0 ||
    0          
541 0           (end - p) < plen)
542             {
543             psTraceCrypto("Error parsing salt len length\n");
544 0           return PS_PARSE_FAIL;
545             }
546 0 0         if (getAsnInteger(&p, (uint32) (end - p), &asnint) < 0)
547             {
548             psTraceCrypto("Error parsing salt len\n");
549 0           return PS_PARSE_FAIL;
550             }
551 0 0         if (secondPass)
552             {
553 0 0         if (asnint != cert->saltLen)
554             {
555             psTraceCrypto("Error: salt len doesn't repeat\n");
556 0           return PS_PARSE_FAIL;
557             }
558             }
559 0           cert->saltLen = asnint;
560             }
561 0 0         if ((uint32) (end - p) < 1)
562             {
563 0           goto L_PSS_DONE_OPTIONAL_PARAMS;
564             }
565 0 0         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3))
566             {
567             /* It shall be 1 for this version of the document, which represents
568             the trailer field with hexadecimal value 0xBC */
569 0           p++;
570 0 0         if (getAsnLength(&p, (uint32) (end - p), &plen) < 0 ||
    0          
571 0           (end - p) < plen)
572             {
573             psTraceCrypto("Error parsing rsapss trailer len\n");
574 0           return PS_PARSE_FAIL;
575             }
576 0 0         if (getAsnInteger(&p, (uint32) (end - p), &asnint) < 0 ||
    0          
577 0           asnint != 0x01)
578             {
579             psTraceCrypto("Error parsing rsapss trailer\n");
580 0           return PS_PARSE_FAIL;
581             }
582             }
583 0 0         if (p != end)
584             {
585             psTraceCrypto("Unexpected PSS params\n");
586 0           return PS_PARSE_FAIL;
587             }
588             L_PSS_DONE_OPTIONAL_PARAMS:
589 0           *pp = (unsigned char *) p;
590 0           return PS_SUCCESS;
591             }
592             # endif /* USE_PKCS1_PSS */
593              
594             /******************************************************************************/
595             /*
596             Get the public key (SubjectPublicKeyInfo) in DER format from a psX509Cert_t.
597              
598             Precondition: the certificate must have been parsed with psX509ParseCert or
599             psX509ParseCertFile with the CERT_STORE_UNPARSED_BUFFER flag set.
600             */
601 0           PSPUBLIC int32 psX509GetCertPublicKeyDer(psX509Cert_t *cert,
602             unsigned char *der_out,
603             psSize_t *der_out_len)
604             {
605 0 0         if (!cert || !der_out || !der_out_len)
    0          
    0          
606             {
607 0           return PS_ARG_FAIL;
608             }
609 0 0         if (cert->publicKeyDerOffsetIntoUnparsedBin == 0
610 0 0         || cert->publicKeyDerLen == 0)
611             {
612             psTraceCrypto("No DER format public key stored in this cert. " \
613             "CERT_STORE_DN_BUFFER flag was not used when parsing?");
614 0           return PS_ARG_FAIL;
615             }
616              
617 0 0         if (*der_out_len < cert->publicKeyDerLen)
618             {
619             psTraceCrypto("Output buffer is too small");
620 0           *der_out_len = cert->publicKeyDerLen;
621 0           return PS_OUTPUT_LENGTH;
622             }
623              
624 0           memcpy(der_out,
625 0           cert->unparsedBin + cert->publicKeyDerOffsetIntoUnparsedBin,
626 0           cert->publicKeyDerLen);
627              
628 0           *der_out_len = cert->publicKeyDerLen;
629              
630 0           return PS_SUCCESS;
631             }
632              
633             /*
634             Parse a single, DER-encoded ASN.1 Certificate.
635              
636             Preconditions:
637             - *pp points to the first octet of a DER-encoded Certificate.
638             - the length of the DER-encoded Certificate is size octets.
639             - cert points to an allocated and zeroized psX509Cert_t struct.
640              
641             Postconditions:
642             - *pp == (pp_orig + size), where pp_orig is the original (input)
643             value of *pp.
644             - If return value is PS_SUCCESS, cert will contain a parsed
645             and usable certificate.
646             - If return value is < 0, cert->parseStatus will contain information
647             about the reason of the parse failure.
648              
649             @param[in] Pointer to a memory pool
650             @param[in,out] pp Pointer to a pointer pointing to the first octet
651             of a DER-encoded Certificate. After parsing has completed, the underlying
652             pointer will be updated to point to the octet after the final octet
653             of the Certificate.
654             @param[in] size Size of the DER buffer in bytes.
655             @param[in] cert An allocated psX509Cert_t struct to be filled.
656             with the parsed Certificate data.
657             @param[in] flags
658             */
659 2880           static int parse_single_cert(psPool_t *pool, const unsigned char **pp,
660             uint32 size, const unsigned char *far_end,
661             psX509Cert_t *cert, int32 flags)
662             {
663             # ifdef USE_CERT_PARSE
664             const unsigned char *tbsCertStart;
665             unsigned char sha1KeyHash[SHA1_HASH_SIZE];
666             psDigestContext_t hashCtx;
667             psSize_t certLen;
668             const unsigned char *p_subject_pubkey_info;
669             size_t subject_pubkey_info_header_len;
670             # endif /* USE_CERT_PARSE */
671             const unsigned char *certStart, *certEnd, *end, *p;
672             int32_t rc, func_rc;
673             uint32_t oneCertLen;
674             psSize_t len, plen;
675              
676             /*
677             Initialize the cert structure.*/
678 2880           cert->pool = pool;
679 2880           cert->parseStatus = PS_X509_PARSE_FAIL; /* Default to fail status */
680             # ifdef USE_CERT_PARSE
681 2880           cert->extensions.bc.cA = CA_UNDEFINED;
682             # endif /* USE_CERT_PARSE */
683              
684 2880           p = *pp;
685 2880           certStart = p;
686 2880           end = p + size;
687              
688 2880           func_rc = PS_SUCCESS;
689              
690 2880 100         if ((rc = getAsnSequence32(&p, (uint32_t) (far_end - p), &oneCertLen, 0))
691             < 0)
692             {
693             psTraceCrypto("Initial cert parse error\n");
694 1           func_rc = rc;
695 1           goto out;
696             }
697             /* The whole list of certs could be > 64K bytes, but we still
698             restrict individual certs to 64KB */
699 2879 50         if (oneCertLen > 0xFFFF)
700             {
701 0 0         psAssert(oneCertLen <= 0xFFFF);
702 0           func_rc = PS_FAILURE;
703 0           goto out;
704             }
705 2879           end = p + oneCertLen;
706              
707             /*
708             If the user has specified to keep the ASN.1 buffer in the X.509
709             structure, now is the time to account for it
710             */
711 2879 100         if (flags & CERT_STORE_UNPARSED_BUFFER)
712             {
713 258           cert->binLen = oneCertLen + (int32) (p - certStart);
714 258           cert->unparsedBin = psMalloc(pool, cert->binLen);
715 258 50         if (cert->unparsedBin == NULL)
716             {
717 0           psError("Memory allocation error in psX509ParseCert\n");
718 0           func_rc = PS_MEM_FAIL;
719 0           goto out;
720             }
721 258           memcpy(cert->unparsedBin, certStart, cert->binLen);
722             }
723              
724             # ifdef ENABLE_CA_CERT_HASH
725             /* We use the cert_sha1_hash type for the Trusted CA Indication so
726             run a SHA1 has over the entire Certificate DER encoding. */
727             psSha1PreInit(&hashCtx.sha1);
728             psSha1Init(&hashCtx.sha1);
729             psSha1Update(&hashCtx.sha1, certStart,
730             oneCertLen + (int32) (p - certStart));
731             psSha1Final(&hashCtx.sha1, cert->sha1CertHash);
732             # endif
733              
734             # ifdef USE_CERT_PARSE
735 2879           tbsCertStart = p;
736             # endif /* USE_CERT_PARSE */
737             /*
738             TBSCertificate ::= SEQUENCE {
739             version [0] EXPLICIT Version DEFAULT v1,
740             serialNumber CertificateSerialNumber,
741             signature AlgorithmIdentifier,
742             issuer Name,
743             validity Validity,
744             subject Name,
745             subjectPublicKeyInfo SubjectPublicKeyInfo,
746             issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
747             -- If present, version shall be v2 or v3
748             subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
749             -- If present, version shall be v2 or v3
750             extensions [3] EXPLICIT Extensions OPTIONAL
751             -- If present, version shall be v3 }
752             */
753 2879 50         if ((rc = getAsnSequence(&p, (uint32) (end - p), &len)) < 0)
754             {
755             psTraceCrypto("ASN sequence parse error\n");
756 0           func_rc = rc;
757 0           goto out;
758             }
759 2879           certEnd = p + len;
760             # ifdef USE_CERT_PARSE
761             /*
762             Start parsing TBSCertificate contents.
763             */
764 2879           certLen = certEnd - tbsCertStart;
765             /*
766             Version ::= INTEGER { v1(0), v2(1), v3(2) }
767             */
768 2879 50         if ((rc = getExplicitVersion(&p, (uint32) (end - p), 0, &cert->version))
769             < 0)
770             {
771             psTraceCrypto("ASN version parse error\n");
772 0           func_rc = rc;
773 0           goto out;
774             }
775 2879           switch (cert->version)
776             {
777             case 0:
778             case 1:
779             # ifndef ALLOW_VERSION_1_ROOT_CERT_PARSE
780             psTraceCrypto("ERROR: v1 and v2 certificate versions insecure\n");
781 0           cert->parseStatus = PS_X509_UNSUPPORTED_VERSION;
782 0           func_rc = PS_UNSUPPORTED_FAIL;
783 0           goto out;
784             # else
785             /* Allow locally stored, trusted version 1 and version 2 certificates
786             to be parsed. The SSL layer code will still reject non v3
787             certificates that arrive over-the-wire. */
788             /* Version 1 certificates do not have basic constraints to
789             specify a CA flag or path length. Here, the CA flag is implied
790             since v1 certs can only be loaded as root. We explicitly set
791             the pathLengthConstraint to allow up to 2 intermediate certs.
792             This can be adjusted to allow more or less intermediate certs. */
793             cert->extensions.bc.pathLenConstraint = 2;
794             break;
795             # endif /* ALLOW_VERSION_1_ROOT_CERT_PARSE */
796             case 2:
797             /* Typical case of v3 cert */
798 2879           break;
799             default:
800             psTraceIntCrypto("ERROR: unknown certificate version: %d\n",
801             cert->version);
802 0           cert->parseStatus = PS_X509_UNSUPPORTED_VERSION;
803 0           func_rc = PS_UNSUPPORTED_FAIL;
804 0           goto out;
805             }
806             /*
807             CertificateSerialNumber ::= INTEGER
808             There is a special return code for a missing serial number that
809             will get written to the parse warning flag
810             */
811 2879 50         if ((rc = getSerialNum(pool, &p, (uint32) (end - p), &cert->serialNumber,
812             &cert->serialNumberLen)) < 0)
813             {
814             psTraceCrypto("ASN serial number parse error\n");
815 0           func_rc = rc;
816 0           goto out;
817             }
818             /*
819             AlgorithmIdentifier ::= SEQUENCE {
820             algorithm OBJECT IDENTIFIER,
821             parameters ANY DEFINED BY algorithm OPTIONAL }
822             */
823 2879 50         if ((rc = getAsnAlgorithmIdentifier(&p, (uint32) (end - p),
824 2879           &cert->certAlgorithm, &plen)) < 0)
825             {
826             psTraceCrypto("Couldn't parse algorithm identifier for certAlgorithm\n");
827 0           cert->parseStatus = PS_X509_ALG_ID;
828 0           func_rc = rc;
829 0           goto out;
830             }
831 2879 50         if (plen != 0)
832             {
833             # ifdef USE_PKCS1_PSS
834 0 0         if (cert->certAlgorithm == OID_RSASSA_PSS)
835             {
836             /* RSASSA-PSS-params ::= SEQUENCE {
837             hashAlgorithm [0] HashAlgorithm DEFAULT sha1,
838             maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1,
839             saltLength [2] INTEGER DEFAULT 20,
840             trailerField [3] TrailerField DEFAULT trailerFieldBC
841             }
842             */
843 0 0         if ((rc = getAsnSequence(&p, (uint32) (end - p), &len)) < 0)
844             {
845             psTraceCrypto("ASN sequence parse error\n");
846 0           func_rc = rc;
847 0           goto out;
848             }
849             /* Always set the defaults before parsing */
850 0           cert->pssHash = PKCS1_SHA1_ID;
851 0           cert->maskGen = OID_ID_MGF1;
852 0           cert->saltLen = SHA1_HASH_SIZE;
853             /* Something other than defaults to parse here? */
854 0 0         if (len > 0)
855             {
856 0 0         if ((rc = getRsaPssParams(&p, len, cert, 0)) < 0)
857             {
858 0           func_rc = rc;
859 0           goto out;
860             }
861             }
862             }
863             else
864             {
865             psTraceCrypto("Unsupported X.509 certAlgorithm\n");
866 0           func_rc = PS_UNSUPPORTED_FAIL;
867 0           goto out;
868             }
869             # else
870             psTraceCrypto("Unsupported X.509 certAlgorithm\n");
871             func_rc = PS_UNSUPPORTED_FAIL;
872             goto out;
873             # endif
874             }
875             /*
876             Name ::= CHOICE {
877             RDNSequence }
878              
879             RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
880              
881             RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
882              
883             AttributeTypeAndValue ::= SEQUENCE {
884             type AttributeType,
885             value AttributeValue }
886              
887             AttributeType ::= OBJECT IDENTIFIER
888              
889             AttributeValue ::= ANY DEFINED BY AttributeType
890             */
891 2879 50         if ((rc = psX509GetDNAttributes(pool, &p, (uint32) (end - p),
892             &cert->issuer, flags)) < 0)
893             {
894             psTraceCrypto("Couldn't parse issuer DN attributes\n");
895 0           cert->parseStatus = PS_X509_ISSUER_DN;
896 0           func_rc = rc;
897 0           goto out;
898             }
899             /*
900             Validity ::= SEQUENCE {
901             notBefore Time,
902             notAfter Time }
903             */
904 2879 50         if ((rc = getTimeValidity(pool, &p, (uint32) (end - p),
905 2879           &cert->notBeforeTimeType, &cert->notAfterTimeType,
906             &cert->notBefore, &cert->notAfter)) < 0)
907             {
908             psTraceCrypto("Couldn't parse validity\n");
909 0           func_rc = rc;
910 0           goto out;
911             }
912              
913             /* SECURITY - platforms without a date function will always succeed */
914 2879 50         if ((rc = validateDateRange(cert)) < 0)
915             {
916             psTraceCrypto("Validity date check failed\n");
917 0           cert->parseStatus = PS_X509_DATE;
918 0           func_rc = rc;
919 0           goto out;
920             }
921             /*
922             Subject DN
923             */
924 2879           cert->subjectKeyDerOffsetIntoUnparsedBin = (uint16_t) (p - certStart);
925 2879 50         if ((rc = psX509GetDNAttributes(pool, &p, (uint32) (end - p),
926             &cert->subject, flags)) < 0)
927             {
928             psTraceCrypto("Couldn't parse subject DN attributes\n");
929 0           cert->parseStatus = PS_X509_SUBJECT_DN;
930 0           func_rc = rc;
931 0           goto out;
932             }
933             /*
934             SubjectPublicKeyInfo ::= SEQUENCE {
935             algorithm AlgorithmIdentifier,
936             subjectPublicKey BIT STRING }
937             */
938 2879           p_subject_pubkey_info = p;
939              
940 2879           cert->publicKeyDerOffsetIntoUnparsedBin = (uint16_t) (p - certStart);
941              
942 2879 50         if ((rc = getAsnSequence(&p, (uint32) (end - p), &len)) < 0)
943             {
944             psTraceCrypto("Couldn't get ASN sequence for pubKeyAlgorithm\n");
945 0           func_rc = rc;
946 0           goto out;
947             }
948 2879           subject_pubkey_info_header_len = (p - p_subject_pubkey_info);
949 2879           cert->publicKeyDerLen = len + subject_pubkey_info_header_len;
950              
951 2879 50         if ((rc = getAsnAlgorithmIdentifier(&p, (uint32) (end - p),
952 2879           &cert->pubKeyAlgorithm, &plen)) < 0)
953             {
954             psTraceCrypto("Couldn't parse algorithm id for pubKeyAlgorithm\n");
955 0           func_rc = rc;
956 0           goto out;
957             }
958              
959             /* Populate with correct type based on pubKeyAlgorithm OID */
960 2879           switch (cert->pubKeyAlgorithm)
961             {
962             # ifdef USE_ECC
963             case OID_ECDSA_KEY_ALG:
964 105 50         if (plen == 0 || plen > (int32) (end - p))
    50          
965             {
966             psTraceCrypto("Bad params on EC OID\n");
967 0           func_rc = PS_PARSE_FAIL;
968 0           goto out;
969             }
970 105           psInitPubKey(pool, &cert->publicKey, PS_ECC);
971 105 50         if ((rc = getEcPubKey(pool, &p, (uint16_t) (end - p),
972             &cert->publicKey.key.ecc, sha1KeyHash)) < 0)
973             {
974 0 0         if (rc == PS_UNSUPPORTED_FAIL)
975             {
976 0           cert->parseStatus = PS_X509_UNSUPPORTED_ECC_CURVE;
977             }
978 0           func_rc = PS_PARSE_FAIL;
979 0           goto out;
980             }
981             /* keysize will be the size of the public ecc key (2 * privateLen) */
982 105           cert->publicKey.keysize = psEccSize(&cert->publicKey.key.ecc);
983 105 50         if (cert->publicKey.keysize < (MIN_ECC_BITS / 8))
984             {
985             psTraceIntCrypto("ECC key size < %d\n", MIN_ECC_BITS);
986 0           psClearPubKey(&cert->publicKey);
987 0           cert->parseStatus = PS_X509_WEAK_KEY;
988 0           func_rc = PS_PARSE_FAIL;
989 0           goto out;
990             }
991 105           break;
992             # endif
993             # ifdef USE_RSA
994             case OID_RSA_KEY_ALG:
995 2774 50         psAssert(plen == 0); /* No parameters on RSA pub key OID */
996 2774           psInitPubKey(pool, &cert->publicKey, PS_RSA);
997 2774 50         if ((rc = psRsaParseAsnPubKey(pool, &p, (uint16_t) (end - p),
998             &cert->publicKey.key.rsa, sha1KeyHash)) < 0)
999             {
1000             psTraceCrypto("Couldn't get RSA pub key from cert\n");
1001 0           cert->parseStatus = PS_X509_MISSING_RSA;
1002 0           func_rc = rc;
1003 0           goto out;
1004             }
1005 2774           cert->publicKey.keysize = psRsaSize(&cert->publicKey.key.rsa);
1006              
1007 2774 50         if (cert->publicKey.keysize < (MIN_RSA_BITS / 8))
1008             {
1009             psTraceIntCrypto("RSA key size < %d\n", MIN_RSA_BITS);
1010 0           psClearPubKey(&cert->publicKey);
1011 0           cert->parseStatus = PS_X509_WEAK_KEY;
1012 0           func_rc = PS_UNSUPPORTED_FAIL;
1013 0           goto out;
1014             }
1015              
1016 2774           break;
1017             # endif
1018             default:
1019             /* Note 645:RSA, 515:DSA, 518:ECDSA, 32969:GOST */
1020             psTraceIntCrypto(
1021             "Unsupported public key algorithm in cert parse: %d\n",
1022             cert->pubKeyAlgorithm);
1023 0           cert->parseStatus = PS_X509_UNSUPPORTED_KEY_ALG;
1024 0           func_rc = PS_UNSUPPORTED_FAIL;
1025 0           goto out;
1026             }
1027              
1028             # ifdef USE_OCSP
1029             /* A sha1 hash of the public key is useful for OCSP */
1030 2879           memcpy(cert->sha1KeyHash, sha1KeyHash, SHA1_HASH_SIZE);
1031             # endif
1032              
1033             /* As the next three values are optional, we can do a specific test here */
1034 2879 50         if (*p != (ASN_SEQUENCE | ASN_CONSTRUCTED))
1035             {
1036 2879 50         if (getImplicitBitString(pool, &p, (uint32) (end - p),
1037             IMPLICIT_ISSUER_ID, &cert->uniqueIssuerId,
1038 2879 50         &cert->uniqueIssuerIdLen) < 0 ||
1039 2879           getImplicitBitString(pool, &p, (uint32) (end - p),
1040             IMPLICIT_SUBJECT_ID, &cert->uniqueSubjectId,
1041 2879 50         &cert->uniqueSubjectIdLen) < 0 ||
1042 2879           getExplicitExtensions(pool, &p, (uint32) (end - p),
1043             EXPLICIT_EXTENSION, &cert->extensions, 0) < 0)
1044             {
1045             psTraceCrypto("There was an error parsing a certificate\n"
1046             "extension. This is likely caused by an\n"
1047             "extension format that is not currently\n"
1048             "recognized. Please email support\n"
1049             "to add support for the extension.\n");
1050 0           cert->parseStatus = PS_X509_UNSUPPORTED_EXT;
1051 0           func_rc = PS_PARSE_FAIL;
1052 0           goto out;
1053             }
1054             }
1055              
1056             /* This is the end of the cert. Do a check here to be certain */
1057 2879 50         if (certEnd != p)
1058             {
1059             psTraceCrypto("Error. Expecting end of cert\n");
1060 0           cert->parseStatus = PS_X509_EOF;
1061 0           func_rc = PS_LIMIT_FAIL;
1062 0           goto out;
1063             }
1064              
1065             /* Reject any cert without a distinguishedName or subjectAltName */
1066 2879 100         if (cert->subject.commonName == NULL &&
    50          
1067 0 0         cert->subject.country == NULL &&
1068 0 0         cert->subject.state == NULL &&
1069 0 0         cert->subject.organization == NULL &&
1070 0 0         cert->subject.orgUnit == NULL &&
1071 0 0         cert->subject.domainComponent == NULL &&
1072 0           cert->extensions.san == NULL)
1073             {
1074             psTraceCrypto("Error. Cert has no name information\n");
1075 0           cert->parseStatus = PS_X509_MISSING_NAME;
1076 0           func_rc = PS_PARSE_FAIL;
1077 0           goto out;
1078             }
1079             # else /* No TBSCertificate parsing. */
1080             p = certEnd;
1081             # endif /* USE_CERT_PARSE (end of TBSCertificate parsing) */
1082              
1083             /* Certificate signature info */
1084 2879 50         if ((rc = getAsnAlgorithmIdentifier(&p, (uint32) (end - p),
1085 2879           &cert->sigAlgorithm, &plen)) < 0)
1086             {
1087             psTraceCrypto("Couldn't get algorithm identifier for sigAlgorithm\n");
1088 0           func_rc = rc;
1089 0           goto out;
1090             }
1091              
1092 2879 50         if (plen != 0)
1093             {
1094             # ifdef USE_PKCS1_PSS
1095 0 0         if (cert->sigAlgorithm == OID_RSASSA_PSS)
1096             {
1097             /* RSASSA-PSS-params ::= SEQUENCE {
1098             hashAlgorithm [0] HashAlgorithm DEFAULT sha1,
1099             maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1,
1100             saltLength [2] INTEGER DEFAULT 20,
1101             trailerField [3] TrailerField DEFAULT trailerFieldBC
1102             }
1103             */
1104 0 0         if ((rc = getAsnSequence(&p, (uint32) (end - p), &len)) < 0)
1105             {
1106             psTraceCrypto("ASN sequence parse error\n");
1107 0           func_rc = rc;
1108 0           goto out;
1109             }
1110             /* Something other than defaults to parse here? */
1111 0 0         if (len > 0)
1112             {
1113 0 0         if ((rc = getRsaPssParams(&p, len, cert, 1)) < 0)
1114             {
1115 0           func_rc = rc;
1116 0           goto out;
1117             }
1118             }
1119             }
1120             else
1121             {
1122             psTraceCrypto("Unsupported X.509 sigAlgorithm\n");
1123 0           func_rc = PS_UNSUPPORTED_FAIL;
1124 0           goto out;
1125             }
1126             # else
1127             psTraceCrypto("Unsupported X.509 sigAlgorithm\n");
1128             func_rc = PS_UNSUPPORTED_FAIL;
1129             goto out;
1130             # endif /* USE_PKCS1_PSS */
1131             }
1132             # ifdef USE_CERT_PARSE
1133             /*
1134             https://tools.ietf.org/html/rfc5280#section-4.1.1.2
1135             This field MUST contain the same algorithm identifier as the
1136             signature field in the sequence tbsCertificate (Section 4.1.2.3).
1137             */
1138 2879 50         if (cert->certAlgorithm != cert->sigAlgorithm)
1139             {
1140             psTraceIntCrypto("Parse error: mismatched sig alg (tbs = %d ",
1141             cert->certAlgorithm);
1142             psTraceIntCrypto("sig = %d)\n", cert->sigAlgorithm);
1143 0           cert->parseStatus = PS_X509_SIG_MISMATCH;
1144 0           func_rc = PS_PARSE_FAIL;
1145 0           goto out;
1146             }
1147             /*
1148             Compute the hash of the cert here for CA validation
1149             */
1150 2879           switch (cert->certAlgorithm)
1151             {
1152             # ifdef ENABLE_MD5_SIGNED_CERTS
1153             # ifdef USE_MD2
1154             case OID_MD2_RSA_SIG:
1155             psMd2Init(&hashCtx.md2);
1156             psMd2Update(&hashCtx.md2, tbsCertStart, certLen);
1157             psMd2Final(&hashCtx.md2, cert->sigHash);
1158             break;
1159             # endif /* USE_MD2 */
1160             case OID_MD5_RSA_SIG:
1161             psMd5Init(&hashCtx.md5);
1162             psMd5Update(&hashCtx.md5, tbsCertStart, certLen);
1163             psMd5Final(&hashCtx.md5, cert->sigHash);
1164             break;
1165             # endif
1166             # ifdef ENABLE_SHA1_SIGNED_CERTS
1167             case OID_SHA1_RSA_SIG:
1168             case OID_SHA1_RSA_SIG2:
1169             # ifdef USE_ECC
1170             case OID_SHA1_ECDSA_SIG:
1171             # endif
1172 300           psSha1PreInit(&hashCtx.sha1);
1173 300           psSha1Init(&hashCtx.sha1);
1174 300           psSha1Update(&hashCtx.sha1, tbsCertStart, certLen);
1175 300           psSha1Final(&hashCtx.sha1, cert->sigHash);
1176 300           break;
1177             # endif
1178             # ifdef USE_SHA224
1179             case OID_SHA224_RSA_SIG:
1180             # ifdef USE_ECC
1181             case OID_SHA224_ECDSA_SIG:
1182             # endif
1183             psSha224PreInit(&hashCtx.sha256);
1184             psSha224Init(&hashCtx.sha256);
1185             psSha224Update(&hashCtx.sha256, tbsCertStart, certLen);
1186             psSha224Final(&hashCtx.sha256, cert->sigHash);
1187             break;
1188             # endif
1189             # ifdef USE_SHA256
1190             case OID_SHA256_RSA_SIG:
1191             # ifdef USE_ECC
1192             case OID_SHA256_ECDSA_SIG:
1193             # endif
1194 2454           psSha256PreInit(&hashCtx.sha256);
1195 2454           psSha256Init(&hashCtx.sha256);
1196 2454           psSha256Update(&hashCtx.sha256, tbsCertStart, certLen);
1197 2454           psSha256Final(&hashCtx.sha256, cert->sigHash);
1198 2454           break;
1199             # endif
1200             # ifdef USE_SHA384
1201             case OID_SHA384_RSA_SIG:
1202             # ifdef USE_ECC
1203             case OID_SHA384_ECDSA_SIG:
1204             # endif
1205 110           psSha384PreInit(&hashCtx.sha384);
1206 110           psSha384Init(&hashCtx.sha384);
1207 110           psSha384Update(&hashCtx.sha384, tbsCertStart, certLen);
1208 110           psSha384Final(&hashCtx.sha384, cert->sigHash);
1209 110           break;
1210             # endif
1211             # ifdef USE_SHA512
1212             case OID_SHA512_RSA_SIG:
1213             # ifdef USE_ECC
1214             case OID_SHA512_ECDSA_SIG:
1215             # endif
1216 15           psSha512PreInit(&hashCtx.sha512);
1217 15           psSha512Init(&hashCtx.sha512);
1218 15           psSha512Update(&hashCtx.sha512, tbsCertStart, certLen);
1219 15           psSha512Final(&hashCtx.sha512, cert->sigHash);
1220 15           break;
1221             # endif
1222             # ifdef USE_PKCS1_PSS
1223             case OID_RSASSA_PSS:
1224 0           switch (cert->pssHash)
1225             {
1226             # ifdef ENABLE_MD5_SIGNED_CERTS
1227             case PKCS1_MD5_ID:
1228             psMd5Init(&hashCtx.md5);
1229             psMd5Update(&hashCtx.md5, tbsCertStart, certLen);
1230             psMd5Final(&hashCtx.md5, cert->sigHash);
1231             break;
1232             # endif
1233             # ifdef ENABLE_SHA1_SIGNED_CERTS
1234             case PKCS1_SHA1_ID:
1235 0           psSha1PreInit(&hashCtx.sha1);
1236 0           psSha1Init(&hashCtx.sha1);
1237 0           psSha1Update(&hashCtx.sha1, tbsCertStart, certLen);
1238 0           psSha1Final(&hashCtx.sha1, cert->sigHash);
1239 0           break;
1240             # endif
1241             # ifdef USE_SHA224
1242             case PKCS1_SHA224_ID:
1243             psSha224PreInit(&hashCtx.sha256);
1244             psSha224Init(&hashCtx.sha256);
1245             psSha224Update(&hashCtx.sha256, tbsCertStart, certLen);
1246             psSha224Final(&hashCtx.sha256, cert->sigHash);
1247             break;
1248             # endif
1249             # ifdef USE_SHA256
1250             case PKCS1_SHA256_ID:
1251 0           psSha256PreInit(&hashCtx.sha256);
1252 0           psSha256Init(&hashCtx.sha256);
1253 0           psSha256Update(&hashCtx.sha256, tbsCertStart, certLen);
1254 0           psSha256Final(&hashCtx.sha256, cert->sigHash);
1255 0           break;
1256             # endif
1257             # ifdef USE_SHA384
1258             case PKCS1_SHA384_ID:
1259 0           psSha384PreInit(&hashCtx.sha384);
1260 0           psSha384Init(&hashCtx.sha384);
1261 0           psSha384Update(&hashCtx.sha384, tbsCertStart, certLen);
1262 0           psSha384Final(&hashCtx.sha384, cert->sigHash);
1263 0           break;
1264             # endif
1265             # ifdef USE_SHA512
1266             case PKCS1_SHA512_ID:
1267 0           psSha512PreInit(&hashCtx.sha512);
1268 0           psSha512Init(&hashCtx.sha512);
1269 0           psSha512Update(&hashCtx.sha512, tbsCertStart, certLen);
1270 0           psSha512Final(&hashCtx.sha512, cert->sigHash);
1271 0           break;
1272             # endif
1273             default:
1274             psTraceIntCrypto("Unsupported pssHash algorithm: %d\n",
1275             cert->pssHash);
1276 0           cert->parseStatus = PS_X509_UNSUPPORTED_SIG_ALG;
1277 0           func_rc = PS_UNSUPPORTED_FAIL;
1278 0           goto out;
1279             } /* switch pssHash */
1280 0           break;
1281             # endif /* USE_PKCS1_PSS */
1282              
1283             default:
1284             /* Note 1670:MD2 */
1285             psTraceIntCrypto("Unsupported cert algorithm: %d\n",
1286             cert->certAlgorithm);
1287 0           cert->parseStatus = PS_X509_UNSUPPORTED_SIG_ALG;
1288 0           func_rc = PS_UNSUPPORTED_FAIL;
1289 0           goto out;
1290              
1291             } /* switch certAlgorithm */
1292              
1293             /* 6 empty bytes is plenty enough to know if sigHash didn't calculate */
1294 2879 50         if (memcmp(cert->sigHash, "\0\0\0\0\0\0", 6) == 0)
1295             {
1296             psTraceIntCrypto("No library signature alg support for cert: %d\n",
1297             cert->certAlgorithm);
1298 0           cert->parseStatus = PS_X509_UNSUPPORTED_SIG_ALG;
1299 0           func_rc = PS_UNSUPPORTED_FAIL;
1300 0           goto out;
1301             }
1302             # endif /* USE_CERT_PARSE */
1303              
1304 2879 50         if ((rc = psX509GetSignature(pool, &p, (uint32) (end - p),
1305             &cert->signature, &cert->signatureLen)) < 0)
1306             {
1307             psTraceCrypto("Couldn't parse signature\n");
1308 0           cert->parseStatus = PS_X509_SIGNATURE;
1309 0           func_rc = rc;
1310 0           goto out;
1311             }
1312              
1313             # ifndef USE_CERT_PARSE
1314             /* Some APIs need certAlgorithm.*/
1315             cert->certAlgorithm = cert->sigAlgorithm;
1316             # endif /* !USE_CERT_PARSE */
1317              
1318             out:
1319 2880 100         if (func_rc == PS_SUCCESS)
1320             {
1321 2879           cert->parseStatus = PS_X509_PARSE_SUCCESS;
1322 2879 50         psAssert(p == end); /* Must have parsed everything. */
1323             }
1324 2880 50         psAssert(p <= end); /* Must not have parsed too much. */
1325              
1326 2880           *pp = end;
1327              
1328 2880           return func_rc;
1329             }
1330              
1331             /******************************************************************************/
1332             /*
1333             Parse an X509 v3 ASN.1 certificate stream
1334             http://tools.ietf.org/html/rfc3280
1335              
1336             flags
1337             CERT_STORE_UNPARSED_BUFFER
1338             CERT_STORE_DN_BUFFER
1339              
1340             Memory info:
1341             Caller must always free outcert with psX509FreeCert. Even on failure
1342             */
1343 2880           int32 psX509ParseCert(psPool_t *pool, const unsigned char *pp, uint32 size,
1344             psX509Cert_t **outcert, int32 flags)
1345             {
1346             psX509Cert_t *cert;
1347             const unsigned char *p, *far_end;
1348             int32_t parsing, rc;
1349 2880           int32_t numCerts = 0;
1350 2880           int32_t numParsedCerts = 0;
1351              
1352             /*
1353             Allocate the cert structure right away. User MUST always call
1354             psX509FreeCert regardless of whether this function succeeds.
1355             memset is important because the test for NULL is what is used
1356             to determine what to free.
1357              
1358             If the input stream consists of multiple certs, the rest of
1359             the psX509Cert_t structs will be allocated in parse_single_cert().
1360             */
1361 2880           *outcert = cert = psMalloc(pool, sizeof(psX509Cert_t));
1362 2880 50         if (cert == NULL)
1363             {
1364 0           psError("Memory allocation failure in psX509ParseCert\n");
1365 0           return PS_MEM_FAIL;
1366             }
1367 2880           memset(cert, 0x0, sizeof(psX509Cert_t));
1368              
1369             # ifdef ALWAYS_KEEP_CERT_DER
1370             flags |= CERT_STORE_UNPARSED_BUFFER;
1371             # endif /* ALWAYS_KEEP_CERT_DER */
1372              
1373 2880           p = pp;
1374 2880           far_end = p + size;
1375              
1376 2880           parsing = 1;
1377 5759 100         while (parsing)
1378             {
1379             /*
1380             Certificate ::= SEQUENCE {
1381             tbsCertificate TBSCertificate,
1382             signatureAlgorithm AlgorithmIdentifier,
1383             signatureValue BIT STRING }
1384             */
1385 2880           rc = parse_single_cert(pool, &p, size, far_end, cert, flags);
1386 2880 100         if (rc == PS_SUCCESS)
1387             {
1388 2879           numParsedCerts++;
1389             }
1390             else
1391             {
1392 1 50         psAssert(cert->parseStatus != PS_X509_PARSE_SUCCESS);
1393              
1394 1 50         if (!(flags & CERT_ALLOW_BUNDLE_PARTIAL_PARSE))
1395             {
1396 1           return rc;
1397             }
1398             }
1399              
1400 2879           numCerts++;
1401              
1402             /*
1403             Check whether we reached the end of the input DER stream.
1404              
1405             An additional sanity check is to ensure that there are least
1406             MIN_CERT_SIZE bytes left in the stream. We wish to avoid
1407             having to call parse_single_cert for any residual garbage
1408             in the stream.
1409             */
1410             #define MIN_CERT_SIZE 256
1411 2879 50         if ((p != far_end) && (p < (far_end + 1))
    0          
1412 0 0         && (far_end - p) > MIN_CERT_SIZE)
1413             {
1414 0 0         if (*p == 0x0 && *(p + 1) == 0x0)
    0          
1415             {
1416 0           parsing = 0; /* An indefinite length stream was passed in */
1417             /* caller will have to deal with skipping these because they
1418             would have read off the TL of this ASN.1 stream */
1419             }
1420             else
1421             {
1422 0           cert->next = psMalloc(pool, sizeof(psX509Cert_t));
1423 0 0         if (cert->next == NULL)
1424             {
1425 0           psError("Memory allocation error in psX509ParseCert\n");
1426 0           return PS_MEM_FAIL;
1427             }
1428 0           cert = cert->next;
1429 0           memset(cert, 0x0, sizeof(psX509Cert_t));
1430 0           cert->pool = pool;
1431             }
1432             }
1433             else
1434             {
1435 2879           parsing = 0;
1436             }
1437             }
1438              
1439 2879 50         if (numParsedCerts == 0)
1440 0           return PS_PARSE_FAIL;
1441              
1442 2879 50         if (flags & CERT_ALLOW_BUNDLE_PARTIAL_PARSE)
1443             {
1444             /*
1445             Return number of successfully parsed certs.
1446             Note: this flag is never set when called from the SSL layer.
1447             */
1448             psTraceIntCrypto("Parsed %d certs", numParsedCerts);
1449             psTraceIntCrypto(" from a total of %d certs\n", numCerts);
1450 0           return numParsedCerts;
1451             }
1452             else
1453             {
1454             /*
1455             Return length of parsed DER stream.
1456             Some functions in the SSL layer require this.
1457             */
1458 2880           return (int32) (p - pp);
1459             }
1460             }
1461              
1462             # ifdef USE_CERT_PARSE
1463 8640           static void freeOrgUnitList(x509OrgUnit_t *orgUnit, psPool_t *allocPool)
1464             {
1465             x509OrgUnit_t *ou;
1466              
1467 9446 100         while (orgUnit != NULL)
1468             {
1469 806           ou = orgUnit;
1470 806           orgUnit = ou->next;
1471 806           psFree(ou->name, allocPool);
1472 806           psFree(ou, allocPool);
1473             }
1474 8640           }
1475              
1476 8640           static void freeDomainComponentList(x509DomainComponent_t *domainComponent,
1477             psPool_t *allocPool)
1478             {
1479             x509DomainComponent_t *dc;
1480              
1481 8640 50         while (domainComponent != NULL)
1482             {
1483 0           dc = domainComponent;
1484 0           domainComponent = dc->next;
1485 0           psFree(dc->name, allocPool);
1486 0           psFree(dc, allocPool);
1487             }
1488 8640           }
1489              
1490 2880           void x509FreeExtensions(x509v3extensions_t *extensions)
1491             {
1492              
1493             x509GeneralName_t *active, *inc;
1494              
1495             # if defined(USE_FULL_CERT_PARSE) || defined(USE_CERT_GEN)
1496             x509PolicyQualifierInfo_t *qual_info, *qual_info_inc;
1497             x509PolicyInformation_t *pol_info, *pol_info_inc;
1498             x509policyMappings_t *pol_map, *pol_map_inc;
1499             x509authorityInfoAccess_t *authInfo, *authInfoInc;
1500             # endif /* USE_FULL_CERT_PARSE || USE_CERT_GEN */
1501              
1502 2880 50         if (extensions == NULL)
1503             {
1504 0           return;
1505             }
1506 2880 100         if (extensions->san)
1507             {
1508 31           active = extensions->san;
1509 67 100         while (active != NULL)
1510             {
1511 36           inc = active->next;
1512 36           psFree(active->data, extensions->pool);
1513 36           psFree(active, extensions->pool);
1514 36           active = inc;
1515             }
1516             }
1517             # if defined(USE_FULL_CERT_PARSE) || defined(USE_CERT_GEN)
1518 2880 100         if (extensions->issuerAltName)
1519             {
1520 10           active = extensions->issuerAltName;
1521 20 100         while (active != NULL)
1522             {
1523 10           inc = active->next;
1524 10           psFree(active->data, extensions->pool);
1525 10           psFree(active, extensions->pool);
1526 10           active = inc;
1527             }
1528             }
1529              
1530 2880 100         if (extensions->authorityInfoAccess)
1531             {
1532 12           authInfo = extensions->authorityInfoAccess;
1533 30 100         while (authInfo != NULL)
1534             {
1535 18           authInfoInc = authInfo->next;
1536 18           psFree(authInfo->ocsp, extensions->pool);
1537 18           psFree(authInfo->caIssuers, extensions->pool);
1538 18           psFree(authInfo, extensions->pool);
1539 18           authInfo = authInfoInc;
1540             }
1541             }
1542             # endif /* USE_FULL_CERT_PARSE || USE_CERT_GEN */
1543              
1544             # ifdef USE_CRL
1545 2880 50         if (extensions->crlNum)
1546             {
1547 0           psFree(extensions->crlNum, extensions->pool);
1548             }
1549 2880 100         if (extensions->crlDist)
1550             {
1551 82           active = extensions->crlDist;
1552 184 100         while (active != NULL)
1553             {
1554 102           inc = active->next;
1555 102           psFree(active->data, extensions->pool);
1556 102           psFree(active, extensions->pool);
1557 102           active = inc;
1558             }
1559             }
1560             # endif /* CRL */
1561              
1562             # ifdef USE_FULL_CERT_PARSE
1563 2880 50         if (extensions->nameConstraints.excluded)
1564             {
1565 0           active = extensions->nameConstraints.excluded;
1566 0 0         while (active != NULL)
1567             {
1568 0           inc = active->next;
1569 0           psFree(active->data, extensions->pool);
1570 0           psFree(active, extensions->pool);
1571 0           active = inc;
1572             }
1573             }
1574 2880 100         if (extensions->nameConstraints.permitted)
1575             {
1576 5           active = extensions->nameConstraints.permitted;
1577 45 100         while (active != NULL)
1578             {
1579 40           inc = active->next;
1580 40           psFree(active->data, extensions->pool);
1581 40           psFree(active, extensions->pool);
1582 40           active = inc;
1583             }
1584             }
1585             # endif /* USE_FULL_CERT_PARSE */
1586 2880 100         if (extensions->sk.id)
1587             {
1588 2864           psFree(extensions->sk.id, extensions->pool);
1589             }
1590 2880 100         if (extensions->ak.keyId)
1591             {
1592 2379           psFree(extensions->ak.keyId, extensions->pool);
1593             }
1594 2880 100         if (extensions->ak.serialNum)
1595             {
1596 50           psFree(extensions->ak.serialNum,
1597             extensions->pool);
1598             }
1599 2880           psX509FreeDNStruct(&extensions->ak.attribs, extensions->pool);
1600              
1601             # if defined(USE_FULL_CERT_PARSE) || defined(USE_CERT_GEN)
1602 2880           pol_info = extensions->certificatePolicy.policy;
1603 2968 100         while (pol_info != NULL)
1604             {
1605             /* Free PolicyInformation member variables. */
1606 88           pol_info_inc = pol_info->next;
1607 88           psFree(pol_info->policyOid, extensions->pool);
1608 88           qual_info = pol_info->qualifiers;
1609 199 100         while (qual_info != NULL)
1610             {
1611             /* Free QualifierInfo member variables. */
1612 111           qual_info_inc = qual_info->next;
1613 111           psFree(qual_info->cps, extensions->pool);
1614 111           psFree(qual_info->unoticeOrganization, extensions->pool);
1615 111           psFree(qual_info->unoticeExplicitText, extensions->pool);
1616 111           psFree(qual_info, extensions->pool);
1617 111           qual_info = qual_info_inc;
1618             }
1619 88           psFree(pol_info, extensions->pool);
1620 88           pol_info = pol_info_inc;
1621             }
1622              
1623 2880           pol_map = extensions->policyMappings;
1624 2885 100         while (pol_map != NULL)
1625             {
1626 5           pol_map_inc = pol_map->next;
1627 5           psFree(pol_map->issuerDomainPolicy, extensions->pool);
1628 5           psFree(pol_map->subjectDomainPolicy, extensions->pool);
1629 5           psFree(pol_map, extensions->pool);
1630 5           pol_map = pol_map_inc;
1631             }
1632              
1633 2880 50         if (extensions->netscapeComment)
1634             {
1635 0 0         if (extensions->netscapeComment->comment)
1636             {
1637 0           psFree(extensions->netscapeComment->comment, pool);
1638             }
1639 0           psFree(extensions->netscapeComment, pool);
1640             }
1641             # endif /* USE_FULL_CERT_PARSE || USE_CERT_GEN */
1642             }
1643              
1644 0           int32_t psX509GetNumOrganizationalUnits(const x509DNattributes_t *DN)
1645             {
1646             x509OrgUnit_t *ou;
1647 0           int32_t res = 0;
1648              
1649 0 0         if (DN == NULL)
1650             {
1651 0           return PS_ARG_FAIL;
1652             }
1653              
1654 0 0         if (DN->orgUnit == NULL)
1655             {
1656 0           return 0;
1657             }
1658              
1659 0           res = 1;
1660 0           ou = DN->orgUnit;
1661 0 0         while (ou->next != NULL)
1662             {
1663 0           ou = ou->next;
1664 0           res++;
1665             }
1666              
1667 0           return res;
1668             }
1669              
1670 0           x509OrgUnit_t *psX509GetOrganizationalUnit(const x509DNattributes_t *DN,
1671             int32_t index)
1672             {
1673             x509OrgUnit_t *ou;
1674             int32_t i;
1675              
1676 0 0         if (DN == NULL || DN->orgUnit == NULL || index < 0)
    0          
    0          
1677             {
1678 0           return NULL;
1679             }
1680              
1681             /*
1682             Note: the OU list is in reverse order. The last item
1683             (i.e the item with largest index) is at the list head.
1684             */
1685              
1686 0           i = psX509GetNumOrganizationalUnits(DN) - 1; /* Largest index. */
1687 0 0         if (i < 0)
1688             {
1689 0           return NULL;
1690             }
1691              
1692 0           ou = DN->orgUnit;
1693 0 0         if (i == index)
1694             {
1695 0           return ou;
1696             }
1697              
1698 0 0         while (ou->next != NULL)
1699             {
1700 0           ou = ou->next;
1701 0           i--;
1702 0 0         if (i < 0)
1703             {
1704 0           return NULL;
1705             }
1706 0 0         if (i == index)
1707             {
1708 0           return ou;
1709             }
1710             }
1711              
1712 0           return NULL;
1713             }
1714              
1715 0           int32_t psX509GetNumDomainComponents(const x509DNattributes_t *DN)
1716             {
1717             x509DomainComponent_t *dc;
1718 0           int32_t res = 0;
1719              
1720 0 0         if (DN == NULL)
1721             {
1722 0           return PS_ARG_FAIL;
1723             }
1724              
1725 0 0         if (DN->domainComponent == NULL)
1726             {
1727 0           return 0;
1728             }
1729              
1730 0           res = 1;
1731 0           dc = DN->domainComponent;
1732 0 0         while (dc->next != NULL)
1733             {
1734 0           dc = dc->next;
1735 0           res++;
1736             }
1737              
1738 0           return res;
1739             }
1740              
1741 0           x509DomainComponent_t *psX509GetDomainComponent(const x509DNattributes_t *DN,
1742             int32_t index)
1743             {
1744             x509DomainComponent_t *dc;
1745             int32_t i;
1746              
1747 0 0         if (DN == NULL || DN->domainComponent == NULL || index < 0)
    0          
    0          
1748             {
1749 0           return NULL;
1750             }
1751              
1752             /*
1753             Note: the DC list is in reverse order. The last item
1754             (i.e the item with largest index) is at the list head.
1755             */
1756              
1757 0           i = psX509GetNumDomainComponents(DN) - 1; /* Largest index. */
1758 0 0         if (i < 0)
1759             {
1760 0           return NULL;
1761             }
1762              
1763 0           dc = DN->domainComponent;
1764 0 0         if (i == index)
1765             {
1766 0           return dc;
1767             }
1768              
1769 0 0         while (dc->next != NULL)
1770             {
1771 0           dc = dc->next;
1772 0           i--;
1773 0 0         if (i < 0)
1774             {
1775 0           return NULL;
1776             }
1777 0 0         if (i == index)
1778             {
1779 0           return dc;
1780             }
1781             }
1782              
1783 0           return NULL;
1784             }
1785              
1786 0           int32_t psX509GetConcatenatedDomainComponent(const x509DNattributes_t *DN,
1787             char **out_str,
1788             size_t *out_str_len)
1789             {
1790             x509DomainComponent_t *dc;
1791 0           int32_t i = 0;
1792 0           psSize_t total_len = 0;
1793 0           int32_t num_dcs = 0;
1794 0           int32_t pos = 0;
1795              
1796 0 0         if (DN == NULL || out_str == NULL)
    0          
1797             {
1798 0           return PS_ARG_FAIL;
1799             }
1800              
1801 0           num_dcs = psX509GetNumDomainComponents(DN);
1802 0 0         if (num_dcs == 0)
1803             {
1804 0           *out_str = NULL;
1805 0           *out_str_len = 0;
1806 0           return PS_SUCCESS;
1807             }
1808              
1809 0 0         for (i = 0; i < num_dcs; i++)
1810             {
1811 0           dc = psX509GetDomainComponent(DN, i);
1812 0 0         if (dc == NULL)
1813             {
1814 0           return PS_FAILURE;
1815             }
1816 0           total_len += dc->len - DN_NUM_TERMINATING_NULLS;
1817             /* We will add a dot between the components. */
1818 0 0         if (i != (num_dcs - 1))
1819             {
1820 0           total_len += 1;
1821             }
1822             }
1823              
1824 0           total_len += DN_NUM_TERMINATING_NULLS;
1825              
1826 0           *out_str = psMalloc(NULL, total_len);
1827 0 0         if (*out_str == NULL)
1828             {
1829 0           return PS_MEM_FAIL;
1830             }
1831 0           memset(*out_str, 0, total_len);
1832              
1833             /* The top-level DC is usually listed first. So we start from the
1834             other end. */
1835 0           pos = 0;
1836 0 0         for (i = num_dcs - 1; i >= 0; i--)
1837             {
1838 0           dc = psX509GetDomainComponent(DN, i);
1839 0 0         if (dc == NULL)
1840             {
1841 0           psFree(*out_str, NULL);
1842 0           *out_str = NULL;
1843 0           return PS_FAILURE;
1844             }
1845 0           memcpy(*out_str + pos, dc->name,
1846 0           dc->len - DN_NUM_TERMINATING_NULLS);
1847 0           pos += dc->len - DN_NUM_TERMINATING_NULLS;
1848 0 0         if (i != 0)
1849             {
1850 0           (*out_str)[pos] = '.';
1851 0           pos++;
1852             }
1853             }
1854              
1855 0 0         if (pos != total_len - DN_NUM_TERMINATING_NULLS)
1856             {
1857 0           psFree(*out_str, NULL);
1858 0           *out_str = NULL;
1859 0           return PS_FAILURE;
1860             }
1861              
1862 0           *out_str_len = (size_t) total_len;
1863              
1864 0           return PS_SUCCESS;
1865             }
1866             # endif /* USE_CERT_PARSE */
1867             # ifdef USE_FULL_CERT_PARSE
1868             /** Long, ugly function that concatenates all the DN components
1869             to produce OpenSSL-style output.
1870              
1871             This function aims to produce output identical
1872             to X509_NAME_oneline(), which seems to be function used by
1873             the openssl x509 utility to print out DNs.
1874              
1875             The amount of code is rather large, so compile this only
1876             when USE_FULL_CERT_PARSE is defined.
1877              
1878             On success, the caller is responsible for freeing the
1879             returned string.
1880             */
1881 0           static int32_t concatenate_dn(psPool_t *pool,
1882             const x509DNattributes_t *dn,
1883             char **out_str,
1884             size_t *out_str_len)
1885             {
1886 0           size_t total_len = 0;
1887             char *str, *p;
1888 0           const char *country_prefix = "C=";
1889 0           const char *state_prefix = "ST=";
1890 0           const char *organization_prefix = "O=";
1891 0           const char *organizationalUnit_prefix = "OU=";
1892 0           const char *dnQualifier_prefix = "/dnQualifier=";
1893 0           const char *commonName_prefix = "CN=";
1894 0           const char *serialNumber_prefix = "/serialNumber=";
1895 0           const char *domainComponent_prefix = "DC=";
1896              
1897             # ifdef USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD
1898 0           const char *locality_prefix = "L=";
1899 0           const char *title_prefix = "/title=";
1900 0           const char *surname_prefix = "SN=";
1901 0           const char *givenName_prefix = "GN=";
1902 0           const char *initials_prefix = "/initials=";
1903 0           const char *pseudonym_prefix = "/pseudonym=";
1904 0           const char *generationQualifier_prefix = "/generationQualifier=";
1905             # endif /* USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD */
1906             # ifdef USE_EXTRA_DN_ATTRIBUTES
1907             const char *streetAddress_prefix = "/street=";
1908             const char *postalAddress_prefix = "/postalAddress=";
1909             const char *telephoneNumber_prefix = "/telephoneNumber=";
1910             const char *uid_prefix = "/UID=";
1911             const char *name_prefix = "/name=";
1912             const char *email_prefix = "/emailAddress=";
1913             # endif /* USE_EXTRA_DN_ATTRIBUTES */
1914             int num_dcs;
1915 0           int first_len = 1;
1916 0           int first_field = 1;
1917             x509OrgUnit_t *orgUnit;
1918             int num_ous;
1919              
1920 0 0         psAssert(dn != NULL && out_str != NULL);
    0          
1921              
1922             # define INC_LEN(X) \
1923             if (dn->X ## Len > 0) { \
1924             if (!first_len && X ## _prefix[0] != '/') { \
1925             total_len += 2; \
1926             } \
1927             first_len = 0; \
1928             total_len += strlen(X ## _prefix) + \
1929             dn->X ## Len - \
1930             DN_NUM_TERMINATING_NULLS; \
1931             }
1932              
1933 0 0         INC_LEN(country);
    0          
    0          
1934 0 0         INC_LEN(state);
    0          
    0          
1935 0 0         INC_LEN(organization);
    0          
    0          
1936 0           num_ous = psX509GetNumOrganizationalUnits(dn);
1937 0 0         if (num_ous > 0)
1938             {
1939             int i;
1940 0 0         for (i = 0; i < num_ous; i++)
1941             {
1942 0           orgUnit = psX509GetOrganizationalUnit(dn, i);
1943 0 0         if (orgUnit == NULL)
1944             {
1945 0           return PS_FAILURE;
1946             }
1947 0 0         if (first_len)
1948             {
1949 0           first_len = 0;
1950             }
1951             else
1952             {
1953 0           total_len += 2;
1954             }
1955 0           total_len += strlen(organizationalUnit_prefix);
1956 0           total_len += orgUnit->len - DN_NUM_TERMINATING_NULLS;
1957             }
1958             }
1959 0 0         INC_LEN(dnQualifier);
    0          
    0          
1960 0 0         INC_LEN(commonName);
    0          
    0          
1961 0 0         INC_LEN(serialNumber);
    0          
    0          
1962              
1963             # ifdef USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD
1964 0 0         INC_LEN(locality);
    0          
    0          
1965 0 0         INC_LEN(title);
    0          
    0          
1966 0 0         INC_LEN(surname);
    0          
    0          
1967 0 0         INC_LEN(givenName);
    0          
    0          
1968 0 0         INC_LEN(initials);
    0          
    0          
1969 0 0         INC_LEN(pseudonym);
    0          
    0          
1970 0 0         INC_LEN(generationQualifier);
    0          
    0          
1971             # endif /* USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD */
1972              
1973             # ifdef USE_EXTRA_DN_ATTRIBUTES
1974             INC_LEN(streetAddress);
1975             INC_LEN(postalAddress);
1976             INC_LEN(telephoneNumber);
1977             INC_LEN(uid);
1978             INC_LEN(name);
1979             INC_LEN(email);
1980             # endif /* USE_EXTRA_DN_ATTRIBUTES */
1981 0           num_dcs = psX509GetNumDomainComponents(dn);
1982 0 0         if (num_dcs > 0)
1983             {
1984             int i;
1985             x509DomainComponent_t *dc;
1986              
1987 0 0         for (i = 0; i < num_dcs; i++)
1988             {
1989 0           total_len += strlen(domainComponent_prefix);
1990 0 0         if (first_len)
1991             {
1992 0           first_len = 0;
1993             }
1994             else
1995             {
1996 0           total_len += 2;
1997             }
1998 0           dc = psX509GetDomainComponent(dn, i);
1999 0 0         if (dc == NULL)
2000             {
2001 0           return PS_FAILURE;
2002             }
2003 0           total_len += dc->len - DN_NUM_TERMINATING_NULLS;
2004             }
2005             }
2006              
2007             /*
2008             Sanity check.*/
2009 0 0         if (total_len > 100000)
2010             {
2011 0           return PS_ARG_FAIL;
2012             }
2013              
2014 0           str = psMalloc(pool, total_len + 1);
2015 0 0         if (str == NULL)
2016             {
2017 0           return PS_MEM_FAIL;
2018             }
2019 0           memset(str, 0, total_len + 1);
2020              
2021 0           p = str;
2022              
2023             /*
2024             We are going to imitate the OpenSSL output format.
2025             For common fields such as country (C) or state (ST), there is
2026             a 1-2 letter ID and the printout is e.g. "ST=[value]".
2027             For other fields, the prefix is "/field_name=[value]".
2028             Note that there is comma and a space ", " before fields with
2029             a 1-2 letter ID, but not before the "/field_name=" fields.
2030             Example:
2031              
2032             C=US, ST=Test State or Province, L=Test Locality, O=Organization Name,
2033             OU=First Organizational Unit Name, OU=Second Organizational Unit
2034             Name, OU=Third Organizational Unit Name, CN=Common Name
2035             /name=GivenName Surname, GN=Givenname, SN=Surname, DC=com,
2036             DC=insidesecure,
2037             DC=test/emailAddress=test@email.address/serialNumber=012bf123aa
2038             /street=MyStreetAddress99/title=Dr./postalAddress=12345
2039             /telephoneNumber=1111-2222-3333/pseudonym=myPseudonym
2040             /generationQualifier=III/initials=G.S.
2041             /dnQualifier=123456789/UID=root
2042             */
2043              
2044             # define PRINT_FIELD(field) \
2045             if (dn->field ## Len > 0) { \
2046             if (first_field) { \
2047             first_field = 0; \
2048             } else { \
2049             if (field ## _prefix[0] != '/') { \
2050             *p++ = ','; \
2051             *p++ = ' '; \
2052             } \
2053             } \
2054             memcpy(p, field ## _prefix, strlen(field ## _prefix)); \
2055             p += strlen(field ## _prefix); \
2056             memcpy(p, dn->field, \
2057             dn->field ## Len - DN_NUM_TERMINATING_NULLS); \
2058             p += dn->field ## Len - DN_NUM_TERMINATING_NULLS; \
2059             }
2060              
2061             /*
2062             The ifdefs are a bit messy, because we wish to use the same
2063             print order as OpenSSL. MatrixSSL divides the fields
2064             into ifdef-wrapped groups differently.
2065             */
2066 0 0         PRINT_FIELD(country);
    0          
    0          
2067 0 0         PRINT_FIELD(state);
    0          
    0          
2068             # ifdef USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD
2069 0 0         PRINT_FIELD(locality);
    0          
    0          
2070             # endif /* USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD */
2071 0 0         PRINT_FIELD(organization);
    0          
    0          
2072 0           num_ous = psX509GetNumOrganizationalUnits(dn);
2073 0 0         if (num_ous > 0)
2074             {
2075             int i;
2076 0 0         for (i = 0; i < num_ous; i++)
2077             {
2078 0           orgUnit = psX509GetOrganizationalUnit(dn, i);
2079 0 0         if (orgUnit == NULL)
2080             {
2081 0           psFree(str, pool);
2082 0           return PS_FAILURE;
2083             }
2084 0 0         if (first_field)
2085             {
2086 0           first_field = 0;
2087             }
2088             else
2089             {
2090 0           *p++ = ',';
2091 0           } *p++ = ' ';
2092 0           memcpy(p, organizationalUnit_prefix,
2093             strlen(organizationalUnit_prefix));
2094 0           p += strlen(organizationalUnit_prefix);
2095 0           memcpy(p, orgUnit->name, orgUnit->len - DN_NUM_TERMINATING_NULLS);
2096 0           p += orgUnit->len - DN_NUM_TERMINATING_NULLS;
2097             }
2098             }
2099 0 0         PRINT_FIELD(commonName);
    0          
    0          
2100             # ifdef USE_EXTRA_DN_ATTRIBUTES
2101             PRINT_FIELD(name);
2102             # endif /* USE_EXTRA_DN_ATTRIBUTES */
2103             # ifdef USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD
2104 0 0         PRINT_FIELD(givenName);
    0          
    0          
2105 0 0         PRINT_FIELD(surname);
    0          
    0          
2106             # endif /* USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD */
2107             # ifdef USE_EXTRA_DN_ATTRIBUTES
2108             /**/
2109             num_dcs = psX509GetNumDomainComponents(dn);
2110             if (num_dcs > 0)
2111             {
2112             int i;
2113             x509DomainComponent_t *dc;
2114              
2115             for (i = 0; i < num_dcs; i++)
2116             {
2117             if (first_field)
2118             {
2119             first_field = 0;
2120             }
2121             else
2122             {
2123             *p++ = ',';
2124             } *p++ = ' ';
2125             memcpy(p, domainComponent_prefix,
2126             strlen(domainComponent_prefix));
2127             p += strlen(domainComponent_prefix);
2128             dc = psX509GetDomainComponent(dn, i);
2129             if (dc == NULL)
2130             {
2131             psFree(str, pool);
2132             return PS_FAILURE;
2133             }
2134             memcpy(p, dc->name, dc->len - DN_NUM_TERMINATING_NULLS);
2135             p += dc->len - DN_NUM_TERMINATING_NULLS;
2136             }
2137             }
2138             PRINT_FIELD(email);
2139             # endif /* USE_EXTRA_DN_ATTRIBUTES */
2140 0 0         PRINT_FIELD(serialNumber);
    0          
    0          
2141             # ifdef USE_EXTRA_DN_ATTRIBUTES
2142             PRINT_FIELD(streetAddress);
2143             # endif /* USE_EXTRA_DN_ATTRIBUTES */
2144             # ifdef USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD
2145 0 0         PRINT_FIELD(title);
    0          
    0          
2146             # endif /* USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD */
2147             # ifdef USE_EXTRA_DN_ATTRIBUTES
2148             PRINT_FIELD(postalAddress);
2149             PRINT_FIELD(telephoneNumber);
2150             # endif /* USE_EXTRA_DN_ATTRIBUTES */
2151             # ifdef USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD
2152 0 0         PRINT_FIELD(pseudonym);
    0          
    0          
2153 0 0         PRINT_FIELD(generationQualifier);
    0          
    0          
2154 0 0         PRINT_FIELD(initials);
    0          
    0          
2155             # endif /* USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD */
2156 0 0         PRINT_FIELD(dnQualifier);
    0          
    0          
2157             # ifdef USE_EXTRA_DN_ATTRIBUTES
2158             PRINT_FIELD(uid);
2159             # endif /* USE_EXTRA_DN_ATTRIBUTES */
2160              
2161 0 0         psAssert(total_len == (p - str));
2162              
2163 0           *p++ = '\0';
2164 0           *out_str = str;
2165 0           *out_str_len = total_len;
2166              
2167 0           return PS_SUCCESS;
2168             }
2169              
2170 0           int32_t psX509GetOnelineDN(const x509DNattributes_t *DN,
2171             char **out_str,
2172             size_t *out_str_len)
2173             {
2174 0           return concatenate_dn(NULL, DN, out_str, out_str_len);
2175             }
2176              
2177             # endif /* USE_FULL_CERT_PARSE */
2178              
2179             /******************************************************************************/
2180             /*
2181             User must call after all calls to psX509ParseCert
2182             (we violate the coding standard a bit here for clarity)
2183             */
2184 2158           void psX509FreeCert(psX509Cert_t *cert)
2185             {
2186             psX509Cert_t *curr, *next;
2187             psPool_t *pool;
2188              
2189 2158           curr = cert;
2190 5038 100         while (curr)
2191             {
2192 2880           pool = curr->pool;
2193 2880 100         if (curr->unparsedBin)
2194             {
2195 258           psFree(curr->unparsedBin, pool);
2196             }
2197             # ifdef USE_CERT_PARSE
2198 2880           psX509FreeDNStruct(&curr->issuer, pool);
2199 2880           psX509FreeDNStruct(&curr->subject, pool);
2200 2880 100         if (curr->serialNumber)
2201             {
2202 2879           psFree(curr->serialNumber, pool);
2203             }
2204 2880 100         if (curr->notBefore)
2205             {
2206 2879           psFree(curr->notBefore, pool);
2207             }
2208 2880 100         if (curr->notAfter)
2209             {
2210 2879           psFree(curr->notAfter, pool);
2211             }
2212 2880 100         if (curr->signature)
2213             {
2214 2879           psFree(curr->signature, pool);
2215             }
2216 2880 50         if (curr->uniqueIssuerId)
2217             {
2218 0           psFree(curr->uniqueIssuerId, pool);
2219             }
2220 2880 50         if (curr->uniqueSubjectId)
2221             {
2222 0           psFree(curr->uniqueSubjectId, pool);
2223             }
2224              
2225              
2226 2880 100         if (curr->publicKey.type != PS_NOKEY)
2227             {
2228 2879           switch (curr->pubKeyAlgorithm)
2229             {
2230             # ifdef USE_RSA
2231             case OID_RSA_KEY_ALG:
2232 2774           psRsaClearKey(&curr->publicKey.key.rsa);
2233 2774           break;
2234             # endif
2235              
2236             # ifdef USE_ECC
2237             case OID_ECDSA_KEY_ALG:
2238 105           psEccClearKey(&curr->publicKey.key.ecc);
2239 105           break;
2240             # endif
2241              
2242             default:
2243 0           psAssert(0);
2244 0           break;
2245             }
2246 2879           curr->publicKey.type = PS_NOKEY;
2247             }
2248              
2249 2880           x509FreeExtensions(&curr->extensions);
2250             # endif /* USE_CERT_PARSE */
2251 2880           next = curr->next;
2252 2880           psFree(curr, pool);
2253 2880           curr = next;
2254             }
2255 2158           }
2256              
2257             /******************************************************************************/
2258             /*
2259             Currently just returning the raw BIT STRING and size in bytes
2260             */
2261             # define MIN_HASH_SIZE 16
2262 2879           int32_t psX509GetSignature(psPool_t *pool, const unsigned char **pp, psSize_t len,
2263             unsigned char **sig, psSize_t *sigLen)
2264             {
2265 2879           const unsigned char *p = *pp, *end;
2266             psSize_t llen;
2267              
2268 2879           end = p + len;
2269 5758 50         if (len < 1 || (*(p++) != ASN_BIT_STRING) ||
2270 5758 50         getAsnLength(&p, len - 1, &llen) < 0 ||
2271 2879 50         (uint32) (end - p) < llen ||
2272 2879           llen < (1 + MIN_HASH_SIZE))
2273             {
2274              
2275             psTraceCrypto("Initial parse error in getSignature\n");
2276 0           return PS_PARSE_FAIL;
2277             }
2278             /* We assume this ignore_bits byte is always 0. */
2279 2879 50         psAssert(*p == 0);
2280 2879           p++;
2281             /* Length was including the ignore_bits byte, subtract it */
2282 2879           *sigLen = llen - 1;
2283 2879           *sig = psMalloc(pool, *sigLen);
2284 2879 50         if (*sig == NULL)
2285             {
2286 0           psError("Memory allocation error in getSignature\n");
2287 0           return PS_MEM_FAIL;
2288             }
2289 2879           memcpy(*sig, p, *sigLen);
2290 2879           *pp = p + *sigLen;
2291 2879           return PS_SUCCESS;
2292             }
2293              
2294             # ifdef USE_CERT_PARSE
2295             /******************************************************************************/
2296             /*
2297             Validate the expected name against a subset of the GeneralName rules
2298             for DNS, Email and IP types.
2299             We assume the expected name is not maliciously entered. If it is, it may
2300             match an invalid GeneralName in a remote cert chain.
2301             Returns 0 on valid format, PS_FAILURE on invalid format of GeneralName
2302             */
2303 0           int32_t psX509ValidateGeneralName(const char *n)
2304             {
2305             const char *c;
2306             int atfound; /* Ampersand found */
2307             int notip; /* Not an ip address */
2308              
2309 0 0         if (n == NULL)
2310             {
2311 0           return 0;
2312             }
2313              
2314             /* Must be at least one character */
2315 0 0         if (*n == '\0')
2316             {
2317 0           return PS_FAILURE;
2318             }
2319              
2320 0           atfound = notip = 0;
2321 0 0         for (c = n; *c != '\0'; c++ )
2322             {
2323              
2324             /* Negative tests first in the loop */
2325             /* Can't have any combination of . and - and @ together */
2326 0 0         if (c != n)
2327             {
2328 0 0         if (*c == '.' && *(c - 1) == '.')
    0          
2329             {
2330 0           return PS_FAILURE;
2331             }
2332 0 0         if (*c == '.' && *(c - 1) == '-')
    0          
2333             {
2334 0           return PS_FAILURE;
2335             }
2336 0 0         if (*c == '.' && *(c - 1) == '@')
    0          
2337             {
2338 0           return PS_FAILURE;
2339             }
2340 0 0         if (*c == '-' && *(c - 1) == '.')
    0          
2341             {
2342 0           return PS_FAILURE;
2343             }
2344 0 0         if (*c == '-' && *(c - 1) == '-')
    0          
2345             {
2346 0           return PS_FAILURE;
2347             }
2348 0 0         if (*c == '-' && *(c - 1) == '@')
    0          
2349             {
2350 0           return PS_FAILURE;
2351             }
2352 0 0         if (*c == '@' && *(c - 1) == '.')
    0          
2353             {
2354 0           return PS_FAILURE;
2355             }
2356 0 0         if (*c == '@' && *(c - 1) == '-')
    0          
2357             {
2358 0           return PS_FAILURE;
2359             }
2360 0 0         if (*c == '@' && *(c - 1) == '@')
    0          
2361             {
2362 0           return PS_FAILURE;
2363             }
2364             }
2365              
2366             /* Note whether we have hit a non numeric name */
2367 0 0         if (*c != '.' && (*c < '0' || *c > '9'))
    0          
    0          
2368             {
2369 0           notip++;
2370             }
2371              
2372             /* Now positive tests */
2373             /* Cannot start or end with . or -, but can contain them */
2374 0 0         if (c != n && *(c + 1) != '\0' && (*c == '.' || *c == '-'))
    0          
    0          
    0          
2375             {
2376 0           continue;
2377             }
2378             /* Can contain at most one @ , and not at the start or end */
2379 0 0         if (*c == '@')
2380             {
2381 0           atfound++;
2382 0 0         if (c != n && *(c + 1) != '\0' && atfound == 1)
    0          
    0          
2383             {
2384 0           continue;
2385             }
2386             }
2387             /* Numbers allowed generally */
2388 0 0         if (*c >= '0' && *c <= '9')
    0          
2389             {
2390 0           continue;
2391             }
2392             /* Upper and lowercase characters allowed */
2393 0 0         if (*c >= 'A' && *c <= 'Z')
    0          
2394             {
2395 0           continue;
2396             }
2397 0 0         if (*c >= 'a' && *c <= 'z')
    0          
2398             {
2399 0           continue;
2400             }
2401              
2402             /* Everything else is a failure */
2403 0           return PS_FAILURE;
2404             }
2405             /* RFC 1034 states if it's not an IP, it can't start with a number,
2406             However, RFC 1123 updates this and does allow a number as the
2407             first character of a DNS name.
2408             See the X.509 RFC: http://tools.ietf.org/html/rfc5280#section-4.2.1.6 */
2409 0 0         if (atfound && (*n >= '0' && *n <= '9'))
    0          
    0          
2410             {
2411 0           return PS_FAILURE;
2412             }
2413              
2414             /* We could at this point store whether it is a DNS, Email or IP */
2415              
2416 0           return 0;
2417             }
2418              
2419             /******************************************************************************/
2420             /*
2421             Parses a sequence of GeneralName types*/
2422 183           static int32_t parseGeneralNames(psPool_t *pool, const unsigned char **buf,
2423             psSize_t len, const unsigned char *extEnd,
2424             x509GeneralName_t **name, int16_t limit)
2425             {
2426             psSize_t otherNameLen;
2427             const unsigned char *p, *c, *save, *end;
2428             x509GeneralName_t *activeName, *firstName, *prevName;
2429              
2430 183 100         if (*name == NULL)
2431             {
2432 128           firstName = NULL;
2433             }
2434             else
2435             {
2436 55           firstName = *name;
2437             }
2438 183           p = *buf;
2439 183           end = p + len;
2440              
2441             # define MIN_GENERALNAME_LEN 3 /* 1 tag, 1 length octet, 1 content octet.*/
2442 371 100         while (len > MIN_GENERALNAME_LEN)
2443             {
2444 188 100         if (firstName == NULL)
2445             {
2446 128           activeName = firstName = psMalloc(pool, sizeof(x509GeneralName_t));
2447 128 50         if (activeName == NULL)
2448             {
2449 0           return PS_MEM_FAIL;
2450             }
2451 128           memset(firstName, 0x0, sizeof(x509GeneralName_t));
2452 128           firstName->pool = pool;
2453 128           *name = firstName;
2454             }
2455             else
2456             {
2457             /*
2458             Find the end
2459             */
2460 60           prevName = firstName;
2461 60           activeName = firstName->next;
2462 165 100         while (activeName != NULL)
2463             {
2464 105           prevName = activeName;
2465 105           activeName = activeName->next;
2466             }
2467 60           prevName->next = psMalloc(pool, sizeof(x509GeneralName_t));
2468 60 50         if (prevName->next == NULL)
2469             {
2470 0           return PS_MEM_FAIL;
2471             }
2472 60           activeName = prevName->next;
2473 60           memset(activeName, 0x0, sizeof(x509GeneralName_t));
2474 60           activeName->pool = pool;
2475             }
2476 188           activeName->id = *p & 0xF;
2477 188           p++; len--;
2478 188           switch (activeName->id)
2479             {
2480             case GN_OTHER:
2481 0           strncpy((char *) activeName->name, "other",
2482             sizeof(activeName->name) - 1);
2483             /* OtherName ::= SEQUENCE {
2484             type-id OBJECT IDENTIFIER,
2485             value [0] EXPLICIT ANY DEFINED BY type-id }
2486             */
2487 0           save = p;
2488 0 0         if (getAsnLength(&p, (uint32) (extEnd - p), &otherNameLen) < 0 ||
    0          
2489 0 0         otherNameLen < 1 ||
2490 0           (uint32) (extEnd - p) < otherNameLen)
2491             {
2492             psTraceCrypto("ASN parse error SAN otherName\n");
2493 0           return PS_PARSE_FAIL;
2494             }
2495 0 0         if (*(p++) != ASN_OID
2496 0 0         || getAsnLength(&p, (int32) (extEnd - p), &activeName->oidLen) < 0
2497 0 0         || (uint32) (extEnd - p) < activeName->oidLen
2498 0 0         || activeName->oidLen > sizeof(activeName->oid))
2499             {
2500              
2501             psTraceCrypto("ASN parse error SAN otherName oid\n");
2502 0           return -1;
2503             }
2504             /* Note activeName->oidLen could be zero here */
2505 0           memcpy(activeName->oid, p, activeName->oidLen);
2506 0           p += activeName->oidLen;
2507             /* value looks like
2508             0xA0, , , ,
2509             We're supporting only string-type TYPE so just skipping it
2510             */
2511 0 0         if ((uint32) (extEnd - p) < 1 || *p != 0xA0)
    0          
2512             {
2513             psTraceCrypto("ASN parse error SAN otherName\n");
2514 0           return PS_PARSE_FAIL;
2515             }
2516 0           p++; /* Jump over A0 */
2517 0 0         if (getAsnLength(&p, (uint32) (extEnd - p), &otherNameLen) < 0 ||
    0          
2518 0 0         otherNameLen < 1 ||
2519 0           (uint32) (extEnd - p) < otherNameLen)
2520             {
2521             psTraceCrypto("ASN parse error SAN otherName value\n");
2522 0           return PS_PARSE_FAIL;
2523             }
2524 0 0         if ((uint32) (extEnd - p) < 1)
2525             {
2526             psTraceCrypto("ASN parse error SAN otherName len\n");
2527 0           return PS_PARSE_FAIL;
2528             }
2529             /* TODO - validate *p == STRING type? */
2530 0           p++; /* Jump over TYPE */
2531 0 0         if (len <= (p - save))
2532             {
2533             psTraceCrypto("ASN len error in parseGeneralNames\n");
2534 0           return PS_PARSE_FAIL;
2535             }
2536             else
2537             {
2538 0           len -= (p - save);
2539             }
2540 0           break;
2541             case GN_EMAIL:
2542 60           strncpy((char *) activeName->name, "email",
2543             sizeof(activeName->name) - 1);
2544 60           break;
2545             case GN_DNS:
2546 21           strncpy((char *) activeName->name, "DNS",
2547             sizeof(activeName->name) - 1);
2548 21           break;
2549             case GN_X400:
2550 0           strncpy((char *) activeName->name, "x400Address",
2551             sizeof(activeName->name) - 1);
2552 0           break;
2553             case GN_DIR:
2554 5           strncpy((char *) activeName->name, "directoryName",
2555             sizeof(activeName->name) - 1);
2556 5           break;
2557             case GN_EDI:
2558 0           strncpy((char *) activeName->name, "ediPartyName",
2559             sizeof(activeName->name) - 1);
2560 0           break;
2561             case GN_URI:
2562 102           strncpy((char *) activeName->name, "URI",
2563             sizeof(activeName->name) - 1);
2564 102           break;
2565             case GN_IP:
2566 0           strncpy((char *) activeName->name, "iPAddress",
2567             sizeof(activeName->name) - 1);
2568 0           break;
2569             case GN_REGID:
2570 0           strncpy((char *) activeName->name, "registeredID",
2571             sizeof(activeName->name) - 1);
2572 0           break;
2573             default:
2574 0           strncpy((char *) activeName->name, "unknown",
2575             sizeof(activeName->name) - 1);
2576 0           break;
2577             }
2578              
2579 188           save = p;
2580 188 50         if (getAsnLength(&p, (uint32) (extEnd - p), &activeName->dataLen) < 0 ||
    50          
2581 188 50         activeName->dataLen < 1 ||
2582 188           (uint32) (extEnd - p) < activeName->dataLen)
2583             {
2584             psTraceCrypto("ASN len error in parseGeneralNames\n");
2585 0           return PS_PARSE_FAIL;
2586             }
2587 188 50         if (len <= (p - save))
2588             {
2589             psTraceCrypto("ASN len error in parseGeneralNames\n");
2590 0           return PS_PARSE_FAIL;
2591             }
2592             else
2593             {
2594 188           len -= (p - save);
2595             }
2596 188 50         if (len < activeName->dataLen)
2597             {
2598             psTraceCrypto("ASN len error in parseGeneralNames\n");
2599 0           return PS_PARSE_FAIL;
2600             }
2601              
2602             /* Currently we validate that the IA5String fields are printable
2603             At a minimum, this prevents attacks with null terminators or
2604             invisible characters in the certificate.
2605             Additional validation of name format is done indirectly
2606             via byte comparison to the expected name in ValidateGeneralName
2607             or directly by the user in the certificate callback */
2608 188           switch (activeName->id)
2609             {
2610             case GN_EMAIL:
2611             case GN_DNS:
2612             case GN_URI:
2613 183           save = p + activeName->dataLen;
2614 7357 100         for (c = p; c < save; c++)
2615             {
2616 7174 50         if (*c < ' ' || *c > '~')
    50          
2617             {
2618             psTraceCrypto("ASN invalid GeneralName character\n");
2619 0           return PS_PARSE_FAIL;
2620             }
2621             }
2622 183           break;
2623             case GN_IP:
2624 0 0         if (activeName->dataLen < 4)
2625             {
2626             psTraceCrypto("Unknown GN_IP format\n");
2627 0           return PS_PARSE_FAIL;
2628             }
2629 0           break;
2630             default:
2631 5           break;
2632             }
2633              
2634 188           activeName->data = psMalloc(pool, activeName->dataLen + 1);
2635 188 50         if (activeName->data == NULL)
2636             {
2637 0           psError("Memory allocation error: activeName->data\n");
2638 0           return PS_MEM_FAIL;
2639             }
2640             /* This guarantees data is null terminated, even for non IA5Strings */
2641 188           memset(activeName->data, 0x0, activeName->dataLen + 1);
2642 188           memcpy(activeName->data, p, activeName->dataLen);
2643              
2644 188           p = p + activeName->dataLen;
2645 188           len -= activeName->dataLen;
2646              
2647 188 50         if (limit > 0)
2648             {
2649 0 0         if (--limit == 0)
2650             {
2651 0           *buf = end;
2652 0           return PS_SUCCESS;
2653             }
2654             }
2655             }
2656 183           *buf = p;
2657 183           return PS_SUCCESS;
2658             }
2659              
2660             /**
2661             Look up an OID in our known oid table.
2662             @param[in] oid Array of OID segments to look up in table.
2663             @param[in] oidlen Number of segments in 'oid'
2664             @return A valid OID enum on success, 0 on failure.
2665             */
2666 10733           static oid_e psFindOid(const uint32_t oid[MAX_OID_LEN], uint8_t oidlen)
2667             {
2668             int i, j;
2669              
2670 10733 50         psAssert(oidlen <= MAX_OID_LEN);
2671 89380 100         for (j = 0; oid_list[j].id != 0; j++)
2672             {
2673 242062 50         for (i = 0; i < oidlen; i++)
2674             {
2675 242062 100         if ((uint16_t) (oid[i] & 0xFFFF) != oid_list[j].oid[i])
2676             {
2677 78647           break;
2678             }
2679 163415 100         if ((i + 1) == oidlen)
2680             {
2681 9229           return oid_list[j].id;
2682             }
2683             }
2684             }
2685 1504           return 0;
2686             }
2687              
2688             # ifdef USE_CRYPTO_TRACE
2689             /**
2690             Print an OID in dot notation, with it's symbolic name, if found.
2691             @param[in] oid Array of OID segments print.
2692             @param[in] oidlen Number of segments in 'oid'
2693             @return void
2694             */
2695             static void psTraceOid(uint32_t oid[MAX_OID_LEN], uint8_t oidlen)
2696             {
2697             int i, j, found;
2698              
2699             for (i = 0; i < oidlen; i++)
2700             {
2701             if ((i + 1) < oidlen)
2702             {
2703             psTraceIntCrypto("%u.", oid[i]);
2704             }
2705             else
2706             {
2707             psTraceIntCrypto("%u", oid[i]);
2708             }
2709             }
2710             found = 0;
2711             for (j = 0; oid_list[j].oid[0] != 0 && !found; j++)
2712             {
2713             for (i = 0; i < oidlen; i++)
2714             {
2715             if ((uint8_t) (oid[i] & 0xFF) != oid_list[j].oid[i])
2716             {
2717             break;
2718             }
2719             if ((i + 1) == oidlen)
2720             {
2721             psTraceStrCrypto(" (%s)", oid_list[j].name);
2722             found++;
2723             }
2724             }
2725             }
2726             psTraceCrypto("\n");
2727             }
2728             # else
2729             # define psTraceOid(A, B)
2730             # endif
2731              
2732             /******************************************************************************/
2733             /*
2734             X509v3 extensions
2735             */
2736              
2737             # ifdef USE_FULL_CERT_PARSE
2738             static
2739 111           int32_t parsePolicyQualifierInfo(psPool_t *pool,
2740             const unsigned char *p,
2741             const unsigned char *extEnd,
2742             psSize_t fullExtLen,
2743             x509PolicyQualifierInfo_t *qualInfo,
2744             psSize_t *qual_info_len)
2745             {
2746 111           uint32_t oid[MAX_OID_LEN] = { 0 };
2747             uint8_t oidlen;
2748             oid_e noid;
2749             psSize_t len;
2750             const unsigned char *qualifierStart, *qualifierEnd;
2751             const unsigned char *noticeNumbersEnd;
2752             int i;
2753             int32_t noticeNumber;
2754              
2755 111           qualifierStart = p;
2756              
2757             /* Parse a PolicyQualifierInfo. */
2758 111 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
2759             {
2760             psTraceCrypto("Error parsing certificatePolicies extension\n");
2761 0           return PS_PARSE_FAIL;
2762             }
2763 111           *qual_info_len = len + (p - qualifierStart);
2764 111           qualifierEnd = qualifierStart + *qual_info_len;
2765              
2766             /* Parse policyQualifierId. */
2767 111 50         if (len < 1 || *p++ != ASN_OID)
    50          
2768             {
2769             psTraceCrypto("Malformed policy qualifier header\n");
2770 0           return PS_PARSE_FAIL;
2771             }
2772 111 50         if (getAsnLength(&p, fullExtLen, &len) < 0 ||
    50          
2773 111           fullExtLen < len)
2774             {
2775             psTraceCrypto("Malformed extension length\n");
2776 0           return PS_PARSE_FAIL;
2777             }
2778 111 50         if ((oidlen = asnParseOid(p, len, oid)) < 1)
2779             {
2780             psTraceCrypto("Malformed extension OID\n");
2781 0           return PS_PARSE_FAIL;
2782             }
2783             /* PolicyQualifierId ::= OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice )*/
2784 111           noid = psFindOid(oid, oidlen);
2785 111           p += len;
2786 111 100         if (noid == oid_id_qt_cps)
2787             {
2788 81 50         if (*p++ != ASN_IA5STRING)
2789             {
2790             psTraceCrypto("Malformed extension OID\n");
2791 0           return PS_PARSE_FAIL;
2792             }
2793 81 50         if (getAsnLength(&p, fullExtLen, &len) < 0 ||
    50          
2794 81           fullExtLen < len)
2795             {
2796             psTraceCrypto("Malformed extension length\n");
2797 0           return PS_PARSE_FAIL;
2798             }
2799 81           qualInfo->cps = psMalloc(pool, len + 1);
2800 81           qualInfo->cpsLen = len;
2801 81           memcpy(qualInfo->cps,
2802             p, len);
2803 81           qualInfo->cps[len] = 0; /* Store as C string. */
2804 81           p += len;
2805             }
2806 30 50         else if (noid == oid_id_qt_unotice)
2807             {
2808              
2809             /* UserNotice ::= SEQUENCE {
2810             noticeRef NoticeReference OPTIONAL,
2811             explicitText DisplayText OPTIONAL } */
2812 30 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
2813             {
2814             psTraceCrypto("Error parsing certificatePolicies extension\n");
2815 0           return PS_PARSE_FAIL;
2816             }
2817 30 50         if (len == 0 || p >= qualifierEnd)
    50          
2818             {
2819             /* No optional noticeRef or explicitText.
2820             Nothing left to parse. */
2821 0           return PS_SUCCESS;
2822             }
2823 30 50         if (*p == (ASN_SEQUENCE | ASN_CONSTRUCTED))
2824             {
2825             /* NoticeReference ::= SEQUENCE {
2826             organization DisplayText,
2827             noticeNumbers SEQUENCE OF INTEGER } */
2828 0 0         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
2829             {
2830             psTraceCrypto("Error parsing certificatePolicies extension\n");
2831 0           return PS_PARSE_FAIL;
2832             }
2833             /* Parse explicitText. */
2834 0 0         if (*p != ASN_UTF8STRING &&
    0          
2835 0 0         *p != ASN_VISIBLE_STRING &&
2836 0 0         *p != ASN_BMPSTRING &&
2837 0           *p != ASN_IA5STRING)
2838             {
2839             psTraceCrypto("Error parsing certificatePolicies extension."
2840             "Only UTF8String, IA5String, BMPString and "
2841             "VisibleString are supported in NoticeReferences.\n");
2842 0           return PS_PARSE_FAIL;
2843             }
2844 0           qualInfo->unoticeOrganizationEncoding = *p;
2845 0           p++;
2846             /* Parse organization. */
2847 0 0         if (getAsnLength(&p, fullExtLen, &len) < 0 ||
    0          
2848 0           fullExtLen < len)
2849             {
2850             psTraceCrypto("Malformed extension length\n");
2851 0           return PS_PARSE_FAIL;
2852             }
2853 0           qualInfo->unoticeOrganization = psMalloc(pool, len + 1);
2854 0 0         if (qualInfo->unoticeOrganization == NULL)
2855             {
2856 0           return PS_MEM_FAIL;
2857             }
2858 0           qualInfo->unoticeOrganizationLen = len;
2859 0           memcpy(qualInfo->unoticeOrganization, p, len);
2860 0           qualInfo->unoticeOrganization[len] = 0; /* Store as C string. */
2861 0           p += len;
2862             /* Parse noticeNumbers. */
2863 0 0         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
2864             {
2865             psTraceCrypto("Error parsing certificatePolicies extension\n");
2866 0           return PS_PARSE_FAIL;
2867             }
2868 0           noticeNumbersEnd = p + len;
2869 0           i = 0;
2870 0 0         while (p != noticeNumbersEnd)
2871             {
2872 0 0         if (i == MAX_UNOTICE_NUMBERS)
2873             {
2874             psTraceCrypto("Too many UserNoticeNumbers.\n");
2875 0           return PS_PARSE_FAIL;
2876             }
2877 0 0         if (getAsnInteger(&p, len, ¬iceNumber) < 0)
2878             {
2879             psTraceCrypto("Malformed extension length\n");
2880 0           return PS_PARSE_FAIL;
2881             }
2882 0           qualInfo->unoticeNumbers[i] = noticeNumber;
2883 0           i++;
2884             }
2885 0           qualInfo->unoticeNumbersLen = i;
2886             }
2887 30 50         if (p >= qualifierEnd)
2888             {
2889             /* The UserNotice contained noticeRef, but not explicitText. */
2890 0           return PS_SUCCESS;
2891             }
2892             /* Parse explicitText. */
2893 30 50         if (*p != ASN_UTF8STRING &&
    100          
2894 10 50         *p != ASN_VISIBLE_STRING &&
2895 0 0         *p != ASN_BMPSTRING &&
2896 0           *p != ASN_IA5STRING)
2897             {
2898             psTraceCrypto("Error parsing certificatePolicies extension."
2899             "Only UTF8String, IA5String, BMPString and "
2900             "VisibleString are supported in explicitText.\n");
2901 0           return PS_PARSE_FAIL;
2902             }
2903 30           qualInfo->unoticeExplicitTextEncoding = *p;
2904 30           p++;
2905 30 50         if (getAsnLength(&p, fullExtLen, &len) < 0 ||
    50          
2906 30           fullExtLen < len)
2907             {
2908             psTraceCrypto("Malformed extension length\n");
2909 0           return PS_PARSE_FAIL;
2910             }
2911 30           qualInfo->unoticeExplicitText = psMalloc(pool, len + 1);
2912 30 50         if (qualInfo->unoticeExplicitText == NULL)
2913             {
2914 0           return PS_MEM_FAIL;
2915             }
2916 30           qualInfo->unoticeExplicitTextLen = len;
2917 30           memcpy(qualInfo->unoticeExplicitText, p, len);
2918 30           qualInfo->unoticeExplicitText[len] = 0; /* Store as C string. */
2919 30           p += len;
2920             }
2921             else
2922             {
2923             psTraceCrypto("Unsupported policyQualifierId\n");
2924 0           return PS_PARSE_FAIL;
2925             }
2926              
2927 111           return PS_SUCCESS;
2928             }
2929              
2930             static
2931 88           int32_t parsePolicyInformation(psPool_t *pool,
2932             const unsigned char *p,
2933             const unsigned char *extEnd,
2934             psSize_t fullExtLen,
2935             x509PolicyInformation_t *polInfo,
2936             psSize_t *pol_info_len)
2937             {
2938 88           uint32_t oid[MAX_OID_LEN] = { 0 };
2939             uint8_t oidlen;
2940             psSize_t len;
2941             const unsigned char *qualifierEnd;
2942             const unsigned char *polInfoStart, *polInfoEnd;
2943             x509PolicyQualifierInfo_t *qualInfo;
2944             psSize_t qualInfoLen;
2945             int i;
2946              
2947 88           polInfoStart = p;
2948              
2949             /*
2950             PolicyInformation ::= SEQUENCE {
2951             policyIdentifier CertPolicyId,
2952             policyQualifiers SEQUENCE SIZE (1..MAX) OF
2953             PolicyQualifierInfo OPTIONAL }
2954             */
2955              
2956 88 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
2957             {
2958             psTraceCrypto("Error parsing certificatePolicies extension\n");
2959 0           return PS_PARSE_FAIL;
2960             }
2961 88           *pol_info_len = len + (p - polInfoStart);
2962 88           polInfoEnd = polInfoStart + *pol_info_len;
2963              
2964             /* Parse CertPolicyId. */
2965 88 50         if (*p++ != ASN_OID)
2966             {
2967             psTraceCrypto("Malformed extension header\n");
2968 0           return PS_PARSE_FAIL;
2969             }
2970 88 50         if (getAsnLength(&p, fullExtLen, &len) < 0 ||
    50          
2971 88           fullExtLen < len)
2972             {
2973             psTraceCrypto("Malformed extension length\n");
2974 0           return PS_PARSE_FAIL;
2975             }
2976 88 50         if ((oidlen = asnParseOid(p, len, oid)) < 1)
2977             {
2978             psTraceCrypto("Malformed extension OID\n");
2979 0           return PS_PARSE_FAIL;
2980             }
2981 88           p += len;
2982 88 50         if (oidlen == 0 || oidlen > MAX_OID_LEN)
    50          
2983             {
2984             psTraceCrypto("Malformed extension OID\n");
2985 0           return PS_PARSE_FAIL;
2986             }
2987              
2988             /* Store the policy ID. */
2989 88           polInfo->policyOid = psMalloc(pool, oidlen * sizeof(uint32_t));
2990 88 50         if (polInfo->policyOid == NULL)
2991             {
2992 0           return PS_MEM_FAIL;
2993             }
2994 755 100         for (i = 0; i < oidlen; i++)
2995             {
2996 667           polInfo->policyOid[i] = oid[i];
2997             }
2998 88           polInfo->policyOidLen = oidlen;
2999              
3000 88 100         if ((p >= polInfoEnd) ||
    50          
3001 81           (*p != (ASN_SEQUENCE | ASN_CONSTRUCTED)))
3002             {
3003             /* No optional PolicyQualifierInfos. */
3004 7           return PS_SUCCESS;
3005             }
3006              
3007             /* Parse policyQualifiers := SEQUENCE SIZE (1..MAX) OF
3008             PolicyQualifierInfo OPTIONAL*/
3009 81 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
3010             {
3011             psTraceCrypto("Error parsing certificatePolicies extension\n");
3012 0           return PS_PARSE_FAIL;
3013             }
3014 81           qualifierEnd = p + len;
3015              
3016 81           polInfo->qualifiers = psMalloc(pool, sizeof(x509PolicyQualifierInfo_t));
3017 81 50         if (polInfo->qualifiers == NULL)
3018             {
3019 0           return PS_MEM_FAIL;
3020             }
3021 81           memset(polInfo->qualifiers, 0, sizeof(x509PolicyQualifierInfo_t));
3022 81           qualInfo = polInfo->qualifiers;
3023              
3024             /* Parse initial PolicyQualifierInfo. */
3025 81 50         if (parsePolicyQualifierInfo(pool,
3026             p,
3027             extEnd,
3028             fullExtLen,
3029             qualInfo,
3030             &qualInfoLen) < 0)
3031             {
3032 0           return PS_PARSE_FAIL;
3033             }
3034 81           p += qualInfoLen;
3035              
3036             /* More PolicyQualifierInfos? */
3037 111 100         while ((p < qualifierEnd)
3038 30 50         && (p < extEnd)
3039 30 50         && (*p == (ASN_SEQUENCE | ASN_CONSTRUCTED)))
3040             {
3041 30           qualInfo->next = psMalloc(pool, sizeof(x509PolicyQualifierInfo_t));
3042 30 50         if (qualInfo->next == NULL)
3043             {
3044 0           return PS_MEM_FAIL;
3045             }
3046 30           memset(qualInfo->next, 0, sizeof(x509PolicyQualifierInfo_t));
3047 30           qualInfo = qualInfo->next;
3048              
3049 30 50         if (parsePolicyQualifierInfo(pool,
3050             p,
3051             extEnd,
3052             fullExtLen,
3053             qualInfo,
3054             &qualInfoLen) < 0)
3055             {
3056 0           return PS_PARSE_FAIL;
3057             }
3058 30           p += qualInfoLen;
3059             }
3060              
3061 88           return PS_SUCCESS;
3062             }
3063              
3064             static
3065 0           int32_t parsePolicyConstraints(psPool_t *pool,
3066             const unsigned char *p,
3067             const unsigned char *extEnd,
3068             x509policyConstraints_t *policyConstraints,
3069             psSize_t *polConstraintsLen)
3070             {
3071             psSize_t len;
3072             const unsigned char *polConstraintsStart, *polConstraintsEnd;
3073             unsigned char tag;
3074 0           int num_ints = 0;
3075              
3076             /*
3077             PolicyConstraints ::= SEQUENCE {
3078             requireExplicitPolicy [0] SkipCerts OPTIONAL,
3079             inhibitPolicyMapping [1] SkipCerts OPTIONAL }
3080              
3081             SkipCerts ::= INTEGER (0..MAX)
3082             */
3083              
3084 0           polConstraintsStart = p;
3085              
3086 0 0         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
3087             {
3088             psTraceCrypto("Error parsing policyConstraints extension\n");
3089 0           return PS_PARSE_FAIL;
3090             }
3091 0           polConstraintsEnd = p + len;
3092 0           *polConstraintsLen = (polConstraintsEnd - polConstraintsStart);
3093              
3094 0 0         if (len == 0)
3095             {
3096             /* Empty PolicyConstraints. This is allowed by RFC 5280:
3097             "The behavior of clients that encounter an empty policy
3098             constraints field is not addressed in this profile.*/
3099 0           return PS_SUCCESS;
3100             }
3101              
3102             /* Parse up to 2 SkipCerts INTEGERS with context-specific tags 0 and 1. */
3103 0 0         while ( num_ints < 2 && (*p == ASN_CONTEXT_SPECIFIC ||
    0          
    0          
3104 0           *p == (ASN_CONTEXT_SPECIFIC + 1)) )
3105             {
3106 0           tag = *p++;
3107 0 0         if (getAsnLength(&p, (uint32) (polConstraintsEnd - p), &len) < 0 ||
    0          
3108 0           (uint32) (polConstraintsEnd - p) < len)
3109             {
3110             psTraceCrypto("getAsnLength failure in policyConstraints parsing\n");
3111 0           return PS_PARSE_FAIL;
3112             }
3113             /* We only accept single-octet SkipCerts values. Should be enough
3114             for all reasonable applications. */
3115 0 0         if (len != 1)
3116             {
3117             psTraceCrypto("Too large SkipCerts value in PolicyConstraints.\n");
3118 0           return PS_PARSE_FAIL;
3119             }
3120 0 0         if (tag == ASN_CONTEXT_SPECIFIC)
3121             {
3122 0           policyConstraints->requireExplicitPolicy = (int32_t) *p;
3123             }
3124             else
3125             {
3126 0           policyConstraints->inhibitPolicyMappings = (int32_t) *p;
3127             }
3128 0           p += len;
3129 0           ++num_ints;
3130             }
3131              
3132 0 0         if (p != polConstraintsEnd)
3133             {
3134             psTraceCrypto("Error parsing policyConstraints extension\n");
3135 0           return PS_PARSE_FAIL;
3136             }
3137              
3138 0           return PS_SUCCESS;
3139             }
3140              
3141             static
3142 5           int32_t parsePolicyMappings(psPool_t *pool,
3143             const unsigned char *p,
3144             const unsigned char *extEnd,
3145             x509policyMappings_t *policyMappings,
3146             psSize_t *polMappingsLen)
3147             {
3148 5           uint32_t oid[MAX_OID_LEN] = { 0 };
3149             psSize_t len, oidlen;
3150             const unsigned char *polMappingsStart, *polMappingsEnd;
3151             x509policyMappings_t *pol_map;
3152             int i;
3153 5           int num_mappings = 0;
3154              
3155             /*
3156             PolicyMappings ::= SEQUENCE SIZE (1..MAX) OF SEQUENCE {
3157             issuerDomainPolicy CertPolicyId,
3158             subjectDomainPolicy CertPolicyId }
3159             */
3160              
3161 5           polMappingsStart = p;
3162              
3163 5 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
3164             {
3165             psTraceCrypto("Error parsing policyMappings extension\n");
3166 0           return PS_PARSE_FAIL;
3167             }
3168 5           polMappingsEnd = p + len;
3169 5           *polMappingsLen = (polMappingsEnd - polMappingsStart);
3170              
3171 5           pol_map = policyMappings;
3172 10 100         while (p < polMappingsEnd &&
    50          
3173 5           *p == (ASN_SEQUENCE | ASN_CONSTRUCTED))
3174             {
3175              
3176 5 50         if (num_mappings > 0)
3177             {
3178 0           pol_map->next = psMalloc(pool, sizeof(x509policyMappings_t));
3179 0 0         if (pol_map->next == NULL)
3180             {
3181 0           return PS_MEM_FAIL;
3182             }
3183 0           memset(pol_map->next, 0, sizeof(x509policyMappings_t));
3184 0           pol_map = pol_map->next;
3185             }
3186              
3187 5 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
3188             {
3189             psTraceCrypto("Error parsing policyMappings extension\n");
3190 0           return PS_PARSE_FAIL;
3191             }
3192              
3193             /* Parse issuerDomainPolicy OID. */
3194 5 50         if (*p++ != ASN_OID)
3195             {
3196             psTraceCrypto("Malformed extension header\n");
3197 0           return PS_PARSE_FAIL;
3198             }
3199              
3200 5 50         if (getAsnLength(&p, (uint32) (polMappingsEnd - p), &len) < 0 ||
    50          
3201 5           (uint32) (polMappingsEnd - p) < len)
3202             {
3203             psTraceCrypto("getAsnLength failure in policyMappings parsing\n");
3204 0           return PS_PARSE_FAIL;
3205             }
3206 5           memset(oid, 0, sizeof(oid));
3207 5 50         if ((oidlen = asnParseOid(p, len, oid)) < 1)
3208             {
3209             psTraceCrypto("Malformed extension OID\n");
3210 0           return PS_PARSE_FAIL;
3211             }
3212 5           p += len;
3213              
3214 5           pol_map->issuerDomainPolicy = psMalloc(pool,
3215             oidlen * sizeof(uint32_t));
3216 5           memset(pol_map->issuerDomainPolicy, 0, oidlen * sizeof(uint32_t));
3217              
3218 40 100         for (i = 0; i < oidlen; i++)
3219             {
3220 35           pol_map->issuerDomainPolicy[i] = oid[i];
3221             }
3222 5           pol_map->issuerDomainPolicyLen = oidlen;
3223              
3224             /* Parse subjectDomainPolicy OID. */
3225 5 50         if (*p++ != ASN_OID)
3226             {
3227             psTraceCrypto("Malformed extension header\n");
3228 0           return PS_PARSE_FAIL;
3229             }
3230              
3231 5 50         if (getAsnLength(&p, (uint32) (polMappingsEnd - p), &len) < 0 ||
    50          
3232 5           (uint32) (polMappingsEnd - p) < len)
3233             {
3234             psTraceCrypto("getAsnLength failure in policyMappings parsing\n");
3235 0           return PS_PARSE_FAIL;
3236             }
3237 5           memset(oid, 0, sizeof(oid));
3238 5 50         if ((oidlen = asnParseOid(p, len, oid)) < 1)
3239             {
3240             psTraceCrypto("Malformed extension OID\n");
3241 0           return PS_PARSE_FAIL;
3242             }
3243 5           p += len;
3244              
3245 5           pol_map->subjectDomainPolicy = psMalloc(pool,
3246             oidlen * sizeof(uint32_t));
3247 5           memset(pol_map->subjectDomainPolicy, 0, oidlen * sizeof(uint32_t));
3248              
3249 40 100         for (i = 0; i < oidlen; i++)
3250             {
3251 35           pol_map->subjectDomainPolicy[i] = oid[i];
3252             }
3253 5           pol_map->subjectDomainPolicyLen = oidlen;
3254              
3255 5           ++num_mappings;
3256             }
3257              
3258 5 50         if (p != polMappingsEnd)
3259             {
3260             psTraceCrypto("Error parsing policyMappings extension\n");
3261 0           return PS_PARSE_FAIL;
3262             }
3263              
3264 5           return PS_SUCCESS;
3265             }
3266              
3267             static
3268 12           int32_t parseAuthorityInfoAccess(psPool_t *pool,
3269             const unsigned char *p,
3270             const unsigned char *extEnd,
3271             x509authorityInfoAccess_t **authInfo,
3272             psSize_t *authInfoLen)
3273             {
3274             psSize_t len, oidlen, adLen;
3275             const unsigned char *authInfoStart, *authInfoEnd;
3276             x509authorityInfoAccess_t *pAuthInfo;
3277 12           uint32_t oid[MAX_OID_LEN] = { 0 };
3278             oid_e noid;
3279 12           int first_entry = 0;
3280              
3281 12           authInfoStart = p;
3282             /*
3283              
3284             id-pe-authorityInfoAccess OBJECT IDENTIFIER ::= { id-pe 1 }
3285              
3286             AuthorityInfoAccessSyntax ::=
3287             SEQUENCE SIZE (1..MAX) OF AccessDescription
3288              
3289             AccessDescription ::= SEQUENCE {
3290             accessMethod OBJECT IDENTIFIER,
3291             accessLocation GeneralName }
3292              
3293             id-ad OBJECT IDENTIFIER ::= { id-pkix 48 }
3294              
3295             id-ad-caIssuers OBJECT IDENTIFIER ::= { id-ad 2 }
3296              
3297             id-ad-ocsp OBJECT IDENTIFIER ::= { id-ad 1 }
3298             */
3299              
3300             /* AuthorityInfoAccessSyntax. */
3301 12 50         if (getAsnSequence(&p, (int32) (extEnd - p), &len) < 0)
3302             {
3303             psTraceCrypto("Error parsing authKeyId extension\n");
3304 0           return PS_PARSE_FAIL;
3305             }
3306              
3307 12           authInfoEnd = p + len;
3308 12           *authInfoLen = (authInfoEnd - authInfoStart);
3309              
3310 12 50         if (*authInfo == NULL)
3311             {
3312 12           *authInfo = psMalloc(pool, sizeof(x509authorityInfoAccess_t));
3313 12 50         if (*authInfo == NULL)
3314             {
3315 0           return PS_MEM_FAIL;
3316             }
3317 12           memset(*authInfo, 0, sizeof(x509authorityInfoAccess_t));
3318 12           first_entry = 1;
3319             }
3320              
3321 12           pAuthInfo = *authInfo;
3322              
3323 30 100         while (p < authInfoEnd &&
    50          
3324 18           *p == (ASN_SEQUENCE | ASN_CONSTRUCTED))
3325             {
3326              
3327             /* Find the end of the list. */
3328 18 50         while (pAuthInfo->next != NULL)
3329             {
3330 0           pAuthInfo = pAuthInfo->next;
3331             }
3332 18 100         if (!first_entry)
3333             {
3334             /* Malloc space for a new entry. */
3335 6           pAuthInfo->next = psMalloc(pool,
3336             sizeof(x509authorityInfoAccess_t));
3337 6 50         if (pAuthInfo->next == NULL)
3338             {
3339 0           return PS_MEM_FAIL;
3340             }
3341 6           memset(pAuthInfo->next, 0,
3342             sizeof(x509authorityInfoAccess_t));
3343 6           pAuthInfo = pAuthInfo->next;
3344             }
3345             else
3346             {
3347 12           first_entry = 0;
3348             }
3349              
3350             /* AccessDescription. */
3351 18 50         if (getAsnSequence(&p, (int32) (extEnd - p), &adLen) < 0)
3352             {
3353             psTraceCrypto("Error parsing authKeyId extension\n");
3354 0           return PS_PARSE_FAIL;
3355             }
3356             /* accessMethod. */
3357 18 50         if (*p++ != ASN_OID)
3358             {
3359             psTraceCrypto("Malformed extension header\n");
3360 0           return PS_PARSE_FAIL;
3361             }
3362 18 50         if (getAsnLength(&p, (uint32) (authInfoEnd - p), &len) < 0 ||
    50          
3363 18           (uint32) (authInfoEnd - p) < len)
3364             {
3365             psTraceCrypto("getAsnLength failure in authInfo parsing\n");
3366 0           return PS_PARSE_FAIL;
3367             }
3368 18           memset(oid, 0, sizeof(oid));
3369 18 50         if ((oidlen = asnParseOid(p, len, oid)) < 1)
3370             {
3371             psTraceCrypto("Malformed extension OID\n");
3372 0           return PS_PARSE_FAIL;
3373             }
3374 18           noid = psFindOid(oid, oidlen);
3375 18           p += len;
3376 18 100         if (noid != oid_id_ad_caIssuers &&
    50          
3377             noid != oid_id_ad_ocsp)
3378             {
3379             psTraceCrypto("Unsupported AccessDescription: "
3380             "only oid_ad_caIssuers and id_ad_ocsp "
3381             "are supported. \n");
3382 0           return PS_PARSE_FAIL;
3383             }
3384             /* accessLocation. */
3385 18 50         switch (*p++)
3386             {
3387             case (ASN_CONTEXT_SPECIFIC + 6):
3388             /* uniformResourceIdentifier [6] IA5String. */
3389 18 50         if (getAsnLength(&p, (uint32) (authInfoEnd - p), &len) < 0 ||
    50          
3390 18           (uint32) (authInfoEnd - p) < len)
3391             {
3392             psTraceCrypto("getAsnLength failure in authInfo parsing\n");
3393 0           return PS_PARSE_FAIL;
3394             }
3395 18 100         if (noid == oid_id_ad_ocsp)
3396             {
3397 12           pAuthInfo->ocsp = psMalloc(pool, len);
3398 12 50         if (pAuthInfo->ocsp == NULL)
3399             {
3400 0           return PS_MEM_FAIL;
3401             }
3402 12           memcpy(pAuthInfo->ocsp, p, len);
3403 12           pAuthInfo->ocspLen = len;
3404 12           p += len;
3405             }
3406             else /* oid_id_ad_caIssuers */
3407             {
3408 6           pAuthInfo->caIssuers = psMalloc(pool, len);
3409 6 50         if (pAuthInfo->caIssuers == NULL)
3410             {
3411 0           return PS_MEM_FAIL;
3412             }
3413 6           memcpy(pAuthInfo->caIssuers, p, len);
3414 6           pAuthInfo->caIssuersLen = len;
3415 6           p += len;
3416             }
3417 18           break;
3418             default:
3419             psTraceCrypto("Unsupported string type in AUTH_INFO ACC "
3420             "(only uniformResourceIdenfitier is "
3421             "supported). \n");
3422 0           return PS_PARSE_FAIL;
3423             }
3424             } /* Next AccessDescription, if any. */
3425              
3426 12           return PS_SUCCESS;
3427             }
3428             # endif /* USE_FULL_CERT_PARSE */
3429              
3430 2879           int32_t getExplicitExtensions(psPool_t *pool, const unsigned char **pp,
3431             psSize_t inlen, int32_t expVal,
3432             x509v3extensions_t *extensions, uint8_t known)
3433             {
3434 2879           const unsigned char *p = *pp, *end;
3435             const unsigned char *extEnd, *extStart, *save;
3436             unsigned char critical;
3437             psSize_t len, fullExtLen;
3438             uint32_t oid[MAX_OID_LEN];
3439             uint8_t oidlen;
3440             oid_e noid;
3441              
3442             # ifdef USE_FULL_CERT_PARSE
3443             psSize_t subExtLen;
3444             const unsigned char *subSave;
3445 2879           int32_t nc = 0;
3446             x509PolicyInformation_t *pPolicy;
3447             const unsigned char *policiesEnd;
3448             # endif /* USE_FULL_CERT_PARSE */
3449              
3450 2879           end = p + inlen;
3451 2879 50         if (inlen < 1)
3452             {
3453 0           return PS_ARG_FAIL;
3454             }
3455 2879           extensions->pool = pool;
3456 2879           extensions->bc.cA = CA_UNDEFINED;
3457              
3458 2879 50         if (known)
3459             {
3460 0           goto KNOWN_EXT;
3461             }
3462             /*
3463             Not treating this as an error because it is optional.
3464             */
3465 2879 50         if (*p != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | expVal))
3466             {
3467 0           return 0;
3468             }
3469 2879           p++;
3470 2879 50         if (getAsnLength(&p, (uint32) (end - p), &len) < 0 ||
    50          
3471 2879           (uint32) (end - p) < len)
3472             {
3473             psTraceCrypto("Initial getAsnLength failure in extension parse\n");
3474 0           return PS_PARSE_FAIL;
3475             }
3476             KNOWN_EXT:
3477             /*
3478             Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
3479              
3480             Extension ::= SEQUENCE {
3481             extnID OBJECT IDENTIFIER,
3482             extnValue OCTET STRING }
3483             */
3484 2879 50         if (getAsnSequence(&p, (uint32) (end - p), &len) < 0 ||
    50          
3485 2879           (uint32) (end - p) < len)
3486             {
3487             psTraceCrypto("Initial getAsnSequence failure in extension parse\n");
3488 0           return PS_PARSE_FAIL;
3489             }
3490 2879           extEnd = p + len;
3491 13440 100         while ((p != extEnd) && *p == (ASN_SEQUENCE | ASN_CONSTRUCTED))
    50          
3492             {
3493 10561 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &fullExtLen) < 0)
3494             {
3495             psTraceCrypto("getAsnSequence failure in extension parse\n");
3496 0           return PS_PARSE_FAIL;
3497             }
3498 10561           extStart = p;
3499             /*
3500             Conforming CAs MUST support key identifiers, basic constraints,
3501             key usage, and certificate policies extensions
3502             */
3503 10561 50         if (extEnd - p < 1 || *p++ != ASN_OID)
    50          
3504             {
3505             psTraceCrypto("Malformed extension header\n");
3506 0           return PS_PARSE_FAIL;
3507             }
3508 10561 50         if (getAsnLength(&p, (uint32) (extEnd - p), &len) < 0 ||
    50          
3509 10561           (uint32) (extEnd - p) < len)
3510             {
3511             psTraceCrypto("Malformed extension length\n");
3512 0           return PS_PARSE_FAIL;
3513             }
3514 10561 50         if ((oidlen = asnParseOid(p, len, oid)) < 1)
3515             {
3516             psTraceCrypto("Malformed extension OID\n");
3517 0           return PS_PARSE_FAIL;
3518             }
3519 10561           noid = psFindOid(oid, oidlen);
3520 10561           p += len;
3521             /*
3522             Possible boolean value here for 'critical' id. It's a failure if a
3523             critical extension is found that is not supported
3524             */
3525 10561           critical = 0;
3526 10561 50         if (extEnd - p < 1)
3527             {
3528             psTraceCrypto("Malformed extension length\n");
3529 0           return PS_PARSE_FAIL;
3530             }
3531 10561 100         if (*p == ASN_BOOLEAN)
3532             {
3533 1313           p++;
3534 1313 50         if (extEnd - p < 2)
3535             {
3536             psTraceCrypto("Error parsing critical id len for cert extension\n");
3537 0           return PS_PARSE_FAIL;
3538             }
3539 1313 50         if (*p != 1)
3540             {
3541             psTraceCrypto("Error parsing critical id for cert extension\n");
3542 0           return PS_PARSE_FAIL;
3543             }
3544 1313           p++;
3545 1313 50         if (*p > 0)
3546             {
3547             /* Officially DER TRUE must be 0xFF, openssl is more lax */
3548 1313           if (*p != 0xFF)
3549             {
3550             psTraceCrypto("Warning: DER BOOLEAN TRUE should be 0xFF\n");
3551             }
3552 1313           critical = 1;
3553             }
3554 1313           p++;
3555             }
3556 21122 50         if (extEnd - p < 1 || (*p++ != ASN_OCTET_STRING) ||
3557 21122 50         getAsnLength(&p, (uint32) (extEnd - p), &len) < 0 ||
3558 10561           (uint32) (extEnd - p) < len)
3559             {
3560             psTraceCrypto("Expecting OCTET STRING in ext parse\n");
3561 0           return PS_PARSE_FAIL;
3562             }
3563              
3564             /* Set bits 1..9 to indicate criticality of known extensions */
3565 10561 100         if (critical)
3566             {
3567 1313           extensions->critFlags |= EXT_CRIT_FLAG(noid);
3568             }
3569              
3570 10561           switch (noid)
3571             {
3572             /*
3573             BasicConstraints ::= SEQUENCE {
3574             cA BOOLEAN DEFAULT FALSE,
3575             pathLenConstraint INTEGER (0..MAX) OPTIONAL }
3576             */
3577             case OID_ENUM(id_ce_basicConstraints):
3578 2879 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
3579             {
3580             psTraceCrypto("Error parsing BasicConstraints extension\n");
3581 0           return PS_PARSE_FAIL;
3582             }
3583             /*
3584             "This goes against PKIX guidelines but some CAs do it and some
3585             software requires this to avoid interpreting an end user
3586             certificate as a CA."
3587             - OpenSSL certificate configuration doc
3588              
3589             basicConstraints=CA:FALSE
3590             */
3591 2879 100         if (len == 0)
3592             {
3593 1405           extensions->bc.cA = CA_FALSE;
3594 1405           break;
3595             }
3596             /*
3597             Have seen some certs that don't include a cA bool.
3598             */
3599 1474 50         if (*p == ASN_BOOLEAN)
3600             {
3601 1474 50         if (extEnd - p < 3)
3602             {
3603             psTraceCrypto("Error parsing BC extension\n");
3604 0           return PS_PARSE_FAIL;
3605             }
3606 1474           p++;
3607 1474 50         if (*p++ != 1)
3608             {
3609             psTraceCrypto("Error parse BasicConstraints CA bool\n");
3610 0           return PS_PARSE_FAIL;
3611             }
3612             /* Officially DER TRUE must be 0xFF, openssl is more lax */
3613 1474 50         if (*p > 0 && *p != 0xFF)
3614             {
3615             psTraceCrypto("Warning: cA TRUE should be 0xFF\n");
3616             }
3617 1474 50         if (*p > 0)
3618             {
3619 1474           extensions->bc.cA = CA_TRUE;
3620             }
3621             else
3622             {
3623 0           extensions->bc.cA = CA_FALSE;
3624             }
3625 1474           p++;
3626             }
3627             else
3628             {
3629 0           extensions->bc.cA = CA_FALSE;
3630             }
3631             /*
3632             Now need to check if there is a path constraint. Only makes
3633             sense if cA is true. If it's missing, there is no limit to
3634             the cert path
3635             */
3636 1474 100         if (*p == ASN_INTEGER)
3637             {
3638 56 50         if (getAsnInteger(&p, (uint32) (extEnd - p),
3639 56           &(extensions->bc.pathLenConstraint)) < 0)
3640             {
3641             psTraceCrypto("Error parsing BasicConstraints pathLen\n");
3642 0           return PS_PARSE_FAIL;
3643             }
3644             }
3645             else
3646             {
3647 1418           extensions->bc.pathLenConstraint = -1;
3648             }
3649 1474           break;
3650              
3651             case OID_ENUM(id_ce_subjectAltName):
3652 31 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
3653             {
3654             psTraceCrypto("Error parsing altSubjectName extension\n");
3655 0           return PS_PARSE_FAIL;
3656             }
3657             /* NOTE: The final limit parameter was introduced for this
3658             case because a well known search engine site sends back
3659             about 7 KB worth of subject alt names and that has created
3660             memory problems for a couple users. Set the -1 here to
3661             something reasonable (5) if you've found yourself here
3662             for this memory reason */
3663 31 50         if (parseGeneralNames(pool, &p, len, extEnd, &extensions->san,
3664             -1) < 0)
3665             {
3666             psTraceCrypto("Error parsing altSubjectName names\n");
3667 0           return PS_PARSE_FAIL;
3668             }
3669              
3670 31           break;
3671              
3672             case OID_ENUM(id_ce_keyUsage):
3673             /*
3674             KeyUsage ::= BIT STRING {
3675             digitalSignature (0),
3676             nonRepudiation (1),
3677             keyEncipherment (2),
3678             dataEncipherment (3),
3679             keyAgreement (4),
3680             keyCertSign (5),
3681             cRLSign (6),
3682             encipherOnly (7),
3683             decipherOnly (8) }
3684             */
3685 691 50         if (*p++ != ASN_BIT_STRING)
3686             {
3687             psTraceCrypto("Error parsing keyUsage extension\n");
3688 0           return PS_PARSE_FAIL;
3689             }
3690 691 50         if (getAsnLength(&p, (int32) (extEnd - p), &len) < 0 ||
    50          
3691 691           (uint32) (extEnd - p) < len)
3692             {
3693             psTraceCrypto("Malformed keyUsage extension\n");
3694 0           return PS_PARSE_FAIL;
3695             }
3696 691 50         if (len < 2)
3697             {
3698             psTraceCrypto("Malformed keyUsage extension\n");
3699 0           return PS_PARSE_FAIL;
3700             }
3701             /*
3702             If the lenth is <= 3, then there might be a
3703             KEY_USAGE_DECIPHER_ONLY (or maybe just some empty bytes).
3704             */
3705 691 50         if (len >= 3)
3706             {
3707 0 0         if (p[2] == (KEY_USAGE_DECIPHER_ONLY >> 8) && p[0] == 7)
    0          
3708             {
3709 0           extensions->keyUsageFlags |= KEY_USAGE_DECIPHER_ONLY;
3710             }
3711             }
3712 691           extensions->keyUsageFlags |= p[1];
3713 691           p = p + len;
3714 691           break;
3715              
3716             case OID_ENUM(id_ce_extKeyUsage):
3717 12 50         if (getAsnSequence(&p, (int32) (extEnd - p), &fullExtLen) < 0)
3718             {
3719             psTraceCrypto("Error parsing authKeyId extension\n");
3720 0           return PS_PARSE_FAIL;
3721             }
3722 12           save = p;
3723 55 100         while (fullExtLen > 0)
3724             {
3725 43 50         if (*p++ != ASN_OID)
3726             {
3727             psTraceCrypto("Malformed extension header\n");
3728 0           return PS_PARSE_FAIL;
3729             }
3730 43 50         if (getAsnLength(&p, fullExtLen, &len) < 0 ||
    50          
3731 43           fullExtLen < len)
3732             {
3733             psTraceCrypto("Malformed extension length\n");
3734 0           return PS_PARSE_FAIL;
3735             }
3736 43 50         if ((oidlen = asnParseOid(p, len, oid)) < 1)
3737             {
3738             psTraceCrypto("Malformed extension OID\n");
3739 0           return PS_PARSE_FAIL;
3740             }
3741 43           noid = psFindOid(oid, oidlen);
3742 43           p += len;
3743 43 50         if (fullExtLen < (uint32) (p - save))
3744             {
3745             psTraceCrypto("Inner OID parse fail EXTND_KEY_USAGE\n");
3746 0           return PS_PARSE_FAIL;
3747             }
3748 43           fullExtLen -= (p - save);
3749 43           save = p;
3750 43           switch (noid)
3751             {
3752             case OID_ENUM(id_kp_serverAuth):
3753 7           extensions->ekuFlags |= EXT_KEY_USAGE_TLS_SERVER_AUTH;
3754 7           break;
3755             case OID_ENUM(id_kp_clientAuth):
3756 11           extensions->ekuFlags |= EXT_KEY_USAGE_TLS_CLIENT_AUTH;
3757 11           break;
3758             case OID_ENUM(id_kp_codeSigning):
3759 5           extensions->ekuFlags |= EXT_KEY_USAGE_CODE_SIGNING;
3760 5           break;
3761             case OID_ENUM(id_kp_emailProtection):
3762 10           extensions->ekuFlags |= EXT_KEY_USAGE_EMAIL_PROTECTION;
3763 10           break;
3764             case OID_ENUM(id_kp_timeStamping):
3765 5           extensions->ekuFlags |= EXT_KEY_USAGE_TIME_STAMPING;
3766 5           break;
3767             case OID_ENUM(id_kp_OCSPSigning):
3768 5           extensions->ekuFlags |= EXT_KEY_USAGE_OCSP_SIGNING;
3769 5           break;
3770             case OID_ENUM(id_ce_eku_anyExtendedKeyUsage):
3771 0           extensions->ekuFlags |= EXT_KEY_USAGE_ANY;
3772 0           break;
3773             default:
3774             psTraceCrypto("WARNING: Unknown EXT_KEY_USAGE:");
3775             psTraceOid(oid, oidlen);
3776 0           break;
3777             } /* end switch */
3778             }
3779 12           break;
3780              
3781             # ifdef USE_FULL_CERT_PARSE
3782              
3783             case OID_ENUM(id_ce_nameConstraints):
3784 5 50         if (critical)
3785             {
3786             /* We're going to fail if critical since no real
3787             pattern matching is happening yet */
3788             psTraceCrypto("ERROR: critical nameConstraints unsupported\n");
3789 0           return PS_PARSE_FAIL;
3790             }
3791 5 50         if (getAsnSequence(&p, (int32) (extEnd - p), &fullExtLen) < 0)
3792             {
3793             psTraceCrypto("Error parsing authKeyId extension\n");
3794 0           return PS_PARSE_FAIL;
3795             }
3796 10 100         while (fullExtLen > 0)
3797             {
3798 5           save = p;
3799              
3800 5 50         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
3801             {
3802             /* permittedSubtrees */
3803 5           p++;
3804 5           nc = 0;
3805             }
3806 5 50         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
3807             {
3808             /* excludedSubtrees */
3809 0           p++;
3810 0           nc = 1;
3811             }
3812 5           subExtLen = 0;
3813 5 50         if (getAsnLength(&p, (uint32) (extEnd - p), &subExtLen) < 0 ||
    50          
3814 5 50         subExtLen < 1 || (uint32) (extEnd - p) < subExtLen)
3815             {
3816             psTraceCrypto("ASN get len error in nameConstraint\n");
3817 0           return PS_PARSE_FAIL;
3818             }
3819 5 50         if (fullExtLen < (subExtLen + (p - save)))
3820             {
3821             psTraceCrypto("fullExtLen parse fail nameConstraint\n");
3822 0           return PS_PARSE_FAIL;
3823             }
3824 5           fullExtLen -= subExtLen + (p - save);
3825 45 100         while (subExtLen > 0)
3826             {
3827 40           subSave = p;
3828 40 50         if (getAsnSequence(&p, (int32) (extEnd - p), &len) < 0)
3829             {
3830             psTraceCrypto("Error parsing nameConst ext\n");
3831 0           return PS_PARSE_FAIL;
3832             }
3833 40 50         if (subExtLen < (len + (p - subSave)))
3834             {
3835             psTraceCrypto("subExtLen fail nameConstraint\n");
3836 0           return PS_PARSE_FAIL;
3837             }
3838 40           subExtLen -= len + (p - subSave);
3839 40 50         if (nc == 0)
3840             {
3841 40 50         if (parseGeneralNames(pool, &p, len, extEnd,
3842             &extensions->nameConstraints.permitted, -1) < 0)
3843             {
3844             psTraceCrypto("Error parsing nameConstraint\n");
3845 0           return PS_PARSE_FAIL;
3846             }
3847             }
3848             else
3849             {
3850 0 0         if (parseGeneralNames(pool, &p, len, extEnd,
3851             &extensions->nameConstraints.excluded, -1) < 0)
3852             {
3853             psTraceCrypto("Error parsing nameConstraint\n");
3854 0           return PS_PARSE_FAIL;
3855             }
3856             }
3857             }
3858             }
3859 5           break;
3860              
3861             # ifdef USE_CRL
3862             case OID_ENUM(id_ce_cRLNumber):
3863             /* A required extension within a CRL. Our getSerialNum is
3864             the version of getInteger that allows very large
3865             numbers. Spec says this could be 20 octets long */
3866 0 0         if (getSerialNum(pool, &p, (int32) (extEnd - p),
3867             &(extensions->crlNum), &len) < 0)
3868             {
3869             psTraceCrypto("Error parsing ak.serialNum\n");
3870 0           return PS_PARSE_FAIL;
3871             }
3872 0           extensions->crlNumLen = len;
3873 0           break;
3874              
3875             case OID_ENUM(id_ce_issuingDistributionPoint):
3876             /* RFC 3280 - Although the extension is critical, conforming
3877             implementations are not required to support this extension. */
3878 0           p++;
3879 0           p = p + (fullExtLen - (p - extStart));
3880 0           break;
3881              
3882             case OID_ENUM(id_ce_cRLDistributionPoints):
3883 82 50         if (getAsnSequence(&p, (int32) (extEnd - p), &fullExtLen) < 0)
3884             {
3885             psTraceCrypto("Error parsing authKeyId extension\n");
3886 0           return PS_PARSE_FAIL;
3887             }
3888              
3889 184 100         while (fullExtLen > 0)
3890             {
3891 102           save = p;
3892 102 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
3893             {
3894             psTraceCrypto("getAsnSequence fail in crldist parse\n");
3895 0           return PS_PARSE_FAIL;
3896             }
3897 102 50         if (fullExtLen < (len + (p - save)))
3898             {
3899             psTraceCrypto("fullExtLen parse fail crldist\n");
3900 0           return PS_PARSE_FAIL;
3901             }
3902 102           fullExtLen -= len + (p - save);
3903             /* All memebers are optional */
3904 102 50         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
3905             {
3906             /* DistributionPointName */
3907 102           p++;
3908 102 50         if (getAsnLength(&p, (uint32) (extEnd - p), &len) < 0 ||
    50          
3909 102 50         len < 1 || (uint32) (extEnd - p) < len)
3910             {
3911             psTraceCrypto("ASN get len error in CRL extension\n");
3912 0           return PS_PARSE_FAIL;
3913             }
3914              
3915 102 50         if ((*p & 0xF) == 0) /* fullName (GeneralNames) */
3916             {
3917 102           p++;
3918 102 50         if (getAsnLength(&p, (uint32) (extEnd - p), &len) < 0
3919 102 50         || len < 1 || (uint32) (extEnd - p) < len)
    50          
3920             {
3921             psTraceCrypto("ASN get len error in CRL extension\n");
3922 0           return PS_PARSE_FAIL;
3923             }
3924 102 50         if (parseGeneralNames(pool, &p, len, extEnd,
3925             &extensions->crlDist, -1) > 0)
3926             {
3927             psTraceCrypto("dist gen name parse fail\n");
3928 0           return PS_PARSE_FAIL;
3929             }
3930             }
3931 0 0         else if ((*p & 0xF) == 1) /* RelativeDistName */
3932             {
3933 0           p++;
3934             /* RelativeDistName not parsed */
3935 0 0         if (getAsnLength(&p, (uint32) (extEnd - p), &len) < 0
3936 0 0         || len < 1 || (uint32) (extEnd - p) < len)
    0          
3937             {
3938             psTraceCrypto("ASN get len error in CRL extension\n");
3939 0           return PS_PARSE_FAIL;
3940             }
3941 0           p += len;
3942             }
3943             else
3944             {
3945             psTraceCrypto("DistributionPointName parse fail\n");
3946 0           return PS_PARSE_FAIL;
3947             }
3948             }
3949 102 50         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
3950             {
3951 0           p++;
3952             /* ReasonFlags not parsed */
3953 0 0         if (getAsnLength(&p, (uint32) (extEnd - p), &len) < 0 ||
    0          
3954 0 0         len < 1 || (uint32) (extEnd - p) < len)
3955             {
3956             psTraceCrypto("ASN get len error in CRL extension\n");
3957 0           return PS_PARSE_FAIL;
3958             }
3959 0           p += len;
3960             }
3961 102 50         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2))
3962             {
3963 0           p++;
3964             /* General Names not parsed */
3965 0 0         if (getAsnLength(&p, (uint32) (extEnd - p), &len) < 0 ||
    0          
3966 0 0         len < 1 || (uint32) (extEnd - p) < len)
3967             {
3968             psTraceCrypto("ASN get len error in CRL extension\n");
3969 0           return PS_PARSE_FAIL;
3970             }
3971 0           p += len;
3972             }
3973             }
3974 82           break;
3975             case OID_ENUM(id_pe_authorityInfoAccess):
3976 12 50         if (parseAuthorityInfoAccess(pool, p,
3977             extEnd,
3978             &extensions->authorityInfoAccess,
3979             &len) < 0)
3980             {
3981 0           return PS_PARSE_FAIL;
3982             }
3983 12           p += len;
3984 12           break;
3985             # endif /* USE_CRL */
3986             # endif /* FULL_CERT_PARSE */
3987              
3988             case OID_ENUM(id_ce_authorityKeyIdentifier):
3989             /*
3990             AuthorityKeyIdentifier ::= SEQUENCE {
3991             keyIdentifier [0] KeyIdentifier OPTIONAL,
3992             authorityCertIssuer [1] GeneralNames OPTIONAL,
3993             authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
3994              
3995             KeyIdentifier ::= OCTET STRING
3996             */
3997 2379 50         if (getAsnSequence(&p, (int32) (extEnd - p), &len) < 0)
3998             {
3999             psTraceCrypto("Error parsing authKeyId extension\n");
4000 0           return PS_PARSE_FAIL;
4001             }
4002             /* Have seen a cert that has a zero length ext here. Let it pass. */
4003 2379 50         if (len == 0)
4004             {
4005 0           break;
4006             }
4007             /* All members are optional */
4008 2379 50         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 0))
4009             {
4010 2379           p++;
4011 2379 50         if (getAsnLength(&p, (int32) (extEnd - p),
4012 2379 50         &extensions->ak.keyLen) < 0 ||
4013 2379           (uint32) (extEnd - p) < extensions->ak.keyLen)
4014             {
4015             psTraceCrypto("Error keyLen in authKeyId extension\n");
4016 0           return PS_PARSE_FAIL;
4017             }
4018 2379           extensions->ak.keyId = psMalloc(pool, extensions->ak.keyLen);
4019 2379 50         if (extensions->ak.keyId == NULL)
4020             {
4021 0           psError("Mem allocation err: extensions->ak.keyId\n");
4022 0           return PS_MEM_FAIL;
4023             }
4024 2379           memcpy(extensions->ak.keyId, p, extensions->ak.keyLen);
4025 2379           p = p + extensions->ak.keyLen;
4026             }
4027 2379 100         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
4028             {
4029 50           p++;
4030 50 50         if (getAsnLength(&p, (int32) (extEnd - p), &len) < 0 ||
    50          
4031 50 50         len < 1 || (uint32) (extEnd - p) < len)
4032             {
4033             psTraceCrypto("ASN get len error in authKeyId extension\n");
4034 0           return PS_PARSE_FAIL;
4035             }
4036 50 50         if ((*p ^ ASN_CONTEXT_SPECIFIC ^ ASN_CONSTRUCTED) != 4)
4037             {
4038             /* We are just dealing with DN formats here */
4039             psTraceIntCrypto("Error auth key-id name type: %d\n",
4040             *p ^ ASN_CONTEXT_SPECIFIC ^ ASN_CONSTRUCTED);
4041 0           return PS_PARSE_FAIL;
4042             }
4043 50           p++;
4044 50 50         if (getAsnLength(&p, (int32) (extEnd - p), &len) < 0 ||
    50          
4045 50           (uint32) (extEnd - p) < len)
4046             {
4047             psTraceCrypto("ASN get len error2 in authKeyId extension\n");
4048 0           return PS_PARSE_FAIL;
4049             }
4050 50 50         if (psX509GetDNAttributes(pool, &p, (int32) (extEnd - p),
4051             &(extensions->ak.attribs), 0) < 0)
4052             {
4053             psTraceCrypto("Error parsing ak.attribs\n");
4054 0           return PS_PARSE_FAIL;
4055             }
4056             }
4057 2379 100         if ((*p == (ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2)) ||
    50          
4058 2329           (*p == ASN_INTEGER))
4059             {
4060             /*
4061             Treat as a serial number (not a native INTEGER)
4062             */
4063 50 50         if (getSerialNum(pool, &p, (int32) (extEnd - p),
4064             &(extensions->ak.serialNum), &len) < 0)
4065             {
4066             psTraceCrypto("Error parsing ak.serialNum\n");
4067 0           return PS_PARSE_FAIL;
4068             }
4069 50           extensions->ak.serialNumLen = len;
4070             }
4071 2379           break;
4072              
4073             case OID_ENUM(id_ce_subjectKeyIdentifier):
4074             /*
4075             The value of the subject key identifier MUST be the value
4076             placed in the key identifier field of the Auth Key Identifier
4077             extension of certificates issued by the subject of
4078             this certificate.
4079             */
4080 2864 50         if (*p++ != ASN_OCTET_STRING || getAsnLength(&p,
    50          
4081 2864 50         (int32) (extEnd - p), &(extensions->sk.len)) < 0 ||
4082 2864           (uint32) (extEnd - p) < extensions->sk.len)
4083             {
4084             psTraceCrypto("Error parsing subjectKeyId extension\n");
4085 0           return PS_PARSE_FAIL;
4086             }
4087 2864           extensions->sk.id = psMalloc(pool, extensions->sk.len);
4088 2864 50         if (extensions->sk.id == NULL)
4089             {
4090 0           psError("Memory allocation error extensions->sk.id\n");
4091 0           return PS_MEM_FAIL;
4092             }
4093 2864           memcpy(extensions->sk.id, p, extensions->sk.len);
4094 2864           p = p + extensions->sk.len;
4095 2864           break;
4096             # ifdef USE_FULL_CERT_PARSE
4097              
4098             case OID_ENUM(id_ce_certificatePolicies):
4099             /*
4100             certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
4101             */
4102             /* Parse certificatePolicies := SEQUENCE SIZE (1..MAX) OF
4103             PolicyInformation. */
4104 87 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
4105             {
4106             psTraceCrypto("Error parsing certificatePolicies extension\n");
4107 0           return PS_PARSE_FAIL;
4108             }
4109 87           policiesEnd = p + len;
4110             extensions->certificatePolicy.policy
4111 87           = psMalloc(pool, sizeof(x509PolicyInformation_t));
4112 87           memset(extensions->certificatePolicy.policy, 0,
4113             sizeof(x509PolicyInformation_t));
4114 87           pPolicy = extensions->certificatePolicy.policy;
4115              
4116             /* Parse a single PolicyInformation. */
4117 87 50         if (parsePolicyInformation(pool, p, extEnd, fullExtLen,
4118             pPolicy, &len) < 0)
4119             {
4120 0           return PS_PARSE_FAIL;
4121             }
4122 87           p += len;
4123              
4124             /* Parse further PolicyInformations, if present. */
4125 88 100         while ((p < policiesEnd)
4126 1 50         && (p < extEnd)
4127 1 50         && (*p == (ASN_SEQUENCE | ASN_CONSTRUCTED)))
4128             {
4129              
4130 1           pPolicy->next = psMalloc(pool, sizeof(x509PolicyInformation_t));
4131 1           memset(pPolicy->next, 0, sizeof(x509PolicyInformation_t));
4132 1           pPolicy = pPolicy->next;
4133 1 50         if (parsePolicyInformation(pool, p, extEnd, fullExtLen,
4134             pPolicy, &len) < 0)
4135             {
4136 0           return PS_PARSE_FAIL;
4137             }
4138 1           p += len;
4139             } /* End or PolicyInformation parsing. */
4140 87           break;
4141             case OID_ENUM(id_ce_policyConstraints):
4142 0 0         if (parsePolicyConstraints(pool, p,
4143             extEnd,
4144             &extensions->policyConstraints,
4145             &len) < 0)
4146             {
4147 0           return PS_PARSE_FAIL;
4148             }
4149 0           p += len;
4150 0           break;
4151             case OID_ENUM(id_ce_policyMappings):
4152 5           extensions->policyMappings = psMalloc(pool,
4153             sizeof(x509policyMappings_t));
4154 5           memset(extensions->policyMappings, 0, sizeof(x509policyMappings_t));
4155 5 50         if (parsePolicyMappings(pool, p,
4156             extEnd,
4157             extensions->policyMappings,
4158             &len) < 0)
4159             {
4160 0           return PS_PARSE_FAIL;
4161             }
4162              
4163 5           p += len;
4164 5           break;
4165             case OID_ENUM(id_ce_issuerAltName):
4166 10 50         if (getAsnSequence(&p, (uint32) (extEnd - p), &len) < 0)
4167             {
4168             psTraceCrypto("Error parsing issuerAltName extension\n");
4169 0           return PS_PARSE_FAIL;
4170             }
4171             /* NOTE: The final limit parameter was introduced for this
4172             case because a well known search engine site sends back
4173             about 7 KB worth of subject alt names and that has created
4174             memory problems for a couple users. Set the -1 here to
4175             something reasonable (5) if you've found yourself here
4176             for this memory reason */
4177 10 50         if (parseGeneralNames(pool, &p, len, extEnd, &extensions->issuerAltName,
4178             -1) < 0)
4179             {
4180             psTraceCrypto("Error parsing altSubjectName names\n");
4181 0           return PS_PARSE_FAIL;
4182             }
4183 10           break;
4184             # endif /* USE_FULL_CERT_PARSE */
4185             /* These extensions are known but not handled */
4186             case OID_ENUM(id_ce_subjectDirectoryAttributes):
4187             case OID_ENUM(id_ce_inhibitAnyPolicy):
4188             case OID_ENUM(id_ce_freshestCRL):
4189             case OID_ENUM(id_pe_subjectInfoAccess):
4190             default:
4191             /* Unsupported or skipping because USE_FULL_CERT_PARSE undefd */
4192 1504 50         if (critical)
4193             {
4194             psTraceCrypto("Unsupported critical ext encountered: ");
4195             psTraceOid(oid, oidlen);
4196             # ifndef ALLOW_UNKNOWN_CRITICAL_EXTENSIONS
4197 0           _psTrace("An unsupported critical extension was "
4198             "encountered. X.509 specifications say "
4199             "connections must be terminated in this case. "
4200             "Define ALLOW_UNKNOWN_CRITICAL_EXTENSIONS to "
4201             "bypass this rule if testing and email Inside "
4202             "support to inquire about this extension.\n");
4203 0           return PS_PARSE_FAIL;
4204             # else
4205             # ifdef WIN32
4206             # pragma message("IGNORING UNKNOWN CRITICAL EXTENSIONS IS A SECURITY RISK")
4207             # else
4208             # warning "IGNORING UNKNOWN CRITICAL EXTENSIONS IS A SECURITY RISK"
4209             # endif
4210             # endif
4211             }
4212 1504           p++;
4213             /*
4214             Skip over based on the length reported from the ASN_SEQUENCE
4215             surrounding the entire extension. It is not a guarantee that
4216             the value of the extension itself will contain it's own length.
4217             */
4218 1504           p = p + (fullExtLen - (p - extStart));
4219 1504           break;
4220             }
4221             }
4222 2879           *pp = p;
4223 2879           return 0;
4224             }
4225              
4226             /******************************************************************************/
4227             /*
4228             Although a certificate serial number is encoded as an integer type, that
4229             doesn't prevent it from being abused as containing a variable length
4230             binary value. Get it here.
4231             */
4232 2929           int32_t getSerialNum(psPool_t *pool, const unsigned char **pp, psSize_t len,
4233             unsigned char **sn, psSize_t *snLen)
4234             {
4235 2929           const unsigned char *p = *pp;
4236             psSize_t vlen;
4237              
4238 2929 100         if ((*p != (ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2)) &&
    50          
4239 2879           (*p != ASN_INTEGER))
4240             {
4241             psTraceCrypto("X.509 getSerialNum failed on first bytes\n");
4242 0           return PS_PARSE_FAIL;
4243             }
4244 2929           p++;
4245              
4246 2929 50         if (len < 1 || getAsnLength(&p, len - 1, &vlen) < 0 || (len - 1) < vlen)
    50          
    50          
4247             {
4248             psTraceCrypto("ASN getSerialNum failed\n");
4249 0           return PS_PARSE_FAIL;
4250             }
4251 2929           *snLen = vlen;
4252              
4253 2929 50         if (vlen > 0)
4254             {
4255 2929           *sn = psMalloc(pool, vlen);
4256 2929 50         if (*sn == NULL)
4257             {
4258 0           psError("Memory allocation failure in getSerialNum\n");
4259 0           return PS_MEM_FAIL;
4260             }
4261 2929           memcpy(*sn, p, vlen);
4262 2929           p += vlen;
4263             }
4264 2929           *pp = p;
4265 2929           return PS_SUCCESS;
4266             }
4267              
4268             /******************************************************************************/
4269             /**
4270             Explicit value encoding has an additional tag layer.
4271             */
4272 2879           static int32_t getExplicitVersion(const unsigned char **pp, psSize_t len,
4273             int32_t expVal, int32_t *val)
4274             {
4275 2879           const unsigned char *p = *pp;
4276             psSize_t exLen;
4277              
4278 2879 50         if (len < 1)
4279             {
4280             psTraceCrypto("Invalid length to getExplicitVersion\n");
4281 0           return PS_PARSE_FAIL;
4282             }
4283             /*
4284             This is an optional value, so don't error if not present. The default
4285             value is version 1
4286             */
4287 2879 50         if (*p != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | expVal))
4288             {
4289 0           *val = 0;
4290 0           return PS_SUCCESS;
4291             }
4292 2879           p++;
4293 2879 50         if (getAsnLength(&p, len - 1, &exLen) < 0 || (len - 1) < exLen)
    50          
4294             {
4295             psTraceCrypto("getAsnLength failure in getExplicitVersion\n");
4296 0           return PS_PARSE_FAIL;
4297             }
4298 2879 50         if (getAsnInteger(&p, exLen, val) < 0)
4299             {
4300             psTraceCrypto("getAsnInteger failure in getExplicitVersion\n");
4301 0           return PS_PARSE_FAIL;
4302             }
4303 2879           *pp = p;
4304 2879           return PS_SUCCESS;
4305             }
4306              
4307             /******************************************************************************/
4308             /**
4309             Tests if the certificate was issued before the given date.
4310             Because there is no actual issuance date in the certificate, we use the
4311             'notBefore' date (the initial date the certificate is valid) as the
4312             effective issuance date.
4313             @security This api is used to be more lenient on certificates that are still
4314             valid, but were created before certain more strict certificate rules
4315             were specified.
4316              
4317             @param[in] rfc The RFC to check against.
4318             @param[in] cert The cert to check the issuing date on.
4319             @return 1 if yes, 0 if no, -1 on parse error.
4320             */
4321 1148           static int32 issuedBefore(rfc_e rfc, const psX509Cert_t *cert)
4322             {
4323             unsigned char *c;
4324             unsigned int y;
4325             unsigned short m;
4326             psBrokenDownTime_t t;
4327             int32 err;
4328              
4329             /* Validate the 'not before' date */
4330 1148 50         if ((c = (unsigned char *) cert->notBefore) == NULL)
4331             {
4332 0           return PS_FAILURE;
4333             }
4334 1148 50         err = psBrokenDownTimeImport(
4335             &t, (const char *) c, strlen((const char *) c),
4336 1148           cert->notBeforeTimeType == ASN_UTCTIME ?
4337             PS_BROKENDOWN_TIME_IMPORT_2DIGIT_YEAR : 0);
4338              
4339 1148 50         if (err)
4340             {
4341 0           return err;
4342             }
4343              
4344             /* Get y and m from broken-down time. */
4345 1148           y = 1900 + (unsigned int) t.tm_year;
4346 1148           m = 1 + (unsigned short) t.tm_mon;
4347              
4348             /* Must have been issued at least when X509v3 was added */
4349 1148 50         if (y < 1996 || m < 1 || m > 12)
    50          
    50          
4350             {
4351 0           return -1;
4352             }
4353 1148           switch (rfc)
4354             {
4355             case RFC_6818:
4356 0 0         if (y < 2013) /* No month check needed for Jan */
4357             {
4358 0           return 1;
4359             }
4360 0           return 0;
4361             case RFC_5280:
4362 0 0         if (y < 2008 || (y == 2008 && m < 5))
    0          
    0          
4363             {
4364 0           return 1;
4365             }
4366 0           return 0;
4367             case RFC_3280:
4368 1148 50         if (y < 2002 || (y == 2002 && m < 4))
    50          
    0          
4369             {
4370 0           return 1;
4371             }
4372 1148           return 0;
4373             case RFC_2459:
4374 0 0         if (y < 1999) /* No month check needed for Jan */
4375             {
4376 0           return 1;
4377             }
4378 0           return 0;
4379             default:
4380 1148           return -1;
4381             }
4382             return -1;
4383             }
4384              
4385             /**
4386             Validate the dates in the cert to machine date.
4387             SECURITY - always succeeds on systems without date support
4388             Returns
4389             0 on parse success (FAIL_DATE_FLAG could be set)
4390             PS_FAILURE on parse error
4391             */
4392 2879           static int32 validateDateRange(psX509Cert_t *cert)
4393             {
4394             int32 err;
4395             psBrokenDownTime_t timeNow;
4396             psBrokenDownTime_t timeNowLinger;
4397             psBrokenDownTime_t beforeTime;
4398             psBrokenDownTime_t afterTime;
4399             psBrokenDownTime_t afterTimeLinger;
4400              
4401 2879 50         if (cert->notBefore == NULL || cert->notAfter == NULL)
    50          
4402             {
4403 0           return PS_FAIL;
4404             }
4405              
4406 2879           err = psGetBrokenDownGMTime(&timeNow, 0);
4407 2879 50         if (err != PS_SUCCESS)
4408             {
4409 0           return PS_FAIL;
4410             }
4411              
4412 2879           memcpy(&timeNowLinger, &timeNow, sizeof timeNowLinger);
4413 2879           err = psBrokenDownTimeAdd(&timeNowLinger, PS_X509_TIME_LINGER);
4414 2879 50         if (err != PS_SUCCESS)
4415             {
4416 0           return PS_FAIL;
4417             }
4418              
4419 2879 100         err = psBrokenDownTimeImport(
4420 5758           &beforeTime, cert->notBefore, strlen(cert->notBefore),
4421 2879           cert->notBeforeTimeType == ASN_UTCTIME ?
4422             PS_BROKENDOWN_TIME_IMPORT_2DIGIT_YEAR : 0);
4423 2879 50         if (err != PS_SUCCESS)
4424             {
4425 0           return PS_FAIL;
4426             }
4427              
4428 2879 100         err = psBrokenDownTimeImport(
4429 5758           &afterTime, cert->notAfter, strlen(cert->notAfter),
4430 2879           cert->notAfterTimeType == ASN_UTCTIME ?
4431             PS_BROKENDOWN_TIME_IMPORT_2DIGIT_YEAR : 0);
4432 2879 50         if (err != PS_SUCCESS)
4433             {
4434 0           return PS_FAIL;
4435             }
4436              
4437 2879           memcpy(&afterTimeLinger, &afterTime, sizeof afterTimeLinger);
4438 2879           err = psBrokenDownTimeAdd(&afterTimeLinger, PS_X509_TIME_LINGER);
4439 2879 50         if (err != PS_SUCCESS)
4440             {
4441 0           return PS_FAIL;
4442             }
4443              
4444 2879 50         if (psBrokenDownTimeCmp(&beforeTime, &timeNowLinger) > 0)
4445             {
4446             /* beforeTime is in future. */
4447 0           cert->authFailFlags |= PS_CERT_AUTH_FAIL_DATE_FLAG;
4448             }
4449 2879 50         else if (psBrokenDownTimeCmp(&timeNow, &afterTimeLinger) > 0)
4450             {
4451             /* afterTime is in past. */
4452 0           cert->authFailFlags |= PS_CERT_AUTH_FAIL_DATE_FLAG;
4453             }
4454 2879           return 0;
4455             }
4456              
4457              
4458             /******************************************************************************/
4459             /*
4460             Implementation specific date parser.
4461             */
4462 2879           static int32_t getTimeValidity(psPool_t *pool, const unsigned char **pp,
4463             psSize_t len, int32_t *notBeforeTimeType,
4464             int32_t *notAfterTimeType,
4465             char **notBefore, char **notAfter)
4466             {
4467 2879           const unsigned char *p = *pp, *end;
4468             psSize_t seqLen, timeLen;
4469              
4470 2879           end = p + len;
4471 5758 50         if (len < 1 || *(p++) != (ASN_SEQUENCE | ASN_CONSTRUCTED) ||
4472 5758 50         getAsnLength(&p, len - 1, &seqLen) < 0 ||
4473 2879           (uint32) (end - p) < seqLen)
4474             {
4475             psTraceCrypto("getTimeValidity failed on inital parse\n");
4476 0           return PS_PARSE_FAIL;
4477             }
4478             /*
4479             Have notBefore and notAfter times in UTCTime or GeneralizedTime formats
4480             */
4481 2879 50         if ((end - p) < 1 || ((*p != ASN_UTCTIME) && (*p != ASN_GENERALIZEDTIME)))
    100          
    50          
4482             {
4483             psTraceCrypto("Malformed validity\n");
4484 0           return PS_PARSE_FAIL;
4485             }
4486 2879           *notBeforeTimeType = *p;
4487 2879           p++;
4488             /*
4489             Allocate them as null terminated strings
4490             */
4491 2879 50         if (getAsnLength(&p, seqLen, &timeLen) < 0 || (uint32) (end - p) < timeLen)
    50          
4492             {
4493             psTraceCrypto("Malformed validity 2\n");
4494 0           return PS_PARSE_FAIL;
4495             }
4496 2879 50         if (timeLen > MAX_TIME_LEN)
4497             {
4498 0           return PS_PARSE_FAIL;
4499             }
4500 2879           *notBefore = psMalloc(pool, timeLen + 1);
4501 2879 50         if (*notBefore == NULL)
4502             {
4503 0           psError("Memory allocation error in getTimeValidity for notBefore\n");
4504 0           return PS_MEM_FAIL;
4505             }
4506 2879           memcpy(*notBefore, p, timeLen);
4507 2879           (*notBefore)[timeLen] = '\0';
4508 2879           p = p + timeLen;
4509 2879 50         if ((end - p) < 1 || ((*p != ASN_UTCTIME) && (*p != ASN_GENERALIZEDTIME)))
    100          
    50          
4510             {
4511             psTraceCrypto("Malformed validity 3\n");
4512 0           return PS_PARSE_FAIL;
4513             }
4514 2879           *notAfterTimeType = *p;
4515 2879           p++;
4516 2879 50         if (getAsnLength(&p, seqLen - timeLen, &timeLen) < 0 ||
    50          
4517 2879           (uint32) (end - p) < timeLen)
4518             {
4519             psTraceCrypto("Malformed validity 4\n");
4520 0           return PS_PARSE_FAIL;
4521             }
4522 2879 50         if (timeLen > MAX_TIME_LEN)
4523             {
4524 0           return PS_PARSE_FAIL;
4525             }
4526 2879           *notAfter = psMalloc(pool, timeLen + 1);
4527 2879 50         if (*notAfter == NULL)
4528             {
4529 0           psError("Memory allocation error in getTimeValidity for notAfter\n");
4530 0           return PS_MEM_FAIL;
4531             }
4532 2879           memcpy(*notAfter, p, timeLen);
4533 2879           (*notAfter)[timeLen] = '\0';
4534 2879           p = p + timeLen;
4535              
4536 2879           *pp = p;
4537 2879           return PS_SUCCESS;
4538             }
4539              
4540             /******************************************************************************/
4541             /*
4542             Could be optional. If the tag doesn't contain the value from the left
4543             of the IMPLICIT keyword we don't have a match and we don't incr the pointer.
4544             */
4545 5758           static int32_t getImplicitBitString(psPool_t *pool, const unsigned char **pp,
4546             psSize_t len, int32_t impVal, unsigned char **bitString,
4547             psSize_t *bitLen)
4548             {
4549 5758           const unsigned char *p = *pp;
4550             int32_t ignore_bits;
4551              
4552 5758 50         if (len < 1)
4553             {
4554             psTraceCrypto("Initial parse error in getImplicitBitString\n");
4555 0           return PS_PARSE_FAIL;
4556             }
4557             /*
4558             We don't treat this case as an error, because of the optional nature.
4559             */
4560 5758 50         if (*p != (ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | impVal))
4561             {
4562 5758           return PS_SUCCESS;
4563             }
4564              
4565 0           p++;
4566 0 0         if (getAsnLength(&p, len, bitLen) < 0
4567 0 0         || *bitLen < 2)
4568             {
4569             psTraceCrypto("Malformed implicitBitString\n");
4570 0           return PS_PARSE_FAIL;
4571             }
4572 0           ignore_bits = *p++;
4573 0           (*bitLen)--;
4574 0 0         psAssert(ignore_bits == 0);
4575              
4576 0           *bitString = psMalloc(pool, *bitLen);
4577 0 0         if (*bitString == NULL)
4578             {
4579 0           psError("Memory allocation error in getImplicitBitString\n");
4580 0           return PS_MEM_FAIL;
4581             }
4582 0           memcpy(*bitString, p, *bitLen);
4583 0           *pp = p + *bitLen;
4584 5758           return PS_SUCCESS;
4585             }
4586              
4587              
4588             /******************************************************************************/
4589             /*
4590             Implementations of this specification MUST be prepared to receive
4591             the following standard attribute types in issuer names:
4592             country, organization, organizational-unit, distinguished name qualifier,
4593             state or province name, and common name
4594             */
4595 5808           int32_t psX509GetDNAttributes(psPool_t *pool, const unsigned char **pp,
4596             psSize_t len, x509DNattributes_t *attribs, uint32_t flags)
4597             {
4598 5808           const unsigned char *p = *pp;
4599             const unsigned char *dnEnd, *dnStart, *moreInSetPtr;
4600             x509OrgUnit_t *orgUnit;
4601             x509DomainComponent_t *domainComponent;
4602             int32 id, stringType, checkHiddenNull, moreInSet;
4603             psSize_t llen, setlen, arcLen;
4604             char *stringOut;
4605             uint32_t i;
4606              
4607             # ifdef USE_SHA1
4608             psSha1_t hash;
4609             # elif defined(USE_SHA256)
4610             psSha256_t hash;
4611             # else
4612             /* TODO can we avoid hash altogether? We do not free/finalize the hash ctx on error return below. */
4613             # error USE_SHA1 or USE_SHA256 must be defined
4614             # endif
4615              
4616 5808           dnStart = p;
4617 5808 50         if (getAsnSequence(&p, len, &llen) < 0)
4618             {
4619 0           return PS_PARSE_FAIL;
4620             }
4621 5808           dnEnd = p + llen;
4622              
4623             /*
4624             The possibility of a CERTIFICATE_REQUEST message. Set aside full DN
4625             */
4626 5808 100         if (flags & CERT_STORE_DN_BUFFER)
4627             {
4628 3438           attribs->dnencLen = (uint32) (dnEnd - dnStart);
4629 3438           attribs->dnenc = psMalloc(pool, attribs->dnencLen);
4630 3438 50         if (attribs->dnenc == NULL)
4631             {
4632 0           psError("Memory allocation error in getDNAttributes\n");
4633 0           return PS_MEM_FAIL;
4634             }
4635 3438           memcpy(attribs->dnenc, dnStart, attribs->dnencLen);
4636             }
4637 5808           moreInSet = 0;
4638 28643 100         while (p < dnEnd)
4639             {
4640 22835 50         if (getAsnSet(&p, (uint32) (dnEnd - p), &setlen) < 0)
4641             {
4642             psTraceCrypto("Malformed DN attributes\n");
4643 0           return PS_PARSE_FAIL;
4644             }
4645             /* 99.99% of certs have one attribute per SET but did come across
4646             one that nested a couple at this level so let's watch out for
4647             that with the "moreInSet" logic */
4648             MORE_IN_SET:
4649 22835           moreInSetPtr = p;
4650 22835 50         if (getAsnSequence(&p, (uint32) (dnEnd - p), &llen) < 0)
4651             {
4652             psTraceCrypto("Malformed DN attributes 2\n");
4653 0           return PS_PARSE_FAIL;
4654             }
4655 22835 50         if (moreInSet > 0)
4656             {
4657 0           moreInSet -= llen + (int32) (p - moreInSetPtr);
4658             }
4659             else
4660             {
4661 22835 50         if (setlen != llen + (int32) (p - moreInSetPtr))
4662             {
4663 0           moreInSet = setlen - (int32) (p - moreInSetPtr) - llen;
4664             }
4665             }
4666 45670 50         if (dnEnd <= p || (*(p++) != ASN_OID) ||
4667 45670 50         getAsnLength(&p, (uint32) (dnEnd - p), &arcLen) < 0 ||
4668 22835           (uint32) (dnEnd - p) < arcLen)
4669             {
4670             psTraceCrypto("Malformed DN attributes 3\n");
4671 0           return PS_PARSE_FAIL;
4672             }
4673             /*
4674             id-at OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 4}
4675             id-at-commonName OBJECT IDENTIFIER ::= {id-at 3}
4676             id-at-serialNumber OBJECT IDENTIFIER ::= {id-at 5}
4677             id-at-countryName OBJECT IDENTIFIER ::= {id-at 6}
4678             id-at-localityName OBJECT IDENTIFIER ::= {id-at 7}
4679             id-at-stateOrProvinceName OBJECT IDENTIFIER ::= {id-at 8}
4680             id-at-organizationName OBJECT IDENTIFIER ::= {id-at 10}
4681             id-at-organizationalUnitName OBJECT IDENTIFIER ::= {id-at 11}
4682             */
4683 22835           *pp = p;
4684             /*
4685             Currently we are skipping OIDs not of type {joint-iso-ccitt(2) ds(5) 4}
4686             (domainComponent is currently the only exception).
4687             However, we could be dealing with an OID we MUST support per RFC.
4688             */
4689 22835 50         if (dnEnd - p < 2)
4690             {
4691             psTraceCrypto("Malformed DN attributes 4\n");
4692 0           return PS_LIMIT_FAIL;
4693             }
4694              
4695             /*
4696             Check separately for domainComponent and uid, since those do not
4697             start with the 0x5504 (id-at) pattern the code below expects.
4698             */
4699             /*
4700             Note: According to RFC 5280, "... implementations of this
4701             specification MUST be prepared to receive the domainComponent
4702             attribute, as defined in [RFC4519]."
4703             */
4704 22835 50         if (arcLen == 10 &&
    0          
4705 0 0         *p == 0x09 &&
4706 0 0         *(p + 1) == 0x92 &&
4707 0 0         *(p + 2) == 0x26 &&
4708 0 0         *(p + 3) == 0x89 &&
4709 0 0         *(p + 4) == 0x93 &&
4710 0 0         *(p + 5) == 0xf2 &&
4711 0 0         *(p + 6) == 0x2c &&
4712 0 0         *(p + 7) == 0x64 &&
4713 0           *(p + 8) == 0x01)
4714             {
4715 0 0         if (*(p + 9) == 0x19)
4716             {
4717 0           p += 10;
4718 0           id = ATTRIB_DOMAIN_COMPONENT;
4719 0           goto oid_parsing_done;
4720             }
4721             # ifdef USE_EXTRA_DN_ATTRIBUTES
4722             else if (*(p + 9) == 0x01)
4723             {
4724             p += 10;
4725             id = ATTRIB_UID;
4726             goto oid_parsing_done;
4727             }
4728             # endif /* USE_EXTRA_DN_ATTRIBUTES */
4729             }
4730             # ifdef USE_EXTRA_DN_ATTRIBUTES
4731             if (arcLen == 9 &&
4732             *p == 0x2a &&
4733             *(p + 1) == 0x86 &&
4734             *(p + 2) == 0x48 &&
4735             *(p + 3) == 0x86 &&
4736             *(p + 4) == 0xf7 &&
4737             *(p + 5) == 0x0d &&
4738             *(p + 6) == 0x01 &&
4739             *(p + 7) == 0x09 &&
4740             *(p + 8) == 0x01)
4741             {
4742             p += 9;
4743             id = ATTRIB_EMAIL;
4744             goto oid_parsing_done;
4745             }
4746             # endif /* USE_EXTRA_DN_ATTRIBUTES */
4747              
4748             /* check id-at */
4749 22835 100         if ((*p++ != 85) || (*p++ != 4))
    50          
4750             {
4751             /* OIDs we are not parsing */
4752 20           p = *pp;
4753             /*
4754             Move past the OID and string type, get data size, and skip it.
4755             NOTE: Have had problems parsing older certs in this area.
4756             */
4757 20 50         if ((uint32) (dnEnd - p) < arcLen + 1)
4758             {
4759             psTraceCrypto("Malformed DN attributes 5\n");
4760 0           return PS_LIMIT_FAIL;
4761             }
4762 20           p += arcLen + 1;
4763 20 50         if (getAsnLength(&p, (uint32) (dnEnd - p), &llen) < 0 ||
    50          
4764 20           (uint32) (dnEnd - p) < llen)
4765             {
4766             psTraceCrypto("Malformed DN attributes 6\n");
4767 0           return PS_PARSE_FAIL;
4768             }
4769 20           p = p + llen;
4770 20           continue;
4771             }
4772             /* Next are the id of the attribute type and the ASN string type */
4773 22815 50         if (arcLen != 3 || dnEnd - p < 2)
    50          
4774             {
4775             psTraceCrypto("Malformed DN attributes 7\n");
4776 0           return PS_LIMIT_FAIL;
4777             }
4778 22815           id = (int32) * p++;
4779             oid_parsing_done:
4780             /* Done with OID parsing */
4781 22815           stringType = (int32) * p++;
4782              
4783 22815 50         if (getAsnLength(&p, (uint32) (dnEnd - p), &llen) < 0 ||
    50          
4784 22815           (uint32) (dnEnd - p) < llen)
4785             {
4786             psTraceCrypto("Malformed DN attributes 8\n");
4787 0           return PS_LIMIT_FAIL;
4788             }
4789             /*
4790             For the known 8-bit character string types, we flag that we want
4791             to test for a hidden null in the middle of the string to address the
4792             issue of www.goodguy.com\0badguy.com.
4793             For validation purposes, BMPSTRINGs are converted to UTF-8 format.
4794             */
4795 22815           checkHiddenNull = PS_FALSE;
4796 22815           switch (stringType)
4797             {
4798             case ASN_BMPSTRING:
4799             {
4800             /* MatrixSSL generally uses single byte character string
4801             formats. This function converts ASN_BMPSTRING to
4802             UTF-8 for further handling. */
4803 0           unsigned char *uc_stringOut = NULL;
4804             size_t length;
4805             int32 str_err;
4806 0           str_err = psToUtf8String(pool,
4807             (const unsigned char *) p,
4808             (size_t) llen,
4809             (psStringType_t) ASN_BMPSTRING,
4810             &uc_stringOut,
4811             &length,
4812             # if DN_NUM_TERMINATING_NULLS == 2
4813             PS_STRING_DUAL_NIL
4814             # elif DN_NUM_TERMINATING_NULLS == 1
4815             0
4816             # else
4817             # error "Unsupported value for DN_NUM_TERMINATING_NULLS."
4818             # endif
4819             );
4820 0 0         if (str_err != PS_SUCCESS)
4821             {
4822 0           return str_err;
4823             }
4824             /* Length checking. */
4825 0 0         if (length >= 0x7FFE)
4826             {
4827             /* Notice if length is too long to fit in 15 bits. */
4828 0           psFree(uc_stringOut, pool);
4829 0           return PS_LIMIT_FAIL;
4830             }
4831 0           stringOut = (char *) uc_stringOut;
4832 0           p = p + llen;
4833 0           llen = (uint16_t) length + DN_NUM_TERMINATING_NULLS;
4834 0           break;
4835             }
4836             case ASN_PRINTABLESTRING:
4837             case ASN_UTF8STRING:
4838             case ASN_IA5STRING:
4839             case ASN_T61STRING:
4840             /* coverity[unterminated_case] */
4841 22815           checkHiddenNull = PS_TRUE;
4842             /* fall through */
4843             case ASN_BIT_STRING:
4844 22815           stringOut = psMalloc(pool, llen + DN_NUM_TERMINATING_NULLS);
4845 22815 50         if (stringOut == NULL)
4846             {
4847 0           psError("Memory allocation error in getDNAttributes\n");
4848 0           return PS_MEM_FAIL;
4849             }
4850 22815           memcpy(stringOut, p, llen);
4851             /*
4852             Terminate with DN_NUM_TERMINATING_NULLS null chars to support
4853             standard string manipulations with any potential unicode types.
4854             */
4855 68445 100         for (i = 0; i < DN_NUM_TERMINATING_NULLS; i++)
4856             {
4857 45630           stringOut[llen + i] = '\0';
4858             }
4859              
4860 22815 50         if (checkHiddenNull)
4861             {
4862 22815 50         if ((uint32) strlen(stringOut) != llen)
4863             {
4864 0           psFree(stringOut, pool);
4865             psTraceCrypto("Malformed DN attributes 9\n");
4866 0           return PS_PARSE_FAIL;
4867             }
4868             }
4869              
4870 22815           p = p + llen;
4871 22815           llen += DN_NUM_TERMINATING_NULLS; /* Add null bytes for length assignments */
4872 22815           break;
4873             default:
4874             psTraceIntCrypto("Unsupported DN attrib type %d\n", stringType);
4875 0           return PS_UNSUPPORTED_FAIL;
4876             }
4877              
4878 22815           switch (id)
4879             {
4880             case ATTRIB_COUNTRY_NAME:
4881 5717 50         if (attribs->country)
4882             {
4883 0           psFree(attribs->country, pool);
4884             }
4885 5717           attribs->country = stringOut;
4886 5717           attribs->countryType = (short) stringType;
4887 5717           attribs->countryLen = (short) llen;
4888 5717           break;
4889             case ATTRIB_ORGANIZATION:
4890 5798 50         if (attribs->organization)
4891             {
4892 0           psFree(attribs->organization, pool);
4893             }
4894 5798           attribs->organization = stringOut;
4895 5798           attribs->organizationType = (short) stringType;
4896 5798           attribs->organizationLen = (short) llen;
4897 5798           break;
4898             case ATTRIB_ORG_UNIT:
4899 806           orgUnit = psMalloc(pool, sizeof(x509OrgUnit_t));
4900 806           orgUnit->name = stringOut;
4901 806           orgUnit->type = (short) stringType;
4902 806           orgUnit->len = llen;
4903             /* Push the org unit onto the front of the list */
4904 806           orgUnit->next = attribs->orgUnit;
4905 806           attribs->orgUnit = orgUnit;
4906 806           break;
4907             case ATTRIB_DN_QUALIFIER:
4908 0 0         if (attribs->dnQualifier)
4909             {
4910 0           psFree(attribs->dnQualifier, pool);
4911             }
4912 0           attribs->dnQualifier = stringOut;
4913 0           attribs->dnQualifierType = (short) stringType;
4914 0           attribs->dnQualifierLen = (short) llen;
4915 0           break;
4916             case ATTRIB_STATE_PROVINCE:
4917 4475 50         if (attribs->state)
4918             {
4919 0           psFree(attribs->state, pool);
4920             }
4921 4475           attribs->state = stringOut;
4922 4475           attribs->stateType = (short) stringType;
4923 4475           attribs->stateLen = (short) llen;
4924 4475           break;
4925             case ATTRIB_COMMON_NAME:
4926 5708 50         if (attribs->commonName)
4927             {
4928 0           psFree(attribs->commonName, pool);
4929             }
4930 5708           attribs->commonName = stringOut;
4931 5708           attribs->commonNameType = (short) stringType;
4932 5708           attribs->commonNameLen = (short) llen;
4933 5708           break;
4934             case ATTRIB_SERIALNUMBER:
4935 30 50         if (attribs->serialNumber)
4936             {
4937 0           psFree(attribs->serialNumber, pool);
4938             }
4939 30           attribs->serialNumber = stringOut;
4940 30           attribs->serialNumberType = (short) stringType;
4941 30           attribs->serialNumberLen = (short) llen;
4942 30           break;
4943             case ATTRIB_DOMAIN_COMPONENT:
4944 0           domainComponent = psMalloc(pool, sizeof(x509DomainComponent_t));
4945 0           domainComponent->name = stringOut;
4946 0           domainComponent->type = (short) stringType;
4947 0           domainComponent->len = llen;
4948             /* Push the org unit onto the front of the list */
4949 0           domainComponent->next = attribs->domainComponent;
4950 0           attribs->domainComponent = domainComponent;
4951 0           break;
4952             # ifdef USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD
4953             case ATTRIB_LOCALITY:
4954 281 50         if (attribs->locality)
4955             {
4956 0           psFree(attribs->locality, pool);
4957             }
4958 281           attribs->locality = stringOut;
4959 281           attribs->localityType = (short) stringType;
4960 281           attribs->localityLen = (short) llen;
4961 281           break;
4962             case ATTRIB_TITLE:
4963 0 0         if (attribs->title)
4964             {
4965 0           psFree(attribs->title, pool);
4966             }
4967 0           attribs->title = stringOut;
4968 0           attribs->titleType = (short) stringType;
4969 0           attribs->titleLen = (short) llen;
4970 0           break;
4971             case ATTRIB_SURNAME:
4972 0 0         if (attribs->surname)
4973             {
4974 0           psFree(attribs->surname, pool);
4975             }
4976 0           attribs->surname = stringOut;
4977 0           attribs->surnameType = (short) stringType;
4978 0           attribs->surnameLen = (short) llen;
4979 0           break;
4980             case ATTRIB_GIVEN_NAME:
4981 0 0         if (attribs->givenName)
4982             {
4983 0           psFree(attribs->givenName, pool);
4984             }
4985 0           attribs->givenName = stringOut;
4986 0           attribs->givenNameType = (short) stringType;
4987 0           attribs->givenNameLen = (short) llen;
4988 0           break;
4989             case ATTRIB_INITIALS:
4990 0 0         if (attribs->initials)
4991             {
4992 0           psFree(attribs->initials, pool);
4993             }
4994 0           attribs->initials = stringOut;
4995 0           attribs->initialsType = (short) stringType;
4996 0           attribs->initialsLen = (short) llen;
4997 0           break;
4998             case ATTRIB_PSEUDONYM:
4999 0 0         if (attribs->pseudonym)
5000             {
5001 0           psFree(attribs->pseudonym, pool);
5002             }
5003 0           attribs->pseudonym = stringOut;
5004 0           attribs->pseudonymType = (short) stringType;
5005 0           attribs->pseudonymLen = (short) llen;
5006 0           break;
5007             case ATTRIB_GEN_QUALIFIER:
5008 0 0         if (attribs->generationQualifier)
5009             {
5010 0           psFree(attribs->generationQualifier, pool);
5011             }
5012 0           attribs->generationQualifier = stringOut;
5013 0           attribs->generationQualifierType = (short) stringType;
5014 0           attribs->generationQualifierLen = (short) llen;
5015 0           break;
5016             # endif /* USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD */
5017             # ifdef USE_EXTRA_DN_ATTRIBUTES
5018             case ATTRIB_STREET_ADDRESS:
5019             if (attribs->streetAddress)
5020             {
5021             psFree(attribs->streetAddress, pool);
5022             }
5023             attribs->streetAddress = stringOut;
5024             attribs->streetAddressType = (short) stringType;
5025             attribs->streetAddressLen = (short) llen;
5026             break;
5027             case ATTRIB_POSTAL_ADDRESS:
5028             if (attribs->postalAddress)
5029             {
5030             psFree(attribs->postalAddress, pool);
5031             }
5032             attribs->postalAddress = stringOut;
5033             attribs->postalAddressType = (short) stringType;
5034             attribs->postalAddressLen = (short) llen;
5035             break;
5036             case ATTRIB_TELEPHONE_NUMBER:
5037             if (attribs->telephoneNumber)
5038             {
5039             psFree(attribs->telephoneNumber, pool);
5040             }
5041             attribs->telephoneNumber = stringOut;
5042             attribs->telephoneNumberType = (short) stringType;
5043             attribs->telephoneNumberLen = (short) llen;
5044             break;
5045             case ATTRIB_UID:
5046             if (attribs->uid)
5047             {
5048             psFree(attribs->uid, pool);
5049             }
5050             attribs->uid = stringOut;
5051             attribs->uidType = (short) stringType;
5052             attribs->uidLen = (short) llen;
5053             break;
5054             case ATTRIB_NAME:
5055             if (attribs->name)
5056             {
5057             psFree(attribs->name, pool);
5058             }
5059             attribs->name = stringOut;
5060             attribs->nameType = (short) stringType;
5061             attribs->nameLen = (short) llen;
5062             break;
5063             case ATTRIB_EMAIL:
5064             if (attribs->email)
5065             {
5066             psFree(attribs->email, pool);
5067             }
5068             attribs->email = stringOut;
5069             attribs->emailType = (short) stringType;
5070             attribs->emailLen = (short) llen;
5071             break;
5072             # endif /* USE_EXTRA_DN_ATTRIBUTES */
5073             default:
5074             /* Not a MUST support, so just ignore unknown */
5075 0           psFree(stringOut, pool);
5076 0           stringOut = NULL;
5077 0           break;
5078             }
5079 22815 50         if (moreInSet)
5080             {
5081 0           goto MORE_IN_SET;
5082             }
5083             }
5084             /* Hash is used to quickly compare DNs */
5085             # ifdef USE_SHA1
5086 5808           psSha1PreInit(&hash);
5087 5808           psSha1Init(&hash);
5088 5808           psSha1Update(&hash, dnStart, (dnEnd - dnStart));
5089 5808           psSha1Final(&hash, (unsigned char *) attribs->hash);
5090             # else
5091             psSha256PreInit(&hash);
5092             psSha256Init(&hash);
5093             psSha256Update(&hash, dnStart, (dnEnd - dnStart));
5094             psSha256Final(&hash, (unsigned char *) attribs->hash);
5095             # endif
5096 5808           *pp = p;
5097 5808           return PS_SUCCESS;
5098             }
5099              
5100             /******************************************************************************/
5101             /*
5102             Free helper
5103             */
5104 8640           void psX509FreeDNStruct(x509DNattributes_t *dn, psPool_t *allocPool)
5105             {
5106 8640           psFree(dn->dnenc, allocPool);
5107              
5108 8640           psFree(dn->country, allocPool);
5109 8640           psFree(dn->organization, allocPool);
5110 8640           freeOrgUnitList(dn->orgUnit, allocPool);
5111 8640           psFree(dn->dnQualifier, allocPool);
5112 8640           psFree(dn->state, allocPool);
5113 8640           psFree(dn->commonName, allocPool);
5114 8640           psFree(dn->serialNumber, allocPool);
5115 8640           freeDomainComponentList(dn->domainComponent, allocPool);
5116             # ifdef USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD
5117 8640           psFree(dn->locality, allocPool);
5118 8640           psFree(dn->title, allocPool);
5119 8640           psFree(dn->surname, allocPool);
5120 8640           psFree(dn->givenName, allocPool);
5121 8640           psFree(dn->initials, allocPool);
5122 8640           psFree(dn->pseudonym, allocPool);
5123 8640           psFree(dn->generationQualifier, allocPool);
5124             # endif /* USE_EXTRA_DN_ATTRIBUTES_RFC5280_SHOULD */
5125             # ifdef USE_EXTRA_DN_ATTRIBUTES
5126             psFree(dn->streetAddress, allocPool);
5127             psFree(dn->postalAddress, allocPool);
5128             psFree(dn->telephoneNumber, allocPool);
5129             psFree(dn->uid, allocPool);
5130             psFree(dn->name, allocPool);
5131             psFree(dn->email, allocPool);
5132             # endif /* USE_EXTRA_DN_ATTRIBUTES */
5133 8640           }
5134              
5135              
5136             /******************************************************************************/
5137             /*
5138             Fundamental routine to test whether the supplied issuerCert issued
5139             the supplied subjectCert. There are currently two tests that are
5140             performed here:
5141             1. A strict SHA1 hash comparison of the Distinguished Name details
5142             2. A test of the public key cryptographic cert signature
5143              
5144             subjectCert may be a chain. Cert chains must always be passed with
5145             the child-most as the first in the list (the 'next' structure member
5146             points to the parent). The authentication of the entire chain
5147             will be tested before the issuerCert is used to authenticate the
5148             parent-most certificate
5149              
5150             issuerCert will always be a treated as a single certificate even if it
5151             is a chain
5152              
5153             If there is no issuerCert the parent-most subejct cert will always
5154             be tested as a self-signed CA certificate.
5155              
5156             So there are three uses:
5157             1. Test a cert was issued by another (single subjectCert, single issuerCert)
5158             1. Test a self signed cert (single cert to subjectCert, no issuerCert)
5159             2. Test a CA terminated chain (cert chain to subjectCert, no issuerCert)
5160              
5161             This function exits with a failure code on the first authentication
5162             that doesn't succeed. The 'authStatus' members may be examined for more
5163             information of where the authentication failed.
5164              
5165             The 'authStatus' member of the issuerCert will be set to PS_FALSE
5166             since it will not be authenticated.
5167              
5168             The 'authStatus' members of the subjectCert structures will always
5169             be reset to PS_FALSE when this routine is called and set to PS_TRUE
5170             when authenticated. Any error during the authentication will set the
5171             current subject cert 'authStatus' member to PS_CERT_AUTH_FAIL and the
5172             function will return with an error code.
5173              
5174             Return codes:
5175             PS_SUCCESS - yes
5176              
5177             PS_CERT_AUTH_FAIL - nope. these certs are not a match
5178             PS_UNSUPPORTED_FAIL - unrecognized cert format
5179             PS_ARG_FAIL - local, psRsaDecryptPub
5180             PS_LIMIT_FAIL - psRsaDecryptPub
5181             PS_FAILURE - internal psRsaDecryptPub failure
5182              
5183             There is nothing for the caller to free at the completion of this
5184             routine.
5185             */
5186 1295           int32 psX509AuthenticateCert(psPool_t *pool, psX509Cert_t *subjectCert,
5187             psX509Cert_t *issuerCert, psX509Cert_t **foundIssuer,
5188             void *hwCtx, void *poolUserPtr)
5189             {
5190             psX509Cert_t *ic, *sc;
5191             int32 sigType, rc;
5192             uint32 sigLen;
5193 1295           void *rsaData = NULL;
5194              
5195             # ifdef USE_ECC
5196             int32 sigStat;
5197             # endif /* USE_ECC */
5198             # ifdef USE_RSA
5199             unsigned char sigOut[10 + MAX_HASH_SIZE + 9]; /* Max size */
5200 1295           unsigned char *tempSig = NULL;
5201             # endif /* USE_RSA */
5202 1295           psPool_t *pkiPool = NULL;
5203             # ifdef USE_PKCS1_PSS
5204             psSize_t pssLen;
5205             # endif
5206              
5207 1295           rc = 0;
5208 1295           sigLen = 0;
5209 1295 50         if (subjectCert == NULL)
5210             {
5211             psTraceCrypto("No subject cert given to psX509AuthenticateCert\n");
5212 0           return PS_ARG_FAIL;
5213             }
5214              
5215             /*
5216             Determine what we've been passed
5217             */
5218 1295 100         if (issuerCert == NULL)
5219             {
5220             /* reset auth flags in subjectCert chain and find first sc and ic */
5221 1           sc = subjectCert;
5222 3 100         while (sc)
5223             {
5224 2           sc->authStatus = PS_FALSE;
5225 2           sc = sc->next;
5226             }
5227             /* Now see if this is a chain or just a single cert */
5228 1           sc = subjectCert;
5229 1 50         if (sc->next == NULL)
5230             {
5231 0           ic = sc; /* A single subject cert for self-signed test */
5232             }
5233             else
5234             {
5235 1           ic = sc->next;
5236             }
5237             }
5238             else
5239             {
5240 1294           issuerCert->authStatus = PS_FALSE;
5241 1294           ic = issuerCert; /* Easy case of single subject and single issuer */
5242 1294           sc = subjectCert;
5243             }
5244              
5245             /*
5246             Error on first problem seen and set the subject status to FAIL
5247             */
5248 2445 100         while (ic)
5249             {
5250             /*
5251             Certificate authority constraint only available in version 3 certs.
5252             Only parsing version 3 certs by default though.
5253             */
5254 1296 50         if ((ic->version > 1) && (ic->extensions.bc.cA != CA_TRUE))
    50          
5255             {
5256 0 0         if (sc != ic)
5257             {
5258             psTraceCrypto("Issuer does not have basicConstraint CA permissions\n");
5259 0           sc->authStatus = PS_CERT_AUTH_FAIL_BC;
5260 0           return PS_CERT_AUTH_FAIL_BC;
5261             }
5262             }
5263              
5264             /*
5265             Use sha1 hash of issuer fields computed at parse time to compare
5266             */
5267 1296 100         if (memcmp(sc->issuer.hash, ic->subject.hash, SHA1_HASH_SIZE) != 0)
5268             {
5269             /* #define ALLOW_INTERMEDIATES_AS_ROOTS */
5270             # ifdef ALLOW_INTERMEDIATES_AS_ROOTS
5271             /* In a typical deployment, we have this trust chain:
5272             leaf->intermediate->(root)
5273             Where leaf and intermediate are sent by the peer and root is loaded by the
5274             application as a trusted CA.
5275             In some cases, it may not be desireable to load the root cert as a CA and
5276             validate every certificate it has signed. This is usually due to a
5277             legacy v1 certificate or certificate using a weak cryptographic
5278             algorithm.
5279             Ideally, the certificate chain can be re-issued or cross-signed by a modern
5280             root certifiate. However, a workaround is to load the final intermediate
5281             certificate in the application as a trusted, non self-signed root.
5282             The peer sends the leaf->intermediate chain as before, but the application
5283             loads the intermediate, not the root as a trusted CA cert.
5284             Without special treatment, this arranement will fail validation because the
5285             intermediate has been issued by 'root', and that is what it wants to validate
5286             against. However, if we check to see if a copy of intermediate is itself in the
5287             issuer list, then we have validated to a trusted root and do not need
5288             to verify the signature on the intermediate.
5289             Note this implementation only allows the last cert in the chain sent by
5290             the client to be treated as root, for example in a chain with 2 intermediates:
5291             Peer sends l->i1->i2->(root)
5292             Valid CA to load: i2 or root
5293             Invalid CA to load: l or i1
5294             */
5295             if (sc->signatureLen == ic->signatureLen
5296             && memcmpct(sc->signature, ic->signature, sc->signatureLen) == 0)
5297             {
5298             /* Skip some of the signature and issuer checks */
5299             goto L_INTERMEDIATE_ROOT;
5300             }
5301             # endif
5302             if (sc == ic)
5303             {
5304             psTraceCrypto("Info: not a self-signed certificate\n");
5305             }
5306             else
5307             {
5308             psTraceCrypto("Issuer DN attributes do not match subject\n");
5309             }
5310 146           sc->authStatus = PS_CERT_AUTH_FAIL_DN;
5311 146           return PS_CERT_AUTH_FAIL_DN;
5312             }
5313              
5314             # ifdef USE_CRL
5315             /* This function operates on the global cache */
5316 1150           psCRL_determineRevokedStatus(sc);
5317             /* The only status that is going to make us terminate the connection
5318             immediately is if we find REVOKED_AND_AUTHENTICATED */
5319 1150 50         if (sc->revokedStatus == CRL_CHECK_REVOKED_AND_AUTHENTICATED)
5320             {
5321 0           sc->authStatus = PS_CERT_AUTH_FAIL_REVOKED;
5322 0           return PS_CERT_AUTH_FAIL_REVOKED;
5323             }
5324             # endif
5325              
5326             /*
5327             Signature confirmation
5328             The sigLen is the ASN.1 size in bytes for encoding the hash.
5329             The magic 10 is comprised of the SEQUENCE and ALGORITHM ID overhead.
5330             The magic 9, 8, or 5 is the OID length of the corresponding algorithm.
5331             */
5332 1150           switch (sc->sigAlgorithm)
5333             {
5334             # ifdef USE_RSA
5335             # ifdef ENABLE_MD5_SIGNED_CERTS
5336             # ifdef USE_MD2
5337             case OID_MD2_RSA_SIG:
5338             # endif
5339             case OID_MD5_RSA_SIG:
5340             sigType = RSA_TYPE_SIG;
5341             sigLen = 10 + MD5_HASH_SIZE + 8;
5342             break;
5343             # endif
5344             # ifdef ENABLE_SHA1_SIGNED_CERTS
5345             case OID_SHA1_RSA_SIG:
5346             case OID_SHA1_RSA_SIG2:
5347 0           sigLen = 10 + SHA1_HASH_SIZE + 5;
5348 0           sigType = RSA_TYPE_SIG;
5349 0           break;
5350             # endif
5351             # ifdef USE_SHA224
5352             case OID_SHA224_RSA_SIG:
5353             sigLen = 10 + SHA224_HASH_SIZE + 9;
5354             sigType = RSA_TYPE_SIG;
5355             break;
5356             # endif
5357             # ifdef USE_SHA256
5358             case OID_SHA256_RSA_SIG:
5359 1150           sigLen = 10 + SHA256_HASH_SIZE + 9;
5360 1150           sigType = RSA_TYPE_SIG;
5361 1150           break;
5362             # endif
5363             # ifdef USE_SHA384
5364             case OID_SHA384_RSA_SIG:
5365 0           sigLen = 10 + SHA384_HASH_SIZE + 9;
5366 0           sigType = RSA_TYPE_SIG;
5367 0           break;
5368             # endif
5369             # ifdef USE_SHA512
5370             case OID_SHA512_RSA_SIG:
5371 0           sigLen = 10 + SHA512_HASH_SIZE + 9;
5372 0           sigType = RSA_TYPE_SIG;
5373 0           break;
5374             # endif
5375             # endif /* USE_RSA */
5376             # ifdef USE_ECC
5377             # ifdef ENABLE_SHA1_SIGNED_CERTS
5378             case OID_SHA1_ECDSA_SIG:
5379 0           sigLen = SHA1_HASH_SIZE;
5380 0           sigType = ECDSA_TYPE_SIG;
5381 0           break;
5382             # endif
5383             # ifdef USE_SHA224
5384             case OID_SHA224_ECDSA_SIG:
5385             sigLen = SHA224_HASH_SIZE;
5386             sigType = ECDSA_TYPE_SIG;
5387             break;
5388             # endif
5389             # ifdef USE_SHA256
5390             case OID_SHA256_ECDSA_SIG:
5391 0           sigLen = SHA256_HASH_SIZE;
5392 0           sigType = ECDSA_TYPE_SIG;
5393 0           break;
5394             # endif
5395             # ifdef USE_SHA384
5396             case OID_SHA384_ECDSA_SIG:
5397 0           sigLen = SHA384_HASH_SIZE;
5398 0           sigType = ECDSA_TYPE_SIG;
5399 0           break;
5400             # endif
5401             # ifdef USE_SHA512
5402             case OID_SHA512_ECDSA_SIG:
5403 0           sigLen = SHA512_HASH_SIZE;
5404 0           sigType = ECDSA_TYPE_SIG;
5405 0           break;
5406             # endif
5407             # endif /* USE_ECC */
5408              
5409             # ifdef USE_PKCS1_PSS
5410             case OID_RSASSA_PSS:
5411 0           switch (sc->pssHash)
5412             {
5413             # ifdef ENABLE_MD5_SIGNED_CERTS
5414             case PKCS1_MD5_ID:
5415             sigLen = MD5_HASH_SIZE;
5416             break;
5417             # endif
5418             # ifdef ENABLE_SHA1_SIGNED_CERTS
5419             case PKCS1_SHA1_ID:
5420 0           sigLen = SHA1_HASH_SIZE;
5421 0           break;
5422             # endif
5423             # ifdef USE_SHA224
5424             case PKCS1_SHA224_ID:
5425             sigLen = SHA224_HASH_SIZE;
5426             break;
5427             # endif
5428             # ifdef USE_SHA256
5429             case PKCS1_SHA256_ID:
5430 0           sigLen = SHA256_HASH_SIZE;
5431 0           break;
5432             # endif
5433             # ifdef USE_SHA384
5434             case PKCS1_SHA384_ID:
5435 0           sigLen = SHA384_HASH_SIZE;
5436 0           break;
5437             # endif
5438             # ifdef USE_SHA512
5439             case PKCS1_SHA512_ID:
5440 0           sigLen = SHA512_HASH_SIZE;
5441 0           break;
5442             # endif
5443             default:
5444 0           return PS_UNSUPPORTED_FAIL;
5445             }
5446 0           sigType = RSAPSS_TYPE_SIG;
5447 0           break;
5448             # endif
5449             default:
5450 0           sigType = PS_UNSUPPORTED_FAIL;
5451 0           break;
5452             }
5453              
5454 1150 50         if (sigType == PS_UNSUPPORTED_FAIL)
5455             {
5456 0           sc->authStatus = PS_CERT_AUTH_FAIL_SIG;
5457             psTraceIntCrypto("Unsupported certificate signature algorithm %d\n",
5458             subjectCert->sigAlgorithm);
5459 0           return sigType;
5460             }
5461              
5462             # ifdef USE_RSA
5463             if (sigType == RSA_TYPE_SIG || sigType == RSAPSS_TYPE_SIG)
5464             {
5465             }
5466             /* Now do the signature validation */
5467 1150 50         if (sigType == RSA_TYPE_SIG)
5468             {
5469 1150 50         psAssert(sigLen <= sizeof(sigOut));
5470             /*
5471             psRsaDecryptPub destroys the 'in' parameter so let it be a tmp
5472             */
5473 1150           tempSig = psMalloc(pool, sc->signatureLen);
5474 1150 50         if (tempSig == NULL)
5475             {
5476 0           psError("Memory allocation error: psX509AuthenticateCert\n");
5477 0           return PS_MEM_FAIL;
5478             }
5479 1150           memcpy(tempSig, sc->signature, sc->signatureLen);
5480              
5481 1150 50         if ((rc = psRsaDecryptPub(pkiPool, &ic->publicKey.key.rsa,
5482 1150           tempSig, sc->signatureLen, sigOut, sigLen, rsaData)) < 0)
5483             {
5484              
5485             psTraceCrypto("Unable to RSA decrypt certificate signature\n");
5486 0           sc->authStatus = PS_CERT_AUTH_FAIL_SIG;
5487 0           psFree(tempSig, pool);
5488 0           return rc;
5489             }
5490 1150           psFree(tempSig, pool);
5491 1150           rc = x509ConfirmSignature(sc->sigHash, sigOut, sigLen);
5492             }
5493             # if defined(USE_PKCS1_PSS) && !defined(USE_PKCS1_PSS_VERIFY_ONLY)
5494 1150 50         if (sigType == RSAPSS_TYPE_SIG)
5495             {
5496 0           tempSig = psMalloc(pool, sc->signatureLen);
5497 0 0         if (tempSig == NULL)
5498             {
5499 0           psError("Memory allocation error: psX509AuthenticateCert\n");
5500 0           return PS_MEM_FAIL;
5501             }
5502 0           pssLen = sc->signatureLen;
5503 0 0         if ((rc = psRsaCrypt(pkiPool, &ic->publicKey.key.rsa,
5504 0           sc->signature, sc->signatureLen, tempSig, &pssLen,
5505             PS_PUBKEY, rsaData)) < 0)
5506             {
5507 0           psFree(tempSig, pool);
5508 0           return rc;
5509             }
5510              
5511 0 0         if (psPkcs1PssDecode(pkiPool, sc->sigHash, sigLen, tempSig,
5512 0           pssLen, sc->saltLen, sc->pssHash, ic->publicKey.keysize * 8,
5513             &rc) < 0)
5514             {
5515 0           psFree(tempSig, pool);
5516 0           return PS_FAILURE;
5517             }
5518 0           psFree(tempSig, pool);
5519              
5520 0 0         if (rc == 0)
5521             {
5522             /* This is an indication the hash did NOT match */
5523 0           rc = -1; /* The test below is looking for < 0 */
5524             }
5525             }
5526             # endif /* defined(USE_PKCS1_PSS) && !defined(USE_PKCS1_PSS_VERIFY_ONLY) */
5527             # endif /* USE_RSA */
5528              
5529             # ifdef USE_ECC
5530 1150 50         if (sigType == ECDSA_TYPE_SIG)
5531             {
5532 0 0         if ((rc = psEccDsaVerify(pkiPool,
5533 0           &ic->publicKey.key.ecc,
5534 0           sc->sigHash, sigLen,
5535 0           sc->signature, sc->signatureLen,
5536             &sigStat, rsaData)) != 0)
5537             {
5538             psTraceCrypto("Error validating ECDSA certificate signature\n");
5539 0           sc->authStatus = PS_CERT_AUTH_FAIL_SIG;
5540 0           return rc;
5541             }
5542 0 0         if (sigStat == -1)
5543             {
5544             /* No errors, but signature didn't pass */
5545             psTraceCrypto("ECDSA certificate signature failed\n");
5546 0           rc = -1;
5547             }
5548             }
5549             # endif /* USE_ECC */
5550              
5551             /*
5552             Test what happen in the signature test?
5553             */
5554 1150 50         if (rc < PS_SUCCESS)
5555             {
5556 0           sc->authStatus = PS_CERT_AUTH_FAIL_SIG;
5557 0           return rc;
5558             }
5559              
5560              
5561             /* X.509 extension tests. Problems below here will be collected
5562             in flags and given to the user */
5563              
5564             /* Verify subject key and auth key if either is non-zero */
5565 1150 50         if (sc->extensions.ak.keyLen > 0 || ic->extensions.sk.len > 0)
    0          
5566             {
5567 1150 50         if (ic->extensions.sk.len != sc->extensions.ak.keyLen)
5568             {
5569             /* The one exception to this test would be if this is a
5570             self-signed CA being authenticated with the exact same
5571             self-signed CA and that certificate does not popluate
5572             the Authority Key Identifier extension */
5573 0 0         if ((sc->signatureLen == ic->signatureLen) &&
    0          
5574 0           (memcmp(sc->signature, ic->signature, ic->signatureLen)
5575             == 0))
5576             {
5577 0 0         if (sc->extensions.ak.keyLen != 0)
5578             {
5579             psTraceCrypto("Subject/Issuer key id mismatch\n");
5580 0           sc->authStatus = PS_CERT_AUTH_FAIL_AUTHKEY;
5581             }
5582             }
5583             else
5584             {
5585             psTraceCrypto("Subject/Issuer key id mismatch\n");
5586 0           sc->authStatus = PS_CERT_AUTH_FAIL_AUTHKEY;
5587             }
5588             }
5589             else
5590             {
5591 1150 50         if (memcmp(ic->extensions.sk.id, sc->extensions.ak.keyId,
5592 1150           ic->extensions.sk.len) != 0)
5593             {
5594             psTraceCrypto("Subject/Issuer key id data mismatch\n");
5595 0           sc->authStatus = PS_CERT_AUTH_FAIL_AUTHKEY;
5596             }
5597             }
5598             }
5599              
5600             /* Ensure keyCertSign of KeyUsage. The second byte of the BIT STRING
5601             will always contain the relevant information. */
5602 1150 100         if ( !(ic->extensions.keyUsageFlags & KEY_USAGE_KEY_CERT_SIGN))
5603             {
5604             /* @security If keyUsageFlags is zero, it may not exist at all
5605             in the cert. This is allowed if the cert was issued before
5606             the RFC was updated to require this field for CA certificates.
5607             RFC3280 and above specify this as a MUST for CACerts. */
5608 1148 50         if (ic->extensions.keyUsageFlags == 0)
5609             {
5610 1148           rc = issuedBefore(RFC_3280, ic);
5611             }
5612             else
5613             {
5614 0           rc = 0; /* Awkward code to force the compare below */
5615             }
5616             /* Iff rc == 1 we won't error */
5617 1148 50         if (!rc)
5618             {
5619             psTraceCrypto("Issuer does not allow keyCertSign in keyUsage\n");
5620 1148           sc->authFailFlags |= PS_CERT_AUTH_FAIL_KEY_USAGE_FLAG;
5621 1148           sc->authStatus = PS_CERT_AUTH_FAIL_EXTENSION;
5622             }
5623 0 0         else if (rc < 0)
5624             {
5625             psTraceCrypto("Issue date check failed\n");
5626 0           return PS_PARSE_FAIL;
5627             }
5628             }
5629             # ifdef ALLOW_INTERMEDIATES_AS_ROOTS
5630             L_INTERMEDIATE_ROOT:
5631             # endif
5632             /* If date was out of range in parse, and we have no other auth errors,
5633             set it here. Other errors "take priority" in the return code, although
5634             all can be accessed with authFailFlags. */
5635 1150 100         if (sc->authStatus == PS_FALSE
5636 2 50         && sc->authFailFlags & PS_CERT_AUTH_FAIL_DATE_FLAG)
5637             {
5638 0           sc->authStatus = PS_CERT_AUTH_FAIL_EXTENSION;
5639             }
5640             /*
5641             Fall through to here only if passed all non-failure checks.
5642             */
5643 1150 100         if (sc->authStatus == PS_FALSE) /* Hasn't been touched */
5644             {
5645 2           sc->authStatus = PS_CERT_AUTH_PASS;
5646             }
5647             /*
5648             Loop control for finding next ic and sc.
5649             */
5650 1150 100         if (ic == sc)
5651             {
5652 1           *foundIssuer = ic;
5653 1           ic = NULL; /* Single self-signed test completed */
5654             }
5655 1149 100         else if (ic == issuerCert)
5656             {
5657 1148           *foundIssuer = ic;
5658 1148           ic = NULL; /* If issuerCert was used, that is always final test */
5659             }
5660             else
5661             {
5662 1           sc = ic;
5663 1           ic = sc->next;
5664 1 50         if (ic == NULL) /* Reached end of chain */
5665             {
5666 1           *foundIssuer = ic;
5667 1           ic = sc; /* Self-signed test on final subectCert chain */
5668             }
5669             }
5670              
5671             }
5672 1295           return PS_SUCCESS;
5673             }
5674              
5675             # ifdef USE_RSA
5676             /******************************************************************************/
5677             /*
5678             Do the signature validation for a subject certificate against a
5679             known CA certificate
5680             */
5681 1150           static int32_t x509ConfirmSignature(const unsigned char *sigHash,
5682             const unsigned char *sigOut, psSize_t sigLen)
5683             {
5684             const unsigned char *end;
5685 1150           const unsigned char *p = sigOut;
5686             unsigned char hash[MAX_HASH_SIZE];
5687             int32_t oi;
5688             psSize_t len, plen;
5689              
5690 1150           end = p + sigLen;
5691             /*
5692             DigestInfo ::= SEQUENCE {
5693             digestAlgorithm DigestAlgorithmIdentifier,
5694             digest Digest }
5695              
5696             DigestAlgorithmIdentifier ::= AlgorithmIdentifier
5697              
5698             Digest ::= OCTET STRING
5699             */
5700 1150 50         if (getAsnSequence(&p, (uint32) (end - p), &len) < 0)
5701             {
5702             psTraceCrypto("Initial parse error in x509ConfirmSignature\n");
5703 0           return PS_PARSE_FAIL;
5704             }
5705              
5706             /* Could be MD5 or SHA1 */
5707 1150 50         if (getAsnAlgorithmIdentifier(&p, (uint32) (end - p), &oi, &plen) < 0)
5708             {
5709             psTraceCrypto("Algorithm ID parse error in x509ConfirmSignature\n");
5710 0           return PS_PARSE_FAIL;
5711             }
5712 1150 50         psAssert(plen == 0);
5713 2300           if ((*p++ != ASN_OCTET_STRING) ||
5714 2300 50         getAsnLength(&p, (uint32) (end - p), &len) < 0 ||
5715 1150           (uint32) (end - p) < len)
5716             {
5717             psTraceCrypto("getAsnLength parse error in x509ConfirmSignature\n");
5718 0           return PS_PARSE_FAIL;
5719             }
5720 1150           memcpy(hash, p, len);
5721 1150           switch (oi)
5722             {
5723             # ifdef ENABLE_MD5_SIGNED_CERTS
5724             # ifdef USE_MD2
5725             case OID_MD2_ALG:
5726             # endif
5727             case OID_MD5_ALG:
5728             if (len != MD5_HASH_SIZE)
5729             {
5730             psTraceCrypto("MD5_HASH_SIZE error in x509ConfirmSignature\n");
5731             return PS_LIMIT_FAIL;
5732             }
5733             break;
5734             # endif
5735             # ifdef ENABLE_SHA1_SIGNED_CERTS
5736             case OID_SHA1_ALG:
5737 0 0         if (len != SHA1_HASH_SIZE)
5738             {
5739             psTraceCrypto("SHA1_HASH_SIZE error in x509ConfirmSignature\n");
5740 0           return PS_LIMIT_FAIL;
5741             }
5742 0           break;
5743             # endif
5744             # ifdef USE_SHA224
5745             case OID_SHA224_ALG:
5746             if (len != SHA224_HASH_SIZE)
5747             {
5748             psTraceCrypto("SHA224_HASH_SIZE error in x509ConfirmSignature\n");
5749             return PS_LIMIT_FAIL;
5750             }
5751             break;
5752             # endif
5753             # ifdef USE_SHA256
5754             case OID_SHA256_ALG:
5755 1150 50         if (len != SHA256_HASH_SIZE)
5756             {
5757             psTraceCrypto("SHA256_HASH_SIZE error in x509ConfirmSignature\n");
5758 0           return PS_LIMIT_FAIL;
5759             }
5760 1150           break;
5761             # endif
5762             # ifdef USE_SHA384
5763             case OID_SHA384_ALG:
5764 0 0         if (len != SHA384_HASH_SIZE)
5765             {
5766             psTraceCrypto("SHA384_HASH_SIZE error in x509ConfirmSignature\n");
5767 0           return PS_LIMIT_FAIL;
5768             }
5769 0           break;
5770             # endif
5771             # ifdef USE_SHA512
5772             case OID_SHA512_ALG:
5773 0 0         if (len != SHA512_HASH_SIZE)
5774             {
5775             psTraceCrypto("SHA512_HASH_SIZE error in x509ConfirmSignature\n");
5776 0           return PS_LIMIT_FAIL;
5777             }
5778 0           break;
5779             # endif
5780             default:
5781             psTraceCrypto("Unsupported alg ID error in x509ConfirmSignature\n");
5782 0           return PS_UNSUPPORTED_FAIL;
5783             }
5784             /* hash should match sigHash */
5785 1150 50         if (memcmpct(hash, sigHash, len) != 0)
5786             {
5787             psTraceCrypto("Signature failure in x509ConfirmSignature\n");
5788 0           return PS_SIGNATURE_MISMATCH;
5789             }
5790 1150           return PS_SUCCESS;
5791             }
5792             # endif /* USE_RSA */
5793              
5794             /******************************************************************************/
5795             # endif /* USE_CERT_PARSE */
5796              
5797             # ifdef USE_OCSP
5798              
5799             /******************************************************************************/
5800              
5801 0           static int32_t parse_nonce_ext(const unsigned char *p, size_t sz,
5802             psBuf_t *nonceExtension)
5803             {
5804             psParseBuf_t pb;
5805             psParseBuf_t extensions;
5806             psParseBuf_t extension;
5807              
5808 0           memset(nonceExtension, 0, sizeof(psBuf_t));
5809 0 0         if (psParseBufFromStaticData(&pb, p, sz) == PS_SUCCESS)
5810             {
5811 0 0         if (psParseBufTryReadTagSub(&pb, &extensions, 0xA1))
5812             {
5813 0 0         while (psParseBufTryReadSequenceSub(&extensions,
5814             &extension))
5815             {
5816             psParseBuf_t sub;
5817 0           psParseBufReadSequenceSub(&extension, &sub);
5818 0 0         if (psParseBufTrySkipBytes(
5819             &sub,
5820             (const unsigned char *)
5821             "\x06\x09\x2b\x06\x01\x05"
5822             "\x05\x07\x30\x01\x02", 11))
5823             {
5824 0           psParseBufReadTagRef(
5825             &sub, nonceExtension, 0x04);
5826             }
5827 0           psParseBufFinish(&sub);
5828 0 0         if (psParseBufFinish(&extension) != PS_SUCCESS)
5829             {
5830 0           break;
5831             }
5832             }
5833 0           psParseBufFinish(&extensions);
5834             }
5835             }
5836 0           return PS_SUCCESS; /* No parsing errors detected. */
5837             }
5838              
5839 0           static void parseSingleResponseRevocationTimeAndReason(
5840             const unsigned char *p,
5841             psSize_t glen,
5842             psOcspSingleResponse_t *res)
5843             {
5844             /* Note: res has to have been cleared before this function.
5845             The function does not fill-in the relevant fields if they are
5846             not found. */
5847              
5848             /* get revocation time ASN.1 (GeneralizedTime / 0x18) */
5849 0 0         if (glen >= sizeof(res->revocationTime) + 2 &&
    0          
5850 0 0         p[0] == 0x18 && p[1] == sizeof(res->revocationTime))
5851             {
5852 0           memcpy(res->revocationTime, p + 2,
5853             sizeof(res->revocationTime));
5854             /* revocationReason [0] EXPLICIT CRLReason OPTIONAL
5855             CRLReason ::= ENUMERATED [RFC 5280] */
5856 0 0         if (glen >= sizeof(res->revocationTime) + 0x5 &&
    0          
5857 0 0         p[17] == 0xa0 && /* [0] */
5858 0 0         p[18] == 0x03 && /* length */
5859 0 0         p[19] == 0x0a && /* ENUMERATED */
5860 0 0         p[20] == 0x01 && /* length */
5861 0 0         p[21] <= 10 && /* CRL reason code 0-10, excluding 7. */
5862 0           p[21] != 7)
5863             {
5864 0           res->revocationReason = p[21];
5865             }
5866             }
5867 0           }
5868              
5869 0           static int32_t parseSingleResponse(uint32_t len, const unsigned char **cp,
5870             const unsigned char *end, psOcspSingleResponse_t *res)
5871             {
5872             const unsigned char *p;
5873             psSize_t glen, plen;
5874             int32_t oi;
5875              
5876 0           p = *cp;
5877              
5878             /* SingleResponse ::= SEQUENCE {
5879             certID CertID,
5880             certStatus CertStatus,
5881             thisUpdate GeneralizedTime,
5882             nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL,
5883             singleExtensions [1] EXPLICIT Extensions OPTIONAL }
5884             */
5885 0 0         if (getAsnSequence(&p, (int32) (end - p), &glen) < 0)
5886             {
5887             psTraceCrypto("Initial parseSingleResponse parse failure\n");
5888 0           return PS_PARSE_FAIL;
5889             }
5890             /* CertID ::= SEQUENCE {
5891             hashAlgorithm AlgorithmIdentifier
5892             {DIGEST-ALGORITHM, {...}},
5893             issuerNameHash OCTET STRING, -- Hash of issuer's DN
5894             issuerKeyHash OCTET STRING, -- Hash of issuer's public key
5895             serialNumber CertificateSerialNumber }
5896             */
5897 0 0         if (getAsnSequence(&p, (int32) (end - p), &glen) < 0)
5898             {
5899             psTraceCrypto("Initial parseSingleResponse parse failure\n");
5900 0           return PS_PARSE_FAIL;
5901             }
5902 0 0         if (getAsnAlgorithmIdentifier(&p, (int32) (end - p), &oi, &plen) < 0)
5903             {
5904 0           return PS_FAILURE;
5905             }
5906 0 0         psAssert(plen == 0);
5907 0           res->certIdHashAlg = oi;
5908              
5909 0           if ((*p++ != ASN_OCTET_STRING) ||
5910 0 0         getAsnLength(&p, (int32) (end - p), &glen) < 0 ||
5911 0           (uint32) (end - p) < glen)
5912             {
5913 0           return PS_PARSE_FAIL;
5914             }
5915 0           res->certIdNameHash = p;
5916 0           p += glen;
5917              
5918 0           if ((*p++ != ASN_OCTET_STRING) ||
5919 0 0         getAsnLength(&p, (int32) (end - p), &glen) < 0 ||
5920 0           (uint32) (end - p) < glen)
5921             {
5922 0           return PS_PARSE_FAIL;
5923             }
5924 0           res->certIdKeyHash = p;
5925 0           p += glen;
5926              
5927             /* serialNumber CertificateSerialNumber
5928              
5929             CertificateSerialNumber ::= INTEGER
5930             */
5931 0 0         if ((*p != (ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2)) &&
    0          
5932 0           (*p != ASN_INTEGER))
5933             {
5934             psTraceCrypto("X.509 getSerialNum failed on first bytes\n");
5935 0           return PS_PARSE_FAIL;
5936             }
5937 0           p++;
5938              
5939 0 0         if (getAsnLength(&p, (int32) (end - p), &glen) < 0 ||
    0          
5940 0           (uint32) (end - p) < glen)
5941             {
5942             psTraceCrypto("ASN getSerialNum failed\n");
5943 0           return PS_PARSE_FAIL;
5944             }
5945 0           res->certIdSerialLen = glen;
5946 0           res->certIdSerial = p;
5947 0           p += glen;
5948              
5949             /* CertStatus ::= CHOICE {
5950             good [0] IMPLICIT NULL,
5951             revoked [1] IMPLICIT RevokedInfo,
5952             unknown [2] IMPLICIT UnknownInfo }
5953             */
5954 0           memset(res->revocationTime, 0, sizeof(res->revocationTime));
5955 0           res->revocationReason = 0;
5956 0 0         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 0))
5957             {
5958 0           res->certStatus = 0;
5959 0           p += 2;
5960             }
5961 0 0         else if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
5962             {
5963 0           res->certStatus = 1;
5964             psTraceCrypto("OCSP CertStatus is revoked.\n");
5965             /* RevokedInfo ::= SEQUENCE {
5966             revocationTime GeneralizedTime,
5967             revocationReason [0] EXPLICIT CRLReason OPTIONAL }
5968             */
5969 0           p += 1;
5970 0 0         if (getAsnLength(&p, (int32) (end - p), &glen) < 0)
5971             {
5972             psTraceCrypto("Initial parseSingleResponse parse failure\n");
5973 0           return PS_PARSE_FAIL;
5974             }
5975             /* subfunction for parsing RevokedInfo. */
5976 0           parseSingleResponseRevocationTimeAndReason(p, glen, res);
5977 0           p += glen;
5978             }
5979 0 0         else if (*p == (ASN_CONTEXT_SPECIFIC | ASN_PRIMITIVE | 2))
5980             {
5981 0           res->certStatus = 2;
5982 0           p += 2; /* TOOD: Untested parse. Might be CONSTRUCTED encoding */
5983             /* UnknownInfo ::= NULL */
5984             }
5985             else
5986             {
5987             psTraceCrypto("OCSP CertStatus parse fail\n");
5988 0           return PS_PARSE_FAIL;
5989             }
5990              
5991             /* thisUpdate GeneralizedTime, */
5992 0 0         if ((end - p) < 1 || (*p != ASN_GENERALIZEDTIME))
    0          
5993             {
5994             psTraceCrypto("Malformed thisUpdate OCSP\n");
5995 0           return PS_PARSE_FAIL;
5996             }
5997 0           p++;
5998 0 0         if (getAsnLength(&p, (uint32) (end - p), &glen) < 0 ||
    0          
5999 0           (uint32) (end - p) < glen)
6000             {
6001 0           return PS_PARSE_FAIL;
6002             }
6003 0           res->thisUpdateLen = glen;
6004 0           res->thisUpdate = p;
6005 0           p += glen;
6006              
6007             /* nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL, */
6008 0           res->nextUpdate = NULL;
6009 0           res->nextUpdateLen = 0;
6010 0 0         if ((uint32) (end - p) >= 2 &&
    0          
6011 0           *p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
6012             {
6013 0           p++;
6014 0 0         if (getAsnLength(&p, (uint32) (end - p), &glen) < 0 ||
    0          
6015 0           (uint32) (end - p) < glen)
6016             {
6017 0           return PS_PARSE_FAIL;
6018             }
6019 0 0         if (*p == ASN_GENERALIZEDTIME && glen > 2)
    0          
6020             {
6021 0           res->nextUpdate = p + 2;
6022 0           res->nextUpdateLen = glen - 2;
6023             }
6024 0           p += glen;
6025             }
6026              
6027             /* singleExtensions [1] EXPLICIT Extensions OPTIONAL */
6028 0 0         if ((uint32) (end - p) >= 2 &&
    0          
6029 0           *p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
6030             {
6031 0           p++;
6032 0 0         if (getAsnLength(&p, (uint32) (end - p), &glen) < 0 ||
    0          
6033 0           (uint32) (end - p) < glen)
6034             {
6035 0           return PS_PARSE_FAIL;
6036             }
6037             /* TODO */
6038 0           p += glen; /* SKIPPING */
6039             }
6040              
6041 0           *cp = (unsigned char *) p;
6042 0           return PS_SUCCESS;
6043             }
6044              
6045 0           static int32_t ocspParseBasicResponse(psPool_t *pool, uint32_t len,
6046             const unsigned char **cp, unsigned char *end,
6047             psOcspResponse_t *res)
6048             {
6049             const unsigned char *p, *seqend, *startRes, *endRes;
6050             psOcspSingleResponse_t *singleResponse;
6051             psSha1_t sha;
6052              
6053             # ifdef USE_SHA256
6054             psSha256_t sha2;
6055             # endif
6056             # ifdef USE_SHA384
6057             psSha384_t sha3;
6058             # endif
6059             # ifdef USE_SHA512
6060             psSha512_t sha512;
6061             # endif
6062             psSize_t glen, plen;
6063             uint32_t blen;
6064             int32_t version, oid;
6065             int32_t cert_res;
6066              
6067             /* id-pkix-ocsp-basic
6068              
6069             BasicOCSPResponse ::= SEQUENCE {
6070             tbsResponseData ResponseData,
6071             signatureAlgorithm AlgorithmIdentifier,
6072             signature BIT STRING,
6073             certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
6074             */
6075 0           p = *cp;
6076              
6077 0 0         if (getAsnSequence(&p, (uint32) (end - p), &glen) < 0)
6078             {
6079             psTraceCrypto("Initial parse error in ocspParseBasicResponse\n");
6080 0           return PS_PARSE_FAIL;
6081             }
6082             /*
6083             ResponseData ::= SEQUENCE {
6084             version [0] EXPLICIT Version DEFAULT v1,
6085             responderID ResponderID,
6086             producedAt GeneralizedTime,
6087             responses SEQUENCE OF SingleResponse,
6088             responseExtensions [1] EXPLICIT Extensions OPTIONAL }
6089             */
6090 0           startRes = p; /* A response signature will be over ResponseData */
6091 0 0         if (getAsnSequence(&p, (uint32) (end - p), &glen) < 0)
6092             {
6093             psTraceCrypto("Early ResponseData parse error in psOcspParseResponse\n");
6094 0           return PS_PARSE_FAIL;
6095             }
6096 0 0         if (getExplicitVersion(&p, (uint32) (end - p), 0, &version) < 0)
6097             {
6098             psTraceCrypto("Version parse error in ResponseData\n");
6099 0           return PS_PARSE_FAIL;
6100             }
6101 0           res->version = version;
6102 0 0         if (version != 0)
6103             {
6104             psTraceIntCrypto("WARNING: Unknown OCSP ResponseData version %d\n",
6105             version);
6106 0           return PS_VERSION_UNSUPPORTED;
6107             }
6108             /*
6109             ResponderID ::= CHOICE {
6110             byName [1] Name,
6111             byKey [2] KeyHash }
6112             */
6113              
6114 0 0         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
6115             {
6116             const unsigned char *p2;
6117 0           p++;
6118 0 0         if (getAsnLength32(&p, (uint32_t) (end - p), &blen, 0) < 0 ||
    0          
6119 0 0         (uint32_t) (end - p) < blen || blen == 0)
6120             {
6121             psTraceCrypto("Error parsing Name in ResponseData\n");
6122 0           return PS_PARSE_FAIL;
6123             }
6124 0           res->responderName = p;
6125 0           res->responderKeyHash = NULL;
6126 0           p2 = p;
6127 0           p += blen;
6128             /* Check contents of ASN Sequence containing Name. */
6129 0           if ((*p2++ != (ASN_CONSTRUCTED | ASN_SEQUENCE)) ||
6130 0 0         getAsnLength32(&p2, (int32) (end - p2), &blen, 0) < 0 ||
6131 0           p != p2 + blen)
6132             {
6133             psTraceCrypto("Error parsing Name in ResponseData\n");
6134 0           res->responderName = NULL;
6135 0           return PS_PARSE_FAIL;
6136             }
6137             }
6138 0 0         else if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2))
6139             {
6140 0           p++;
6141 0 0         if (getAsnLength32(&p, (uint32_t) (end - p), &blen, 0) < 0 ||
    0          
6142 0           (uint32_t) (end - p) < blen)
6143             {
6144             psTraceCrypto("Error parsing KeyHash in ResponseData\n");
6145 0           return PS_PARSE_FAIL;
6146             }
6147             /* KeyHash ::= OCTET STRING -- SHA-1 hash of responder's public key
6148             -- (i.e., the SHA-1 hash of the value of the
6149             -- BIT STRING subjectPublicKey [excluding
6150             -- the tag, length, and number of unused
6151             -- bits] in the responder's certificate) */
6152 0           if ((*p++ != ASN_OCTET_STRING) ||
6153 0 0         getAsnLength(&p, (int32) (end - p), &glen) < 0 ||
6154 0 0         (uint32) (end - p) < glen ||
6155 0           glen != SHA1_HASH_SIZE)
6156             {
6157              
6158             psTraceCrypto("Couldn't parse KeyHash in ResponseData\n");
6159 0           return PS_FAILURE;
6160             }
6161 0 0         psAssert(glen == SHA1_HASH_SIZE);
6162 0           res->responderName = NULL;
6163 0           res->responderKeyHash = p;
6164 0           p += SHA1_HASH_SIZE;
6165             }
6166             else
6167             {
6168             psTraceCrypto("ResponderID parse error in ResponseData\n");
6169 0           return PS_PARSE_FAIL;
6170             }
6171              
6172             /* producedAt GeneralizedTime, */
6173 0 0         if ((end - p) < 1 || (*p != ASN_GENERALIZEDTIME))
    0          
6174             {
6175             psTraceCrypto("Malformed thisUpdate CRL\n");
6176 0           return PS_PARSE_FAIL;
6177             }
6178 0           p++;
6179 0 0         if (getAsnLength(&p, (uint32) (end - p), &glen) < 0 ||
    0          
6180 0           (uint32) (end - p) < glen)
6181             {
6182             psTraceCrypto("Malformed producedAt in ResponseData\n");
6183 0           return PS_PARSE_FAIL;
6184             }
6185             /* Perform quick parsing on data. */
6186 0 0         if (psBrokenDownTimeImport(NULL, (const char *) p, glen, 0) < 0)
6187             {
6188 0           return PS_PARSE_FAIL;
6189             }
6190 0           res->timeProducedLen = glen;
6191 0           res->timeProduced = p;
6192 0           p += glen;
6193              
6194             /* responses SEQUENCE OF SingleResponse, */
6195 0 0         if (getAsnSequence(&p, (int32) (end - p), &glen) < 0)
6196             {
6197             psTraceCrypto("Initial SingleResponse parse failure\n");
6198 0           return PS_PARSE_FAIL;
6199             }
6200              
6201 0           seqend = p + glen;
6202              
6203 0           plen = 0; /* for MAX_OCSP_RESPONSES control */
6204 0 0         while (p < seqend)
6205             {
6206 0           singleResponse = &res->singleResponse[plen];
6207 0 0         if (parseSingleResponse(glen, &p, seqend, singleResponse) < 0)
6208             {
6209 0           return PS_PARSE_FAIL;
6210             }
6211 0           plen++;
6212 0 0         if (p < seqend)
6213             {
6214             /* Additional responses */
6215 0 0         if (plen == MAX_OCSP_RESPONSES)
6216             {
6217             psTraceCrypto("ERROR: Multiple OCSP SingleResponse items. ");
6218             psTraceCrypto("Increase MAX_OCSP_RESPONSES to support\n");
6219 0           return PS_PARSE_FAIL;
6220             }
6221             }
6222             }
6223             /* responseExtensions [1] EXPLICIT Extensions OPTIONAL } */
6224 0 0         if (*p == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
6225             {
6226 0 0         if (parse_nonce_ext(p, end - p, &res->nonce) != PS_SUCCESS)
6227             {
6228 0           return PS_PARSE_FAIL;
6229             }
6230 0           p++;
6231 0 0         if (getAsnLength(&p, (uint32) (end - p), &glen) < 0 ||
    0          
6232 0           (uint32) (end - p) < glen)
6233             {
6234 0           return PS_PARSE_FAIL;
6235             }
6236             /* TODO: */
6237 0           p += glen; /* SKIPPING */
6238             }
6239 0           endRes = p;
6240              
6241             /* ResponseData DONE. On to signature:
6242              
6243             signatureAlgorithm AlgorithmIdentifier
6244             signature BIT STRING,
6245              
6246             The value for signature SHALL be computed on the hash of the DER
6247             encoding of ResponseData. The responder MAY include certificates in
6248             the certs field of BasicOCSPResponse that help the OCSP client
6249             verify the responder's signature. If no certificates are included,
6250             then certs SHOULD be absent. */
6251 0 0         if (getAsnAlgorithmIdentifier(&p, (uint32) (end - p), &oid, &plen) < 0)
6252             {
6253             psTraceCrypto("Initial SingleResponse parse failure\n");
6254 0           return PS_PARSE_FAIL;
6255             }
6256 0 0         if (plen > 0)
6257             {
6258             psTraceCrypto("Algorithm parameters on ResponseData sigAlg\n");
6259 0           p += plen;
6260             }
6261 0           res->sigAlg = oid;
6262              
6263 0           switch (oid)
6264             {
6265             /* OSCP requires SHA1 so no wrapper here */
6266             case OID_SHA1_RSA_SIG:
6267             case OID_SHA1_RSA_SIG2:
6268             # ifdef USE_ECC
6269             case OID_SHA1_ECDSA_SIG:
6270             # endif
6271 0           res->hashLen = SHA1_HASH_SIZE;
6272 0           psSha1PreInit(&sha);
6273 0           psSha1Init(&sha);
6274 0           psSha1Update(&sha, startRes, (int32) (endRes - startRes));
6275 0           psSha1Final(&sha, res->hashResult);
6276 0           break;
6277             # ifdef USE_SHA224
6278             case OID_SHA224_RSA_SIG:
6279             # ifdef USE_ECC
6280             case OID_SHA224_ECDSA_SIG:
6281             # endif
6282             res->hashLen = SHA224_HASH_SIZE;
6283             psSha224PreInit(&sha2);
6284             psSha224Init(&sha2);
6285             psSha224Update(&sha2, startRes, (int32) (endRes - startRes));
6286             psSha224Final(&sha2, res->hashResult);
6287             break;
6288             # endif
6289             # ifdef USE_SHA256
6290             case OID_SHA256_RSA_SIG:
6291             # ifdef USE_ECC
6292             case OID_SHA256_ECDSA_SIG:
6293             # endif
6294 0           res->hashLen = SHA256_HASH_SIZE;
6295 0           psSha256PreInit(&sha2);
6296 0           psSha256Init(&sha2);
6297 0           psSha256Update(&sha2, startRes, (int32) (endRes - startRes));
6298 0           psSha256Final(&sha2, res->hashResult);
6299 0           break;
6300             # endif
6301             # ifdef USE_SHA384
6302             case OID_SHA384_RSA_SIG:
6303             # ifdef USE_ECC
6304             case OID_SHA384_ECDSA_SIG:
6305             # endif
6306 0           res->hashLen = SHA384_HASH_SIZE;
6307 0           psSha384PreInit(&sha3);
6308 0           psSha384Init(&sha3);
6309 0           psSha384Update(&sha3, startRes, (int32) (endRes - startRes));
6310 0           psSha384Final(&sha3, res->hashResult);
6311 0           break;
6312             # endif
6313             # ifdef USE_SHA512
6314             case OID_SHA512_RSA_SIG:
6315             # ifdef USE_ECC
6316             case OID_SHA512_ECDSA_SIG:
6317             # endif
6318 0           res->hashLen = SHA512_HASH_SIZE;
6319 0           psSha512PreInit(&sha512);
6320 0           psSha512Init(&sha512);
6321 0           psSha512Update(&sha512, startRes, (int32) (endRes - startRes));
6322 0           psSha512Final(&sha512, res->hashResult);
6323 0           break;
6324             # endif
6325             default:
6326             psTraceCrypto("No support for sigAlg in OCSP ResponseData\n");
6327 0           return PS_UNSUPPORTED_FAIL;
6328             }
6329              
6330 0 0         if (*p++ != ASN_BIT_STRING)
6331             {
6332             psTraceCrypto("Error parsing signature in ResponseData\n");
6333 0           return PS_PARSE_FAIL;
6334             }
6335 0 0         if (getAsnLength(&p, (int32) (end - p), &glen) < 0 ||
    0          
6336 0           (uint32) (end - p) < glen)
6337             {
6338             psTraceCrypto("Error parsing signature in ResponseData\n");
6339 0           return PS_PARSE_FAIL;
6340             }
6341 0 0         if (*p++ != 0)
6342             {
6343             psTraceCrypto("Error parsing ignore bits in ResponseData sig\n");
6344 0           return PS_PARSE_FAIL;
6345             }
6346 0           glen--; /* ignore bits above */
6347 0           res->sig = p;
6348 0           res->sigLen = glen;
6349 0           p += glen;
6350              
6351             /* certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } */
6352 0 0         if (end != p)
6353             {
6354             /* The responder MAY include certificates in the certs field of
6355             BasicOCSPResponse that help the OCSP client verify the responder's
6356             signature. */
6357 0 0         if (*p != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
6358             {
6359             psTraceCrypto("Unexpected Certificage encoding in OCSPResponse\n");
6360 0           return PS_PARSE_FAIL;
6361             }
6362 0           p++;
6363 0 0         if (getAsnLength(&p, (uint32) (end - p), &glen) < 0 ||
    0          
6364 0           (uint32) (end - p) < glen)
6365             {
6366 0           return PS_PARSE_FAIL;
6367             }
6368             /* If here, this is the cert that issued the OCSPResponse. Will
6369             authenticate during psOcspResponseValidateOld */
6370 0 0         if (getAsnSequence(&p, (uint32) (end - p), &glen) < 0)
6371             {
6372             psTraceCrypto("\n");
6373 0           return PS_PARSE_FAIL;
6374             }
6375 0 0         psAssert(glen == (end - p));
6376             /* will handle multiple certs if needed.
6377             Store certificate for reference. */
6378 0           cert_res = psX509ParseCert(pool, p, glen, &res->OCSPResponseCert,
6379             CERT_STORE_UNPARSED_BUFFER);
6380 0 0         if (cert_res < 0)
6381             {
6382 0           psX509FreeCert(res->OCSPResponseCert);
6383 0           return PS_PARSE_FAIL;
6384             }
6385 0           p += cert_res;
6386             }
6387 0 0         psAssert(p == end);
6388              
6389 0           *cp = (unsigned char *) p;
6390 0           return PS_SUCCESS;
6391             }
6392              
6393 0           int32_t psOcspResponseGetStatus(int32_t rc)
6394             {
6395             /* Check if response code is within
6396             PS_OCSP_MALFORMED_REQUEST ... PS_OCSP_UNAUTHORIZED range. */
6397 0 0         if (rc >= PS_OCSP_MALFORMED_REQUEST && rc <= PS_OCSP_UNAUTHORIZED)
    0          
6398             {
6399 0           rc -= PS_OCSP_MALFORMED_REQUEST - 1;
6400             /* Return code 4 is not used. */
6401 0 0         if (rc != 4)
6402             {
6403 0           return rc;
6404             }
6405             }
6406              
6407 0 0         return rc == PS_SUCCESS ? 0 /* successful */ : PS_FAILURE /* other error */;
6408             }
6409              
6410 0           int32_t psOcspParseResponse(psPool_t *pool, int32_t len, unsigned char **cp,
6411             unsigned char *end, psOcspResponse_t *response)
6412             {
6413             const unsigned char *p;
6414             int32_t err;
6415             int32_t status, oi;
6416             psSize_t glen;
6417             uint32_t blen;
6418              
6419 0           p = *cp;
6420             /* psTraceBytes("OCSPResponse", p, len); */
6421             /*
6422             OCSPResponse ::= SEQUENCE {
6423             responseStatus OCSPResponseStatus,
6424             responseBytes [0] EXPLICIT ResponseBytes OPTIONAL }
6425             */
6426 0 0         if (getAsnSequence(&p, (uint32) (end - p), &glen) < 0)
6427             {
6428             psTraceCrypto("Initial parse error in psOcspParseResponse\n");
6429 0           return PS_PARSE_FAIL;
6430             }
6431 0 0         if (getAsnEnumerated(&p, (uint32) (end - p), &status) < 0)
6432             {
6433             psTraceCrypto("Enum parse error in psOcspParseResponse\n");
6434 0           return PS_PARSE_FAIL;
6435             }
6436             /*
6437             OCSPResponseStatus ::= ENUMERATED {
6438             successful (0), -- Response has valid confirmations
6439             malformedRequest (1), -- Illegal confirmation request
6440             internalError (2), -- Internal error in issuer
6441             tryLater (3), -- Try again later
6442             -- (4) is not used
6443             sigRequired (5), -- Must sign the request
6444             unauthorized (6) -- Request unauthorized
6445             }
6446             */
6447 0 0         if (status != 0)
6448             {
6449             /* Something other than success. List right above here */
6450             psTraceCrypto("OCSPResponse contains no valid confirmations\n");
6451 0 0         if (status <= 6 && status != 4)
    0          
6452             {
6453             /* Map status codes to return codes. */
6454 0           return status + (PS_OCSP_MALFORMED_REQUEST - 1);
6455             }
6456             /* Status code is outside valid range. */
6457 0           return PS_PARSE_FAIL;
6458             }
6459              
6460             /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL, */
6461 0 0         if (*p == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
6462             {
6463 0           p++;
6464 0 0         if (getAsnLength32(&p, (uint32_t) (end - p), &blen, 0) < 0 ||
    0          
6465 0           (uint32_t) (end - p) < blen)
6466             {
6467             psTraceCrypto("Error parsing UserKeyingMaterial\n");
6468 0           return PS_PARSE_FAIL;
6469             }
6470              
6471             /* ResponseBytes ::= SEQUENCE {
6472             responseType OBJECT IDENTIFIER,
6473             response OCTET STRING }
6474             */
6475 0 0         if (getAsnSequence(&p, (uint32) (end - p), &glen) < 0)
6476             {
6477             psTraceCrypto("ResponseBytes parse error in psOcspParseResponse\n");
6478 0           return PS_PARSE_FAIL;
6479             }
6480 0           response->responseType = p;
6481 0 0         if (getAsnOID(&p, (uint32) (end - p), &oi, 1, &glen) < 0)
6482             {
6483 0           response->responseType = NULL;
6484             psTraceCrypto("responseType parse error in psOcspParseResponse\n");
6485 0           return PS_PARSE_FAIL;
6486             }
6487 0           if ((*p++ != ASN_OCTET_STRING) ||
6488 0 0         getAsnLength32(&p, (int32) (end - p), &blen, 0) < 0 ||
6489 0           (uint32) (end - p) < blen)
6490             {
6491              
6492             psTraceCrypto("Couldn't parse response in psOcspParseResponse\n");
6493 0           return PS_PARSE_FAIL;
6494             }
6495 0 0         if (oi == OID_BASIC_OCSP_RESPONSE)
6496             {
6497             /* id-pkix-ocsp-basic
6498              
6499             BasicOCSPResponse ::= SEQUENCE {
6500             tbsResponseData ResponseData,
6501             signatureAlgorithm AlgorithmIdentifier,
6502             signature BIT STRING,
6503             certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
6504             */
6505             /* Clear response except keep response type.
6506             Response type only remains valid as long as parsed response
6507             is valid. */
6508 0           const unsigned char *responseType = response->responseType;
6509 0           memset(response, 0, sizeof(*response));
6510 0           response->responseType = responseType;
6511 0           err = ocspParseBasicResponse(pool, blen, &p, end, response);
6512 0 0         if (err < 0)
6513             {
6514             psTraceCrypto("ocspParseBasicResponse failure\n");
6515 0           return err;
6516             }
6517             }
6518             else
6519             {
6520             psTraceCrypto("unsupported responseType in psOcspParseResponse\n");
6521 0           return PS_MESSAGE_UNSUPPORTED;
6522             }
6523             }
6524 0 0         psAssert(end == p);
6525 0           *cp = (unsigned char *) p;
6526 0           return PS_SUCCESS;
6527             }
6528              
6529             /* Check validity of OCSP response and obtain the date stamps from it.
6530              
6531             If time_now is not provided, the current time will be requested from
6532             the oeprating system.
6533             This function extracts data information from parsed OCSP response.
6534             Because the dates in psOcspResponse_t are references to memory containing
6535             binary OCSP response, that memory must not have been released before calling
6536             this function. time_linger is useful to deal with the fact that the
6537             peer and this host may have tiny difference in their clocks.
6538              
6539             @param response Pointer to OCSP response structure (from psOcspParseResponse)
6540             @param index The index of OCSP single response to handle (0 for the first).
6541             @param timeNow A pointer to structure filled in with psGetBrokenDownGMTime(),
6542             or gmtime(), structure initialized to all zero or NULL.
6543             @param producedAt If non-NULL Will be filled in with time the structure
6544             was produced.
6545             @param thisUpdate If non-NULL Will be filled in with time the OCSP
6546             information was updated (usually the same as producedAt).
6547             @param nextUpdate If non-NULL Will be filled in with time the OCSP
6548             information needs to be updated.
6549             @param time_linger Amout of flexibility in comparison of times.
6550             Recommended value: PS_OCSP_TIME_LINGER (120)
6551             @retval PS_SUCCESS If the dates were extracted from response and the
6552             response in comparison with timeNow is valid.
6553             @retval PS_TIMEOUT_FAIL The datas were extracted from response, but
6554             the response has timed out. (Or the response is too far in future.)
6555             @retval PS_PARSE_FAIL If error occurred parsing the data information in
6556             the request.
6557             */
6558 0           int32_t psOcspResponseCheckDates(psOcspResponse_t *response,
6559             int index,
6560             psBrokenDownTime_t *timeNow,
6561             psBrokenDownTime_t *producedAt,
6562             psBrokenDownTime_t *thisUpdate,
6563             psBrokenDownTime_t *nextUpdate,
6564             int time_linger)
6565             {
6566             psBrokenDownTime_t tmp, tmp2, tmp3, tmp4;
6567 0           unsigned char ok = 1;
6568             int32 err;
6569             psOcspSingleResponse_t *subjectResponse;
6570             psBrokenDownTime_t timeNowLinger;
6571              
6572 0 0         if (index >= MAX_OCSP_RESPONSES)
6573             {
6574 0           return PS_ARG_FAIL;
6575             }
6576              
6577 0 0         if (timeNow == NULL)
6578             {
6579 0           memset(&tmp, 0, sizeof tmp);
6580 0           timeNow = &tmp;
6581             }
6582              
6583 0 0         if (timeNow->tm_year == 0)
6584             {
6585             /* The structure appears not filled in, use psGetBrokenDownGMTime() to
6586             get the current time. */
6587 0           err = psGetBrokenDownGMTime(timeNow, 0);
6588 0 0         if (err != PS_SUCCESS)
6589             {
6590 0           return PS_FAIL;
6591             }
6592             }
6593 0           memcpy(&timeNowLinger, timeNow, sizeof timeNowLinger);
6594 0           err = psBrokenDownTimeAdd(&timeNowLinger, time_linger);
6595 0 0         if (err != PS_SUCCESS)
6596             {
6597 0           return PS_FAIL;
6598             }
6599              
6600 0 0         if (thisUpdate == NULL)
6601             {
6602 0           thisUpdate = &tmp2;
6603             }
6604              
6605 0 0         if (nextUpdate == NULL)
6606             {
6607 0           nextUpdate = &tmp3;
6608             }
6609              
6610 0 0         if (producedAt == NULL)
6611             {
6612 0           producedAt = &tmp4;
6613             }
6614              
6615 0           ok &= psBrokenDownTimeImport(producedAt,
6616 0           (const char *) response->timeProduced,
6617 0           response->timeProducedLen,
6618 0           0) == PS_SUCCESS;
6619              
6620 0           subjectResponse = &response->singleResponse[index];
6621              
6622 0 0         if (subjectResponse->thisUpdate)
6623             {
6624 0           ok &= psBrokenDownTimeImport(thisUpdate,
6625 0           (const char *) subjectResponse->thisUpdate,
6626 0           subjectResponse->thisUpdateLen,
6627 0           0) == PS_SUCCESS;
6628             }
6629             else
6630             {
6631 0           ok = 0;
6632             }
6633              
6634 0 0         if (subjectResponse->nextUpdate != NULL)
6635             {
6636             /* Next update provided, OCSP is valid until that time. */
6637 0           ok &= psBrokenDownTimeImport(nextUpdate,
6638 0           (const char *) subjectResponse->nextUpdate,
6639 0           subjectResponse->nextUpdateLen,
6640 0           0) == PS_SUCCESS;
6641             }
6642 0 0         else if (ok)
6643             {
6644             /* If there is no next update, the server supports
6645             continous updates and nextUpdate time is considered
6646             identical to the this update time. */
6647 0           ok &= psBrokenDownTimeImport(nextUpdate,
6648 0           (const char *) subjectResponse->thisUpdate,
6649 0           subjectResponse->thisUpdateLen,
6650 0           0) == PS_SUCCESS;
6651             }
6652              
6653 0 0         if (ok == 1)
6654             {
6655             /* Consider linger when comparing nextUpdateTime. */
6656             psBrokenDownTime_t nextUpdateTimeLinger;
6657 0           memcpy(&nextUpdateTimeLinger, nextUpdate, sizeof nextUpdateTimeLinger);
6658 0           err = psBrokenDownTimeAdd(&nextUpdateTimeLinger, time_linger);
6659 0 0         if (err != PS_SUCCESS)
6660             {
6661 0           return err;
6662             }
6663              
6664             /* Now check that current time considering linger is between
6665             thisUpdate and nextUpdate. */
6666              
6667 0 0         if (psBrokenDownTimeCmp(thisUpdate, &timeNowLinger) > 0)
6668             {
6669             /* thisUpdate is in future even considering linger => reject. */
6670 0           err = PS_TIMEOUT_FAIL;
6671             }
6672 0 0         else if (psBrokenDownTimeCmp(&nextUpdateTimeLinger, timeNow) < 0)
6673             {
6674             /* nextUpdate is in past even considering linger => reject. */
6675 0           err = PS_TIMEOUT_FAIL;
6676             }
6677             else
6678             {
6679             /* err has already been set to PS_SUCCESS */
6680             }
6681             }
6682             else
6683             {
6684 0           err = PS_PARSE_FAIL;
6685             }
6686 0           return err;
6687             }
6688              
6689              
6690             /* Diff the current time against the OCSP timestamp and confirm it's not
6691             longer than the user is willing to trust. */
6692 0           static int32_t checkOCSPtimestamp(psOcspResponse_t *response, int index)
6693             {
6694 0           return psOcspResponseCheckDates(response, index, NULL, NULL, NULL, NULL,
6695             PS_OCSP_TIME_LINGER);
6696             }
6697              
6698             /* Partial OCSP request parser: just locate nonceExtension if present. */
6699 0           static int32_t parseOcspReq(const void *data, size_t datalen,
6700             psBuf_t *nonceExtension)
6701             {
6702             psParseBuf_t pb;
6703             psParseBuf_t ocspRequest;
6704             psParseBuf_t tbsRequest;
6705             psParseBuf_t extensions;
6706             psParseBuf_t extension;
6707             psParseBuf_t requestList;
6708             psParseBuf_t request;
6709             psParseBuf_t requestCert;
6710             psParseBuf_t requestCertContent;
6711             int rc;
6712              
6713 0           rc = psParseBufFromStaticData(&pb, data, datalen);
6714 0 0         if (rc != PS_SUCCESS)
6715             {
6716 0           return rc;
6717             }
6718 0           psParseBufReadSequenceSub(&pb, &ocspRequest);
6719             /* Ensure subbuffer is advanced and main buffer is not. */
6720 0           psParseBufReadSequenceSub(&ocspRequest, &tbsRequest);
6721             /* Ignore version number (v1 == 0) if present. */
6722 0           psParseBufTrySkipBytes(&tbsRequest, (const unsigned char *)
6723             "\xA0\x03\x02\x01\x00", 5);
6724             /* Skip requestorName if present. */
6725 0           psParseBufTrySkipTag(&tbsRequest, 0xA1);
6726             /* Skip requestList (must be present with at least one request). */
6727 0           psParseBufReadSequenceSub(&tbsRequest, &requestList);
6728 0           psParseBufReadSequenceSub(&requestList, &request);
6729 0           psParseBufReadSequenceSub(&request, &requestCert);
6730 0           psParseBufReadSequenceSub(&requestCert, &requestCertContent);
6731 0           psParseBufFinish(&requestCertContent);
6732 0           psParseBufFinish(&requestCert);
6733 0           psParseBufFinish(&request);
6734 0           psParseBufFinish(&requestList);
6735 0 0         if (psParseBufTryReadTagSub(&tbsRequest, &extensions, 0xA2))
6736             {
6737 0 0         while (psParseBufTryReadSequenceSub(&extensions, &extension))
6738             {
6739             psParseBuf_t sub;
6740 0           psParseBufReadSequenceSub(&extension, &sub);
6741 0 0         if (psParseBufTrySkipBytes(
6742             &sub,
6743             (const unsigned char *)
6744             "\x06\x09\x2b\x06\x01\x05"
6745             "\x05\x07\x30\x01\x02", 11))
6746             {
6747 0           psParseBufReadTagRef(
6748             &sub, nonceExtension, 0x04);
6749             }
6750 0           psParseBufFinish(&sub);
6751 0 0         if (psParseBufFinish(&extension) != PS_SUCCESS)
6752             {
6753 0           break;
6754             }
6755             }
6756 0           psParseBufFinish(&extensions);
6757             }
6758 0           psParseBufFinish(&tbsRequest);
6759 0           return psParseBufFinish(&ocspRequest);
6760             }
6761              
6762             #define RESPONDER_NAME_MAX_LENGTH 1024
6763              
6764 0           static int32_t ocspMatchResponderCert(const psOcspResponse_t *response,
6765             const psX509Cert_t *curr)
6766             {
6767 0 0         if (response->responderKeyHash != NULL)
6768             {
6769             /* Match certificate using key hash. */
6770 0 0         if (memcmpct(response->responderKeyHash, curr->sha1KeyHash, 20) == 0)
6771             {
6772 0           return PS_SUCCESS;
6773             }
6774             }
6775 0 0         else if (response->responderName != NULL)
6776             {
6777             uint32_t len;
6778             /* Obtain the length of name tag including header.
6779             Note: responderName has already been validated during parsing,
6780             so getAsnTagLenUnsafe is ok.
6781             */
6782 0           len = getAsnTagLenUnsafe(response->responderName);
6783              
6784 0 0         if (len < 2 || len > RESPONDER_NAME_MAX_LENGTH)
    0          
6785             {
6786 0           return PS_FAILURE;
6787             }
6788              
6789             /* Match certificate using subject name. */
6790 0 0         if (curr->unparsedBin == NULL ||
    0          
6791 0           curr->binLen < curr->subjectKeyDerOffsetIntoUnparsedBin + len)
6792             {
6793 0           return PS_FAILURE;
6794             }
6795              
6796 0 0         if (memcmpct(curr->unparsedBin +
6797 0           curr->subjectKeyDerOffsetIntoUnparsedBin,
6798 0           response->responderName, len) == 0)
6799             {
6800 0           return PS_SUCCESS;
6801             }
6802             }
6803 0           return PS_FAILURE;
6804             }
6805              
6806 0           int32_t psOcspResponseValidate(psPool_t *pool, psX509Cert_t *trustedOCSP,
6807             psX509Cert_t *srvCerts, psOcspResponse_t *response,
6808             psValidateOCSPResponseOptions_t *vOpts
6809             )
6810             {
6811             static psValidateOCSPResponseOptions_t vOptsDefault;
6812             psX509Cert_t *curr, *issuer, *subject, *ocspResIssuer;
6813             psOcspSingleResponse_t *subjectResponse;
6814             unsigned char sigOut[MAX_HASH_SIZE];
6815             int32 sigOutLen, sigType, index;
6816 0           psPool_t *pkiPool = NULL;
6817              
6818 0           psBool_t knownFlag = PS_FALSE;
6819 0           psBool_t revocationFlag = PS_FALSE;
6820 0           psBuf_t nonceExtReq = { NULL };
6821              
6822             /* use default validation options if not specified. */
6823 0 0         if (vOpts == NULL)
6824             {
6825 0           vOpts = &vOptsDefault;
6826             }
6827              
6828             /* Find interesting options from request. */
6829 0 0         if (vOpts->request)
6830             {
6831 0           int rc = parseOcspReq(vOpts->request, vOpts->requestLen,
6832             &nonceExtReq);
6833 0 0         if (rc != PS_SUCCESS)
6834             {
6835 0           return PS_ARG_FAIL;
6836             }
6837             }
6838              
6839             /* Find the OCSP cert that signed the response. First place to look is
6840             within the OCSPResponse itself */
6841 0           issuer = NULL;
6842 0 0         if (response->OCSPResponseCert)
6843             {
6844             /* If there is a cert here it is something that has to be authenticated.
6845             We will either leave this case with a successful auth or failure */
6846 0           curr = response->OCSPResponseCert;
6847 0 0         while (curr != NULL)
6848             {
6849             /* The outer responderKeyHash should be matching one of the certs
6850             that was attached to the OCSPResonse itself */
6851 0 0         if (ocspMatchResponderCert(response, curr) == PS_SUCCESS)
6852             {
6853             /* Found it... but now we have to authenticate it against
6854             our known list of CAs. issuer in the context of this
6855             function is the OCSPResponse issuer but here we are looking
6856             for the CA of THAT cert so it's 'subject' in this area */
6857 0           subject = curr;
6858 0           ocspResIssuer = trustedOCSP; /* preloaded sslKeys->CA */
6859 0 0         while (ocspResIssuer)
6860             {
6861 0 0         if (memcmp(ocspResIssuer->subject.hash,
6862 0           subject->issuer.hash, 20) == 0)
6863             {
6864              
6865 0 0         if (psX509AuthenticateCert(pool, subject, ocspResIssuer,
6866             &ocspResIssuer, NULL, NULL) == 0)
6867             {
6868             /* OK, we held the CA that issued the OCSPResponse
6869             so we'll now trust that cert that was provided
6870             in the OCSPResponse */
6871 0           ocspResIssuer = NULL;
6872 0           issuer = subject;
6873             }
6874             else
6875             {
6876             /* Auth failure */
6877             psTraceCrypto("Attached OCSP cert didn't auth\n");
6878 0           return PS_FAILURE;
6879             }
6880             }
6881             else
6882             {
6883 0           ocspResIssuer = ocspResIssuer->next;
6884             }
6885             }
6886 0           curr = NULL;
6887             }
6888             else
6889             {
6890 0           curr = curr->next;
6891             }
6892             }
6893 0 0         if (issuer == NULL)
6894             {
6895             psTraceCrypto("Found no CA to authenticate attached OCSP cert\n");
6896 0           return PS_FAILURE; /* no preloaded CA to auth cert in response */
6897             }
6898             }
6899              
6900             /* Issuer will be NULL if there was no certificate attached to the
6901             OCSP response. Now look to the user loaded CA files */
6902 0 0         if (issuer == NULL)
6903             {
6904 0           curr = trustedOCSP;
6905 0 0         while (curr != NULL)
6906             {
6907             /* Currently looking for the subjectKey extension to match the
6908             public key hash from the response */
6909 0 0         if (ocspMatchResponderCert(response, curr) == PS_SUCCESS)
6910             {
6911 0           issuer = curr;
6912 0           curr = NULL;
6913             }
6914             else
6915             {
6916 0           curr = curr->next;
6917             }
6918             }
6919             }
6920              
6921             /* It is possible a certificate embedded in the server certificate
6922             chain was itself the OCSP responder */
6923 0 0         if (issuer == NULL)
6924             {
6925             /* Don't look at the first cert in the chain because that is the
6926             one we are trying to find the OCSP responder public key for */
6927 0           curr = srvCerts->next;
6928 0 0         while (curr != NULL)
6929             {
6930             /* Currently looking for the subjectKey extension to match the
6931             public key hash from the response */
6932 0 0         if (ocspMatchResponderCert(response, curr) == PS_SUCCESS)
6933             {
6934 0           issuer = curr;
6935 0           curr = NULL;
6936             }
6937             else
6938             {
6939 0           curr = curr->next;
6940             }
6941             }
6942             }
6943              
6944 0 0         if (issuer == NULL)
6945             {
6946             psTraceCrypto("Unable to locate OCSP responder CA for validation\n");
6947 0           return PS_FAILURE;
6948             }
6949              
6950             /* Now check to see that the response is vouching for the subject cert
6951             that we are interested in. The subject will always be the first
6952             cert in the server CERTIFICATE chain */
6953 0           subject = srvCerts;
6954              
6955             /* Now look to match this cert within the singleResponse members.
6956              
6957             There are three components to a CertID that should be used to validate
6958             we are looking at the correct OCSP response for the subjecct cert.
6959              
6960             It appears the only "unique" portion of our subject cert that
6961             went into the signature of this response is the serial number.
6962             The "issuer" information of the subject cert also went into the
6963             signature but that isn't exactly unique. Seems a bit odd that the
6964             combo of the issuer and the serial number are the only thing that tie
6965             this subject cert back to the response but serial numbers are the basis
6966             for CRL as well so it must be good enough */
6967 0           index = 0;
6968 0 0         while (index < MAX_OCSP_RESPONSES)
6969             {
6970 0           subjectResponse = &response->singleResponse[index];
6971 0 0         if ((subject->serialNumberLen == subjectResponse->certIdSerialLen) &&
    0          
6972 0           (memcmp(subject->serialNumber, subjectResponse->certIdSerial,
6973 0           subject->serialNumberLen) == 0))
6974             {
6975 0           break; /* got it */
6976             }
6977 0           index++;
6978             }
6979 0 0         if (index == MAX_OCSP_RESPONSES)
6980             {
6981             psTraceCrypto("Unable to locate our subject cert in OCSP response\n");
6982 0           return PS_FAILURE;
6983             }
6984 0 0         if (vOpts->index_p != NULL)
6985             {
6986 0           *(vOpts->index_p) = index; /* Write index of response. */
6987             }
6988              
6989             /* Obtain general revocation status. */
6990 0 0         if (subjectResponse->certStatus == 0)
6991             {
6992 0           knownFlag = PS_TRUE;
6993 0           revocationFlag = PS_FALSE;
6994             }
6995 0 0         else if (subjectResponse->certStatus == 1)
6996             {
6997 0           knownFlag = PS_TRUE;
6998 0           revocationFlag = PS_TRUE;
6999             /* certificate is revoked, but still check rest of the response. */
7000             }
7001              
7002             /* Is the response within the acceptable time window */
7003 0 0         if (checkOCSPtimestamp(response, index) != PS_SUCCESS)
7004             {
7005             psTraceCrypto("ERROR: OCSP response older than threshold\n");
7006 0           return PS_FAILURE;
7007             }
7008              
7009             /* Check if nonces match. */
7010 0 0         if (nonceExtReq.buf && vOpts->nonceMatch)
    0          
7011             {
7012 0 0         if (response->nonce.buf == NULL)
7013             {
7014             /* No nonce in response. */
7015 0           *(vOpts->nonceMatch) = PS_FALSE;
7016             }
7017             else
7018             {
7019             /* Compare nonces. */
7020 0           *(vOpts->nonceMatch) = psBufEq(&nonceExtReq, &response->nonce);
7021             }
7022             }
7023              
7024             # if 0
7025             /* The issuer here is pointing to the cert that signed the OCSPRespose
7026             and that is not necessarily the parent of the subject cert we
7027             are looking at. If we want to include this test, we'd need to
7028             find the issuer of the subject and look at the KeyHash as
7029             an additional verification */
7030              
7031             /* Issuer portion of the validation - the subject cert issuer key and name
7032             hash should match what the subjectResponse reports
7033              
7034             POSSIBLE PROBLEMS: Only supporting a SHA1 hash here. The MatrixSSL
7035             parser will only use SHA1 for the DN and key hash. Just warning on
7036             this for now. The signature validation will catch any key mismatch */
7037             if (subjectResponse->certIdHashAlg != OID_SHA1_ALG)
7038             {
7039             psTraceCrypto("WARNING: Non-SHA1 OCSP CertID. Issuer check bypassed\n");
7040             }
7041             else
7042             {
7043             if (memcmp(subjectResponse->certIdKeyHash, issuer->sha1KeyHash, 20)
7044             != 0)
7045             {
7046             psTraceCrypto("Failed OCP issuer key hash validation\n");
7047             return PS_FAILURE;
7048             }
7049             /* Either subject->issuer or issuer->subject would work for testing */
7050             if (memcmp(subjectResponse->certIdNameHash, issuer->subject.hash, 20)
7051             != 0)
7052             {
7053             psTraceCrypto("Failed OCP issuer name hash validation\n");
7054             return PS_FAILURE;
7055             }
7056             }
7057             # endif /* 0 */
7058              
7059             /* Finally do the sig validation */
7060 0           switch (response->sigAlg)
7061             {
7062             # ifdef USE_SHA224
7063             case OID_SHA224_RSA_SIG:
7064             sigOutLen = SHA224_HASH_SIZE;
7065             sigType = PS_RSA;
7066             break;
7067             case OID_SHA224_ECDSA_SIG:
7068             sigOutLen = SHA224_HASH_SIZE;
7069             sigType = PS_ECC;
7070             break;
7071             # endif
7072             # ifdef USE_SHA256
7073             case OID_SHA256_RSA_SIG:
7074 0           sigOutLen = SHA256_HASH_SIZE;
7075 0           sigType = PS_RSA;
7076 0           break;
7077             case OID_SHA256_ECDSA_SIG:
7078 0           sigOutLen = SHA256_HASH_SIZE;
7079 0           sigType = PS_ECC;
7080 0           break;
7081             # endif
7082             # ifdef USE_SHA384
7083             case OID_SHA384_RSA_SIG:
7084 0           sigOutLen = SHA384_HASH_SIZE;
7085 0           sigType = PS_RSA;
7086 0           break;
7087             case OID_SHA384_ECDSA_SIG:
7088 0           sigOutLen = SHA384_HASH_SIZE;
7089 0           sigType = PS_ECC;
7090 0           break;
7091             # endif
7092             # ifdef USE_SHA512
7093             case OID_SHA512_RSA_SIG:
7094 0           sigOutLen = SHA512_HASH_SIZE;
7095 0           sigType = PS_RSA;
7096 0           break;
7097             case OID_SHA512_ECDSA_SIG:
7098 0           sigOutLen = SHA512_HASH_SIZE;
7099 0           sigType = PS_ECC;
7100 0           break;
7101             # endif
7102             case OID_SHA1_RSA_SIG:
7103             case OID_SHA1_RSA_SIG2:
7104 0           sigOutLen = SHA1_HASH_SIZE;
7105 0           sigType = PS_RSA;
7106 0           break;
7107             case OID_SHA1_ECDSA_SIG:
7108 0           sigOutLen = SHA1_HASH_SIZE;
7109 0           sigType = PS_ECC;
7110 0           break;
7111             default:
7112             /* Should have been caught in parse phase */
7113 0           return PS_UNSUPPORTED_FAIL;
7114             }
7115              
7116             /* Finally test the signature */
7117 0 0         if (sigType == PS_RSA)
7118             {
7119 0 0         if (issuer->publicKey.type != PS_RSA)
7120             {
7121 0           return PS_FAILURE;
7122             }
7123 0 0         if (pubRsaDecryptSignedElement(pkiPool, &issuer->publicKey.key.rsa,
7124 0           (unsigned char *) response->sig, response->sigLen, sigOut,
7125             sigOutLen, NULL) < 0)
7126             {
7127             psTraceCrypto("Unable to decode signature in psOcspResponseValidateOld\n");
7128 0           return PS_FAILURE;
7129             }
7130 0 0         if (memcmp(response->hashResult, sigOut, sigOutLen) != 0)
7131             {
7132             psTraceCrypto("OCSP RSA signature validation failed\n");
7133 0           return PS_FAILURE;
7134             }
7135             }
7136             # ifdef USE_ECC
7137             else
7138             {
7139 0 0         if (issuer->publicKey.type != PS_ECC)
7140             {
7141 0           return PS_FAILURE;
7142             }
7143             /* ECDSA signature */
7144 0           index = 0;
7145 0 0         if (psEccDsaVerify(pkiPool, &issuer->publicKey.key.ecc,
7146 0           response->hashResult, sigOutLen, (unsigned char *) response->sig,
7147 0           response->sigLen, &index, NULL) < 0)
7148             {
7149             psTraceCrypto("ECC OCSP sig validation");
7150 0           return PS_FAILURE;
7151             }
7152 0 0         if (index != 1)
7153             {
7154             psTraceCrypto("OCSP ECDSA signature validation failed\n");
7155 0           return PS_FAILURE;
7156             }
7157             }
7158             # endif
7159              
7160 0 0         if (vOpts->knownFlag)
7161             {
7162 0           *(vOpts->knownFlag) = knownFlag;
7163             }
7164              
7165 0 0         if (knownFlag == PS_FALSE)
7166             {
7167             /* The certificate is not known. */
7168 0           return PS_FAILURE;
7169             }
7170             else
7171             {
7172 0 0         if (vOpts->revocationFlag)
7173             {
7174 0           *(vOpts->revocationFlag) = revocationFlag;
7175             }
7176              
7177 0 0         if (vOpts->revocationTime)
7178             {
7179 0           (void) psBrokenDownTimeImport(
7180             vOpts->revocationTime,
7181 0           (const char *) subjectResponse->revocationTime,
7182             sizeof(subjectResponse->revocationTime), 0);
7183             }
7184              
7185 0 0         if (vOpts->revocationReason)
7186             {
7187 0           *(vOpts->revocationReason) =
7188 0           subjectResponse->revocationReason;
7189             }
7190              
7191             /* Function fails if certificate was revoked. */
7192 0 0         if (revocationFlag)
7193             {
7194 0           return PS_CERT_AUTH_FAIL_REVOKED;
7195             }
7196             }
7197              
7198             /* Was able to successfully confirm OCSP signature for our subject */
7199 0           return PS_SUCCESS;
7200             }
7201              
7202 0           int32_t psOcspResponseValidateOld(psPool_t *pool, psX509Cert_t *trustedOCSP,
7203             psX509Cert_t *srvCerts,
7204             psOcspResponse_t *response)
7205             {
7206 0           return psOcspResponseValidate(pool, trustedOCSP, srvCerts, response, NULL);
7207             }
7208              
7209 0           void psOcspResponseUninit(psOcspResponse_t *res)
7210             {
7211 0           psX509FreeCert(res->OCSPResponseCert);
7212 0           memset(res, 0, sizeof(*res));
7213 0           }
7214              
7215              
7216             # endif /* USE_OCSP */
7217              
7218             #endif /* USE_X509 */
7219             /******************************************************************************/
7220