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