1 /*
2  * X.509v3 certificate parsing and processing (RFC 3280 profile)
3  * Copyright (c) 2006-2011, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "utils/includes.h"
10 #include "rsn_supp/wpa.h"
11 #include "utils/common.h"
12 #include "crypto/crypto.h"
13 #include "tls/asn1.h"
14 #include "tls/x509v3.h"
15 
16 #include "eap_peer/eap_i.h"
17 
x509_free_name(struct x509_name * name)18 static void x509_free_name(struct x509_name *name)
19 {
20 	size_t i;
21 
22 	for (i = 0; i < name->num_attr; i++) {
23 		os_free(name->attr[i].value);
24 		name->attr[i].value = NULL;
25 		name->attr[i].type = X509_NAME_ATTR_NOT_USED;
26 	}
27 	name->num_attr = 0;
28 	os_free(name->email);
29 	name->email = NULL;
30 
31 	os_free(name->alt_email);
32 	os_free(name->dns);
33 	os_free(name->uri);
34 	os_free(name->ip);
35 	name->alt_email = name->dns = name->uri = NULL;
36 	name->ip = NULL;
37 	name->ip_len = 0;
38 	os_memset(&name->rid, 0, sizeof(name->rid));
39 }
40 
41 
42 /**
43  * x509_certificate_free - Free an X.509 certificate
44  * @cert: Certificate to be freed
45  */
x509_certificate_free(struct x509_certificate * cert)46 void x509_certificate_free(struct x509_certificate *cert)
47 {
48 	if (cert == NULL)
49 		return;
50 	if (cert->next) {
51 		wpa_printf(MSG_DEBUG, "X509: x509_certificate_free: cer=%p "
52 			   "was still on a list (next=%p)\n",
53 			   cert, cert->next);
54 	}
55 	x509_free_name(&cert->issuer);
56 	x509_free_name(&cert->subject);
57 	os_free(cert->public_key);
58 	os_free(cert->sign_value);
59 	os_free(cert);
60 }
61 
62 
63 /**
64  * x509_certificate_free - Free an X.509 certificate chain
65  * @cert: Pointer to the first certificate in the chain
66  */
x509_certificate_chain_free(struct x509_certificate * cert)67 void x509_certificate_chain_free(struct x509_certificate *cert)
68 {
69 	struct x509_certificate *next;
70 
71 	while (cert) {
72 		next = cert->next;
73 		cert->next = NULL;
74 		x509_certificate_free(cert);
75 		cert = next;
76 	}
77 }
78 
79 
x509_whitespace(char c)80 static int x509_whitespace(char c)
81 {
82 	return c == ' ' || c == '\t';
83 }
84 
85 
x509_str_strip_whitespace(char * a)86 static void x509_str_strip_whitespace(char *a)
87 {
88 	char *ipos, *opos;
89 	int remove_whitespace = 1;
90 
91 	ipos = opos = a;
92 
93 	while (*ipos) {
94 		if (remove_whitespace && x509_whitespace(*ipos))
95 			ipos++;
96 		else {
97 			remove_whitespace = x509_whitespace(*ipos);
98 			*opos++ = *ipos++;
99 		}
100 	}
101 
102 	*opos-- = '\0';
103 	if (opos > a && x509_whitespace(*opos))
104 		*opos = '\0';
105 }
106 
107 
x509_str_compare(const char * a,const char * b)108 static int x509_str_compare(const char *a, const char *b)
109 {
110 	char *aa, *bb;
111 	int ret;
112 
113 	if (!a && b)
114 		return -1;
115 	if (a && !b)
116 		return 1;
117 	if (!a && !b)
118 		return 0;
119 
120 	aa = os_strdup(a);
121 	bb = os_strdup(b);
122 
123 	if (aa == NULL || bb == NULL) {
124 		os_free(aa);
125 		os_free(bb);
126 		return strcasecmp(a, b);
127 	}
128 
129 	x509_str_strip_whitespace(aa);
130 	x509_str_strip_whitespace(bb);
131 
132 	ret = strcasecmp(aa, bb);
133 
134 	os_free(aa);
135 	os_free(bb);
136 
137 	return ret;
138 }
139 
140 
141 /**
142  * x509_name_compare - Compare X.509 certificate names
143  * @a: Certificate name
144  * @b: Certificate name
145  * Returns: <0, 0, or >0 based on whether a is less than, equal to, or
146  * greater than b
147  */
x509_name_compare(struct x509_name * a,struct x509_name * b)148 int x509_name_compare(struct x509_name *a, struct x509_name *b)
149 {
150 	int res;
151 	size_t i;
152 
153 	if (!a && b)
154 		return -1;
155 	if (a && !b)
156 		return 1;
157 	if (!a && !b)
158 		return 0;
159 	if (a->num_attr < b->num_attr)
160 		return -1;
161 	if (a->num_attr > b->num_attr)
162 		return 1;
163 
164 	for (i = 0; i < a->num_attr; i++) {
165 		if (a->attr[i].type < b->attr[i].type)
166 			return -1;
167 		if (a->attr[i].type > b->attr[i].type)
168 			return -1;
169 		res = x509_str_compare(a->attr[i].value, b->attr[i].value);
170 		if (res)
171 			return res;
172 	}
173 	res = x509_str_compare(a->email, b->email);
174 	if (res)
175 		return res;
176 
177 	return 0;
178 }
179 
180 
x509_parse_algorithm_identifier(const u8 * buf,size_t len,struct x509_algorithm_identifier * id,const u8 ** next)181 static int x509_parse_algorithm_identifier(
182 	const u8 *buf, size_t len,
183 	struct x509_algorithm_identifier *id, const u8 **next)
184 {
185 	struct asn1_hdr hdr;
186 	const u8 *pos, *end;
187 
188 	/*
189 	 * AlgorithmIdentifier ::= SEQUENCE {
190 	 *     algorithm            OBJECT IDENTIFIER,
191 	 *     parameters           ANY DEFINED BY algorithm OPTIONAL
192 	 * }
193 	 */
194 
195 	if (asn1_get_next(buf, len, &hdr) < 0 ||
196 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
197 	    hdr.tag != ASN1_TAG_SEQUENCE) {
198 		wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE "
199 			   "(AlgorithmIdentifier) - found class %d tag 0x%x",
200 			   hdr.class, hdr.tag);
201 		return -1;
202 	}
203 	pos = hdr.payload;
204 	end = pos + hdr.length;
205 
206 	if (end > buf + len)
207 		return -1;
208 
209 	*next = end;
210 
211 	if (asn1_get_oid(pos, end - pos, &id->oid, &pos))
212 		return -1;
213 
214 	/* TODO: optional parameters */
215 
216 	return 0;
217 }
218 
219 
x509_parse_public_key(const u8 * buf,size_t len,struct x509_certificate * cert,const u8 ** next)220 static int x509_parse_public_key(const u8 *buf, size_t len,
221 				 struct x509_certificate *cert,
222 				 const u8 **next)
223 {
224 	struct asn1_hdr hdr;
225 	const u8 *pos, *end;
226 
227 	/*
228 	 * SubjectPublicKeyInfo ::= SEQUENCE {
229 	 *     algorithm            AlgorithmIdentifier,
230 	 *     subjectPublicKey     BIT STRING
231 	 * }
232 	 */
233 
234 	pos = buf;
235 	end = buf + len;
236 
237 	if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
238 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
239 	    hdr.tag != ASN1_TAG_SEQUENCE) {
240 		wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE "
241 			   "(SubjectPublicKeyInfo) - found class %d tag 0x%x",
242 			   hdr.class, hdr.tag);
243 		return -1;
244 	}
245 	pos = hdr.payload;
246 
247 	if (pos + hdr.length > end)
248 		return -1;
249 	end = pos + hdr.length;
250 	*next = end;
251 
252 	if (x509_parse_algorithm_identifier(pos, end - pos,
253 					    &cert->public_key_alg, &pos))
254 		return -1;
255 
256 	if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
257 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
258 	    hdr.tag != ASN1_TAG_BITSTRING) {
259 		wpa_printf(MSG_DEBUG, "X509: Expected BITSTRING "
260 			   "(subjectPublicKey) - found class %d tag 0x%x",
261 			   hdr.class, hdr.tag);
262 		return -1;
263 	}
264 	if (hdr.length < 1)
265 		return -1;
266 	pos = hdr.payload;
267 	if (*pos) {
268 		wpa_printf(MSG_DEBUG, "X509: BITSTRING - %d unused bits",
269 			   *pos);
270 		/*
271 		 * TODO: should this be rejected? X.509 certificates are
272 		 * unlikely to use such a construction. Now we would end up
273 		 * including the extra bits in the buffer which may also be
274 		 * ok.
275 		 */
276 	}
277 	os_free(cert->public_key);
278 	cert->public_key = os_malloc(hdr.length - 1);
279 	if (cert->public_key == NULL) {
280 		wpa_printf(MSG_DEBUG, "X509: Failed to allocate memory for "
281 			   "public key");
282 		return -1;
283 	}
284 	os_memcpy(cert->public_key, pos + 1, hdr.length - 1);
285 	cert->public_key_len = hdr.length - 1;
286 	wpa_hexdump(MSG_MSGDUMP, "X509: subjectPublicKey",
287 		    cert->public_key, cert->public_key_len);
288 
289 	return 0;
290 }
291 
292 
x509_parse_name(const u8 * buf,size_t len,struct x509_name * name,const u8 ** next)293 static int x509_parse_name(const u8 *buf, size_t len, struct x509_name *name,
294 			   const u8 **next)
295 {
296 	struct asn1_hdr hdr;
297 	const u8 *pos, *end, *set_pos, *set_end, *seq_pos, *seq_end;
298 	struct asn1_oid oid;
299 	char *val;
300 
301 	/*
302 	 * Name ::= CHOICE { RDNSequence }
303 	 * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
304 	 * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
305 	 * AttributeTypeAndValue ::= SEQUENCE {
306 	 *     type     AttributeType,
307 	 *     value    AttributeValue
308 	 * }
309 	 * AttributeType ::= OBJECT IDENTIFIER
310 	 * AttributeValue ::= ANY DEFINED BY AttributeType
311 	 */
312 
313 	if (asn1_get_next(buf, len, &hdr) < 0 ||
314 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
315 	    hdr.tag != ASN1_TAG_SEQUENCE) {
316 		wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE "
317 			   "(Name / RDNSequencer) - found class %d tag 0x%x",
318 			   hdr.class, hdr.tag);
319 		return -1;
320 	}
321 	pos = hdr.payload;
322 
323 	if (pos + hdr.length > buf + len)
324 		return -1;
325 
326 	end = *next = pos + hdr.length;
327 
328 	while (pos < end) {
329 		enum x509_name_attr_type type;
330 
331 		if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
332 		    hdr.class != ASN1_CLASS_UNIVERSAL ||
333 		    hdr.tag != ASN1_TAG_SET) {
334 			wpa_printf(MSG_DEBUG, "X509: Expected SET "
335 				   "(RelativeDistinguishedName) - found class "
336 				   "%d tag 0x%x", hdr.class, hdr.tag);
337 			x509_free_name(name);
338 			return -1;
339 		}
340 
341 		set_pos = hdr.payload;
342 		pos = set_end = hdr.payload + hdr.length;
343 
344 		if (asn1_get_next(set_pos, set_end - set_pos, &hdr) < 0 ||
345 		    hdr.class != ASN1_CLASS_UNIVERSAL ||
346 		    hdr.tag != ASN1_TAG_SEQUENCE) {
347 			wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE "
348 				   "(AttributeTypeAndValue) - found class %d "
349 				   "tag 0x%x", hdr.class, hdr.tag);
350 			x509_free_name(name);
351 			return -1;
352 		}
353 
354 		seq_pos = hdr.payload;
355 		seq_end = hdr.payload + hdr.length;
356 
357 		if (asn1_get_oid(seq_pos, seq_end - seq_pos, &oid, &seq_pos)) {
358 			x509_free_name(name);
359 			return -1;
360 		}
361 
362 		if (asn1_get_next(seq_pos, seq_end - seq_pos, &hdr) < 0 ||
363 		    hdr.class != ASN1_CLASS_UNIVERSAL) {
364 			wpa_printf(MSG_DEBUG, "X509: Failed to parse "
365 				   "AttributeValue");
366 			x509_free_name(name);
367 			return -1;
368 		}
369 
370 		/* RFC 3280:
371 		 * MUST: country, organization, organizational-unit,
372 		 * distinguished name qualifier, state or province name,
373 		 * common name, serial number.
374 		 * SHOULD: locality, title, surname, given name, initials,
375 		 * pseudonym, generation qualifier.
376 		 * MUST: domainComponent (RFC 2247).
377 		 */
378 		type = X509_NAME_ATTR_NOT_USED;
379 		if (oid.len == 4 &&
380 		    oid.oid[0] == 2 && oid.oid[1] == 5 && oid.oid[2] == 4) {
381 			/* id-at ::= 2.5.4 */
382 			switch (oid.oid[3]) {
383 			case 3:
384 				/* commonName */
385 				type = X509_NAME_ATTR_CN;
386 				break;
387 			case 6:
388 				/*  countryName */
389 				type = X509_NAME_ATTR_C;
390 				break;
391 			case 7:
392 				/* localityName */
393 				type = X509_NAME_ATTR_L;
394 				break;
395 			case 8:
396 				/* stateOrProvinceName */
397 				type = X509_NAME_ATTR_ST;
398 				break;
399 			case 10:
400 				/* organizationName */
401 				type = X509_NAME_ATTR_O;
402 				break;
403 			case 11:
404 				/* organizationalUnitName */
405 				type = X509_NAME_ATTR_OU;
406 				break;
407 			}
408 		} else if (oid.len == 7 &&
409 			   oid.oid[0] == 1 && oid.oid[1] == 2 &&
410 			   oid.oid[2] == 840 && oid.oid[3] == 113549 &&
411 			   oid.oid[4] == 1 && oid.oid[5] == 9 &&
412 			   oid.oid[6] == 1) {
413 			/* 1.2.840.113549.1.9.1 - e-mailAddress */
414 			os_free(name->email);
415 			name->email = os_malloc(hdr.length + 1);
416 			if (name->email == NULL) {
417 				x509_free_name(name);
418 				return -1;
419 			}
420 			os_memcpy(name->email, hdr.payload, hdr.length);
421 			name->email[hdr.length] = '\0';
422 			continue;
423 		} else if (oid.len == 7 &&
424 			   oid.oid[0] == 0 && oid.oid[1] == 9 &&
425 			   oid.oid[2] == 2342 && oid.oid[3] == 19200300 &&
426 			   oid.oid[4] == 100 && oid.oid[5] == 1 &&
427 			   oid.oid[6] == 25) {
428 			/* 0.9.2342.19200300.100.1.25 - domainComponent */
429 			type = X509_NAME_ATTR_DC;
430 		}
431 
432 		if (type == X509_NAME_ATTR_NOT_USED) {
433 			wpa_hexdump(MSG_DEBUG, "X509: Unrecognized OID",
434 				    (u8 *) oid.oid,
435 				    oid.len * sizeof(oid.oid[0]));
436 			wpa_hexdump_ascii(MSG_MSGDUMP, "X509: Attribute Data",
437 					  hdr.payload, hdr.length);
438 			continue;
439 		}
440 
441 		if (name->num_attr == X509_MAX_NAME_ATTRIBUTES) {
442 			wpa_printf(MSG_INFO, "X509: Too many Name attributes");
443 			x509_free_name(name);
444 			return -1;
445 		}
446 
447 		val = (char *)dup_binstr(hdr.payload, hdr.length);
448 		if (val == NULL) {
449 			x509_free_name(name);
450 			return -1;
451 		}
452 		if (os_strlen(val) != hdr.length) {
453 			wpa_printf(MSG_INFO, "X509: Reject certificate with "
454 				   "embedded NUL byte in a string (%s[NUL])",
455 				   val);
456 			os_free(val);
457 			x509_free_name(name);
458 			return -1;
459 		}
460 
461 		name->attr[name->num_attr].type = type;
462 		name->attr[name->num_attr].value = val;
463 		name->num_attr++;
464 	}
465 
466 	return 0;
467 }
468 
469 
x509_name_attr_str(enum x509_name_attr_type type)470 static char * x509_name_attr_str(enum x509_name_attr_type type)
471 {
472 #ifndef ESPRESSIF_USE
473 	switch (type) {
474 	case X509_NAME_ATTR_NOT_USED:
475 		return "[N/A]";
476 	case X509_NAME_ATTR_DC:
477 		return "DC";
478 	case X509_NAME_ATTR_CN:
479 		return "CN";
480 	case X509_NAME_ATTR_C:
481 		return "C";
482 	case X509_NAME_ATTR_L:
483 		return "L";
484 	case X509_NAME_ATTR_ST:
485 		return "ST";
486 	case X509_NAME_ATTR_O:
487 		return "O";
488 	case X509_NAME_ATTR_OU:
489 		return "OU";
490 	}
491 	return "?";
492 #else
493     static char name_attr[6];
494 	switch (type) {
495         case X509_NAME_ATTR_NOT_USED:
496             strcpy(name_attr, "[N/A]");
497             break;
498         case X509_NAME_ATTR_DC:
499             strcpy(name_attr, "DC");
500             break;
501         case X509_NAME_ATTR_CN:
502             strcpy(name_attr, "CN");
503             break;
504         case X509_NAME_ATTR_C:
505             strcpy(name_attr, "C");
506             break;
507         case X509_NAME_ATTR_L:
508             strcpy(name_attr, "L");
509             break;
510         case X509_NAME_ATTR_ST:
511             strcpy(name_attr, "ST");
512             break;
513         case X509_NAME_ATTR_O:
514             strcpy(name_attr, "O");
515             break;
516         case X509_NAME_ATTR_OU:
517             strcpy(name_attr, "OU");
518             break;
519         default :
520             strcpy(name_attr, "?");
521 	}
522 	return name_attr;
523 #endif
524 }
525 
526 
527 /**
528  * x509_name_string - Convert an X.509 certificate name into a string
529  * @name: Name to convert
530  * @buf: Buffer for the string
531  * @len: Maximum buffer length
532  */
x509_name_string(struct x509_name * name,char * buf,size_t len)533 void x509_name_string(struct x509_name *name, char *buf, size_t len)
534 {
535 	char *pos, *end;
536 	int ret;
537 	size_t i;
538 
539 	if (len == 0)
540 		return;
541 
542 	pos = buf;
543 	end = buf + len;
544 
545 	for (i = 0; i < name->num_attr; i++) {
546 		ret = os_snprintf(pos, end - pos, "%s=%s, ",
547 				  x509_name_attr_str(name->attr[i].type),
548 				  name->attr[i].value);
549 		if (ret < 0 || ret >= end - pos)
550 			goto done;
551 		pos += ret;
552 	}
553 
554 	if (pos > buf + 1 && pos[-1] == ' ' && pos[-2] == ',') {
555 		pos--;
556 		*pos = '\0';
557 		pos--;
558 		*pos = '\0';
559 	}
560 
561 	if (name->email) {
562 		ret = os_snprintf(pos, end - pos, "/emailAddress=%s",
563 				  name->email);
564 		if (ret < 0 || ret >= end - pos)
565 			goto done;
566 		pos += ret;
567 	}
568 
569 done:
570 	end[-1] = '\0';
571 }
572 
573 
x509_parse_time(const u8 * buf,size_t len,u8 asn1_tag,os_time_t * val)574 static int x509_parse_time(const u8 *buf, size_t len, u8 asn1_tag,
575 			   os_time_t *val)
576 {
577 	return 0;
578 }
579 
580 
x509_parse_validity(const u8 * buf,size_t len,struct x509_certificate * cert,const u8 ** next)581 static int x509_parse_validity(const u8 *buf, size_t len,
582 			       struct x509_certificate *cert, const u8 **next)
583 {
584 	struct asn1_hdr hdr;
585 	const u8 *pos;
586 	size_t plen;
587 
588 	/*
589 	 * Validity ::= SEQUENCE {
590 	 *     notBefore      Time,
591 	 *     notAfter       Time
592 	 * }
593 	 *
594 	 * RFC 3280, 4.1.2.5:
595 	 * CAs conforming to this profile MUST always encode certificate
596 	 * validity dates through the year 2049 as UTCTime; certificate
597 	 * validity dates in 2050 or later MUST be encoded as GeneralizedTime.
598 	 */
599 
600 	if (asn1_get_next(buf, len, &hdr) < 0 ||
601 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
602 	    hdr.tag != ASN1_TAG_SEQUENCE) {
603 		wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE "
604 			   "(Validity) - found class %d tag 0x%x",
605 			   hdr.class, hdr.tag);
606 		return -1;
607 	}
608 	pos = hdr.payload;
609 	plen = hdr.length;
610 
611 	if (pos + plen > buf + len)
612 		return -1;
613 
614 	*next = pos + plen;
615 
616 	if (asn1_get_next(pos, plen, &hdr) < 0 ||
617 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
618 	    x509_parse_time(hdr.payload, hdr.length, hdr.tag,
619 			    &cert->not_before) < 0) {
620 		wpa_hexdump_ascii(MSG_DEBUG, "X509: Failed to parse notBefore "
621 				  "Time", hdr.payload, hdr.length);
622 		return -1;
623 	}
624 
625 	pos = hdr.payload + hdr.length;
626 	plen = *next - pos;
627 
628 	if (asn1_get_next(pos, plen, &hdr) < 0 ||
629 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
630 	    x509_parse_time(hdr.payload, hdr.length, hdr.tag,
631 			    &cert->not_after) < 0) {
632 		wpa_hexdump_ascii(MSG_DEBUG, "X509: Failed to parse notAfter "
633 				  "Time", hdr.payload, hdr.length);
634 		return -1;
635 	}
636 
637 	wpa_printf(MSG_DEBUG, "X509: Validity: notBefore: %lu notAfter: %lu",
638 		   (unsigned long) cert->not_before,
639 		   (unsigned long) cert->not_after);
640 
641 	return 0;
642 }
643 
644 
x509_id_ce_oid(struct asn1_oid * oid)645 static int x509_id_ce_oid(struct asn1_oid *oid)
646 {
647 	/* id-ce arc from X.509 for standard X.509v3 extensions */
648 	return oid->len >= 4 &&
649 		oid->oid[0] == 2 /* joint-iso-ccitt */ &&
650 		oid->oid[1] == 5 /* ds */ &&
651 		oid->oid[2] == 29 /* id-ce */;
652 }
653 
654 
x509_parse_ext_key_usage(struct x509_certificate * cert,const u8 * pos,size_t len)655 static int x509_parse_ext_key_usage(struct x509_certificate *cert,
656 				    const u8 *pos, size_t len)
657 {
658 	struct asn1_hdr hdr;
659 
660 	/*
661 	 * KeyUsage ::= BIT STRING {
662 	 *     digitalSignature        (0),
663 	 *     nonRepudiation          (1),
664 	 *     keyEncipherment         (2),
665 	 *     dataEncipherment        (3),
666 	 *     keyAgreement            (4),
667 	 *     keyCertSign             (5),
668 	 *     cRLSign                 (6),
669 	 *     encipherOnly            (7),
670 	 *     decipherOnly            (8) }
671 	 */
672 
673 	if (asn1_get_next(pos, len, &hdr) < 0 ||
674 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
675 	    hdr.tag != ASN1_TAG_BITSTRING ||
676 	    hdr.length < 1) {
677 		wpa_printf(MSG_DEBUG, "X509: Expected BIT STRING in "
678 			   "KeyUsage; found %d tag 0x%x len %d",
679 			   hdr.class, hdr.tag, hdr.length);
680 		return -1;
681 	}
682 
683 	cert->extensions_present |= X509_EXT_KEY_USAGE;
684 	cert->key_usage = asn1_bit_string_to_long(hdr.payload, hdr.length);
685 
686 	wpa_printf(MSG_DEBUG, "X509: KeyUsage 0x%lx", cert->key_usage);
687 
688 	return 0;
689 }
690 
691 
x509_parse_ext_basic_constraints(struct x509_certificate * cert,const u8 * pos,size_t len)692 static int x509_parse_ext_basic_constraints(struct x509_certificate *cert,
693 					    const u8 *pos, size_t len)
694 {
695 	struct asn1_hdr hdr;
696 	unsigned long value;
697 	size_t left;
698 
699 	/*
700 	 * BasicConstraints ::= SEQUENCE {
701 	 * cA                      BOOLEAN DEFAULT FALSE,
702 	 * pathLenConstraint       INTEGER (0..MAX) OPTIONAL }
703 	 */
704 
705 	if (asn1_get_next(pos, len, &hdr) < 0 ||
706 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
707 	    hdr.tag != ASN1_TAG_SEQUENCE) {
708 		wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE in "
709 			   "BasicConstraints; found %d tag 0x%x",
710 			   hdr.class, hdr.tag);
711 		return -1;
712 	}
713 
714 	cert->extensions_present |= X509_EXT_BASIC_CONSTRAINTS;
715 
716 	if (hdr.length == 0)
717 		return 0;
718 
719 	if (asn1_get_next(hdr.payload, hdr.length, &hdr) < 0 ||
720 	    hdr.class != ASN1_CLASS_UNIVERSAL) {
721 		wpa_printf(MSG_DEBUG, "X509: Failed to parse "
722 			   "BasicConstraints");
723 		return -1;
724 	}
725 
726 	if (hdr.tag == ASN1_TAG_BOOLEAN) {
727 		if (hdr.length != 1) {
728 			wpa_printf(MSG_DEBUG, "X509: Unexpected "
729 				   "Boolean length (%u) in BasicConstraints",
730 				   hdr.length);
731 			return -1;
732 		}
733 		cert->ca = hdr.payload[0];
734 
735 		if (hdr.payload + hdr.length == pos + len) {
736 			wpa_printf(MSG_DEBUG, "X509: BasicConstraints - cA=%d",
737 				   cert->ca);
738 			return 0;
739 		}
740 
741 		if (asn1_get_next(hdr.payload + hdr.length, len - hdr.length,
742 				  &hdr) < 0 ||
743 		    hdr.class != ASN1_CLASS_UNIVERSAL) {
744 			wpa_printf(MSG_DEBUG, "X509: Failed to parse "
745 				   "BasicConstraints");
746 			return -1;
747 		}
748 	}
749 
750 	if (hdr.tag != ASN1_TAG_INTEGER) {
751 		wpa_printf(MSG_DEBUG, "X509: Expected INTEGER in "
752 			   "BasicConstraints; found class %d tag 0x%x",
753 			   hdr.class, hdr.tag);
754 		return -1;
755 	}
756 
757 	pos = hdr.payload;
758 	left = hdr.length;
759 	value = 0;
760 	while (left) {
761 		value <<= 8;
762 		value |= *pos++;
763 		left--;
764 	}
765 
766 	cert->path_len_constraint = value;
767 	cert->extensions_present |= X509_EXT_PATH_LEN_CONSTRAINT;
768 
769 	wpa_printf(MSG_DEBUG, "X509: BasicConstraints - cA=%d "
770 		   "pathLenConstraint=%lu",
771 		   cert->ca, cert->path_len_constraint);
772 
773 	return 0;
774 }
775 
776 
x509_parse_alt_name_rfc8222(struct x509_name * name,const u8 * pos,size_t len)777 static int x509_parse_alt_name_rfc8222(struct x509_name *name,
778 				       const u8 *pos, size_t len)
779 {
780 	/* rfc822Name IA5String */
781 	wpa_hexdump_ascii(MSG_MSGDUMP, "X509: altName - rfc822Name", pos, len);
782 	os_free(name->alt_email);
783 	name->alt_email = (char *)os_zalloc(len + 1);
784 	if (name->alt_email == NULL)
785 		return -1;
786 	os_memcpy(name->alt_email, pos, len);
787 	if (os_strlen(name->alt_email) != len) {
788 		wpa_printf(MSG_INFO, "X509: Reject certificate with "
789 			   "embedded NUL byte in rfc822Name (%s[NUL])",
790 			   name->alt_email);
791 		os_free(name->alt_email);
792 		name->alt_email = NULL;
793 		return -1;
794 	}
795 	return 0;
796 }
797 
798 
x509_parse_alt_name_dns(struct x509_name * name,const u8 * pos,size_t len)799 static int x509_parse_alt_name_dns(struct x509_name *name,
800 				   const u8 *pos, size_t len)
801 {
802 	/* dNSName IA5String */
803 	wpa_hexdump_ascii(MSG_MSGDUMP, "X509: altName - dNSName", pos, len);
804 	os_free(name->dns);
805 	name->dns = (char *)os_zalloc(len + 1);
806 	if (name->dns == NULL)
807 		return -1;
808 	os_memcpy(name->dns, pos, len);
809 	if (os_strlen(name->dns) != len) {
810 		wpa_printf(MSG_INFO, "X509: Reject certificate with "
811 			   "embedded NUL byte in dNSName (%s[NUL])",
812 			   name->dns);
813 		os_free(name->dns);
814 		name->dns = NULL;
815 		return -1;
816 	}
817 	return 0;
818 }
819 
820 
x509_parse_alt_name_uri(struct x509_name * name,const u8 * pos,size_t len)821 static int x509_parse_alt_name_uri(struct x509_name *name,
822 				   const u8 *pos, size_t len)
823 {
824 	/* uniformResourceIdentifier IA5String */
825 	wpa_hexdump_ascii(MSG_MSGDUMP,
826 			  "X509: altName - uniformResourceIdentifier",
827 			  pos, len);
828 	os_free(name->uri);
829 	name->uri = (char *)os_zalloc(len + 1);
830 	if (name->uri == NULL)
831 		return -1;
832 	os_memcpy(name->uri, pos, len);
833 	if (os_strlen(name->uri) != len) {
834 		wpa_printf(MSG_INFO, "X509: Reject certificate with "
835 			   "embedded NUL byte in uniformResourceIdentifier "
836 			   "(%s[NUL])", name->uri);
837 		os_free(name->uri);
838 		name->uri = NULL;
839 		return -1;
840 	}
841 	return 0;
842 }
843 
844 
x509_parse_alt_name_ip(struct x509_name * name,const u8 * pos,size_t len)845 static int x509_parse_alt_name_ip(struct x509_name *name,
846 				       const u8 *pos, size_t len)
847 {
848 	/* iPAddress OCTET STRING */
849 	wpa_hexdump(MSG_MSGDUMP, "X509: altName - iPAddress", pos, len);
850 	os_free(name->ip);
851 	name->ip = os_malloc(len);
852 	if (name->ip == NULL)
853 		return -1;
854 	os_memcpy(name->ip, pos, len);
855 	name->ip_len = len;
856 	return 0;
857 }
858 
859 
x509_parse_alt_name_rid(struct x509_name * name,const u8 * pos,size_t len)860 static int x509_parse_alt_name_rid(struct x509_name *name,
861 				   const u8 *pos, size_t len)
862 {
863 	char buf[80];
864 
865 	/* registeredID OBJECT IDENTIFIER */
866 	if (asn1_parse_oid(pos, len, &name->rid) < 0)
867 		return -1;
868 
869 	asn1_oid_to_str(&name->rid, buf, sizeof(buf));
870 	wpa_printf(MSG_DEBUG, "X509: altName - registeredID: %s", buf);
871 
872 	return 0;
873 }
874 
875 
x509_parse_ext_alt_name(struct x509_name * name,const u8 * pos,size_t len)876 static int x509_parse_ext_alt_name(struct x509_name *name,
877 				   const u8 *pos, size_t len)
878 {
879 	struct asn1_hdr hdr;
880 	const u8 *p, *end;
881 
882 	/*
883 	 * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
884 	 *
885 	 * GeneralName ::= CHOICE {
886 	 *     otherName                       [0]     OtherName,
887 	 *     rfc822Name                      [1]     IA5String,
888 	 *     dNSName                         [2]     IA5String,
889 	 *     x400Address                     [3]     ORAddress,
890 	 *     directoryName                   [4]     Name,
891 	 *     ediPartyName                    [5]     EDIPartyName,
892 	 *     uniformResourceIdentifier       [6]     IA5String,
893 	 *     iPAddress                       [7]     OCTET STRING,
894 	 *     registeredID                    [8]     OBJECT IDENTIFIER }
895 	 *
896 	 * OtherName ::= SEQUENCE {
897 	 *     type-id    OBJECT IDENTIFIER,
898 	 *     value      [0] EXPLICIT ANY DEFINED BY type-id }
899 	 *
900 	 * EDIPartyName ::= SEQUENCE {
901 	 *     nameAssigner            [0]     DirectoryString OPTIONAL,
902 	 *     partyName               [1]     DirectoryString }
903 	 */
904 
905 	for (p = pos, end = pos + len; p < end; p = hdr.payload + hdr.length) {
906 		int res;
907 
908 		if (asn1_get_next(p, end - p, &hdr) < 0) {
909 			wpa_printf(MSG_DEBUG, "X509: Failed to parse "
910 				   "SubjectAltName item");
911 			return -1;
912 		}
913 
914 		if (hdr.class != ASN1_CLASS_CONTEXT_SPECIFIC)
915 			continue;
916 
917 		switch (hdr.tag) {
918 		case 1:
919 			res = x509_parse_alt_name_rfc8222(name, hdr.payload,
920 							  hdr.length);
921 			break;
922 		case 2:
923 			res = x509_parse_alt_name_dns(name, hdr.payload,
924 						      hdr.length);
925 			break;
926 		case 6:
927 			res = x509_parse_alt_name_uri(name, hdr.payload,
928 						      hdr.length);
929 			break;
930 		case 7:
931 			res = x509_parse_alt_name_ip(name, hdr.payload,
932 						     hdr.length);
933 			break;
934 		case 8:
935 			res = x509_parse_alt_name_rid(name, hdr.payload,
936 						      hdr.length);
937 			break;
938 		case 0: /* TODO: otherName */
939 		case 3: /* TODO: x500Address */
940 		case 4: /* TODO: directoryName */
941 		case 5: /* TODO: ediPartyName */
942 		default:
943 			res = 0;
944 			break;
945 		}
946 		if (res < 0)
947 			return res;
948 	}
949 
950 	return 0;
951 }
952 
953 
x509_parse_ext_subject_alt_name(struct x509_certificate * cert,const u8 * pos,size_t len)954 static int x509_parse_ext_subject_alt_name(struct x509_certificate *cert,
955 					   const u8 *pos, size_t len)
956 {
957 	struct asn1_hdr hdr;
958 
959 	/* SubjectAltName ::= GeneralNames */
960 
961 	if (asn1_get_next(pos, len, &hdr) < 0 ||
962 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
963 	    hdr.tag != ASN1_TAG_SEQUENCE) {
964 		wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE in "
965 			   "SubjectAltName; found %d tag 0x%x",
966 			   hdr.class, hdr.tag);
967 		return -1;
968 	}
969 
970 	wpa_printf(MSG_DEBUG, "X509: SubjectAltName");
971 	cert->extensions_present |= X509_EXT_SUBJECT_ALT_NAME;
972 
973 	if (hdr.length == 0)
974 		return 0;
975 
976 	return x509_parse_ext_alt_name(&cert->subject, hdr.payload,
977 				       hdr.length);
978 }
979 
980 
x509_parse_ext_issuer_alt_name(struct x509_certificate * cert,const u8 * pos,size_t len)981 static int x509_parse_ext_issuer_alt_name(struct x509_certificate *cert,
982 					  const u8 *pos, size_t len)
983 {
984 	struct asn1_hdr hdr;
985 
986 	/* IssuerAltName ::= GeneralNames */
987 
988 	if (asn1_get_next(pos, len, &hdr) < 0 ||
989 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
990 	    hdr.tag != ASN1_TAG_SEQUENCE) {
991 		wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE in "
992 			   "IssuerAltName; found %d tag 0x%x",
993 			   hdr.class, hdr.tag);
994 		return -1;
995 	}
996 
997 	wpa_printf(MSG_DEBUG, "X509: IssuerAltName");
998 	cert->extensions_present |= X509_EXT_ISSUER_ALT_NAME;
999 
1000 	if (hdr.length == 0)
1001 		return 0;
1002 
1003 	return x509_parse_ext_alt_name(&cert->issuer, hdr.payload,
1004 				       hdr.length);
1005 }
1006 
1007 
x509_parse_extension_data(struct x509_certificate * cert,struct asn1_oid * oid,const u8 * pos,size_t len)1008 static int x509_parse_extension_data(struct x509_certificate *cert,
1009 				     struct asn1_oid *oid,
1010 				     const u8 *pos, size_t len)
1011 {
1012 	if (!x509_id_ce_oid(oid))
1013 		return 1;
1014 
1015 	/* TODO: add other extensions required by RFC 3280, Ch 4.2:
1016 	 * certificate policies (section 4.2.1.5)
1017 	 * name constraints (section 4.2.1.11)
1018 	 * policy constraints (section 4.2.1.12)
1019 	 * extended key usage (section 4.2.1.13)
1020 	 * inhibit any-policy (section 4.2.1.15)
1021 	 */
1022 	switch (oid->oid[3]) {
1023 	case 15: /* id-ce-keyUsage */
1024 		return x509_parse_ext_key_usage(cert, pos, len);
1025 	case 17: /* id-ce-subjectAltName */
1026 		return x509_parse_ext_subject_alt_name(cert, pos, len);
1027 	case 18: /* id-ce-issuerAltName */
1028 		return x509_parse_ext_issuer_alt_name(cert, pos, len);
1029 	case 19: /* id-ce-basicConstraints */
1030 		return x509_parse_ext_basic_constraints(cert, pos, len);
1031 	default:
1032 		return 1;
1033 	}
1034 }
1035 
1036 
x509_parse_extension(struct x509_certificate * cert,const u8 * pos,size_t len,const u8 ** next)1037 static int x509_parse_extension(struct x509_certificate *cert,
1038 				const u8 *pos, size_t len, const u8 **next)
1039 {
1040 	const u8 *end;
1041 	struct asn1_hdr hdr;
1042 	struct asn1_oid oid;
1043 	int critical_ext = 0, res;
1044 	char buf[80];
1045 
1046 	/*
1047 	 * Extension  ::=  SEQUENCE  {
1048 	 *     extnID      OBJECT IDENTIFIER,
1049 	 *     critical    BOOLEAN DEFAULT FALSE,
1050 	 *     extnValue   OCTET STRING
1051 	 * }
1052 	 */
1053 
1054 	if (asn1_get_next(pos, len, &hdr) < 0 ||
1055 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
1056 	    hdr.tag != ASN1_TAG_SEQUENCE) {
1057 		wpa_printf(MSG_DEBUG, "X509: Unexpected ASN.1 header in "
1058 			   "Extensions: class %d tag 0x%x; expected SEQUENCE",
1059 			   hdr.class, hdr.tag);
1060 		return -1;
1061 	}
1062 	pos = hdr.payload;
1063 	*next = end = pos + hdr.length;
1064 
1065 	if (asn1_get_oid(pos, end - pos, &oid, &pos) < 0) {
1066 		wpa_printf(MSG_DEBUG, "X509: Unexpected ASN.1 data for "
1067 			   "Extension (expected OID)");
1068 		return -1;
1069 	}
1070 
1071 	if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
1072 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
1073 	    (hdr.tag != ASN1_TAG_BOOLEAN &&
1074 	     hdr.tag != ASN1_TAG_OCTETSTRING)) {
1075 		wpa_printf(MSG_DEBUG, "X509: Unexpected ASN.1 header in "
1076 			   "Extensions: class %d tag 0x%x; expected BOOLEAN "
1077 			   "or OCTET STRING", hdr.class, hdr.tag);
1078 		return -1;
1079 	}
1080 
1081 	if (hdr.tag == ASN1_TAG_BOOLEAN) {
1082 		if (hdr.length != 1) {
1083 			wpa_printf(MSG_DEBUG, "X509: Unexpected "
1084 				   "Boolean length (%u)", hdr.length);
1085 			return -1;
1086 		}
1087 		critical_ext = hdr.payload[0];
1088 		pos = hdr.payload;
1089 		if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
1090 		    (hdr.class != ASN1_CLASS_UNIVERSAL &&
1091 		     hdr.class != ASN1_CLASS_PRIVATE) ||
1092 		    hdr.tag != ASN1_TAG_OCTETSTRING) {
1093 			wpa_printf(MSG_DEBUG, "X509: Unexpected ASN.1 header "
1094 				   "in Extensions: class %d tag 0x%x; "
1095 				   "expected OCTET STRING",
1096 				   hdr.class, hdr.tag);
1097 			return -1;
1098 		}
1099 	}
1100 
1101 	asn1_oid_to_str(&oid, buf, sizeof(buf));
1102 	wpa_printf(MSG_DEBUG, "X509: Extension: extnID=%s critical=%d",
1103 		   buf, critical_ext);
1104 	wpa_hexdump(MSG_MSGDUMP, "X509: extnValue", hdr.payload, hdr.length);
1105 
1106 	res = x509_parse_extension_data(cert, &oid, hdr.payload, hdr.length);
1107 	if (res < 0)
1108 		return res;
1109 	if (res == 1 && critical_ext) {
1110 		wpa_printf(MSG_INFO, "X509: Unknown critical extension %s",
1111 			   buf);
1112 		//return -1;  //for wpa2 certification , commenout , ignore the error
1113 	}
1114 
1115 	return 0;
1116 }
1117 
1118 
x509_parse_extensions(struct x509_certificate * cert,const u8 * pos,size_t len)1119 static int x509_parse_extensions(struct x509_certificate *cert,
1120 				 const u8 *pos, size_t len)
1121 {
1122 	const u8 *end;
1123 	struct asn1_hdr hdr;
1124 
1125 	/* Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension */
1126 
1127 	if (asn1_get_next(pos, len, &hdr) < 0 ||
1128 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
1129 	    hdr.tag != ASN1_TAG_SEQUENCE) {
1130 		wpa_printf(MSG_DEBUG, "X509: Unexpected ASN.1 data "
1131 			   "for Extensions: class %d tag 0x%x; "
1132 			   "expected SEQUENCE", hdr.class, hdr.tag);
1133 		return -1;
1134 	}
1135 
1136 	pos = hdr.payload;
1137 	end = pos + hdr.length;
1138 
1139 	while (pos < end) {
1140 		if (x509_parse_extension(cert, pos, end - pos, &pos)
1141 		    < 0)
1142 			return -1;
1143 	}
1144 
1145 	return 0;
1146 }
1147 
1148 
x509_parse_tbs_certificate(const u8 * buf,size_t len,struct x509_certificate * cert,const u8 ** next)1149 static int x509_parse_tbs_certificate(const u8 *buf, size_t len,
1150 				      struct x509_certificate *cert,
1151 				      const u8 **next)
1152 {
1153 	struct asn1_hdr hdr;
1154 	const u8 *pos, *end;
1155 	size_t left;
1156 	char sbuf[128];
1157 	unsigned long value;
1158 
1159 	/* tbsCertificate TBSCertificate ::= SEQUENCE */
1160 	if (asn1_get_next(buf, len, &hdr) < 0 ||
1161 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
1162 	    hdr.tag != ASN1_TAG_SEQUENCE) {
1163 		wpa_printf(MSG_DEBUG, "X509: tbsCertificate did not start "
1164 			   "with a valid SEQUENCE - found class %d tag 0x%x",
1165 			   hdr.class, hdr.tag);
1166 		return -1;
1167 	}
1168 	pos = hdr.payload;
1169 	end = *next = pos + hdr.length;
1170 
1171 	/*
1172 	 * version [0]  EXPLICIT Version DEFAULT v1
1173 	 * Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
1174 	 */
1175 	if (asn1_get_next(pos, end - pos, &hdr) < 0)
1176 		return -1;
1177 	pos = hdr.payload;
1178 
1179 	if (hdr.class == ASN1_CLASS_CONTEXT_SPECIFIC) {
1180 		if (asn1_get_next(pos, end - pos, &hdr) < 0)
1181 			return -1;
1182 
1183 		if (hdr.class != ASN1_CLASS_UNIVERSAL ||
1184 		    hdr.tag != ASN1_TAG_INTEGER) {
1185 			wpa_printf(MSG_DEBUG, "X509: No INTEGER tag found for "
1186 				   "version field - found class %d tag 0x%x",
1187 				   hdr.class, hdr.tag);
1188 			return -1;
1189 		}
1190 		if (hdr.length != 1) {
1191 			wpa_printf(MSG_DEBUG, "X509: Unexpected version field "
1192 				   "length %u (expected 1)", hdr.length);
1193 			return -1;
1194 		}
1195 		pos = hdr.payload;
1196 		left = hdr.length;
1197 		value = 0;
1198 		while (left) {
1199 			value <<= 8;
1200 			value |= *pos++;
1201 			left--;
1202 		}
1203 
1204 		cert->version = value;
1205 		if (cert->version != X509_CERT_V1 &&
1206 		    cert->version != X509_CERT_V2 &&
1207 		    cert->version != X509_CERT_V3) {
1208 			wpa_printf(MSG_DEBUG, "X509: Unsupported version %d",
1209 				   cert->version + 1);
1210 			return -1;
1211 		}
1212 
1213 		if (asn1_get_next(pos, end - pos, &hdr) < 0)
1214 			return -1;
1215 	} else
1216 		cert->version = X509_CERT_V1;
1217 	wpa_printf(MSG_DEBUG, "X509: Version X.509v%d", cert->version + 1);
1218 
1219 	/* serialNumber CertificateSerialNumber ::= INTEGER */
1220 	if (hdr.class != ASN1_CLASS_UNIVERSAL ||
1221 	    hdr.tag != ASN1_TAG_INTEGER) {
1222 		wpa_printf(MSG_DEBUG, "X509: No INTEGER tag found for "
1223 			   "serialNumber; class=%d tag=0x%x",
1224 			   hdr.class, hdr.tag);
1225 		return -1;
1226 	}
1227 
1228 	pos = hdr.payload;
1229 	left = hdr.length;
1230 	while (left) {
1231 		cert->serial_number <<= 8;
1232 		cert->serial_number |= *pos++;
1233 		left--;
1234 	}
1235 	wpa_printf(MSG_DEBUG, "X509: serialNumber %lu", cert->serial_number);
1236 
1237 	/* signature AlgorithmIdentifier */
1238 	if (x509_parse_algorithm_identifier(pos, end - pos, &cert->signature,
1239 					    &pos))
1240 		return -1;
1241 
1242 	/* issuer Name */
1243 	if (x509_parse_name(pos, end - pos, &cert->issuer, &pos))
1244 		return -1;
1245 	x509_name_string(&cert->issuer, sbuf, sizeof(sbuf));
1246 	wpa_printf(MSG_DEBUG, "X509: issuer %s", sbuf);
1247 
1248 	/* validity Validity */
1249 	if (x509_parse_validity(pos, end - pos, cert, &pos))
1250 		return -1;
1251 
1252 	/* subject Name */
1253 	if (x509_parse_name(pos, end - pos, &cert->subject, &pos))
1254 		return -1;
1255 	x509_name_string(&cert->subject, sbuf, sizeof(sbuf));
1256 	wpa_printf(MSG_DEBUG, "X509: subject %s", sbuf);
1257 
1258 	/* subjectPublicKeyInfo SubjectPublicKeyInfo */
1259 	if (x509_parse_public_key(pos, end - pos, cert, &pos))
1260 		return -1;
1261 
1262 	if (pos == end)
1263 		return 0;
1264 
1265 	if (cert->version == X509_CERT_V1)
1266 		return 0;
1267 
1268 	if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
1269 	    hdr.class != ASN1_CLASS_CONTEXT_SPECIFIC) {
1270 		wpa_printf(MSG_DEBUG, "X509: Expected Context-Specific"
1271 			   " tag to parse optional tbsCertificate "
1272 			   "field(s); parsed class %d tag 0x%x",
1273 			   hdr.class, hdr.tag);
1274 		return -1;
1275 	}
1276 
1277 	if (hdr.tag == 1) {
1278 		/* issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL */
1279 		wpa_printf(MSG_DEBUG, "X509: issuerUniqueID");
1280 		/* TODO: parse UniqueIdentifier ::= BIT STRING */
1281 
1282 		if (hdr.payload + hdr.length == end)
1283 			return 0;
1284 
1285 		if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
1286 		    hdr.class != ASN1_CLASS_CONTEXT_SPECIFIC) {
1287 			wpa_printf(MSG_DEBUG, "X509: Expected Context-Specific"
1288 				   " tag to parse optional tbsCertificate "
1289 				   "field(s); parsed class %d tag 0x%x",
1290 				   hdr.class, hdr.tag);
1291 			return -1;
1292 		}
1293 	}
1294 
1295 	if (hdr.tag == 2) {
1296 		/* subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL */
1297 		wpa_printf(MSG_DEBUG, "X509: subjectUniqueID");
1298 		/* TODO: parse UniqueIdentifier ::= BIT STRING */
1299 
1300 		if (hdr.payload + hdr.length == end)
1301 			return 0;
1302 
1303 		if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
1304 		    hdr.class != ASN1_CLASS_CONTEXT_SPECIFIC) {
1305 			wpa_printf(MSG_DEBUG, "X509: Expected Context-Specific"
1306 				   " tag to parse optional tbsCertificate "
1307 				   "field(s); parsed class %d tag 0x%x",
1308 				   hdr.class, hdr.tag);
1309 			return -1;
1310 		}
1311 	}
1312 
1313 	if (hdr.tag != 3) {
1314 		wpa_printf(MSG_DEBUG, "X509: Ignored unexpected "
1315 			   "Context-Specific tag %d in optional "
1316 			   "tbsCertificate fields", hdr.tag);
1317 		return 0;
1318 	}
1319 
1320 	/* extensions      [3]  EXPLICIT Extensions OPTIONAL */
1321 
1322 	if (cert->version != X509_CERT_V3) {
1323 		wpa_printf(MSG_DEBUG, "X509: X.509%d certificate and "
1324 			   "Extensions data which are only allowed for "
1325 			   "version 3", cert->version + 1);
1326 		return -1;
1327 	}
1328 
1329 	if (x509_parse_extensions(cert, hdr.payload, hdr.length) < 0)
1330 		return -1;
1331 
1332 	pos = hdr.payload + hdr.length;
1333 	if (pos < end) {
1334 		wpa_hexdump(MSG_DEBUG,
1335 			    "X509: Ignored extra tbsCertificate data",
1336 			    pos, end - pos);
1337 	}
1338 
1339 	return 0;
1340 }
1341 
1342 
x509_rsadsi_oid(struct asn1_oid * oid)1343 static int x509_rsadsi_oid(struct asn1_oid *oid)
1344 {
1345 	return oid->len >= 4 &&
1346 		oid->oid[0] == 1 /* iso */ &&
1347 		oid->oid[1] == 2 /* member-body */ &&
1348 		oid->oid[2] == 840 /* us */ &&
1349 		oid->oid[3] == 113549 /* rsadsi */;
1350 }
1351 
1352 
x509_pkcs_oid(struct asn1_oid * oid)1353 static int x509_pkcs_oid(struct asn1_oid *oid)
1354 {
1355 	return oid->len >= 5 &&
1356 		x509_rsadsi_oid(oid) &&
1357 		oid->oid[4] == 1 /* pkcs */;
1358 }
1359 
1360 
x509_digest_oid(struct asn1_oid * oid)1361 static int x509_digest_oid(struct asn1_oid *oid)
1362 {
1363 	return oid->len >= 5 &&
1364 		x509_rsadsi_oid(oid) &&
1365 		oid->oid[4] == 2 /* digestAlgorithm */;
1366 }
1367 
x509_sha1_oid(struct asn1_oid * oid)1368 static int x509_sha1_oid(struct asn1_oid *oid)
1369 {
1370 	return oid->len == 6 &&
1371 		oid->oid[0] == 1 /* iso */ &&
1372 		oid->oid[1] == 3 /* identified-organization */ &&
1373 		oid->oid[2] == 14 /* oiw */ &&
1374 		oid->oid[3] == 3 /* secsig */ &&
1375 		oid->oid[4] == 2 /* algorithms */ &&
1376 		oid->oid[5] == 26 /* id-sha1 */;
1377 }
1378 
x509_sha2_oid(struct asn1_oid * oid)1379 static int x509_sha2_oid(struct asn1_oid *oid)
1380 {
1381 	return oid->len == 9 &&
1382 		oid->oid[0] == 2 /* joint-iso-itu-t */ &&
1383 		oid->oid[1] == 16 /* country */ &&
1384 		oid->oid[2] == 840 /* us */ &&
1385 		oid->oid[3] == 1 /* organization */ &&
1386 		oid->oid[4] == 101 /* gov */ &&
1387 		oid->oid[5] == 3 /* csor */ &&
1388 		oid->oid[6] == 4 /* nistAlgorithm */ &&
1389 		oid->oid[7] == 2 /* hashAlgs */;
1390 }
1391 
1392 
x509_sha256_oid(struct asn1_oid * oid)1393 static int x509_sha256_oid(struct asn1_oid *oid)
1394 {
1395 	return x509_sha2_oid(oid) &&
1396 		oid->oid[8] == 1 /* sha256 */;
1397 }
1398 
1399 
x509_sha384_oid(struct asn1_oid * oid)1400 static int x509_sha384_oid(struct asn1_oid *oid)
1401 {
1402 	return x509_sha2_oid(oid) &&
1403 		oid->oid[8] == 2 /* sha384 */;
1404 }
1405 
1406 
x509_sha512_oid(struct asn1_oid * oid)1407 static int x509_sha512_oid(struct asn1_oid *oid)
1408 {
1409 	return x509_sha2_oid(oid) &&
1410 		oid->oid[8] == 3 /* sha512 */;
1411 }
1412 
1413 
1414 /**
1415  * x509_certificate_parse - Parse a X.509 certificate in DER format
1416  * @buf: Pointer to the X.509 certificate in DER format
1417  * @len: Buffer length
1418  * Returns: Pointer to the parsed certificate or %NULL on failure
1419  *
1420  * Caller is responsible for freeing the returned certificate by calling
1421  * x509_certificate_free().
1422  */
x509_certificate_parse(const u8 * buf,size_t len)1423 struct x509_certificate * x509_certificate_parse(const u8 *buf, size_t len)
1424 {
1425 	struct asn1_hdr hdr;
1426 	const u8 *pos, *end, *hash_start;
1427 	struct x509_certificate *cert;
1428 
1429 	cert = (struct x509_certificate *)os_zalloc(sizeof(*cert) + len);
1430 	if (cert == NULL)
1431 		return NULL;
1432 	os_memcpy(cert + 1, buf, len);
1433 	cert->cert_start = (u8 *) (cert + 1);
1434 	cert->cert_len = len;
1435 
1436 	pos = buf;
1437 	end = buf + len;
1438 
1439 	/* RFC 3280 - X.509 v3 certificate / ASN.1 DER */
1440 
1441 	/* Certificate ::= SEQUENCE */
1442 	if (asn1_get_next(pos, len, &hdr) < 0 ||
1443 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
1444 	    hdr.tag != ASN1_TAG_SEQUENCE) {
1445 		wpa_printf(MSG_DEBUG, "X509: Certificate did not start with "
1446 			   "a valid SEQUENCE - found class %d tag 0x%x",
1447 			   hdr.class, hdr.tag);
1448 		x509_certificate_free(cert);
1449 		return NULL;
1450 	}
1451 	pos = hdr.payload;
1452 
1453 	if (pos + hdr.length > end) {
1454 		x509_certificate_free(cert);
1455 		return NULL;
1456 	}
1457 
1458 	if (pos + hdr.length < end) {
1459 		wpa_hexdump(MSG_MSGDUMP, "X509: Ignoring extra data after DER "
1460 			    "encoded certificate",
1461 			    pos + hdr.length, end - pos + hdr.length);
1462 		end = pos + hdr.length;
1463 	}
1464 
1465 	hash_start = pos;
1466 	cert->tbs_cert_start = cert->cert_start + (hash_start - buf);
1467 	if (x509_parse_tbs_certificate(pos, end - pos, cert, &pos)) {
1468 		x509_certificate_free(cert);
1469 		return NULL;
1470 	}
1471 	cert->tbs_cert_len = pos - hash_start;
1472 
1473 	/* signatureAlgorithm AlgorithmIdentifier */
1474 	if (x509_parse_algorithm_identifier(pos, end - pos,
1475 					    &cert->signature_alg, &pos)) {
1476 		x509_certificate_free(cert);
1477 		return NULL;
1478 	}
1479 
1480 	/* signatureValue BIT STRING */
1481 	if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
1482 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
1483 	    hdr.tag != ASN1_TAG_BITSTRING) {
1484 		wpa_printf(MSG_DEBUG, "X509: Expected BITSTRING "
1485 			   "(signatureValue) - found class %d tag 0x%x",
1486 			   hdr.class, hdr.tag);
1487 		x509_certificate_free(cert);
1488 		return NULL;
1489 	}
1490 	if (hdr.length < 1) {
1491 		x509_certificate_free(cert);
1492 		return NULL;
1493 	}
1494 	pos = hdr.payload;
1495 	if (*pos) {
1496 		wpa_printf(MSG_DEBUG, "X509: BITSTRING - %d unused bits",
1497 			   *pos);
1498 		/* PKCS #1 v1.5 10.2.1:
1499 		 * It is an error if the length in bits of the signature S is
1500 		 * not a multiple of eight.
1501 		 */
1502 		x509_certificate_free(cert);
1503 		return NULL;
1504 	}
1505 	os_free(cert->sign_value);
1506 	cert->sign_value = os_malloc(hdr.length - 1);
1507 	if (cert->sign_value == NULL) {
1508 		wpa_printf(MSG_DEBUG, "X509: Failed to allocate memory for "
1509 			   "signatureValue");
1510 		x509_certificate_free(cert);
1511 		return NULL;
1512 	}
1513 	os_memcpy(cert->sign_value, pos + 1, hdr.length - 1);
1514 	cert->sign_value_len = hdr.length - 1;
1515 	wpa_hexdump(MSG_MSGDUMP, "X509: signature",
1516 		    cert->sign_value, cert->sign_value_len);
1517 
1518 	return cert;
1519 }
1520 
1521 
1522 /**
1523  * x509_certificate_check_signature - Verify certificate signature
1524  * @issuer: Issuer certificate
1525  * @cert: Certificate to be verified
1526  * Returns: 0 if cert has a valid signature that was signed by the issuer,
1527  * -1 if not
1528  */
x509_certificate_check_signature(struct x509_certificate * issuer,struct x509_certificate * cert)1529 int x509_certificate_check_signature(struct x509_certificate *issuer,
1530 				     struct x509_certificate *cert)
1531 {
1532 	struct crypto_public_key *pk;
1533 	u8 *data;
1534 	const u8 *pos, *end, *next, *da_end;
1535 	size_t data_len;
1536 	struct asn1_hdr hdr;
1537 	struct asn1_oid oid;
1538 	u8 hash[64];
1539 	size_t hash_len;
1540 
1541 	if (!x509_pkcs_oid(&cert->signature.oid) ||
1542 	    cert->signature.oid.len != 7 ||
1543 	    cert->signature.oid.oid[5] != 1 /* pkcs-1 */) {
1544 		wpa_printf(MSG_DEBUG, "X509: Unrecognized signature "
1545 			   "algorithm");
1546 		return -1;
1547 	}
1548 
1549 	pk = crypto_public_key_import(issuer->public_key,
1550 				      issuer->public_key_len);
1551 	if (pk == NULL)
1552 		return -1;
1553 
1554 	data_len = cert->sign_value_len;
1555 	data = os_malloc(data_len);
1556 	if (data == NULL) {
1557 		crypto_public_key_free(pk);
1558 		return -1;
1559 	}
1560 
1561 	if (crypto_public_key_decrypt_pkcs1(pk, cert->sign_value,
1562 					    cert->sign_value_len, data,
1563 					    &data_len) < 0) {
1564 		wpa_printf(MSG_DEBUG, "X509: Failed to decrypt signature");
1565 		crypto_public_key_free(pk);
1566 		os_free(data);
1567 		return -1;
1568 	}
1569 	crypto_public_key_free(pk);
1570 
1571 	wpa_hexdump(MSG_MSGDUMP, "X509: Signature data D", data, data_len);
1572 
1573 	/*
1574 	 * PKCS #1 v1.5, 10.1.2:
1575 	 *
1576 	 * DigestInfo ::= SEQUENCE {
1577 	 *     digestAlgorithm DigestAlgorithmIdentifier,
1578 	 *     digest Digest
1579 	 * }
1580 	 *
1581 	 * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
1582 	 *
1583 	 * Digest ::= OCTET STRING
1584 	 *
1585 	 */
1586 	if (asn1_get_next(data, data_len, &hdr) < 0 ||
1587 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
1588 	    hdr.tag != ASN1_TAG_SEQUENCE) {
1589 		wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE "
1590 			   "(DigestInfo) - found class %d tag 0x%x",
1591 			   hdr.class, hdr.tag);
1592 		os_free(data);
1593 		return -1;
1594 	}
1595 
1596 	pos = hdr.payload;
1597 	end = pos + hdr.length;
1598 
1599 	/*
1600 	 * X.509:
1601 	 * AlgorithmIdentifier ::= SEQUENCE {
1602 	 *     algorithm            OBJECT IDENTIFIER,
1603 	 *     parameters           ANY DEFINED BY algorithm OPTIONAL
1604 	 * }
1605 	 */
1606 
1607 	if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
1608 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
1609 	    hdr.tag != ASN1_TAG_SEQUENCE) {
1610 		wpa_printf(MSG_DEBUG, "X509: Expected SEQUENCE "
1611 			   "(AlgorithmIdentifier) - found class %d tag 0x%x",
1612 			   hdr.class, hdr.tag);
1613 		os_free(data);
1614 		return -1;
1615 	}
1616 	da_end = hdr.payload + hdr.length;
1617 
1618 	if (asn1_get_oid(hdr.payload, hdr.length, &oid, &next)) {
1619 		wpa_printf(MSG_DEBUG, "X509: Failed to parse digestAlgorithm");
1620 		os_free(data);
1621 		return -1;
1622 	}
1623 
1624 	if (x509_sha1_oid(&oid)) {
1625 		if (cert->signature.oid.oid[6] !=
1626 		    5 /* sha-1WithRSAEncryption */) {
1627 			wpa_printf(MSG_DEBUG, "X509: digestAlgorithm SHA1 "
1628 				   "does not match with certificate "
1629 				   "signatureAlgorithm (%lu)",
1630 				   cert->signature.oid.oid[6]);
1631 			os_free(data);
1632 			return -1;
1633 		}
1634 		goto skip_digest_oid;
1635 	}
1636 
1637 	if (x509_sha256_oid(&oid)) {
1638 		if (cert->signature.oid.oid[6] !=
1639 		    11 /* sha2561WithRSAEncryption */) {
1640 			wpa_printf(MSG_DEBUG, "X509: digestAlgorithm SHA256 "
1641 				   "does not match with certificate "
1642 				   "signatureAlgorithm (%lu)",
1643 				   cert->signature.oid.oid[6]);
1644 			os_free(data);
1645 			return -1;
1646 		}
1647 		goto skip_digest_oid;
1648 	}
1649 
1650 	if (x509_sha384_oid(&oid)) {
1651 		if (cert->signature.oid.oid[6] !=
1652 		    12 /* sha384WithRSAEncryption */) {
1653 			wpa_printf(MSG_DEBUG, "X509: digestAlgorithm SHA384 "
1654 				   "does not match with certificate "
1655 				   "signatureAlgorithm (%lu)",
1656 				   cert->signature.oid.oid[6]);
1657 			os_free(data);
1658 			return -1;
1659 		}
1660 		goto skip_digest_oid;
1661 	}
1662 
1663 	if (x509_sha512_oid(&oid)) {
1664 		if (cert->signature.oid.oid[6] !=
1665 		    13 /* sha512WithRSAEncryption */) {
1666 			wpa_printf(MSG_DEBUG, "X509: digestAlgorithm SHA512 "
1667 				   "does not match with certificate "
1668 				   "signatureAlgorithm (%lu)",
1669 				   cert->signature.oid.oid[6]);
1670 			os_free(data);
1671 			return -1;
1672 		}
1673 		goto skip_digest_oid;
1674 	}
1675 
1676 	if (!x509_digest_oid(&oid)) {
1677 		wpa_printf(MSG_DEBUG, "X509: Unrecognized digestAlgorithm");
1678 		os_free(data);
1679 		return -1;
1680 	}
1681 	switch (oid.oid[5]) {
1682 	case 5: /* md5 */
1683 		if (cert->signature.oid.oid[6] != 4 /* md5WithRSAEncryption */)
1684 		{
1685 			wpa_printf(MSG_DEBUG, "X509: digestAlgorithm MD5 does "
1686 				   "not match with certificate "
1687 				   "signatureAlgorithm (%lu)",
1688 				   cert->signature.oid.oid[6]);
1689 			os_free(data);
1690 			return -1;
1691 		}
1692 		break;
1693 	case 2: /* md2 */
1694 	case 4: /* md4 */
1695 	default:
1696 		wpa_printf(MSG_DEBUG, "X509: Unsupported digestAlgorithm "
1697 			   "(%lu)", oid.oid[5]);
1698 		os_free(data);
1699 		return -1;
1700 	}
1701 
1702 skip_digest_oid:
1703 	/* Digest ::= OCTET STRING */
1704 	pos = da_end;
1705 	end = data + data_len;
1706 
1707 	if (asn1_get_next(pos, end - pos, &hdr) < 0 ||
1708 	    hdr.class != ASN1_CLASS_UNIVERSAL ||
1709 	    hdr.tag != ASN1_TAG_OCTETSTRING) {
1710 		wpa_printf(MSG_DEBUG, "X509: Expected OCTETSTRING "
1711 			   "(Digest) - found class %d tag 0x%x",
1712 			   hdr.class, hdr.tag);
1713 		os_free(data);
1714 		return -1;
1715 	}
1716 	wpa_hexdump(MSG_MSGDUMP, "X509: Decrypted Digest",
1717 		    hdr.payload, hdr.length);
1718 
1719 	switch (cert->signature.oid.oid[6]) {
1720 	case 4: /* md5WithRSAEncryption */
1721 		md5_vector(1, &cert->tbs_cert_start, &cert->tbs_cert_len,
1722 			   hash);
1723 		hash_len = 16;
1724 		wpa_hexdump(MSG_MSGDUMP, "X509: Certificate hash (MD5)",
1725 			    hash, hash_len);
1726 		break;
1727 	case 5: /* sha-1WithRSAEncryption */
1728 		sha1_vector(1, &cert->tbs_cert_start, &cert->tbs_cert_len,
1729 			    hash);
1730 		hash_len = 20;
1731 		wpa_hexdump(MSG_MSGDUMP, "X509: Certificate hash (SHA1)",
1732 			    hash, hash_len);
1733 		break;
1734 	case 11: /* sha256WithRSAEncryption */
1735 		sha256_vector(1, &cert->tbs_cert_start, &cert->tbs_cert_len,
1736 				                    hash);
1737 		hash_len = 32;
1738 		wpa_hexdump(MSG_MSGDUMP, "X509: Certificate hash (SHA256)",
1739 			    hash, hash_len);
1740 		break;
1741 	case 12: /* sha384WithRSAEncryption */
1742 		sha384_vector(1, &cert->tbs_cert_start, &cert->tbs_cert_len,
1743 			      hash);
1744 		hash_len = 48;
1745 		wpa_hexdump(MSG_MSGDUMP, "X509: Certificate hash (SHA384)",
1746 			    hash, hash_len);
1747 		break;
1748 	case 13: /* sha512WithRSAEncryption */
1749 		sha512_vector(1, &cert->tbs_cert_start, &cert->tbs_cert_len,
1750 			      hash);
1751 		hash_len = 64;
1752 		wpa_hexdump(MSG_MSGDUMP, "X509: Certificate hash (SHA512)",
1753 			    hash, hash_len);
1754 		break;
1755 	case 2: /* md2WithRSAEncryption */
1756 	default:
1757 		wpa_printf(MSG_INFO, "X509: Unsupported certificate signature "
1758 			   "algorithm (%lu)", cert->signature.oid.oid[6]);
1759 		os_free(data);
1760 		return -1;
1761 	}
1762 
1763 	if (hdr.length != hash_len ||
1764 	    os_memcmp(hdr.payload, hash, hdr.length) != 0) {
1765 		wpa_printf(MSG_INFO, "X509: Certificate Digest does not match "
1766 			   "with calculated tbsCertificate hash");
1767 		os_free(data);
1768 		return -1;
1769 	}
1770 
1771 	os_free(data);
1772 
1773 	wpa_printf(MSG_DEBUG, "X509: Certificate Digest matches with "
1774 		   "calculated tbsCertificate hash");
1775 
1776 	return 0;
1777 }
1778 
1779 
x509_valid_issuer(const struct x509_certificate * cert)1780 static int x509_valid_issuer(const struct x509_certificate *cert)
1781 {
1782 	if ((cert->extensions_present & X509_EXT_BASIC_CONSTRAINTS) &&
1783 	    !cert->ca) {
1784 		wpa_printf(MSG_DEBUG, "X509: Non-CA certificate used as an "
1785 			   "issuer");
1786 		return -1;
1787 	}
1788 
1789 	if (cert->version == X509_CERT_V3 &&
1790 	    !(cert->extensions_present & X509_EXT_BASIC_CONSTRAINTS)) {
1791 		wpa_printf(MSG_DEBUG, "X509: v3 CA certificate did not "
1792 			   "include BasicConstraints extension");
1793 		return -1;
1794 	}
1795 
1796 	if ((cert->extensions_present & X509_EXT_KEY_USAGE) &&
1797 	    !(cert->key_usage & X509_KEY_USAGE_KEY_CERT_SIGN)) {
1798 		wpa_printf(MSG_DEBUG, "X509: Issuer certificate did not have "
1799 			   "keyCertSign bit in Key Usage");
1800 		return -1;
1801 	}
1802 
1803 	return 0;
1804 }
1805 
1806 
1807 /**
1808  * x509_certificate_chain_validate - Validate X.509 certificate chain
1809  * @trusted: List of trusted certificates
1810  * @chain: Certificate chain to be validated (first chain must be issued by
1811  * signed by the second certificate in the chain and so on)
1812  * @reason: Buffer for returning failure reason (X509_VALIDATE_*)
1813  * Returns: 0 if chain is valid, -1 if not
1814  */
x509_certificate_chain_validate(struct x509_certificate * trusted,struct x509_certificate * chain,int * reason,int disable_time_checks)1815 int x509_certificate_chain_validate(struct x509_certificate *trusted,
1816 				    struct x509_certificate *chain,
1817 				    int *reason, int disable_time_checks)
1818 {
1819 	long unsigned idx;
1820 	int chain_trusted = 0;
1821 	struct x509_certificate *cert, *trust;
1822 	char buf[128];
1823 	struct os_time now;
1824 
1825 	*reason = X509_VALIDATE_OK;
1826 
1827 	wpa_printf(MSG_DEBUG, "X509: Validate certificate chain");
1828 	os_get_time(&now);
1829 
1830 	for (cert = chain, idx = 0; cert; cert = cert->next, idx++) {
1831 		x509_name_string(&cert->subject, buf, sizeof(buf));
1832 		wpa_printf(MSG_DEBUG, "X509: %lu: %s", idx, buf);
1833 
1834 		if (chain_trusted)
1835 			continue;
1836 
1837 		if (!disable_time_checks &&
1838 		    ((unsigned long) now.sec <
1839 		     (unsigned long) cert->not_before ||
1840 		     (unsigned long) now.sec >
1841 		     (unsigned long) cert->not_after)) {
1842 			wpa_printf(MSG_INFO, "X509: Certificate not valid "
1843 				   "(now=%lu not_before=%lu not_after=%lu)",
1844 				   (unsigned long)now.sec, (unsigned long)cert->not_before, (unsigned long)cert->not_after);
1845 			*reason = X509_VALIDATE_CERTIFICATE_EXPIRED;
1846 			return -1;
1847 		}
1848 
1849 		if (cert->next) {
1850 			if (x509_name_compare(&cert->issuer,
1851 					      &cert->next->subject) != 0) {
1852 				wpa_printf(MSG_DEBUG, "X509: Certificate "
1853 					   "chain issuer name mismatch");
1854 				x509_name_string(&cert->issuer, buf,
1855 						 sizeof(buf));
1856 				wpa_printf(MSG_DEBUG, "X509: cert issuer: %s",
1857 					   buf);
1858 				x509_name_string(&cert->next->subject, buf,
1859 						 sizeof(buf));
1860 				wpa_printf(MSG_DEBUG, "X509: next cert "
1861 					   "subject: %s", buf);
1862 				*reason = X509_VALIDATE_CERTIFICATE_UNKNOWN;
1863 				return -1;
1864 			}
1865 
1866 			if (x509_valid_issuer(cert->next) < 0) {
1867 				*reason = X509_VALIDATE_BAD_CERTIFICATE;
1868 				return -1;
1869 			}
1870 
1871 			if ((cert->next->extensions_present &
1872 			     X509_EXT_PATH_LEN_CONSTRAINT) &&
1873 			    idx > cert->next->path_len_constraint) {
1874 				wpa_printf(MSG_DEBUG, "X509: pathLenConstraint"
1875 					   " not met (idx=%lu issuer "
1876 					   "pathLenConstraint=%lu)", idx,
1877 					   cert->next->path_len_constraint);
1878 				*reason = X509_VALIDATE_BAD_CERTIFICATE;
1879 				return -1;
1880 			}
1881 
1882 			if (x509_certificate_check_signature(cert->next, cert)
1883 			    < 0) {
1884 				wpa_printf(MSG_DEBUG, "X509: Invalid "
1885 					   "certificate signature within "
1886 					   "chain");
1887 				*reason = X509_VALIDATE_BAD_CERTIFICATE;
1888 				return -1;
1889 			}
1890 		}
1891 
1892 		for (trust = trusted; trust; trust = trust->next) {
1893 			if (x509_name_compare(&cert->issuer, &trust->subject)
1894 			    == 0)
1895 				break;
1896 		}
1897 
1898 		if (trust) {
1899 			wpa_printf(MSG_DEBUG, "X509: Found issuer from the "
1900 				   "list of trusted certificates");
1901 			if (x509_valid_issuer(trust) < 0) {
1902 				*reason = X509_VALIDATE_BAD_CERTIFICATE;
1903 				return -1;
1904 			}
1905 
1906 			if (x509_certificate_check_signature(trust, cert) < 0)
1907 			{
1908 				wpa_printf(MSG_DEBUG, "X509: Invalid "
1909 					   "certificate signature");
1910 				*reason = X509_VALIDATE_BAD_CERTIFICATE;
1911 				return -1;
1912 			}
1913 
1914 			wpa_printf(MSG_DEBUG, "X509: Trusted certificate "
1915 				   "found to complete the chain");
1916 			chain_trusted = 1;
1917 		}
1918 	}
1919 
1920 	if (!chain_trusted) {
1921 		wpa_printf(MSG_DEBUG, "X509: Did not find any of the issuers "
1922 			   "from the list of trusted certificates");
1923 		if (trusted) {
1924 			*reason = X509_VALIDATE_UNKNOWN_CA;
1925 			return -1;
1926 		}
1927 		wpa_printf(MSG_DEBUG, "X509: Certificate chain validation "
1928 			   "disabled - ignore unknown CA issue");
1929 	}
1930 
1931 	wpa_printf(MSG_DEBUG, "X509: Certificate chain valid");
1932 
1933 	return 0;
1934 }
1935 
1936 
1937 /**
1938  * x509_certificate_get_subject - Get a certificate based on Subject name
1939  * @chain: Certificate chain to search through
1940  * @name: Subject name to search for
1941  * Returns: Pointer to the certificate with the given Subject name or
1942  * %NULL on failure
1943  */
1944 struct x509_certificate *
x509_certificate_get_subject(struct x509_certificate * chain,struct x509_name * name)1945 x509_certificate_get_subject(struct x509_certificate *chain,
1946 			     struct x509_name *name)
1947 {
1948 	struct x509_certificate *cert;
1949 
1950 	for (cert = chain; cert; cert = cert->next) {
1951 		if (x509_name_compare(&cert->subject, name) == 0)
1952 			return cert;
1953 	}
1954 	return NULL;
1955 }
1956 
1957 
1958 /**
1959  * x509_certificate_self_signed - Is the certificate self-signed?
1960  * @cert: Certificate
1961  * Returns: 1 if certificate is self-signed, 0 if not
1962  */
x509_certificate_self_signed(struct x509_certificate * cert)1963 int x509_certificate_self_signed(struct x509_certificate *cert)
1964 {
1965 	return x509_name_compare(&cert->issuer, &cert->subject) == 0;
1966 }
1967