SKEYID derivation based on libstrongswan
[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 #include <crypto/hashers/hasher.h>
33
34 #include "constants.h"
35 #include "defs.h"
36 #include "mp_defs.h"
37 #include "log.h"
38 #include "id.h"
39 #include "pkcs1.h"
40 #include "x509.h"
41 #include "crl.h"
42 #include "ca.h"
43 #include "certs.h"
44 #include "keys.h"
45 #include "whack.h"
46 #include "fetch.h"
47 #include "ocsp.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 bool compute_subjectKeyID(x509cert_t *cert, chunk_t subjectKeyID)
1492 {
1493 hasher_t *hasher = lib->crypto->create_hasher(lib->crypto, HASH_SHA1);
1494
1495 if (hasher == NULL)
1496 {
1497 plog(" no SHA-1 hasher available to compute subjectKeyID");
1498 return FALSE;
1499 }
1500 hasher->get_hash(hasher, cert->subjectPublicKey, subjectKeyID.ptr);
1501 hasher->destroy(hasher);
1502 return TRUE;
1503 }
1504
1505 /**
1506 * Extracts an otherName
1507 */
1508 static bool parse_otherName(chunk_t blob, int level0)
1509 {
1510 asn1_parser_t *parser;
1511 chunk_t object;
1512 int objectID;
1513 int oid = OID_UNKNOWN;
1514 bool success = FALSE;
1515
1516 parser = asn1_parser_create(otherNameObjects, blob);
1517 parser->set_top_level(parser, level0);
1518
1519 while (parser->iterate(parser, &objectID, &object))
1520 {
1521 switch (objectID)
1522 {
1523 case ON_OBJ_ID_TYPE:
1524 oid = asn1_known_oid(object);
1525 break;
1526 case ON_OBJ_VALUE:
1527 if (oid == OID_XMPP_ADDR)
1528 {
1529 if (!asn1_parse_simple_object(&object, ASN1_UTF8STRING,
1530 parser->get_level(parser) + 1, "xmppAddr"))
1531 {
1532 goto end;
1533 }
1534 }
1535 break;
1536 default:
1537 break;
1538 }
1539 }
1540 success = parser->success(parser);
1541
1542 end:
1543 parser->destroy(parser);
1544 return success;
1545 }
1546
1547
1548 /**
1549 * Extracts a generalName
1550 */
1551 static generalName_t* parse_generalName(chunk_t blob, int level0)
1552 {
1553 u_char buf[BUF_LEN];
1554 asn1_parser_t *parser;
1555 chunk_t object;
1556 generalName_t *gn = NULL;
1557 int objectID;
1558
1559 parser = asn1_parser_create(generalNameObjects, blob);
1560 parser->set_top_level(parser, level0);
1561
1562 while (parser->iterate(parser, &objectID, &object))
1563 {
1564 bool valid_gn = FALSE;
1565
1566 switch (objectID) {
1567 case GN_OBJ_RFC822_NAME:
1568 case GN_OBJ_DNS_NAME:
1569 case GN_OBJ_URI:
1570 DBG(DBG_PARSING,
1571 DBG_log(" '%.*s'", (int)object.len, object.ptr);
1572 )
1573 valid_gn = TRUE;
1574 break;
1575 case GN_OBJ_DIRECTORY_NAME:
1576 DBG(DBG_PARSING,
1577 dntoa(buf, BUF_LEN, object);
1578 DBG_log(" '%s'", buf)
1579 )
1580 valid_gn = TRUE;
1581 break;
1582 case GN_OBJ_IP_ADDRESS:
1583 DBG(DBG_PARSING,
1584 DBG_log(" '%d.%d.%d.%d'", *object.ptr, *(object.ptr+1),
1585 *(object.ptr+2), *(object.ptr+3));
1586 )
1587 valid_gn = TRUE;
1588 break;
1589 case GN_OBJ_OTHER_NAME:
1590 if (!parse_otherName(object, parser->get_level(parser)+1))
1591 {
1592 goto end;
1593 }
1594 break;
1595 case GN_OBJ_X400_ADDRESS:
1596 case GN_OBJ_EDI_PARTY_NAME:
1597 case GN_OBJ_REGISTERED_ID:
1598 break;
1599 default:
1600 break;
1601 }
1602
1603 if (valid_gn)
1604 {
1605 gn = malloc_thing(generalName_t);
1606 gn->kind = (objectID - GN_OBJ_OTHER_NAME) / 2;
1607 gn->name = object;
1608 gn->next = NULL;
1609 goto end;
1610 }
1611 }
1612
1613 end:
1614 parser->destroy(parser);
1615 return gn;
1616 }
1617
1618 /**
1619 * Extracts one or several GNs and puts them into a chained list
1620 */
1621 static generalName_t* parse_generalNames(chunk_t blob, int level0, bool implicit)
1622 {
1623 asn1_parser_t *parser;
1624 chunk_t object;
1625 int objectID;
1626 generalName_t *top_gn = NULL;
1627
1628 parser = asn1_parser_create(generalNamesObjects, blob);
1629 parser->set_top_level(parser, level0);
1630 parser->set_flags(parser, implicit, FALSE);
1631
1632 while (parser->iterate(parser, &objectID, &object))
1633 {
1634 if (objectID == GENERAL_NAMES_GN)
1635 {
1636 generalName_t *gn = parse_generalName(object,
1637 parser->get_level(parser)+1);
1638 if (gn)
1639 {
1640 gn->next = top_gn;
1641 top_gn = gn;
1642 }
1643 }
1644 }
1645 parser->destroy(parser);
1646
1647 return top_gn;
1648 }
1649
1650 /**
1651 * Returns a directoryName
1652 */
1653 chunk_t get_directoryName(chunk_t blob, int level, bool implicit)
1654 {
1655 chunk_t name = chunk_empty;
1656 generalName_t * gn = parse_generalNames(blob, level, implicit);
1657
1658 if (gn != NULL && gn->kind == GN_DIRECTORY_NAME)
1659 {
1660 name= gn->name;
1661 }
1662 free_generalNames(gn, FALSE);
1663 return name;
1664 }
1665
1666 /**
1667 * Extracts an authoritykeyIdentifier
1668 */
1669 void parse_authorityKeyIdentifier(chunk_t blob, int level0,
1670 chunk_t *authKeyID,
1671 chunk_t *authKeySerialNumber)
1672 {
1673 asn1_parser_t *parser;
1674 chunk_t object;
1675 int objectID;
1676
1677 parser = asn1_parser_create(authKeyIdentifierObjects, blob);
1678 parser->set_top_level(parser, level0);
1679
1680 while (parser->iterate(parser, &objectID, &object))
1681 {
1682 switch (objectID)
1683 {
1684 case AUTH_KEY_ID_KEY_ID:
1685 *authKeyID = object;
1686 break;
1687 case AUTH_KEY_ID_CERT_ISSUER:
1688 {
1689 generalName_t * gn = parse_generalNames(object,
1690 parser->get_level(parser) + 1, TRUE);
1691
1692 free_generalNames(gn, FALSE);
1693 }
1694 break;
1695 case AUTH_KEY_ID_CERT_SERIAL:
1696 *authKeySerialNumber = object;
1697 break;
1698 default:
1699 break;
1700 }
1701 }
1702 parser->destroy(parser);
1703 }
1704
1705 /**
1706 * Extracts an authorityInfoAcess location
1707 */
1708 static void parse_authorityInfoAccess(chunk_t blob, int level0,
1709 chunk_t *accessLocation)
1710 {
1711 asn1_parser_t *parser;
1712 chunk_t object;
1713 int objectID;
1714 int accessMethod = OID_UNKNOWN;
1715
1716 parser = asn1_parser_create(authInfoAccessObjects, blob);
1717 parser->set_top_level(parser, level0);
1718
1719 while (parser->iterate(parser, &objectID, &object))
1720 {
1721 switch (objectID)
1722 {
1723 case AUTH_INFO_ACCESS_METHOD:
1724 accessMethod = asn1_known_oid(object);
1725 break;
1726 case AUTH_INFO_ACCESS_LOCATION:
1727 {
1728 switch (accessMethod)
1729 {
1730 case OID_OCSP:
1731 if (*object.ptr == ASN1_CONTEXT_S_6)
1732 {
1733 if (asn1_length(&object) == ASN1_INVALID_LENGTH)
1734 {
1735 goto end;
1736 }
1737 DBG(DBG_PARSING,
1738 DBG_log(" '%.*s'",(int)object.len, object.ptr)
1739 )
1740
1741 /* only HTTP(S) URIs accepted */
1742 if (strncasecmp(object.ptr, "http", 4) == 0)
1743 {
1744 *accessLocation = object;
1745 goto end;
1746 }
1747 }
1748 plog("warning: ignoring OCSP InfoAccessLocation with unkown protocol");
1749 break;
1750 default:
1751 /* unkown accessMethod, ignoring */
1752 break;
1753 }
1754 }
1755 break;
1756 default:
1757 break;
1758 }
1759 }
1760
1761 end:
1762 parser->destroy(parser);
1763 }
1764
1765 /**
1766 * Extracts extendedKeyUsage OIDs
1767 */
1768 static bool parse_extendedKeyUsage(chunk_t blob, int level0)
1769 {
1770 asn1_parser_t *parser;
1771 chunk_t object;
1772 int objectID;
1773 bool ocsp_signing = FALSE;
1774
1775 parser = asn1_parser_create(extendedKeyUsageObjects, blob);
1776 parser->set_top_level(parser, level0);
1777
1778 while (parser->iterate(parser, &objectID, &object))
1779 {
1780 if (objectID == EXT_KEY_USAGE_PURPOSE_ID
1781 && asn1_known_oid(object) == OID_OCSP_SIGNING)
1782 {
1783 ocsp_signing = TRUE;
1784 }
1785 }
1786 parser->destroy(parser);
1787
1788 return ocsp_signing;
1789 }
1790
1791 /**
1792 * Extracts one or several crlDistributionPoints
1793 * and puts them into a chained list
1794 */
1795 static generalName_t* parse_crlDistributionPoints(chunk_t blob, int level0)
1796 {
1797 asn1_parser_t *parser;
1798 chunk_t object;
1799 int objectID;
1800
1801 generalName_t *top_gn = NULL; /* top of the chained list */
1802 generalName_t **tail_gn = &top_gn; /* tail of the chained list */
1803
1804 parser = asn1_parser_create(crlDistributionPointsObjects, blob);
1805 parser->set_top_level(parser, level0);
1806
1807 while (parser->iterate(parser, &objectID, &object))
1808 {
1809 if (objectID == CRL_DIST_POINTS_FULLNAME)
1810 {
1811 generalName_t *gn;
1812
1813 gn = parse_generalNames(object, parser->get_level(parser)+1, TRUE);
1814 /* append extracted generalNames to existing chained list */
1815 *tail_gn = gn;
1816 /* find new tail of the chained list */
1817 while (gn != NULL)
1818 {
1819 tail_gn = &gn->next; gn = gn->next;
1820 }
1821 }
1822 }
1823 parser->destroy(parser);
1824
1825 return top_gn;
1826 }
1827
1828 /**
1829 * Parses an RSA public key
1830 */
1831 bool parse_RSA_public_key(chunk_t blob, u_int level0, x509cert_t *cert)
1832 {
1833 asn1_parser_t *parser;
1834 chunk_t object;
1835 int objectID;
1836 bool success = FALSE;
1837
1838 parser = asn1_parser_create(pubkeyObjects, blob);
1839 parser->set_top_level(parser, level0);
1840
1841 while (parser->iterate(parser, &objectID, &object))
1842 {
1843 switch (objectID) {
1844 case PUB_KEY_RSA_PUBLIC_KEY:
1845 cert->subjectPublicKey = object;
1846 break;
1847 case PUB_KEY_MODULUS:
1848 if (object.len < RSA_MIN_OCTETS + 1)
1849 {
1850 plog(" " RSA_MIN_OCTETS_UGH);
1851 goto end;
1852 }
1853 if (object.len > RSA_MAX_OCTETS + (size_t)(*object.ptr == 0x00))
1854 {
1855 plog(" " RSA_MAX_OCTETS_UGH);
1856 goto end;
1857 }
1858 cert->modulus = object;
1859 break;
1860 case PUB_KEY_EXPONENT:
1861 cert->publicExponent = object;
1862 break;
1863 }
1864 }
1865 success = parser->success(parser);
1866
1867 end:
1868 parser->destroy(parser);
1869 return success;
1870 }
1871
1872 /**
1873 * Parses an X.509v3 certificate
1874 */
1875 bool parse_x509cert(chunk_t blob, u_int level0, x509cert_t *cert)
1876 {
1877 u_char buf[BUF_LEN];
1878 asn1_parser_t *parser;
1879 chunk_t object;
1880 int objectID;
1881 int extn_oid = OID_UNKNOWN;
1882 bool critical;
1883 bool success = FALSE;
1884
1885 parser = asn1_parser_create(certObjects, blob);
1886 parser->set_top_level(parser, level0);
1887
1888 while (parser->iterate(parser, &objectID, &object))
1889 {
1890 u_int level = parser->get_level(parser) + 1;
1891
1892 switch (objectID) {
1893 case X509_OBJ_CERTIFICATE:
1894 cert->certificate = object;
1895 break;
1896 case X509_OBJ_TBS_CERTIFICATE:
1897 cert->tbsCertificate = object;
1898 break;
1899 case X509_OBJ_VERSION:
1900 cert->version = (object.len) ? (1+(u_int)*object.ptr) : 1;
1901 DBG(DBG_PARSING,
1902 DBG_log(" v%d", cert->version);
1903 )
1904 break;
1905 case X509_OBJ_SERIAL_NUMBER:
1906 cert->serialNumber = object;
1907 break;
1908 case X509_OBJ_SIG_ALG:
1909 cert->sigAlg = asn1_parse_algorithmIdentifier(object, level, NULL);
1910 break;
1911 case X509_OBJ_ISSUER:
1912 cert->issuer = object;
1913 DBG(DBG_PARSING,
1914 dntoa(buf, BUF_LEN, object);
1915 DBG_log(" '%s'",buf)
1916 )
1917 break;
1918 case X509_OBJ_NOT_BEFORE:
1919 cert->notBefore = asn1_parse_time(object, level);
1920 break;
1921 case X509_OBJ_NOT_AFTER:
1922 cert->notAfter = asn1_parse_time(object, level);
1923 break;
1924 case X509_OBJ_SUBJECT:
1925 cert->subject = object;
1926 DBG(DBG_PARSING,
1927 dntoa(buf, BUF_LEN, object);
1928 DBG_log(" '%s'",buf)
1929 )
1930 break;
1931 case X509_OBJ_SUBJECT_PUBLIC_KEY_ALGORITHM:
1932 if (asn1_parse_algorithmIdentifier(object, level, NULL) == OID_RSA_ENCRYPTION)
1933 {
1934 cert->subjectPublicKeyAlgorithm = PUBKEY_ALG_RSA;
1935 }
1936 else
1937 {
1938 plog(" unsupported public key algorithm");
1939 goto end;
1940 }
1941 break;
1942 case X509_OBJ_SUBJECT_PUBLIC_KEY:
1943 if (object.len > 0 && *object.ptr == 0x00)
1944 {
1945 /* skip initial bit string octet defining 0 unused bits */
1946 object = chunk_skip(object, 1);
1947 if (!parse_RSA_public_key(object, level, cert))
1948 {
1949 goto end;
1950 }
1951 }
1952 else
1953 {
1954 plog(" invalid RSA public key format");
1955 goto end;
1956 }
1957 break;
1958 case X509_OBJ_EXTN_ID:
1959 extn_oid = asn1_known_oid(object);
1960 break;
1961 case X509_OBJ_CRITICAL:
1962 critical = object.len && *object.ptr;
1963 DBG(DBG_PARSING,
1964 DBG_log(" %s",(critical)?"TRUE":"FALSE");
1965 )
1966 break;
1967 case X509_OBJ_EXTN_VALUE:
1968 {
1969 switch (extn_oid) {
1970 case OID_SUBJECT_KEY_ID:
1971 if (!asn1_parse_simple_object(&object, ASN1_OCTET_STRING,
1972 level, "keyIdentifier"))
1973 {
1974 goto end;
1975 }
1976 cert->subjectKeyID = object;
1977 break;
1978 case OID_SUBJECT_ALT_NAME:
1979 cert->subjectAltName =
1980 parse_generalNames(object, level, FALSE);
1981 break;
1982 case OID_BASIC_CONSTRAINTS:
1983 cert->isCA =
1984 parse_basicConstraints(object, level);
1985 break;
1986 case OID_CRL_DISTRIBUTION_POINTS:
1987 cert->crlDistributionPoints =
1988 parse_crlDistributionPoints(object, level);
1989 break;
1990 case OID_AUTHORITY_KEY_ID:
1991 parse_authorityKeyIdentifier(object, level
1992 , &cert->authKeyID, &cert->authKeySerialNumber);
1993 break;
1994 case OID_AUTHORITY_INFO_ACCESS:
1995 parse_authorityInfoAccess(object, level, &cert->accessLocation);
1996 break;
1997 case OID_EXTENDED_KEY_USAGE:
1998 cert->isOcspSigner = parse_extendedKeyUsage(object, level);
1999 break;
2000 case OID_NS_REVOCATION_URL:
2001 case OID_NS_CA_REVOCATION_URL:
2002 case OID_NS_CA_POLICY_URL:
2003 case OID_NS_COMMENT:
2004 if (!asn1_parse_simple_object(&object, ASN1_IA5STRING
2005 , level, oid_names[extn_oid].name))
2006 {
2007 goto end;
2008 }
2009 break;
2010 default:
2011 break;
2012 }
2013 }
2014 break;
2015 case X509_OBJ_ALGORITHM:
2016 cert->algorithm = asn1_parse_algorithmIdentifier(object, level, NULL);
2017 break;
2018 case X509_OBJ_SIGNATURE:
2019 cert->signature = object;
2020 break;
2021 default:
2022 break;
2023 }
2024 }
2025 success = parser->success(parser);
2026 time(&cert->installed);
2027
2028 end:
2029 parser->destroy(parser);
2030 return success;
2031 }
2032
2033 /**
2034 * Verify the validity of a certificate by
2035 * checking the notBefore and notAfter dates
2036 */
2037 err_t check_validity(const x509cert_t *cert, time_t *until)
2038 {
2039 time_t current_time;
2040
2041 time(&current_time);
2042 DBG(DBG_CONTROL | DBG_PARSING ,
2043 DBG_log(" not before : %T", &cert->notBefore, TRUE);
2044 DBG_log(" current time: %T", &current_time, TRUE);
2045 DBG_log(" not after : %T", &cert->notAfter, TRUE);
2046 )
2047
2048 if (cert->notAfter < *until)
2049 {
2050 *until = cert->notAfter;
2051 }
2052 if (current_time < cert->notBefore)
2053 {
2054 return "certificate is not valid yet";
2055 }
2056 if (current_time > cert->notAfter)
2057 {
2058 return "certificate has expired";
2059 }
2060 else
2061 {
2062 return NULL;
2063 }
2064 }
2065
2066 /**
2067 * Verifies a X.509 certificate
2068 */
2069 bool verify_x509cert(const x509cert_t *cert, bool strict, time_t *until)
2070 {
2071 int pathlen;
2072
2073 *until = cert->notAfter;
2074
2075 for (pathlen = 0; pathlen < MAX_CA_PATH_LEN; pathlen++)
2076 {
2077 x509cert_t *issuer_cert;
2078 u_char buf[BUF_LEN];
2079 err_t ugh = NULL;
2080
2081 DBG(DBG_CONTROL,
2082 dntoa(buf, BUF_LEN, cert->subject);
2083 DBG_log("subject: '%s'",buf);
2084 dntoa(buf, BUF_LEN, cert->issuer);
2085 DBG_log("issuer: '%s'",buf);
2086 if (cert->authKeyID.ptr != NULL)
2087 {
2088 datatot(cert->authKeyID.ptr, cert->authKeyID.len, ':'
2089 , buf, BUF_LEN);
2090 DBG_log("authkey: %s", buf);
2091 }
2092 )
2093
2094 ugh = check_validity(cert, until);
2095
2096 if (ugh != NULL)
2097 {
2098 plog("%s", ugh);
2099 return FALSE;
2100 }
2101
2102 DBG(DBG_CONTROL,
2103 DBG_log("certificate is valid")
2104 )
2105
2106 lock_authcert_list("verify_x509cert");
2107 issuer_cert = get_authcert(cert->issuer, cert->authKeySerialNumber
2108 , cert->authKeyID, AUTH_CA);
2109
2110 if (issuer_cert == NULL)
2111 {
2112 plog("issuer cacert not found");
2113 unlock_authcert_list("verify_x509cert");
2114 return FALSE;
2115 }
2116 DBG(DBG_CONTROL,
2117 DBG_log("issuer cacert found")
2118 )
2119
2120 if (!check_signature(cert->tbsCertificate, cert->signature
2121 , cert->algorithm, cert->algorithm, issuer_cert))
2122 {
2123 plog("certificate signature is invalid");
2124 unlock_authcert_list("verify_x509cert");
2125 return FALSE;
2126 }
2127 DBG(DBG_CONTROL,
2128 DBG_log("certificate signature is valid")
2129 )
2130 unlock_authcert_list("verify_x509cert");
2131
2132 /* check if cert is a self-signed root ca */
2133 if (pathlen > 0 && same_dn(cert->issuer, cert->subject))
2134 {
2135 DBG(DBG_CONTROL,
2136 DBG_log("reached self-signed root ca")
2137 )
2138 return TRUE;
2139 }
2140 else
2141 {
2142 time_t nextUpdate = *until;
2143 time_t revocationDate = UNDEFINED_TIME;
2144 crl_reason_t revocationReason = REASON_UNSPECIFIED;
2145
2146 /* first check certificate revocation using ocsp */
2147 cert_status_t status = verify_by_ocsp(cert, &nextUpdate
2148 , &revocationDate, &revocationReason);
2149
2150 /* if ocsp service is not available then fall back to crl */
2151 if ((status == CERT_UNDEFINED)
2152 || (status == CERT_UNKNOWN && strict))
2153 {
2154 status = verify_by_crl(cert, &nextUpdate, &revocationDate
2155 , &revocationReason);
2156 }
2157
2158 switch (status)
2159 {
2160 case CERT_GOOD:
2161 /* if status information is stale */
2162 if (strict && nextUpdate < time(NULL))
2163 {
2164 DBG(DBG_CONTROL,
2165 DBG_log("certificate is good but status is stale")
2166 )
2167 remove_x509_public_key(cert);
2168 return FALSE;
2169 }
2170 DBG(DBG_CONTROL,
2171 DBG_log("certificate is good")
2172 )
2173
2174 /* with strict crl policy the public key must have the same
2175 * lifetime as the validity of the ocsp status or crl lifetime
2176 */
2177 if (strict && nextUpdate < *until)
2178 {
2179 *until = nextUpdate;
2180 }
2181 break;
2182 case CERT_REVOKED:
2183 plog("certificate was revoked on %T, reason: %N"
2184 , &revocationDate, TRUE
2185 , crl_reason_names, revocationReason);
2186 remove_x509_public_key(cert);
2187 return FALSE;
2188 case CERT_UNKNOWN:
2189 case CERT_UNDEFINED:
2190 default:
2191 plog("certificate status unknown");
2192 if (strict)
2193 {
2194 remove_x509_public_key(cert);
2195 return FALSE;
2196 }
2197 break;
2198 }
2199 }
2200
2201 /* go up one step in the trust chain */
2202 cert = issuer_cert;
2203 }
2204 plog("maximum ca path length of %d levels exceeded", MAX_CA_PATH_LEN);
2205 return FALSE;
2206 }
2207
2208 /**
2209 * List all X.509 certs in a chained list
2210 */
2211 void list_x509cert_chain(const char *caption, x509cert_t* cert,
2212 u_char auth_flags, bool utc)
2213 {
2214 bool first = TRUE;
2215 time_t now;
2216
2217 /* determine the current time */
2218 time(&now);
2219
2220 while (cert != NULL)
2221 {
2222 if (auth_flags == AUTH_NONE || (auth_flags & cert->authority_flags))
2223 {
2224 unsigned keysize;
2225 char keyid[KEYID_BUF];
2226 u_char buf[BUF_LEN];
2227 cert_t c;
2228
2229 c.type = CERT_X509_SIGNATURE;
2230 c.u.x509 = cert;
2231
2232 if (first)
2233 {
2234 whack_log(RC_COMMENT, " ");
2235 whack_log(RC_COMMENT, "List of X.509 %s Certificates:", caption);
2236 whack_log(RC_COMMENT, " ");
2237 first = FALSE;
2238 }
2239
2240 whack_log(RC_COMMENT, "%T, count: %d", &cert->installed, utc,
2241 cert->count);
2242 dntoa(buf, BUF_LEN, cert->subject);
2243 whack_log(RC_COMMENT, " subject: '%s'", buf);
2244 dntoa(buf, BUF_LEN, cert->issuer);
2245 whack_log(RC_COMMENT, " issuer: '%s'", buf);
2246 datatot(cert->serialNumber.ptr, cert->serialNumber.len, ':'
2247 , buf, BUF_LEN);
2248 whack_log(RC_COMMENT, " serial: %s", buf);
2249 form_keyid(cert->publicExponent, cert->modulus, keyid, &keysize);
2250 whack_log(RC_COMMENT, " pubkey: %4d RSA Key %s%s"
2251 , 8*keysize, keyid
2252 , cert->smartcard ? ", on smartcard" :
2253 (has_private_key(c)? ", has private key" : ""));
2254 whack_log(RC_COMMENT, " validity: not before %T %s",
2255 &cert->notBefore, utc,
2256 (cert->notBefore < now)?"ok":"fatal (not valid yet)");
2257 whack_log(RC_COMMENT, " not after %T %s",
2258 &cert->notAfter, utc,
2259 check_expiry(cert->notAfter, CA_CERT_WARNING_INTERVAL, TRUE));
2260 if (cert->subjectKeyID.ptr != NULL)
2261 {
2262 datatot(cert->subjectKeyID.ptr, cert->subjectKeyID.len, ':'
2263 , buf, BUF_LEN);
2264 whack_log(RC_COMMENT, " subjkey: %s", buf);
2265 }
2266 if (cert->authKeyID.ptr != NULL)
2267 {
2268 datatot(cert->authKeyID.ptr, cert->authKeyID.len, ':'
2269 , buf, BUF_LEN);
2270 whack_log(RC_COMMENT, " authkey: %s", buf);
2271 }
2272 if (cert->authKeySerialNumber.ptr != NULL)
2273 {
2274 datatot(cert->authKeySerialNumber.ptr, cert->authKeySerialNumber.len
2275 , ':', buf, BUF_LEN);
2276 whack_log(RC_COMMENT, " aserial: %s", buf);
2277 }
2278 }
2279 cert = cert->next;
2280 }
2281 }
2282
2283 /**
2284 * List all X.509 end certificates in a chained list
2285 */
2286 void list_x509_end_certs(bool utc)
2287 {
2288 list_x509cert_chain("End", x509certs, AUTH_NONE, utc);
2289 }