9a5714bc95207a5be74a65d42ed671120ba0b938
[strongswan.git] / src / pluto / x509.c
1 /* Support of X.509 certificates
2 * Copyright (C) 2000 Andreas Hess, Patric Lichtsteiner, Roger Wegmann
3 * Copyright (C) 2001 Marco Bertossa, Andreas Schleiss
4 * Copyright (C) 2002 Mario Strasser
5 * Copyright (C) 2000-2009 Andreas Steffen - Hochschule fuer Technik Rapperswil
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2 of the License, or (at your
10 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * for more details.
16 */
17
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <unistd.h>
22 #include <dirent.h>
23 #include <time.h>
24 #include <sys/types.h>
25
26 #include <freeswan.h>
27
28 #include <asn1/asn1.h>
29 #include <asn1/asn1_parser.h>
30 #include <asn1/oid.h>
31 #include <crypto/hashers/hasher.h>
32
33 #include "constants.h"
34 #include "defs.h"
35 #include "mp_defs.h"
36 #include "log.h"
37 #include "id.h"
38 #include "pkcs1.h"
39 #include "x509.h"
40 #include "crl.h"
41 #include "ca.h"
42 #include "certs.h"
43 #include "keys.h"
44 #include "whack.h"
45 #include "fetch.h"
46 #include "ocsp.h"
47
48 /**
49 * Chained lists of X.509 end certificates
50 */
51 static x509cert_t *x509certs = NULL;
52
53 /**
54 * ASN.1 definition of a basicConstraints extension
55 */
56 static const asn1Object_t basicConstraintsObjects[] = {
57 { 0, "basicConstraints", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
58 { 1, "CA", ASN1_BOOLEAN, ASN1_DEF|ASN1_BODY }, /* 1 */
59 { 1, "pathLenConstraint", ASN1_INTEGER, ASN1_OPT|ASN1_BODY }, /* 2 */
60 { 1, "end opt", ASN1_EOC, ASN1_END }, /* 3 */
61 { 0, "exit", ASN1_EOC, ASN1_EXIT }
62 };
63 #define BASIC_CONSTRAINTS_CA 1
64
65 /**
66 * ASN.1 definition of a authorityKeyIdentifier extension
67 */
68 static const asn1Object_t authKeyIdentifierObjects[] = {
69 { 0, "authorityKeyIdentifier", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
70 { 1, "keyIdentifier", ASN1_CONTEXT_S_0, ASN1_OPT|ASN1_BODY }, /* 1 */
71 { 1, "end opt", ASN1_EOC, ASN1_END }, /* 2 */
72 { 1, "authorityCertIssuer", ASN1_CONTEXT_C_1, ASN1_OPT|ASN1_OBJ }, /* 3 */
73 { 1, "end opt", ASN1_EOC, ASN1_END }, /* 4 */
74 { 1, "authorityCertSerialNumber", ASN1_CONTEXT_S_2, ASN1_OPT|ASN1_BODY }, /* 5 */
75 { 1, "end opt", ASN1_EOC, ASN1_END }, /* 6 */
76 { 0, "exit", ASN1_EOC, ASN1_EXIT }
77 };
78 #define AUTH_KEY_ID_KEY_ID 1
79 #define AUTH_KEY_ID_CERT_ISSUER 3
80 #define AUTH_KEY_ID_CERT_SERIAL 5
81
82 /**
83 * ASN.1 definition of a authorityInfoAccess extension
84 */
85 static const asn1Object_t authInfoAccessObjects[] = {
86 { 0, "authorityInfoAccess", ASN1_SEQUENCE, ASN1_LOOP }, /* 0 */
87 { 1, "accessDescription", ASN1_SEQUENCE, ASN1_NONE }, /* 1 */
88 { 2, "accessMethod", ASN1_OID, ASN1_BODY }, /* 2 */
89 { 2, "accessLocation", ASN1_EOC, ASN1_RAW }, /* 3 */
90 { 0, "end loop", ASN1_EOC, ASN1_END }, /* 4 */
91 { 0, "exit", ASN1_EOC, ASN1_EXIT }
92 };
93 #define AUTH_INFO_ACCESS_METHOD 2
94 #define AUTH_INFO_ACCESS_LOCATION 3
95
96 /**
97 * ASN.1 definition of a extendedKeyUsage extension
98 */
99 static const asn1Object_t extendedKeyUsageObjects[] = {
100 { 0, "extendedKeyUsage", ASN1_SEQUENCE, ASN1_LOOP }, /* 0 */
101 { 1, "keyPurposeID", ASN1_OID, ASN1_BODY }, /* 1 */
102 { 0, "end loop", ASN1_EOC, ASN1_END }, /* 2 */
103 { 0, "exit", ASN1_EOC, ASN1_EXIT }
104 };
105 #define EXT_KEY_USAGE_PURPOSE_ID 1
106
107 /**
108 * ASN.1 definition of generalNames
109 */
110 static const asn1Object_t generalNamesObjects[] = {
111 { 0, "generalNames", ASN1_SEQUENCE, ASN1_LOOP }, /* 0 */
112 { 1, "generalName", ASN1_EOC, ASN1_RAW }, /* 1 */
113 { 0, "end loop", ASN1_EOC, ASN1_END }, /* 2 */
114 { 0, "exit", ASN1_EOC, ASN1_EXIT }
115 };
116 #define GENERAL_NAMES_GN 1
117
118 /**
119 * ASN.1 definition of generalName
120 */
121 static const asn1Object_t generalNameObjects[] = {
122 { 0, "otherName", ASN1_CONTEXT_C_0, ASN1_OPT|ASN1_BODY }, /* 0 */
123 { 0, "end choice", ASN1_EOC, ASN1_END }, /* 1 */
124 { 0, "rfc822Name", ASN1_CONTEXT_S_1, ASN1_OPT|ASN1_BODY }, /* 2 */
125 { 0, "end choice", ASN1_EOC, ASN1_END }, /* 3 */
126 { 0, "dnsName", ASN1_CONTEXT_S_2, ASN1_OPT|ASN1_BODY }, /* 4 */
127 { 0, "end choice", ASN1_EOC, ASN1_END }, /* 5 */
128 { 0, "x400Address", ASN1_CONTEXT_S_3, ASN1_OPT|ASN1_BODY }, /* 6 */
129 { 0, "end choice", ASN1_EOC, ASN1_END }, /* 7 */
130 { 0, "directoryName", ASN1_CONTEXT_C_4, ASN1_OPT|ASN1_BODY }, /* 8 */
131 { 0, "end choice", ASN1_EOC, ASN1_END }, /* 9 */
132 { 0, "ediPartyName", ASN1_CONTEXT_C_5, ASN1_OPT|ASN1_BODY }, /* 10 */
133 { 0, "end choice", ASN1_EOC, ASN1_END }, /* 11 */
134 { 0, "URI", ASN1_CONTEXT_S_6, ASN1_OPT|ASN1_BODY }, /* 12 */
135 { 0, "end choice", ASN1_EOC, ASN1_END }, /* 13 */
136 { 0, "ipAddress", ASN1_CONTEXT_S_7, ASN1_OPT|ASN1_BODY }, /* 14 */
137 { 0, "end choice", ASN1_EOC, ASN1_END }, /* 15 */
138 { 0, "registeredID", ASN1_CONTEXT_S_8, ASN1_OPT|ASN1_BODY }, /* 16 */
139 { 0, "end choice", ASN1_EOC, ASN1_END }, /* 17 */
140 { 0, "exit", ASN1_EOC, ASN1_EXIT }
141 };
142 #define GN_OBJ_OTHER_NAME 0
143 #define GN_OBJ_RFC822_NAME 2
144 #define GN_OBJ_DNS_NAME 4
145 #define GN_OBJ_X400_ADDRESS 6
146 #define GN_OBJ_DIRECTORY_NAME 8
147 #define GN_OBJ_EDI_PARTY_NAME 10
148 #define GN_OBJ_URI 12
149 #define GN_OBJ_IP_ADDRESS 14
150 #define GN_OBJ_REGISTERED_ID 16
151
152 /**
153 * ASN.1 definition of otherName
154 */
155 static const asn1Object_t otherNameObjects[] = {
156 {0, "type-id", ASN1_OID, ASN1_BODY }, /* 0 */
157 {0, "value", ASN1_CONTEXT_C_0, ASN1_BODY }, /* 1 */
158 {0, "exit", ASN1_EOC, ASN1_EXIT }
159 };
160 #define ON_OBJ_ID_TYPE 0
161 #define ON_OBJ_VALUE 1
162
163 /**
164 * ASN.1 definition of crlDistributionPoints
165 */
166 static const asn1Object_t crlDistributionPointsObjects[] = {
167 { 0, "crlDistributionPoints", ASN1_SEQUENCE, ASN1_LOOP }, /* 0 */
168 { 1, "DistributionPoint", ASN1_SEQUENCE, ASN1_NONE }, /* 1 */
169 { 2, "distributionPoint", ASN1_CONTEXT_C_0, ASN1_OPT|ASN1_LOOP }, /* 2 */
170 { 3, "fullName", ASN1_CONTEXT_C_0, ASN1_OPT|ASN1_OBJ }, /* 3 */
171 { 3, "end choice", ASN1_EOC, ASN1_END }, /* 4 */
172 { 3, "nameRelToCRLIssuer",ASN1_CONTEXT_C_1, ASN1_OPT|ASN1_BODY }, /* 5 */
173 { 3, "end choice", ASN1_EOC, ASN1_END }, /* 6 */
174 { 2, "end opt", ASN1_EOC, ASN1_END }, /* 7 */
175 { 2, "reasons", ASN1_CONTEXT_C_1, ASN1_OPT|ASN1_BODY }, /* 8 */
176 { 2, "end opt", ASN1_EOC, ASN1_END }, /* 9 */
177 { 2, "crlIssuer", ASN1_CONTEXT_C_2, ASN1_OPT|ASN1_BODY }, /* 10 */
178 { 2, "end opt", ASN1_EOC, ASN1_END }, /* 11 */
179 { 0, "end loop", ASN1_EOC, ASN1_END }, /* 12 */
180 { 0, "exit", ASN1_EOC, ASN1_EXIT }
181 };
182 #define CRL_DIST_POINTS_FULLNAME 3
183
184 /**
185 * ASN.1 definition of RSApublicKey
186 */
187 static const asn1Object_t pubkeyObjects[] = {
188 { 0, "RSAPublicKey", ASN1_SEQUENCE, ASN1_OBJ }, /* 0 */
189 { 1, "modulus", ASN1_INTEGER, ASN1_BODY }, /* 1 */
190 { 1, "publicExponent", ASN1_INTEGER, ASN1_BODY }, /* 2 */
191 { 0, "exit", ASN1_EOC, ASN1_EXIT }
192 };
193 #define PUB_KEY_RSA_PUBLIC_KEY 0
194 #define PUB_KEY_MODULUS 1
195 #define PUB_KEY_EXPONENT 2
196
197 /**
198 * ASN.1 definition of an X.509v3 x509_cert
199 */
200 static const asn1Object_t certObjects[] = {
201 { 0, "certificate", ASN1_SEQUENCE, ASN1_OBJ }, /* 0 */
202 { 1, "tbsCertificate", ASN1_SEQUENCE, ASN1_OBJ }, /* 1 */
203 { 2, "DEFAULT v1", ASN1_CONTEXT_C_0, ASN1_DEF }, /* 2 */
204 { 3, "version", ASN1_INTEGER, ASN1_BODY }, /* 3 */
205 { 2, "serialNumber", ASN1_INTEGER, ASN1_BODY }, /* 4 */
206 { 2, "signature", ASN1_EOC, ASN1_RAW }, /* 5 */
207 { 2, "issuer", ASN1_SEQUENCE, ASN1_OBJ }, /* 6 */
208 { 2, "validity", ASN1_SEQUENCE, ASN1_NONE }, /* 7 */
209 { 3, "notBefore", ASN1_EOC, ASN1_RAW }, /* 8 */
210 { 3, "notAfter", ASN1_EOC, ASN1_RAW }, /* 9 */
211 { 2, "subject", ASN1_SEQUENCE, ASN1_OBJ }, /* 10 */
212 { 2, "subjectPublicKeyInfo", ASN1_SEQUENCE, ASN1_NONE }, /* 11 */
213 { 3, "algorithm", ASN1_EOC, ASN1_RAW }, /* 12 */
214 { 3, "subjectPublicKey", ASN1_BIT_STRING, ASN1_BODY }, /* 13 */
215 { 2, "issuerUniqueID", ASN1_CONTEXT_C_1, ASN1_OPT }, /* 14 */
216 { 2, "end opt", ASN1_EOC, ASN1_END }, /* 15 */
217 { 2, "subjectUniqueID", ASN1_CONTEXT_C_2, ASN1_OPT }, /* 16 */
218 { 2, "end opt", ASN1_EOC, ASN1_END }, /* 17 */
219 { 2, "optional extensions", ASN1_CONTEXT_C_3, ASN1_OPT }, /* 18 */
220 { 3, "extensions", ASN1_SEQUENCE, ASN1_LOOP }, /* 19 */
221 { 4, "extension", ASN1_SEQUENCE, ASN1_NONE }, /* 20 */
222 { 5, "extnID", ASN1_OID, ASN1_BODY }, /* 21 */
223 { 5, "critical", ASN1_BOOLEAN, ASN1_DEF |
224 ASN1_BODY }, /* 22 */
225 { 5, "extnValue", ASN1_OCTET_STRING, ASN1_BODY }, /* 23 */
226 { 3, "end loop", ASN1_EOC, ASN1_END }, /* 24 */
227 { 2, "end opt", ASN1_EOC, ASN1_END }, /* 25 */
228 { 1, "signatureAlgorithm", ASN1_EOC, ASN1_RAW }, /* 26 */
229 { 1, "signatureValue", ASN1_BIT_STRING, ASN1_BODY }, /* 27 */
230 { 0, "exit", ASN1_EOC, ASN1_EXIT }
231 };
232 #define X509_OBJ_CERTIFICATE 0
233 #define X509_OBJ_TBS_CERTIFICATE 1
234 #define X509_OBJ_VERSION 3
235 #define X509_OBJ_SERIAL_NUMBER 4
236 #define X509_OBJ_SIG_ALG 5
237 #define X509_OBJ_ISSUER 6
238 #define X509_OBJ_NOT_BEFORE 8
239 #define X509_OBJ_NOT_AFTER 9
240 #define X509_OBJ_SUBJECT 10
241 #define X509_OBJ_SUBJECT_PUBLIC_KEY_ALGORITHM 12
242 #define X509_OBJ_SUBJECT_PUBLIC_KEY 13
243 #define X509_OBJ_EXTN_ID 21
244 #define X509_OBJ_CRITICAL 22
245 #define X509_OBJ_EXTN_VALUE 23
246 #define X509_OBJ_ALGORITHM 26
247 #define X509_OBJ_SIGNATURE 27
248
249 const x509cert_t empty_x509cert = {
250 NULL , /* *next */
251 UNDEFINED_TIME, /* installed */
252 0 , /* count */
253 FALSE , /* smartcard */
254 AUTH_NONE , /* authority_flags */
255 { NULL, 0 } , /* certificate */
256 { NULL, 0 } , /* tbsCertificate */
257 1 , /* version */
258 { NULL, 0 } , /* serialNumber */
259 OID_UNKNOWN , /* sigAlg */
260 { NULL, 0 } , /* issuer */
261 /* validity */
262 0 , /* notBefore */
263 0 , /* notAfter */
264 { NULL, 0 } , /* subject */
265 /* subjectPublicKeyInfo */
266 OID_UNKNOWN , /* subjectPublicKeyAlgorithm */
267 { NULL, 0 } , /* subjectPublicKey */
268 { NULL, 0 } , /* modulus */
269 { NULL, 0 } , /* publicExponent */
270 /* issuerUniqueID */
271 /* subjectUniqueID */
272 /* extensions */
273 /* extension */
274 /* extnID */
275 /* critical */
276 /* extnValue */
277 FALSE , /* isCA */
278 FALSE , /* isOcspSigner */
279 { NULL, 0 } , /* subjectKeyID */
280 { NULL, 0 } , /* authKeyID */
281 { NULL, 0 } , /* authKeySerialNumber */
282 { NULL, 0 } , /* accessLocation */
283 NULL , /* subjectAltName */
284 NULL , /* crlDistributionPoints */
285 OID_UNKNOWN , /* algorithm */
286 { NULL, 0 } /* signature */
287 };
288
289 /* coding of X.501 distinguished name */
290
291 typedef struct {
292 const u_char *name;
293 chunk_t oid;
294 u_char type;
295 } x501rdn_t;
296
297 /* X.501 acronyms for well known object identifiers (OIDs) */
298
299 static u_char oid_ND[] = {0x02, 0x82, 0x06, 0x01,
300 0x0A, 0x07, 0x14};
301 static u_char oid_UID[] = {0x09, 0x92, 0x26, 0x89, 0x93,
302 0xF2, 0x2C, 0x64, 0x01, 0x01};
303 static u_char oid_DC[] = {0x09, 0x92, 0x26, 0x89, 0x93,
304 0xF2, 0x2C, 0x64, 0x01, 0x19};
305 static u_char oid_CN[] = {0x55, 0x04, 0x03};
306 static u_char oid_S[] = {0x55, 0x04, 0x04};
307 static u_char oid_SN[] = {0x55, 0x04, 0x05};
308 static u_char oid_C[] = {0x55, 0x04, 0x06};
309 static u_char oid_L[] = {0x55, 0x04, 0x07};
310 static u_char oid_ST[] = {0x55, 0x04, 0x08};
311 static u_char oid_O[] = {0x55, 0x04, 0x0A};
312 static u_char oid_OU[] = {0x55, 0x04, 0x0B};
313 static u_char oid_T[] = {0x55, 0x04, 0x0C};
314 static u_char oid_D[] = {0x55, 0x04, 0x0D};
315 static u_char oid_N[] = {0x55, 0x04, 0x29};
316 static u_char oid_G[] = {0x55, 0x04, 0x2A};
317 static u_char oid_I[] = {0x55, 0x04, 0x2B};
318 static u_char oid_ID[] = {0x55, 0x04, 0x2D};
319 static u_char oid_EN[] = {0x60, 0x86, 0x48, 0x01, 0x86,
320 0xF8, 0x42, 0x03, 0x01, 0x03};
321 static u_char oid_E[] = {0x2A, 0x86, 0x48, 0x86, 0xF7,
322 0x0D, 0x01, 0x09, 0x01};
323 static u_char oid_UN[] = {0x2A, 0x86, 0x48, 0x86, 0xF7,
324 0x0D, 0x01, 0x09, 0x02};
325 static u_char oid_TCGID[] = {0x2B, 0x06, 0x01, 0x04, 0x01, 0x89,
326 0x31, 0x01, 0x01, 0x02, 0x02, 0x4B};
327
328 static const x501rdn_t x501rdns[] = {
329 {"ND" , {oid_ND, 7}, ASN1_PRINTABLESTRING},
330 {"UID" , {oid_UID, 10}, ASN1_PRINTABLESTRING},
331 {"DC" , {oid_DC, 10}, ASN1_PRINTABLESTRING},
332 {"CN" , {oid_CN, 3}, ASN1_PRINTABLESTRING},
333 {"S" , {oid_S, 3}, ASN1_PRINTABLESTRING},
334 {"SN" , {oid_SN, 3}, ASN1_PRINTABLESTRING},
335 {"serialNumber" , {oid_SN, 3}, ASN1_PRINTABLESTRING},
336 {"C" , {oid_C, 3}, ASN1_PRINTABLESTRING},
337 {"L" , {oid_L, 3}, ASN1_PRINTABLESTRING},
338 {"ST" , {oid_ST, 3}, ASN1_PRINTABLESTRING},
339 {"O" , {oid_O, 3}, ASN1_PRINTABLESTRING},
340 {"OU" , {oid_OU, 3}, ASN1_PRINTABLESTRING},
341 {"T" , {oid_T, 3}, ASN1_PRINTABLESTRING},
342 {"D" , {oid_D, 3}, ASN1_PRINTABLESTRING},
343 {"N" , {oid_N, 3}, ASN1_PRINTABLESTRING},
344 {"G" , {oid_G, 3}, ASN1_PRINTABLESTRING},
345 {"I" , {oid_I, 3}, ASN1_PRINTABLESTRING},
346 {"ID" , {oid_ID, 3}, ASN1_PRINTABLESTRING},
347 {"EN" , {oid_EN, 10}, ASN1_PRINTABLESTRING},
348 {"employeeNumber" , {oid_EN, 10}, ASN1_PRINTABLESTRING},
349 {"E" , {oid_E, 9}, ASN1_IA5STRING},
350 {"Email" , {oid_E, 9}, ASN1_IA5STRING},
351 {"emailAddress" , {oid_E, 9}, ASN1_IA5STRING},
352 {"UN" , {oid_UN, 9}, ASN1_IA5STRING},
353 {"unstructuredName", {oid_UN, 9}, ASN1_IA5STRING},
354 {"TCGID" , {oid_TCGID, 12}, ASN1_PRINTABLESTRING}
355 };
356
357 #define X501_RDN_ROOF 26
358
359 static u_char ASN1_subjectAltName_oid_str[] = {
360 0x06, 0x03, 0x55, 0x1D, 0x11
361 };
362
363 static const chunk_t ASN1_subjectAltName_oid = chunk_from_buf(ASN1_subjectAltName_oid_str);
364
365 static void update_chunk(chunk_t *ch, int n)
366 {
367 n = (n > -1 && n < (int)ch->len)? n : (int)ch->len-1;
368 ch->ptr += n; ch->len -= n;
369 }
370
371
372 /**
373 * Pointer is set to the first RDN in a DN
374 */
375 static err_t init_rdn(chunk_t dn, chunk_t *rdn, chunk_t *attribute, bool *next)
376 {
377 *rdn = chunk_empty;
378 *attribute = chunk_empty;
379
380 /* a DN is a SEQUENCE OF RDNs */
381
382 if (*dn.ptr != ASN1_SEQUENCE)
383 {
384 return "DN is not a SEQUENCE";
385 }
386
387 rdn->len = asn1_length(&dn);
388
389 if (rdn->len == ASN1_INVALID_LENGTH)
390 {
391 return "Invalid RDN length";
392 }
393 rdn->ptr = dn.ptr;
394
395 /* are there any RDNs ? */
396 *next = rdn->len > 0;
397
398 return NULL;
399 }
400
401 /**
402 * Fetches the next RDN in a DN
403 */
404 static err_t get_next_rdn(chunk_t *rdn, chunk_t * attribute, chunk_t *oid,
405 chunk_t *value, asn1_t *type, bool *next)
406 {
407 chunk_t body;
408
409 /* initialize return values */
410 *oid = chunk_empty;
411 *value = chunk_empty;
412
413 /* if all attributes have been parsed, get next rdn */
414 if (attribute->len <= 0)
415 {
416 /* an RDN is a SET OF attributeTypeAndValue */
417 if (*rdn->ptr != ASN1_SET)
418 {
419 return "RDN is not a SET";
420 }
421 attribute->len = asn1_length(rdn);
422
423 if (attribute->len == ASN1_INVALID_LENGTH)
424 {
425 return "Invalid attribute length";
426 }
427 attribute->ptr = rdn->ptr;
428
429 /* advance to start of next RDN */
430 rdn->ptr += attribute->len;
431 rdn->len -= attribute->len;
432 }
433
434 /* an attributeTypeAndValue is a SEQUENCE */
435 if (*attribute->ptr != ASN1_SEQUENCE)
436 {
437 return "attributeTypeAndValue is not a SEQUENCE";
438 }
439
440 /* extract the attribute body */
441 body.len = asn1_length(attribute);
442
443 if (body.len == ASN1_INVALID_LENGTH)
444 {
445 return "Invalid attribute body length";
446 }
447 body.ptr = attribute->ptr;
448
449 /* advance to start of next attribute */
450 attribute->ptr += body.len;
451 attribute->len -= body.len;
452
453 /* attribute type is an OID */
454 if (*body.ptr != ASN1_OID)
455 {
456 return "attributeType is not an OID";
457 }
458
459 /* extract OID */
460 oid->len = asn1_length(&body);
461
462 if (oid->len == ASN1_INVALID_LENGTH)
463 {
464 return "Invalid attribute OID length";
465 }
466 oid->ptr = body.ptr;
467
468 /* advance to the attribute value */
469 body.ptr += oid->len;
470 body.len -= oid->len;
471
472 /* extract string type */
473 *type = *body.ptr;
474
475 /* extract string value */
476 value->len = asn1_length(&body);
477
478 if (value->len == ASN1_INVALID_LENGTH)
479 {
480 return "Invalid attribute string length";
481 }
482 value->ptr = body.ptr;
483
484 /* are there any RDNs left? */
485 *next = rdn->len > 0 || attribute->len > 0;
486
487 return NULL;
488 }
489
490 /**
491 * Parses an ASN.1 distinguished name int its OID/value pairs
492 */
493 static err_t dn_parse(chunk_t dn, chunk_t *str)
494 {
495 chunk_t rdn, oid, attribute, value;
496 asn1_t type;
497 int oid_code;
498 bool next;
499 bool first = TRUE;
500
501 err_t ugh = init_rdn(dn, &rdn, &attribute, &next);
502
503 if (ugh != NULL) /* a parsing error has occured */
504 {
505 return ugh;
506 }
507
508 while (next)
509 {
510 ugh = get_next_rdn(&rdn, &attribute, &oid, &value, &type, &next);
511
512 if (ugh != NULL) /* a parsing error has occured */
513 {
514 return ugh;
515 }
516
517 if (first) /* first OID/value pair */
518 {
519 first = FALSE;
520 }
521 else /* separate OID/value pair by a comma */
522 {
523 update_chunk(str, snprintf(str->ptr,str->len,", "));
524 }
525
526 /* print OID */
527 oid_code = asn1_known_oid(oid);
528 if (oid_code == OID_UNKNOWN) /* OID not found in list */
529 {
530 hex_str(oid, str);
531 }
532 else
533 {
534 update_chunk(str, snprintf(str->ptr,str->len,"%s",
535 oid_names[oid_code].name));
536 }
537
538 /* print value */
539 update_chunk(str, snprintf(str->ptr,str->len,"=%.*s",
540 (int)value.len,value.ptr));
541 }
542 return NULL;
543 }
544
545 /**
546 * Count the number of wildcard RDNs in a distinguished name
547 */
548 int dn_count_wildcards(chunk_t dn)
549 {
550 chunk_t rdn, attribute, oid, value;
551 asn1_t type;
552 bool next;
553 int wildcards = 0;
554
555 err_t ugh = init_rdn(dn, &rdn, &attribute, &next);
556
557 if (ugh != NULL) /* a parsing error has occured */
558 {
559 return -1;
560 }
561
562 while (next)
563 {
564 ugh = get_next_rdn(&rdn, &attribute, &oid, &value, &type, &next);
565
566 if (ugh != NULL) /* a parsing error has occured */
567 {
568 return -1;
569 }
570 if (value.len == 1 && *value.ptr == '*')
571 {
572 wildcards++; /* we have found a wildcard RDN */
573 }
574 }
575 return wildcards;
576 }
577
578 /**
579 * Prints a binary string in hexadecimal form
580 */
581 void hex_str(chunk_t bin, chunk_t *str)
582 {
583 u_int i;
584 update_chunk(str, snprintf(str->ptr,str->len,"0x"));
585 for (i=0; i < bin.len; i++)
586 update_chunk(str, snprintf(str->ptr,str->len,"%02X",*bin.ptr++));
587 }
588
589
590 /** Converts a binary DER-encoded ASN.1 distinguished name
591 * into LDAP-style human-readable ASCII format
592 */
593 int dntoa(char *dst, size_t dstlen, chunk_t dn)
594 {
595 err_t ugh = NULL;
596 chunk_t str;
597
598 str.ptr = dst;
599 str.len = dstlen;
600 ugh = dn_parse(dn, &str);
601
602 if (ugh != NULL) /* error, print DN as hex string */
603 {
604 DBG(DBG_PARSING,
605 DBG_log("error in DN parsing: %s", ugh)
606 )
607 str.ptr = dst;
608 str.len = dstlen;
609 hex_str(dn, &str);
610 }
611 return (int)(dstlen - str.len);
612 }
613
614 /**
615 * Same as dntoa but prints a special string for a null dn
616 */
617 int dntoa_or_null(char *dst, size_t dstlen, chunk_t dn, const char* null_dn)
618 {
619 if (dn.ptr == NULL)
620 {
621 return snprintf(dst, dstlen, "%s", null_dn);
622 }
623 else
624 {
625 return dntoa(dst, dstlen, dn);
626 }
627 }
628
629
630 /**
631 * Codes ASN.1 lengths up to a size of 16'777'215 bytes
632 */
633 static void code_asn1_length(size_t length, chunk_t *code)
634 {
635 if (length < 128)
636 {
637 code->ptr[0] = length;
638 code->len = 1;
639 }
640 else if (length < 256)
641 {
642 code->ptr[0] = 0x81;
643 code->ptr[1] = (u_char) length;
644 code->len = 2;
645 }
646 else if (length < 65536)
647 {
648 code->ptr[0] = 0x82;
649 code->ptr[1] = length >> 8;
650 code->ptr[2] = length & 0x00ff;
651 code->len = 3;
652 }
653 else
654 {
655 code->ptr[0] = 0x83;
656 code->ptr[1] = length >> 16;
657 code->ptr[2] = (length >> 8) & 0x00ff;
658 code->ptr[3] = length & 0x0000ff;
659 code->len = 4;
660 }
661 }
662
663 /**
664 * Converts an LDAP-style human-readable ASCII-encoded
665 * ASN.1 distinguished name into binary DER-encoded format
666 */
667 err_t atodn(char *src, chunk_t *dn)
668 {
669 /* finite state machine for atodn */
670
671 typedef enum {
672 SEARCH_OID = 0,
673 READ_OID = 1,
674 SEARCH_NAME = 2,
675 READ_NAME = 3,
676 UNKNOWN_OID = 4
677 } state_t;
678
679 u_char oid_len_buf[3];
680 u_char name_len_buf[3];
681 u_char rdn_seq_len_buf[3];
682 u_char rdn_set_len_buf[3];
683 u_char dn_seq_len_buf[3];
684
685 chunk_t asn1_oid_len = { oid_len_buf, 0 };
686 chunk_t asn1_name_len = { name_len_buf, 0 };
687 chunk_t asn1_rdn_seq_len = { rdn_seq_len_buf, 0 };
688 chunk_t asn1_rdn_set_len = { rdn_set_len_buf, 0 };
689 chunk_t asn1_dn_seq_len = { dn_seq_len_buf, 0 };
690 chunk_t oid = chunk_empty;
691 chunk_t name = chunk_empty;
692
693 int whitespace = 0;
694 int rdn_seq_len = 0;
695 int rdn_set_len = 0;
696 int dn_seq_len = 0;
697 int pos = 0;
698
699 err_t ugh = NULL;
700
701 u_char *dn_ptr = dn->ptr + 4;
702
703 state_t state = SEARCH_OID;
704
705 do
706 {
707 switch (state)
708 {
709 case SEARCH_OID:
710 if (*src != ' ' && *src != '/' && *src != ',')
711 {
712 oid.ptr = src;
713 oid.len = 1;
714 state = READ_OID;
715 }
716 break;
717 case READ_OID:
718 if (*src != ' ' && *src != '=')
719 {
720 oid.len++;
721 }
722 else
723 {
724 for (pos = 0; pos < X501_RDN_ROOF; pos++)
725 {
726 if (strlen(x501rdns[pos].name) == oid.len &&
727 strncasecmp(x501rdns[pos].name, oid.ptr, oid.len) == 0)
728 {
729 break; /* found a valid OID */
730 }
731 }
732 if (pos == X501_RDN_ROOF)
733 {
734 ugh = "unknown OID in distinguished name";
735 state = UNKNOWN_OID;
736 break;
737 }
738 code_asn1_length(x501rdns[pos].oid.len, &asn1_oid_len);
739
740 /* reset oid and change state */
741 oid = chunk_empty;
742 state = SEARCH_NAME;
743 }
744 break;
745 case SEARCH_NAME:
746 if (*src != ' ' && *src != '=')
747 {
748 name.ptr = src;
749 name.len = 1;
750 whitespace = 0;
751 state = READ_NAME;
752 }
753 break;
754 case READ_NAME:
755 if (*src != ',' && *src != '/' && *src != '\0')
756 {
757 name.len++;
758 if (*src == ' ')
759 {
760 whitespace++;
761 }
762 else
763 {
764 whitespace = 0;
765 }
766 }
767 else
768 {
769 name.len -= whitespace;
770 code_asn1_length(name.len, &asn1_name_len);
771
772 /* compute the length of the relative distinguished name sequence */
773 rdn_seq_len = 1 + asn1_oid_len.len + x501rdns[pos].oid.len +
774 1 + asn1_name_len.len + name.len;
775 code_asn1_length(rdn_seq_len, &asn1_rdn_seq_len);
776
777 /* compute the length of the relative distinguished name set */
778 rdn_set_len = 1 + asn1_rdn_seq_len.len + rdn_seq_len;
779 code_asn1_length(rdn_set_len, &asn1_rdn_set_len);
780
781 /* encode the relative distinguished name */
782 *dn_ptr++ = ASN1_SET;
783 chunkcpy(dn_ptr, asn1_rdn_set_len);
784 *dn_ptr++ = ASN1_SEQUENCE;
785 chunkcpy(dn_ptr, asn1_rdn_seq_len);
786 *dn_ptr++ = ASN1_OID;
787 chunkcpy(dn_ptr, asn1_oid_len);
788 chunkcpy(dn_ptr, x501rdns[pos].oid);
789 /* encode the ASN.1 character string type of the name */
790 *dn_ptr++ = (x501rdns[pos].type == ASN1_PRINTABLESTRING
791 && !asn1_is_printablestring(name))? ASN1_T61STRING : x501rdns[pos].type;
792 chunkcpy(dn_ptr, asn1_name_len);
793 chunkcpy(dn_ptr, name);
794
795 /* accumulate the length of the distinguished name sequence */
796 dn_seq_len += 1 + asn1_rdn_set_len.len + rdn_set_len;
797
798 /* reset name and change state */
799 name = chunk_empty;
800 state = SEARCH_OID;
801 }
802 break;
803 case UNKNOWN_OID:
804 break;
805 }
806 } while (*src++ != '\0');
807
808 /* complete the distinguished name sequence*/
809 code_asn1_length(dn_seq_len, &asn1_dn_seq_len);
810 dn->ptr += 3 - asn1_dn_seq_len.len;
811 dn->len = 1 + asn1_dn_seq_len.len + dn_seq_len;
812 dn_ptr = dn->ptr;
813 *dn_ptr++ = ASN1_SEQUENCE;
814 chunkcpy(dn_ptr, asn1_dn_seq_len);
815 return ugh;
816 }
817
818 /**
819 * compare two distinguished names by comparing the individual RDNs
820 */
821 bool same_dn(chunk_t a, chunk_t b)
822 {
823 chunk_t rdn_a, rdn_b, attribute_a, attribute_b;
824 chunk_t oid_a, oid_b, value_a, value_b;
825 asn1_t type_a, type_b;
826 bool next_a, next_b;
827
828 /* same lengths for the DNs */
829 if (a.len != b.len)
830 {
831 return FALSE;
832 }
833
834 /* try a binary comparison first */
835 if (memeq(a.ptr, b.ptr, b.len))
836 {
837 return TRUE;
838 }
839
840 /* initialize DN parsing */
841 if (init_rdn(a, &rdn_a, &attribute_a, &next_a) != NULL
842 || init_rdn(b, &rdn_b, &attribute_b, &next_b) != NULL)
843 {
844 return FALSE;
845 }
846
847 /* fetch next RDN pair */
848 while (next_a && next_b)
849 {
850 /* parse next RDNs and check for errors */
851 if (get_next_rdn(&rdn_a, &attribute_a, &oid_a, &value_a, &type_a, &next_a) != NULL
852 || get_next_rdn(&rdn_b, &attribute_b, &oid_b, &value_b, &type_b, &next_b) != NULL)
853 {
854 return FALSE;
855 }
856
857 /* OIDs must agree */
858 if (oid_a.len != oid_b.len || memcmp(oid_a.ptr, oid_b.ptr, oid_b.len) != 0)
859 {
860 return FALSE;
861 }
862
863 /* same lengths for values */
864 if (value_a.len != value_b.len)
865 {
866 return FALSE;
867 }
868
869 /* printableStrings and email RDNs require uppercase comparison */
870 if (type_a == type_b && (type_a == ASN1_PRINTABLESTRING ||
871 (type_a == ASN1_IA5STRING && asn1_known_oid(oid_a) == OID_PKCS9_EMAIL)))
872 {
873 if (strncasecmp(value_a.ptr, value_b.ptr, value_b.len) != 0)
874 {
875 return FALSE;
876 }
877 }
878 else
879 {
880 if (strncmp(value_a.ptr, value_b.ptr, value_b.len) != 0)
881 {
882 return FALSE;
883 }
884 }
885 }
886 /* both DNs must have same number of RDNs */
887 if (next_a || next_b)
888 {
889 return FALSE;
890 }
891
892 /* the two DNs are equal! */
893 return TRUE;
894 }
895
896
897 /**
898 * Compare two distinguished names by comparing the individual RDNs.
899 * A single'*' character designates a wildcard RDN in DN b.
900 */
901 bool match_dn(chunk_t a, chunk_t b, int *wildcards)
902 {
903 chunk_t rdn_a, rdn_b, attribute_a, attribute_b;
904 chunk_t oid_a, oid_b, value_a, value_b;
905 asn1_t type_a, type_b;
906 bool next_a, next_b;
907
908 /* initialize wildcard counter */
909 *wildcards = 0;
910
911 /* initialize DN parsing */
912 if (init_rdn(a, &rdn_a, &attribute_a, &next_a) != NULL
913 || init_rdn(b, &rdn_b, &attribute_b, &next_b) != NULL)
914 {
915 return FALSE;
916 }
917
918 /* fetch next RDN pair */
919 while (next_a && next_b)
920 {
921 /* parse next RDNs and check for errors */
922 if (get_next_rdn(&rdn_a, &attribute_a, &oid_a, &value_a, &type_a, &next_a) != NULL
923 || get_next_rdn(&rdn_b, &attribute_b, &oid_b, &value_b, &type_b, &next_b) != NULL)
924 {
925 return FALSE;
926 }
927
928 /* OIDs must agree */
929 if (oid_a.len != oid_b.len || memcmp(oid_a.ptr, oid_b.ptr, oid_b.len) != 0)
930 {
931 return FALSE;
932 }
933
934 /* does rdn_b contain a wildcard? */
935 if (value_b.len == 1 && *value_b.ptr == '*')
936 {
937 (*wildcards)++;
938 continue;
939 }
940
941 /* same lengths for values */
942 if (value_a.len != value_b.len)
943 {
944 return FALSE;
945 }
946
947 /* printableStrings and email RDNs require uppercase comparison */
948 if (type_a == type_b && (type_a == ASN1_PRINTABLESTRING ||
949 (type_a == ASN1_IA5STRING && asn1_known_oid(oid_a) == OID_PKCS9_EMAIL)))
950 {
951 if (strncasecmp(value_a.ptr, value_b.ptr, value_b.len) != 0)
952 {
953 return FALSE;
954 }
955 }
956 else
957 {
958 if (strncmp(value_a.ptr, value_b.ptr, value_b.len) != 0)
959 {
960 return FALSE;
961 }
962 }
963 }
964
965 /* both DNs must have same number of RDNs */
966 if (next_a || next_b)
967 {
968 return FALSE;
969 }
970
971 /* the two DNs match! */
972 return TRUE;
973 }
974
975 /**
976 * Compare two X.509 certificates by comparing their signatures
977 */
978 bool same_x509cert(const x509cert_t *a, const x509cert_t *b)
979 {
980 return chunk_equals(a->signature, b->signature);
981 }
982
983 /**
984 * For each link pointing to the certificate increase the count by one
985 */
986 void share_x509cert(x509cert_t *cert)
987 {
988 if (cert != NULL)
989 {
990 cert->count++;
991 }
992 }
993
994 /**
995 * Add a X.509 user/host certificate to the chained list
996 */
997 x509cert_t* add_x509cert(x509cert_t *cert)
998 {
999 x509cert_t *c = x509certs;
1000
1001 while (c != NULL)
1002 {
1003 if (same_x509cert(c, cert)) /* already in chain, free cert */
1004 {
1005 free_x509cert(cert);
1006 return c;
1007 }
1008 c = c->next;
1009 }
1010
1011 /* insert new cert at the root of the chain */
1012 lock_certs_and_keys("add_x509cert");
1013 cert->next = x509certs;
1014 x509certs = cert;
1015 DBG(DBG_CONTROL | DBG_PARSING,
1016 DBG_log(" x509 cert inserted")
1017 )
1018 unlock_certs_and_keys("add_x509cert");
1019 return cert;
1020 }
1021
1022 /**
1023 * Choose either subject DN or a subjectAltName as connection end ID
1024 */
1025 void select_x509cert_id(x509cert_t *cert, struct id *end_id)
1026 {
1027 bool copy_subject_dn = TRUE; /* ID is subject DN */
1028
1029 if (end_id->kind != ID_ANY) /* check for matching subjectAltName */
1030 {
1031 generalName_t *gn = cert->subjectAltName;
1032
1033 while (gn != NULL)
1034 {
1035 struct id id = empty_id;
1036
1037 gntoid(&id, gn);
1038 if (same_id(&id, end_id))
1039 {
1040 copy_subject_dn = FALSE; /* take subjectAltName instead */
1041 break;
1042 }
1043 gn = gn->next;
1044 }
1045 }
1046
1047 if (copy_subject_dn)
1048 {
1049 if (end_id->kind != ID_ANY && end_id->kind != ID_DER_ASN1_DN)
1050 {
1051 char buf[BUF_LEN];
1052
1053 idtoa(end_id, buf, BUF_LEN);
1054 plog(" no subjectAltName matches ID '%s', replaced by subject DN", buf);
1055 }
1056 end_id->kind = ID_DER_ASN1_DN;
1057 end_id->name.len = cert->subject.len;
1058 end_id->name.ptr = temporary_cyclic_buffer();
1059 memcpy(end_id->name.ptr, cert->subject.ptr, cert->subject.len);
1060 }
1061 }
1062
1063 /**
1064 * Check for equality between two key identifiers
1065 */
1066 bool same_keyid(chunk_t a, chunk_t b)
1067 {
1068 if (a.ptr == NULL || b.ptr == NULL)
1069 {
1070 return FALSE;
1071 }
1072 return chunk_equals(a, b);
1073 }
1074
1075 /**
1076 * Check for equality between two serial numbers
1077 */
1078 bool same_serial(chunk_t a, chunk_t b)
1079 {
1080 /* do not compare serial numbers if one of them is not defined */
1081 if (a.ptr == NULL || b.ptr == NULL)
1082 {
1083 return TRUE;
1084 }
1085 return chunk_equals(a, b);
1086 }
1087
1088 /**
1089 * Get a X.509 certificate with a given issuer found at a certain position
1090 */
1091 x509cert_t* get_x509cert(chunk_t issuer, chunk_t serial, chunk_t keyid,
1092 x509cert_t *chain)
1093 {
1094 x509cert_t *cert = (chain != NULL)? chain->next : x509certs;
1095
1096 while (cert != NULL)
1097 {
1098 if ((keyid.ptr != NULL) ? same_keyid(keyid, cert->authKeyID)
1099 : (same_dn(issuer, cert->issuer)
1100 && same_serial(serial, cert->authKeySerialNumber)))
1101 {
1102 return cert;
1103 }
1104 cert = cert->next;
1105 }
1106 return NULL;
1107 }
1108
1109 /**
1110 * Encode a linked list of subjectAltNames
1111 */
1112 chunk_t build_subjectAltNames(generalName_t *subjectAltNames)
1113 {
1114 u_char *pos;
1115 chunk_t names;
1116 size_t len = 0;
1117 generalName_t *gn = subjectAltNames;
1118
1119 /* compute the total size of the ASN.1 attributes object */
1120 while (gn != NULL)
1121 {
1122 len += gn->name.len;
1123 gn = gn->next;
1124 }
1125
1126 pos = asn1_build_object(&names, ASN1_SEQUENCE, len);
1127
1128 gn = subjectAltNames;
1129 while (gn != NULL)
1130 {
1131 chunkcpy(pos, gn->name);
1132 gn = gn->next;
1133 }
1134
1135 return asn1_wrap(ASN1_SEQUENCE, "cm"
1136 , ASN1_subjectAltName_oid
1137 , asn1_wrap(ASN1_OCTET_STRING, "m", names));
1138 }
1139
1140 /**
1141 * Build a to-be-signed X.509 certificate body
1142 */
1143 static chunk_t build_tbs_x509cert(x509cert_t *cert, const RSA_public_key_t *rsa)
1144 {
1145 /* version is always X.509v3 */
1146 chunk_t version = asn1_simple_object(ASN1_CONTEXT_C_0, ASN1_INTEGER_2);
1147
1148 chunk_t extensions = chunk_empty;
1149
1150 if (cert->subjectAltName != NULL)
1151 {
1152 extensions = asn1_wrap(ASN1_CONTEXT_C_3, "m"
1153 , asn1_wrap(ASN1_SEQUENCE, "m"
1154 , build_subjectAltNames(cert->subjectAltName)));
1155 }
1156
1157 return asn1_wrap(ASN1_SEQUENCE, "mmccmcmm"
1158 , version
1159 , asn1_simple_object(ASN1_INTEGER, cert->serialNumber)
1160 , asn1_algorithmIdentifier(cert->sigAlg)
1161 , cert->issuer
1162 , asn1_wrap(ASN1_SEQUENCE, "mm"
1163 , asn1_from_time(&cert->notBefore, ASN1_UTCTIME)
1164 , asn1_from_time(&cert->notAfter, ASN1_UTCTIME)
1165 )
1166 , cert->subject
1167 , pkcs1_build_publicKeyInfo(rsa)
1168 , extensions
1169 );
1170 }
1171
1172 /**
1173 * Build a DER-encoded X.509 certificate
1174 */
1175 void build_x509cert(x509cert_t *cert, const RSA_public_key_t *cert_key,
1176 const RSA_private_key_t *signer_key)
1177 {
1178 chunk_t tbs_cert = build_tbs_x509cert(cert, cert_key);
1179
1180 chunk_t signature = pkcs1_build_signature(tbs_cert, cert->sigAlg
1181 , signer_key, TRUE);
1182
1183 cert->certificate = asn1_wrap(ASN1_SEQUENCE, "mcm"
1184 , tbs_cert
1185 , asn1_algorithmIdentifier(cert->sigAlg)
1186 , signature);
1187 }
1188
1189 /**
1190 * Free the dynamic memory used to store generalNames
1191 */
1192 void free_generalNames(generalName_t* gn, bool free_name)
1193 {
1194 while (gn != NULL)
1195 {
1196 generalName_t *gn_top = gn;
1197 if (free_name)
1198 {
1199 free(gn->name.ptr);
1200 }
1201 gn = gn->next;
1202 free(gn_top);
1203 }
1204 }
1205
1206 /**
1207 * Free a X.509 certificate
1208 */
1209 void free_x509cert(x509cert_t *cert)
1210 {
1211 if (cert != NULL)
1212 {
1213 free_generalNames(cert->subjectAltName, FALSE);
1214 free_generalNames(cert->crlDistributionPoints, FALSE);
1215 free(cert->certificate.ptr);
1216 free(cert);
1217 cert = NULL;
1218 }
1219 }
1220
1221 /**
1222 * Release of a certificate decreases the count by one
1223 * the certificate is freed when the counter reaches zero
1224 */
1225 void release_x509cert(x509cert_t *cert)
1226 {
1227 if (cert != NULL && --cert->count == 0)
1228 {
1229 x509cert_t **pp = &x509certs;
1230 while (*pp != cert)
1231 {
1232 pp = &(*pp)->next;
1233 }
1234 *pp = cert->next;
1235 free_x509cert(cert);
1236 }
1237 }
1238
1239 /**
1240 * Stores a chained list of end certs and CA certs
1241 */
1242 void store_x509certs(x509cert_t **firstcert, bool strict)
1243 {
1244 x509cert_t *cacerts = NULL;
1245 x509cert_t **pp = firstcert;
1246
1247 /* first extract CA certs, discarding root CA certs */
1248
1249 while (*pp != NULL)
1250 {
1251 x509cert_t *cert = *pp;
1252
1253 if (cert->isCA)
1254 {
1255 *pp = cert->next;
1256
1257 /* we don't accept self-signed CA certs */
1258 if (same_dn(cert->issuer, cert->subject))
1259 {
1260 plog("self-signed cacert rejected");
1261 free_x509cert(cert);
1262 }
1263 else
1264 {
1265 /* insertion into temporary chain of candidate CA certs */
1266 cert->next = cacerts;
1267 cacerts = cert;
1268 }
1269 }
1270 else
1271 {
1272 pp = &cert->next;
1273 }
1274 }
1275
1276 /* now verify the candidate CA certs */
1277
1278 while (cacerts != NULL)
1279 {
1280 x509cert_t *cert = cacerts;
1281
1282 cacerts = cacerts->next;
1283
1284 if (trust_authcert_candidate(cert, cacerts))
1285 {
1286 add_authcert(cert, AUTH_CA);
1287 }
1288 else
1289 {
1290 plog("intermediate cacert rejected");
1291 free_x509cert(cert);
1292 }
1293 }
1294
1295 /* now verify the end certificates */
1296
1297 pp = firstcert;
1298
1299 while (*pp != NULL)
1300 {
1301 time_t valid_until;
1302 x509cert_t *cert = *pp;
1303
1304 if (verify_x509cert(cert, strict, &valid_until))
1305 {
1306 DBG(DBG_CONTROL | DBG_PARSING,
1307 DBG_log("public key validated")
1308 )
1309 add_x509_public_key(cert, valid_until, DAL_SIGNED);
1310 }
1311 else
1312 {
1313 plog("X.509 certificate rejected");
1314 }
1315 *pp = cert->next;
1316 free_x509cert(cert);
1317 }
1318 }
1319
1320 /**
1321 * Decrypts an RSA signature using the issuer's certificate
1322 */
1323 static bool decrypt_sig(chunk_t sig, int alg, const x509cert_t *issuer_cert,
1324 chunk_t *digest)
1325 {
1326 switch (alg)
1327 {
1328 chunk_t decrypted;
1329
1330 case OID_RSA_ENCRYPTION:
1331 case OID_MD2_WITH_RSA:
1332 case OID_MD5_WITH_RSA:
1333 case OID_SHA1_WITH_RSA:
1334 case OID_SHA1_WITH_RSA_OIW:
1335 case OID_SHA256_WITH_RSA:
1336 case OID_SHA384_WITH_RSA:
1337 case OID_SHA512_WITH_RSA:
1338 {
1339 mpz_t s;
1340 RSA_public_key_t rsa;
1341
1342 init_RSA_public_key(&rsa, issuer_cert->publicExponent
1343 , issuer_cert->modulus);
1344
1345 /* decrypt the signature s = s^e mod n */
1346 n_to_mpz(s, sig.ptr, sig.len);
1347 mpz_powm(s, s, &rsa.e, &rsa.n);
1348
1349 /* convert back to bytes */
1350 decrypted = mpz_to_n(s, rsa.k);
1351 DBG(DBG_PARSING,
1352 DBG_dump_chunk(" decrypted signature: ", decrypted)
1353 )
1354
1355 /* copy the least significant bits of decrypted signature
1356 * into the digest string
1357 */
1358 memcpy(digest->ptr, decrypted.ptr + decrypted.len - digest->len,
1359 digest->len);
1360
1361 /* free memory */
1362 free_RSA_public_content(&rsa);
1363 free(decrypted.ptr);
1364 mpz_clear(s);
1365 return TRUE;
1366 }
1367 default:
1368 digest->len = 0;
1369 return FALSE;
1370 }
1371 }
1372
1373 /**
1374 * Check if a signature over binary blob is genuine
1375 */
1376 bool check_signature(chunk_t tbs, chunk_t sig, int digest_alg, int enc_alg,
1377 const x509cert_t *issuer_cert)
1378 {
1379 u_char digest_buf[MAX_DIGEST_LEN];
1380 u_char decrypted_buf[MAX_DIGEST_LEN];
1381 chunk_t digest = {digest_buf, MAX_DIGEST_LEN};
1382 chunk_t decrypted = {decrypted_buf, MAX_DIGEST_LEN};
1383
1384 DBG(DBG_PARSING,
1385 if (digest_alg != OID_UNKNOWN)
1386 {
1387 DBG_log("signature digest algorithm: '%s'",oid_names[digest_alg].name);
1388 }
1389 else
1390 {
1391 DBG_log("unknown signature digest algorithm");
1392 }
1393 )
1394
1395 if (!compute_digest(tbs, digest_alg, &digest))
1396 {
1397 plog(" digest algorithm not supported");
1398 return FALSE;
1399 }
1400
1401 DBG(DBG_PARSING,
1402 DBG_dump_chunk(" digest:", digest)
1403 )
1404
1405 decrypted.len = digest.len; /* we want the same digest length */
1406
1407 DBG(DBG_PARSING,
1408 if (enc_alg != OID_UNKNOWN)
1409 {
1410 DBG_log("signature encryption algorithm: '%s'",oid_names[enc_alg].name);
1411 }
1412 else
1413 {
1414 DBG_log("unknown signature encryption algorithm");
1415 }
1416 )
1417
1418 if (!decrypt_sig(sig, enc_alg, issuer_cert, &decrypted))
1419 {
1420 plog(" decryption algorithm not supported");
1421 return FALSE;
1422 }
1423
1424 /* check if digests are equal */
1425 return memeq(decrypted.ptr, digest.ptr, digest.len);
1426 }
1427
1428 /**
1429 * Extracts the basicConstraints extension
1430 */
1431 static bool parse_basicConstraints(chunk_t blob, int level0)
1432 {
1433 asn1_parser_t *parser;
1434 chunk_t object;
1435 int objectID;
1436 bool isCA = FALSE;
1437
1438 parser = asn1_parser_create(basicConstraintsObjects, blob);
1439 parser->set_top_level(parser, level0);
1440
1441 while (parser->iterate(parser, &objectID, &object))
1442 {
1443 if (objectID == BASIC_CONSTRAINTS_CA)
1444 {
1445 isCA = object.len && *object.ptr;
1446 DBG(DBG_PARSING,
1447 DBG_log(" %s",(isCA)?"TRUE":"FALSE");
1448 )
1449 }
1450 }
1451 parser->destroy(parser);
1452
1453 return isCA;
1454 }
1455
1456 /**
1457 * Converts a X.500 generalName into an ID
1458 */
1459 void gntoid(struct id *id, const generalName_t *gn)
1460 {
1461 switch(gn->kind)
1462 {
1463 case GN_DNS_NAME: /* ID type: ID_FQDN */
1464 id->kind = ID_FQDN;
1465 id->name = gn->name;
1466 break;
1467 case GN_IP_ADDRESS: /* ID type: ID_IPV4_ADDR */
1468 {
1469 const struct af_info *afi = &af_inet4_info;
1470 err_t ugh = NULL;
1471
1472 id->kind = afi->id_addr;
1473 ugh = initaddr(gn->name.ptr, gn->name.len, afi->af, &id->ip_addr);
1474 }
1475 break;
1476 case GN_RFC822_NAME: /* ID type: ID_USER_FQDN */
1477 id->kind = ID_USER_FQDN;
1478 id->name = gn->name;
1479 break;
1480 default:
1481 id->kind = ID_ANY;
1482 id->name = chunk_empty;
1483 }
1484 }
1485
1486 /**
1487 * Compute the subjectKeyIdentifier according to section 4.2.1.2 of RFC 3280
1488 * as the 160 bit SHA-1 hash of the public key
1489 */
1490 bool compute_subjectKeyID(x509cert_t *cert, chunk_t subjectKeyID)
1491 {
1492 hasher_t *hasher = lib->crypto->create_hasher(lib->crypto, HASH_SHA1);
1493
1494 if (hasher == NULL)
1495 {
1496 plog(" no SHA-1 hasher available to compute subjectKeyID");
1497 return FALSE;
1498 }
1499 hasher->get_hash(hasher, cert->subjectPublicKey, subjectKeyID.ptr);
1500 hasher->destroy(hasher);
1501 return TRUE;
1502 }
1503
1504 /**
1505 * Extracts an otherName
1506 */
1507 static bool parse_otherName(chunk_t blob, int level0)
1508 {
1509 asn1_parser_t *parser;
1510 chunk_t object;
1511 int objectID;
1512 int oid = OID_UNKNOWN;
1513 bool success = FALSE;
1514
1515 parser = asn1_parser_create(otherNameObjects, blob);
1516 parser->set_top_level(parser, level0);
1517
1518 while (parser->iterate(parser, &objectID, &object))
1519 {
1520 switch (objectID)
1521 {
1522 case ON_OBJ_ID_TYPE:
1523 oid = asn1_known_oid(object);
1524 break;
1525 case ON_OBJ_VALUE:
1526 if (oid == OID_XMPP_ADDR)
1527 {
1528 if (!asn1_parse_simple_object(&object, ASN1_UTF8STRING,
1529 parser->get_level(parser) + 1, "xmppAddr"))
1530 {
1531 goto end;
1532 }
1533 }
1534 break;
1535 default:
1536 break;
1537 }
1538 }
1539 success = parser->success(parser);
1540
1541 end:
1542 parser->destroy(parser);
1543 return success;
1544 }
1545
1546
1547 /**
1548 * Extracts a generalName
1549 */
1550 static generalName_t* parse_generalName(chunk_t blob, int level0)
1551 {
1552 u_char buf[BUF_LEN];
1553 asn1_parser_t *parser;
1554 chunk_t object;
1555 generalName_t *gn = NULL;
1556 int objectID;
1557
1558 parser = asn1_parser_create(generalNameObjects, blob);
1559 parser->set_top_level(parser, level0);
1560
1561 while (parser->iterate(parser, &objectID, &object))
1562 {
1563 bool valid_gn = FALSE;
1564
1565 switch (objectID) {
1566 case GN_OBJ_RFC822_NAME:
1567 case GN_OBJ_DNS_NAME:
1568 case GN_OBJ_URI:
1569 DBG(DBG_PARSING,
1570 DBG_log(" '%.*s'", (int)object.len, object.ptr);
1571 )
1572 valid_gn = TRUE;
1573 break;
1574 case GN_OBJ_DIRECTORY_NAME:
1575 DBG(DBG_PARSING,
1576 dntoa(buf, BUF_LEN, object);
1577 DBG_log(" '%s'", buf)
1578 )
1579 valid_gn = TRUE;
1580 break;
1581 case GN_OBJ_IP_ADDRESS:
1582 DBG(DBG_PARSING,
1583 DBG_log(" '%d.%d.%d.%d'", *object.ptr, *(object.ptr+1),
1584 *(object.ptr+2), *(object.ptr+3));
1585 )
1586 valid_gn = TRUE;
1587 break;
1588 case GN_OBJ_OTHER_NAME:
1589 if (!parse_otherName(object, parser->get_level(parser)+1))
1590 {
1591 goto end;
1592 }
1593 break;
1594 case GN_OBJ_X400_ADDRESS:
1595 case GN_OBJ_EDI_PARTY_NAME:
1596 case GN_OBJ_REGISTERED_ID:
1597 break;
1598 default:
1599 break;
1600 }
1601
1602 if (valid_gn)
1603 {
1604 gn = malloc_thing(generalName_t);
1605 gn->kind = (objectID - GN_OBJ_OTHER_NAME) / 2;
1606 gn->name = object;
1607 gn->next = NULL;
1608 goto end;
1609 }
1610 }
1611
1612 end:
1613 parser->destroy(parser);
1614 return gn;
1615 }
1616
1617 /**
1618 * Extracts one or several GNs and puts them into a chained list
1619 */
1620 static generalName_t* parse_generalNames(chunk_t blob, int level0, bool implicit)
1621 {
1622 asn1_parser_t *parser;
1623 chunk_t object;
1624 int objectID;
1625 generalName_t *top_gn = NULL;
1626
1627 parser = asn1_parser_create(generalNamesObjects, blob);
1628 parser->set_top_level(parser, level0);
1629 parser->set_flags(parser, implicit, FALSE);
1630
1631 while (parser->iterate(parser, &objectID, &object))
1632 {
1633 if (objectID == GENERAL_NAMES_GN)
1634 {
1635 generalName_t *gn = parse_generalName(object,
1636 parser->get_level(parser)+1);
1637 if (gn)
1638 {
1639 gn->next = top_gn;
1640 top_gn = gn;
1641 }
1642 }
1643 }
1644 parser->destroy(parser);
1645
1646 return top_gn;
1647 }
1648
1649 /**
1650 * Returns a directoryName
1651 */
1652 chunk_t get_directoryName(chunk_t blob, int level, bool implicit)
1653 {
1654 chunk_t name = chunk_empty;
1655 generalName_t * gn = parse_generalNames(blob, level, implicit);
1656
1657 if (gn != NULL && gn->kind == GN_DIRECTORY_NAME)
1658 {
1659 name= gn->name;
1660 }
1661 free_generalNames(gn, FALSE);
1662 return name;
1663 }
1664
1665 /**
1666 * Extracts an authoritykeyIdentifier
1667 */
1668 void parse_authorityKeyIdentifier(chunk_t blob, int level0,
1669 chunk_t *authKeyID,
1670 chunk_t *authKeySerialNumber)
1671 {
1672 asn1_parser_t *parser;
1673 chunk_t object;
1674 int objectID;
1675
1676 parser = asn1_parser_create(authKeyIdentifierObjects, blob);
1677 parser->set_top_level(parser, level0);
1678
1679 while (parser->iterate(parser, &objectID, &object))
1680 {
1681 switch (objectID)
1682 {
1683 case AUTH_KEY_ID_KEY_ID:
1684 *authKeyID = object;
1685 break;
1686 case AUTH_KEY_ID_CERT_ISSUER:
1687 {
1688 generalName_t * gn = parse_generalNames(object,
1689 parser->get_level(parser) + 1, TRUE);
1690
1691 free_generalNames(gn, FALSE);
1692 }
1693 break;
1694 case AUTH_KEY_ID_CERT_SERIAL:
1695 *authKeySerialNumber = object;
1696 break;
1697 default:
1698 break;
1699 }
1700 }
1701 parser->destroy(parser);
1702 }
1703
1704 /**
1705 * Extracts an authorityInfoAcess location
1706 */
1707 static void parse_authorityInfoAccess(chunk_t blob, int level0,
1708 chunk_t *accessLocation)
1709 {
1710 asn1_parser_t *parser;
1711 chunk_t object;
1712 int objectID;
1713 int accessMethod = OID_UNKNOWN;
1714
1715 parser = asn1_parser_create(authInfoAccessObjects, blob);
1716 parser->set_top_level(parser, level0);
1717
1718 while (parser->iterate(parser, &objectID, &object))
1719 {
1720 switch (objectID)
1721 {
1722 case AUTH_INFO_ACCESS_METHOD:
1723 accessMethod = asn1_known_oid(object);
1724 break;
1725 case AUTH_INFO_ACCESS_LOCATION:
1726 {
1727 switch (accessMethod)
1728 {
1729 case OID_OCSP:
1730 if (*object.ptr == ASN1_CONTEXT_S_6)
1731 {
1732 if (asn1_length(&object) == ASN1_INVALID_LENGTH)
1733 {
1734 goto end;
1735 }
1736 DBG(DBG_PARSING,
1737 DBG_log(" '%.*s'",(int)object.len, object.ptr)
1738 )
1739
1740 /* only HTTP(S) URIs accepted */
1741 if (strncasecmp(object.ptr, "http", 4) == 0)
1742 {
1743 *accessLocation = object;
1744 goto end;
1745 }
1746 }
1747 plog("warning: ignoring OCSP InfoAccessLocation with unkown protocol");
1748 break;
1749 default:
1750 /* unkown accessMethod, ignoring */
1751 break;
1752 }
1753 }
1754 break;
1755 default:
1756 break;
1757 }
1758 }
1759
1760 end:
1761 parser->destroy(parser);
1762 }
1763
1764 /**
1765 * Extracts extendedKeyUsage OIDs
1766 */
1767 static bool parse_extendedKeyUsage(chunk_t blob, int level0)
1768 {
1769 asn1_parser_t *parser;
1770 chunk_t object;
1771 int objectID;
1772 bool ocsp_signing = FALSE;
1773
1774 parser = asn1_parser_create(extendedKeyUsageObjects, blob);
1775 parser->set_top_level(parser, level0);
1776
1777 while (parser->iterate(parser, &objectID, &object))
1778 {
1779 if (objectID == EXT_KEY_USAGE_PURPOSE_ID
1780 && asn1_known_oid(object) == OID_OCSP_SIGNING)
1781 {
1782 ocsp_signing = TRUE;
1783 }
1784 }
1785 parser->destroy(parser);
1786
1787 return ocsp_signing;
1788 }
1789
1790 /**
1791 * Extracts one or several crlDistributionPoints
1792 * and puts them into a chained list
1793 */
1794 static generalName_t* parse_crlDistributionPoints(chunk_t blob, int level0)
1795 {
1796 asn1_parser_t *parser;
1797 chunk_t object;
1798 int objectID;
1799
1800 generalName_t *top_gn = NULL; /* top of the chained list */
1801 generalName_t **tail_gn = &top_gn; /* tail of the chained list */
1802
1803 parser = asn1_parser_create(crlDistributionPointsObjects, blob);
1804 parser->set_top_level(parser, level0);
1805
1806 while (parser->iterate(parser, &objectID, &object))
1807 {
1808 if (objectID == CRL_DIST_POINTS_FULLNAME)
1809 {
1810 generalName_t *gn;
1811
1812 gn = parse_generalNames(object, parser->get_level(parser)+1, TRUE);
1813 /* append extracted generalNames to existing chained list */
1814 *tail_gn = gn;
1815 /* find new tail of the chained list */
1816 while (gn != NULL)
1817 {
1818 tail_gn = &gn->next; gn = gn->next;
1819 }
1820 }
1821 }
1822 parser->destroy(parser);
1823
1824 return top_gn;
1825 }
1826
1827 /**
1828 * Parses an RSA public key
1829 */
1830 bool parse_RSA_public_key(chunk_t blob, u_int level0, x509cert_t *cert)
1831 {
1832 asn1_parser_t *parser;
1833 chunk_t object;
1834 int objectID;
1835 bool success = FALSE;
1836
1837 parser = asn1_parser_create(pubkeyObjects, blob);
1838 parser->set_top_level(parser, level0);
1839
1840 while (parser->iterate(parser, &objectID, &object))
1841 {
1842 switch (objectID) {
1843 case PUB_KEY_RSA_PUBLIC_KEY:
1844 cert->subjectPublicKey = object;
1845 break;
1846 case PUB_KEY_MODULUS:
1847 if (object.len < RSA_MIN_OCTETS + 1)
1848 {
1849 plog(" " RSA_MIN_OCTETS_UGH);
1850 goto end;
1851 }
1852 if (object.len > RSA_MAX_OCTETS + (size_t)(*object.ptr == 0x00))
1853 {
1854 plog(" " RSA_MAX_OCTETS_UGH);
1855 goto end;
1856 }
1857 cert->modulus = object;
1858 break;
1859 case PUB_KEY_EXPONENT:
1860 cert->publicExponent = object;
1861 break;
1862 }
1863 }
1864 success = parser->success(parser);
1865
1866 end:
1867 parser->destroy(parser);
1868 return success;
1869 }
1870
1871 /**
1872 * Parses an X.509v3 certificate
1873 */
1874 bool parse_x509cert(chunk_t blob, u_int level0, x509cert_t *cert)
1875 {
1876 u_char buf[BUF_LEN];
1877 asn1_parser_t *parser;
1878 chunk_t object;
1879 int objectID;
1880 int extn_oid = OID_UNKNOWN;
1881 bool critical;
1882 bool success = FALSE;
1883
1884 parser = asn1_parser_create(certObjects, blob);
1885 parser->set_top_level(parser, level0);
1886
1887 while (parser->iterate(parser, &objectID, &object))
1888 {
1889 u_int level = parser->get_level(parser) + 1;
1890
1891 switch (objectID) {
1892 case X509_OBJ_CERTIFICATE:
1893 cert->certificate = object;
1894 break;
1895 case X509_OBJ_TBS_CERTIFICATE:
1896 cert->tbsCertificate = object;
1897 break;
1898 case X509_OBJ_VERSION:
1899 cert->version = (object.len) ? (1+(u_int)*object.ptr) : 1;
1900 DBG(DBG_PARSING,
1901 DBG_log(" v%d", cert->version);
1902 )
1903 break;
1904 case X509_OBJ_SERIAL_NUMBER:
1905 cert->serialNumber = object;
1906 break;
1907 case X509_OBJ_SIG_ALG:
1908 cert->sigAlg = asn1_parse_algorithmIdentifier(object, level, NULL);
1909 break;
1910 case X509_OBJ_ISSUER:
1911 cert->issuer = object;
1912 DBG(DBG_PARSING,
1913 dntoa(buf, BUF_LEN, object);
1914 DBG_log(" '%s'",buf)
1915 )
1916 break;
1917 case X509_OBJ_NOT_BEFORE:
1918 cert->notBefore = asn1_parse_time(object, level);
1919 break;
1920 case X509_OBJ_NOT_AFTER:
1921 cert->notAfter = asn1_parse_time(object, level);
1922 break;
1923 case X509_OBJ_SUBJECT:
1924 cert->subject = object;
1925 DBG(DBG_PARSING,
1926 dntoa(buf, BUF_LEN, object);
1927 DBG_log(" '%s'",buf)
1928 )
1929 break;
1930 case X509_OBJ_SUBJECT_PUBLIC_KEY_ALGORITHM:
1931 if (asn1_parse_algorithmIdentifier(object, level, NULL) == OID_RSA_ENCRYPTION)
1932 {
1933 cert->subjectPublicKeyAlgorithm = PUBKEY_ALG_RSA;
1934 }
1935 else
1936 {
1937 plog(" unsupported public key algorithm");
1938 goto end;
1939 }
1940 break;
1941 case X509_OBJ_SUBJECT_PUBLIC_KEY:
1942 if (object.len > 0 && *object.ptr == 0x00)
1943 {
1944 /* skip initial bit string octet defining 0 unused bits */
1945 object = chunk_skip(object, 1);
1946 if (!parse_RSA_public_key(object, level, cert))
1947 {
1948 goto end;
1949 }
1950 }
1951 else
1952 {
1953 plog(" invalid RSA public key format");
1954 goto end;
1955 }
1956 break;
1957 case X509_OBJ_EXTN_ID:
1958 extn_oid = asn1_known_oid(object);
1959 break;
1960 case X509_OBJ_CRITICAL:
1961 critical = object.len && *object.ptr;
1962 DBG(DBG_PARSING,
1963 DBG_log(" %s",(critical)?"TRUE":"FALSE");
1964 )
1965 break;
1966 case X509_OBJ_EXTN_VALUE:
1967 {
1968 switch (extn_oid) {
1969 case OID_SUBJECT_KEY_ID:
1970 if (!asn1_parse_simple_object(&object, ASN1_OCTET_STRING,
1971 level, "keyIdentifier"))
1972 {
1973 goto end;
1974 }
1975 cert->subjectKeyID = object;
1976 break;
1977 case OID_SUBJECT_ALT_NAME:
1978 cert->subjectAltName =
1979 parse_generalNames(object, level, FALSE);
1980 break;
1981 case OID_BASIC_CONSTRAINTS:
1982 cert->isCA =
1983 parse_basicConstraints(object, level);
1984 break;
1985 case OID_CRL_DISTRIBUTION_POINTS:
1986 cert->crlDistributionPoints =
1987 parse_crlDistributionPoints(object, level);
1988 break;
1989 case OID_AUTHORITY_KEY_ID:
1990 parse_authorityKeyIdentifier(object, level
1991 , &cert->authKeyID, &cert->authKeySerialNumber);
1992 break;
1993 case OID_AUTHORITY_INFO_ACCESS:
1994 parse_authorityInfoAccess(object, level, &cert->accessLocation);
1995 break;
1996 case OID_EXTENDED_KEY_USAGE:
1997 cert->isOcspSigner = parse_extendedKeyUsage(object, level);
1998 break;
1999 case OID_NS_REVOCATION_URL:
2000 case OID_NS_CA_REVOCATION_URL:
2001 case OID_NS_CA_POLICY_URL:
2002 case OID_NS_COMMENT:
2003 if (!asn1_parse_simple_object(&object, ASN1_IA5STRING
2004 , level, oid_names[extn_oid].name))
2005 {
2006 goto end;
2007 }
2008 break;
2009 default:
2010 break;
2011 }
2012 }
2013 break;
2014 case X509_OBJ_ALGORITHM:
2015 cert->algorithm = asn1_parse_algorithmIdentifier(object, level, NULL);
2016 break;
2017 case X509_OBJ_SIGNATURE:
2018 cert->signature = object;
2019 break;
2020 default:
2021 break;
2022 }
2023 }
2024 success = parser->success(parser);
2025 time(&cert->installed);
2026
2027 end:
2028 parser->destroy(parser);
2029 return success;
2030 }
2031
2032 /**
2033 * Verify the validity of a certificate by
2034 * checking the notBefore and notAfter dates
2035 */
2036 err_t check_validity(const x509cert_t *cert, time_t *until)
2037 {
2038 time_t current_time;
2039
2040 time(&current_time);
2041 DBG(DBG_CONTROL | DBG_PARSING ,
2042 DBG_log(" not before : %T", &cert->notBefore, TRUE);
2043 DBG_log(" current time: %T", &current_time, TRUE);
2044 DBG_log(" not after : %T", &cert->notAfter, TRUE);
2045 )
2046
2047 if (cert->notAfter < *until)
2048 {
2049 *until = cert->notAfter;
2050 }
2051 if (current_time < cert->notBefore)
2052 {
2053 return "certificate is not valid yet";
2054 }
2055 if (current_time > cert->notAfter)
2056 {
2057 return "certificate has expired";
2058 }
2059 else
2060 {
2061 return NULL;
2062 }
2063 }
2064
2065 /**
2066 * Verifies a X.509 certificate
2067 */
2068 bool verify_x509cert(const x509cert_t *cert, bool strict, time_t *until)
2069 {
2070 int pathlen;
2071
2072 *until = cert->notAfter;
2073
2074 for (pathlen = 0; pathlen < MAX_CA_PATH_LEN; pathlen++)
2075 {
2076 x509cert_t *issuer_cert;
2077 u_char buf[BUF_LEN];
2078 err_t ugh = NULL;
2079
2080 DBG(DBG_CONTROL,
2081 dntoa(buf, BUF_LEN, cert->subject);
2082 DBG_log("subject: '%s'",buf);
2083 dntoa(buf, BUF_LEN, cert->issuer);
2084 DBG_log("issuer: '%s'",buf);
2085 if (cert->authKeyID.ptr != NULL)
2086 {
2087 datatot(cert->authKeyID.ptr, cert->authKeyID.len, ':'
2088 , buf, BUF_LEN);
2089 DBG_log("authkey: %s", buf);
2090 }
2091 )
2092
2093 ugh = check_validity(cert, until);
2094
2095 if (ugh != NULL)
2096 {
2097 plog("%s", ugh);
2098 return FALSE;
2099 }
2100
2101 DBG(DBG_CONTROL,
2102 DBG_log("certificate is valid")
2103 )
2104
2105 lock_authcert_list("verify_x509cert");
2106 issuer_cert = get_authcert(cert->issuer, cert->authKeySerialNumber
2107 , cert->authKeyID, AUTH_CA);
2108
2109 if (issuer_cert == NULL)
2110 {
2111 plog("issuer cacert not found");
2112 unlock_authcert_list("verify_x509cert");
2113 return FALSE;
2114 }
2115 DBG(DBG_CONTROL,
2116 DBG_log("issuer cacert found")
2117 )
2118
2119 if (!check_signature(cert->tbsCertificate, cert->signature
2120 , cert->algorithm, cert->algorithm, issuer_cert))
2121 {
2122 plog("certificate signature is invalid");
2123 unlock_authcert_list("verify_x509cert");
2124 return FALSE;
2125 }
2126 DBG(DBG_CONTROL,
2127 DBG_log("certificate signature is valid")
2128 )
2129 unlock_authcert_list("verify_x509cert");
2130
2131 /* check if cert is a self-signed root ca */
2132 if (pathlen > 0 && same_dn(cert->issuer, cert->subject))
2133 {
2134 DBG(DBG_CONTROL,
2135 DBG_log("reached self-signed root ca")
2136 )
2137 return TRUE;
2138 }
2139 else
2140 {
2141 time_t nextUpdate = *until;
2142 time_t revocationDate = UNDEFINED_TIME;
2143 crl_reason_t revocationReason = REASON_UNSPECIFIED;
2144
2145 /* first check certificate revocation using ocsp */
2146 cert_status_t status = verify_by_ocsp(cert, &nextUpdate
2147 , &revocationDate, &revocationReason);
2148
2149 /* if ocsp service is not available then fall back to crl */
2150 if ((status == CERT_UNDEFINED)
2151 || (status == CERT_UNKNOWN && strict))
2152 {
2153 status = verify_by_crl(cert, &nextUpdate, &revocationDate
2154 , &revocationReason);
2155 }
2156
2157 switch (status)
2158 {
2159 case CERT_GOOD:
2160 /* if status information is stale */
2161 if (strict && nextUpdate < time(NULL))
2162 {
2163 DBG(DBG_CONTROL,
2164 DBG_log("certificate is good but status is stale")
2165 )
2166 remove_x509_public_key(cert);
2167 return FALSE;
2168 }
2169 DBG(DBG_CONTROL,
2170 DBG_log("certificate is good")
2171 )
2172
2173 /* with strict crl policy the public key must have the same
2174 * lifetime as the validity of the ocsp status or crl lifetime
2175 */
2176 if (strict && nextUpdate < *until)
2177 {
2178 *until = nextUpdate;
2179 }
2180 break;
2181 case CERT_REVOKED:
2182 plog("certificate was revoked on %T, reason: %N"
2183 , &revocationDate, TRUE
2184 , crl_reason_names, revocationReason);
2185 remove_x509_public_key(cert);
2186 return FALSE;
2187 case CERT_UNKNOWN:
2188 case CERT_UNDEFINED:
2189 default:
2190 plog("certificate status unknown");
2191 if (strict)
2192 {
2193 remove_x509_public_key(cert);
2194 return FALSE;
2195 }
2196 break;
2197 }
2198 }
2199
2200 /* go up one step in the trust chain */
2201 cert = issuer_cert;
2202 }
2203 plog("maximum ca path length of %d levels exceeded", MAX_CA_PATH_LEN);
2204 return FALSE;
2205 }
2206
2207 /**
2208 * List all X.509 certs in a chained list
2209 */
2210 void list_x509cert_chain(const char *caption, x509cert_t* cert,
2211 u_char auth_flags, bool utc)
2212 {
2213 bool first = TRUE;
2214 time_t now;
2215
2216 /* determine the current time */
2217 time(&now);
2218
2219 while (cert != NULL)
2220 {
2221 if (auth_flags == AUTH_NONE || (auth_flags & cert->authority_flags))
2222 {
2223 unsigned keysize;
2224 char keyid[KEYID_BUF];
2225 u_char buf[BUF_LEN];
2226 cert_t c;
2227
2228 c.type = CERT_X509_SIGNATURE;
2229 c.u.x509 = cert;
2230
2231 if (first)
2232 {
2233 whack_log(RC_COMMENT, " ");
2234 whack_log(RC_COMMENT, "List of X.509 %s Certificates:", caption);
2235 whack_log(RC_COMMENT, " ");
2236 first = FALSE;
2237 }
2238
2239 whack_log(RC_COMMENT, "%T, count: %d", &cert->installed, utc,
2240 cert->count);
2241 dntoa(buf, BUF_LEN, cert->subject);
2242 whack_log(RC_COMMENT, " subject: '%s'", buf);
2243 dntoa(buf, BUF_LEN, cert->issuer);
2244 whack_log(RC_COMMENT, " issuer: '%s'", buf);
2245 datatot(cert->serialNumber.ptr, cert->serialNumber.len, ':'
2246 , buf, BUF_LEN);
2247 whack_log(RC_COMMENT, " serial: %s", buf);
2248 form_keyid(cert->publicExponent, cert->modulus, keyid, &keysize);
2249 whack_log(RC_COMMENT, " pubkey: %4d RSA Key %s%s"
2250 , 8*keysize, keyid
2251 , cert->smartcard ? ", on smartcard" :
2252 (has_private_key(c)? ", has private key" : ""));
2253 whack_log(RC_COMMENT, " validity: not before %T %s",
2254 &cert->notBefore, utc,
2255 (cert->notBefore < now)?"ok":"fatal (not valid yet)");
2256 whack_log(RC_COMMENT, " not after %T %s",
2257 &cert->notAfter, utc,
2258 check_expiry(cert->notAfter, CA_CERT_WARNING_INTERVAL, TRUE));
2259 if (cert->subjectKeyID.ptr != NULL)
2260 {
2261 datatot(cert->subjectKeyID.ptr, cert->subjectKeyID.len, ':'
2262 , buf, BUF_LEN);
2263 whack_log(RC_COMMENT, " subjkey: %s", buf);
2264 }
2265 if (cert->authKeyID.ptr != NULL)
2266 {
2267 datatot(cert->authKeyID.ptr, cert->authKeyID.len, ':'
2268 , buf, BUF_LEN);
2269 whack_log(RC_COMMENT, " authkey: %s", buf);
2270 }
2271 if (cert->authKeySerialNumber.ptr != NULL)
2272 {
2273 datatot(cert->authKeySerialNumber.ptr, cert->authKeySerialNumber.len
2274 , ':', buf, BUF_LEN);
2275 whack_log(RC_COMMENT, " aserial: %s", buf);
2276 }
2277 }
2278 cert = cert->next;
2279 }
2280 }
2281
2282 /**
2283 * List all X.509 end certificates in a chained list
2284 */
2285 void list_x509_end_certs(bool utc)
2286 {
2287 list_x509cert_chain("End", x509certs, AUTH_NONE, utc);
2288 }