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