pki: Support absolute --not-before/after issued certificate lifetimes
[strongswan.git] / src / pki / commands / issue.c
1 /*
2 * Copyright (C) 2009 Martin Willi
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include <time.h>
17 #include <errno.h>
18
19 #include "pki.h"
20
21 #include <utils/debug.h>
22 #include <asn1/asn1.h>
23 #include <collections/linked_list.h>
24 #include <credentials/certificates/certificate.h>
25 #include <credentials/certificates/x509.h>
26 #include <credentials/certificates/pkcs10.h>
27
28 /**
29 * Free cert policy with OID
30 */
31 static void destroy_cert_policy(x509_cert_policy_t *policy)
32 {
33 free(policy->oid.ptr);
34 free(policy);
35 }
36
37 /**
38 * Free policy mapping
39 */
40 static void destroy_policy_mapping(x509_policy_mapping_t *mapping)
41 {
42 free(mapping->issuer.ptr);
43 free(mapping->subject.ptr);
44 free(mapping);
45 }
46
47 /**
48 * Free a CRL DistributionPoint
49 */
50 static void destroy_cdp(x509_cdp_t *this)
51 {
52 DESTROY_IF(this->issuer);
53 free(this);
54 }
55
56 /**
57 * Issue a certificate using a CA certificate and key
58 */
59 static int issue()
60 {
61 cred_encoding_type_t form = CERT_ASN1_DER;
62 hash_algorithm_t digest = HASH_SHA1;
63 certificate_t *cert_req = NULL, *cert = NULL, *ca =NULL;
64 private_key_t *private = NULL;
65 public_key_t *public = NULL;
66 bool pkcs10 = FALSE;
67 char *file = NULL, *dn = NULL, *hex = NULL, *cacert = NULL, *cakey = NULL;
68 char *error = NULL, *keyid = NULL;
69 identification_t *id = NULL;
70 linked_list_t *san, *cdps, *ocsp, *permitted, *excluded, *policies, *mappings;
71 int pathlen = X509_NO_CONSTRAINT, inhibit_any = X509_NO_CONSTRAINT;
72 int inhibit_mapping = X509_NO_CONSTRAINT, require_explicit = X509_NO_CONSTRAINT;
73 chunk_t serial = chunk_empty;
74 chunk_t encoding = chunk_empty;
75 time_t not_before, not_after, lifetime = 1095 * 24 * 60 * 60;
76 char *datenb = NULL, *datena = NULL, *dateform = NULL;
77 x509_flag_t flags = 0;
78 x509_t *x509;
79 x509_cdp_t *cdp = NULL;
80 x509_cert_policy_t *policy = NULL;
81 char *arg;
82
83 san = linked_list_create();
84 cdps = linked_list_create();
85 ocsp = linked_list_create();
86 permitted = linked_list_create();
87 excluded = linked_list_create();
88 policies = linked_list_create();
89 mappings = linked_list_create();
90
91 while (TRUE)
92 {
93 switch (command_getopt(&arg))
94 {
95 case 'h':
96 goto usage;
97 case 't':
98 if (streq(arg, "pkcs10"))
99 {
100 pkcs10 = TRUE;
101 }
102 else if (!streq(arg, "pub"))
103 {
104 error = "invalid input type";
105 goto usage;
106 }
107 continue;
108 case 'g':
109 digest = enum_from_name(hash_algorithm_short_names, arg);
110 if (digest == -1)
111 {
112 error = "invalid --digest type";
113 goto usage;
114 }
115 continue;
116 case 'i':
117 file = arg;
118 continue;
119 case 'c':
120 cacert = arg;
121 continue;
122 case 'k':
123 cakey = arg;
124 continue;
125 case 'x':
126 keyid = arg;
127 continue;
128 case 'd':
129 dn = arg;
130 continue;
131 case 'a':
132 san->insert_last(san, identification_create_from_string(arg));
133 continue;
134 case 'l':
135 lifetime = atoi(arg) * 24 * 60 * 60;
136 if (!lifetime)
137 {
138 error = "invalid --lifetime value";
139 goto usage;
140 }
141 continue;
142 case 'D':
143 dateform = arg;
144 continue;
145 case 'F':
146 datenb = arg;
147 continue;
148 case 'T':
149 datena = arg;
150 continue;
151 case 's':
152 hex = arg;
153 continue;
154 case 'b':
155 flags |= X509_CA;
156 continue;
157 case 'p':
158 pathlen = atoi(arg);
159 continue;
160 case 'n':
161 permitted->insert_last(permitted,
162 identification_create_from_string(arg));
163 continue;
164 case 'N':
165 excluded->insert_last(excluded,
166 identification_create_from_string(arg));
167 continue;
168 case 'P':
169 {
170 chunk_t oid;
171
172 oid = asn1_oid_from_string(arg);
173 if (!oid.len)
174 {
175 error = "--cert-policy OID invalid";
176 goto usage;
177 }
178 INIT(policy,
179 .oid = oid,
180 );
181 policies->insert_last(policies, policy);
182 continue;
183 }
184 case 'C':
185 if (!policy)
186 {
187 error = "--cps-uri must follow a --cert-policy";
188 goto usage;
189 }
190 policy->cps_uri = arg;
191 continue;
192 case 'U':
193 if (!policy)
194 {
195 error = "--user-notice must follow a --cert-policy";
196 goto usage;
197 }
198 policy->unotice_text = arg;
199 continue;
200 case 'M':
201 {
202 char *pos = strchr(arg, ':');
203 x509_policy_mapping_t *mapping;
204 chunk_t subject_oid, issuer_oid;
205
206 if (pos)
207 {
208 *pos++ = '\0';
209 issuer_oid = asn1_oid_from_string(arg);
210 subject_oid = asn1_oid_from_string(pos);
211 }
212 if (!pos || !issuer_oid.len || !subject_oid.len)
213 {
214 error = "--policy-map OIDs invalid";
215 goto usage;
216 }
217 INIT(mapping,
218 .issuer = issuer_oid,
219 .subject = subject_oid,
220 );
221 mappings->insert_last(mappings, mapping);
222 continue;
223 }
224 case 'E':
225 require_explicit = atoi(arg);
226 continue;
227 case 'H':
228 inhibit_mapping = atoi(arg);
229 continue;
230 case 'A':
231 inhibit_any = atoi(arg);
232 continue;
233 case 'e':
234 if (streq(arg, "serverAuth"))
235 {
236 flags |= X509_SERVER_AUTH;
237 }
238 else if (streq(arg, "clientAuth"))
239 {
240 flags |= X509_CLIENT_AUTH;
241 }
242 else if (streq(arg, "ikeIntermediate"))
243 {
244 flags |= X509_IKE_INTERMEDIATE;
245 }
246 else if (streq(arg, "crlSign"))
247 {
248 flags |= X509_CRL_SIGN;
249 }
250 else if (streq(arg, "ocspSigning"))
251 {
252 flags |= X509_OCSP_SIGNER;
253 }
254 continue;
255 case 'f':
256 if (!get_form(arg, &form, CRED_CERTIFICATE))
257 {
258 error = "invalid output format";
259 goto usage;
260 }
261 continue;
262 case 'u':
263 INIT(cdp,
264 .uri = arg,
265 );
266 cdps->insert_last(cdps, cdp);
267 continue;
268 case 'I':
269 if (!cdp || cdp->issuer)
270 {
271 error = "--crlissuer must follow a --crl";
272 goto usage;
273 }
274 cdp->issuer = identification_create_from_string(arg);
275 continue;
276 case 'o':
277 ocsp->insert_last(ocsp, arg);
278 continue;
279 case EOF:
280 break;
281 default:
282 error = "invalid --issue option";
283 goto usage;
284 }
285 break;
286 }
287 if (!cacert)
288 {
289 error = "--cacert is required";
290 goto usage;
291 }
292 if (!cakey && !keyid)
293 {
294 error = "--cakey or --keyid is required";
295 goto usage;
296 }
297 if (!calculate_lifetime(dateform, datenb, datena, lifetime,
298 &not_before, &not_after))
299 {
300 error = "invalid --not-before/after datetime";
301 goto usage;
302 }
303 if (dn && *dn)
304 {
305 id = identification_create_from_string(dn);
306 if (id->get_type(id) != ID_DER_ASN1_DN)
307 {
308 error = "supplied --dn is not a distinguished name";
309 goto end;
310 }
311 }
312
313 DBG2(DBG_LIB, "Reading ca certificate:");
314 ca = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
315 BUILD_FROM_FILE, cacert, BUILD_END);
316 if (!ca)
317 {
318 error = "parsing CA certificate failed";
319 goto end;
320 }
321 x509 = (x509_t*)ca;
322 if (!(x509->get_flags(x509) & X509_CA))
323 {
324 error = "CA certificate misses CA basicConstraint";
325 goto end;
326 }
327 public = ca->get_public_key(ca);
328 if (!public)
329 {
330 error = "extracting CA certificate public key failed";
331 goto end;
332 }
333
334 DBG2(DBG_LIB, "Reading ca private key:");
335 if (cakey)
336 {
337 private = lib->creds->create(lib->creds, CRED_PRIVATE_KEY,
338 public->get_type(public),
339 BUILD_FROM_FILE, cakey, BUILD_END);
340 }
341 else
342 {
343 chunk_t chunk;
344
345 chunk = chunk_from_hex(chunk_create(keyid, strlen(keyid)), NULL);
346 private = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_ANY,
347 BUILD_PKCS11_KEYID, chunk, BUILD_END);
348 free(chunk.ptr);
349 }
350 if (!private)
351 {
352 error = "loading CA private key failed";
353 goto end;
354 }
355 if (!private->belongs_to(private, public))
356 {
357 error = "CA private key does not match CA certificate";
358 goto end;
359 }
360 public->destroy(public);
361
362 if (hex)
363 {
364 serial = chunk_from_hex(chunk_create(hex, strlen(hex)), NULL);
365 }
366 else
367 {
368 rng_t *rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
369
370 if (!rng)
371 {
372 error = "no random number generator found";
373 goto end;
374 }
375 if (!rng_allocate_bytes_not_zero(rng, 8, &serial, FALSE))
376 {
377 error = "failed to generate serial number";
378 rng->destroy(rng);
379 goto end;
380 }
381 serial.ptr[0] &= 0x7F;
382 rng->destroy(rng);
383 }
384
385 if (pkcs10)
386 {
387 enumerator_t *enumerator;
388 identification_t *subjectAltName;
389 pkcs10_t *req;
390
391 DBG2(DBG_LIB, "Reading certificate request");
392 if (file)
393 {
394 cert_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
395 CERT_PKCS10_REQUEST,
396 BUILD_FROM_FILE, file, BUILD_END);
397 }
398 else
399 {
400 chunk_t chunk;
401
402 if (!chunk_from_fd(0, &chunk))
403 {
404 fprintf(stderr, "%s: ", strerror(errno));
405 error = "reading certificate request failed";
406 goto end;
407 }
408 cert_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
409 CERT_PKCS10_REQUEST,
410 BUILD_BLOB, chunk, BUILD_END);
411 free(chunk.ptr);
412 }
413 if (!cert_req)
414 {
415 error = "parsing certificate request failed";
416 goto end;
417 }
418
419 /* If not set yet use subject from PKCS#10 certificate request as DN */
420 if (!id)
421 {
422 id = cert_req->get_subject(cert_req);
423 id = id->clone(id);
424 }
425
426 /* Add subjectAltNames from PKCS#10 certificate request */
427 req = (pkcs10_t*)cert_req;
428 enumerator = req->create_subjectAltName_enumerator(req);
429 while (enumerator->enumerate(enumerator, &subjectAltName))
430 {
431 san->insert_last(san, subjectAltName->clone(subjectAltName));
432 }
433 enumerator->destroy(enumerator);
434
435 /* Use public key from PKCS#10 certificate request */
436 public = cert_req->get_public_key(cert_req);
437 }
438 else
439 {
440 DBG2(DBG_LIB, "Reading public key:");
441 if (file)
442 {
443 public = lib->creds->create(lib->creds, CRED_PUBLIC_KEY, KEY_ANY,
444 BUILD_FROM_FILE, file, BUILD_END);
445 }
446 else
447 {
448 chunk_t chunk;
449
450 if (!chunk_from_fd(0, &chunk))
451 {
452 fprintf(stderr, "%s: ", strerror(errno));
453 error = "reading public key failed";
454 goto end;
455 }
456 public = lib->creds->create(lib->creds, CRED_PUBLIC_KEY, KEY_ANY,
457 BUILD_BLOB, chunk, BUILD_END);
458 free(chunk.ptr);
459 }
460 }
461 if (!public)
462 {
463 error = "parsing public key failed";
464 goto end;
465 }
466
467 if (!id)
468 {
469 id = identification_create_from_encoding(ID_DER_ASN1_DN,
470 chunk_from_chars(ASN1_SEQUENCE, 0));
471 }
472
473 cert = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
474 BUILD_SIGNING_KEY, private, BUILD_SIGNING_CERT, ca,
475 BUILD_PUBLIC_KEY, public, BUILD_SUBJECT, id,
476 BUILD_NOT_BEFORE_TIME, not_before, BUILD_DIGEST_ALG, digest,
477 BUILD_NOT_AFTER_TIME, not_after, BUILD_SERIAL, serial,
478 BUILD_SUBJECT_ALTNAMES, san, BUILD_X509_FLAG, flags,
479 BUILD_PATHLEN, pathlen,
480 BUILD_CRL_DISTRIBUTION_POINTS, cdps,
481 BUILD_OCSP_ACCESS_LOCATIONS, ocsp,
482 BUILD_PERMITTED_NAME_CONSTRAINTS, permitted,
483 BUILD_EXCLUDED_NAME_CONSTRAINTS, excluded,
484 BUILD_CERTIFICATE_POLICIES, policies,
485 BUILD_POLICY_MAPPINGS, mappings,
486 BUILD_POLICY_REQUIRE_EXPLICIT, require_explicit,
487 BUILD_POLICY_INHIBIT_MAPPING, inhibit_mapping,
488 BUILD_POLICY_INHIBIT_ANY, inhibit_any,
489 BUILD_END);
490 if (!cert)
491 {
492 error = "generating certificate failed";
493 goto end;
494 }
495 if (!cert->get_encoding(cert, form, &encoding))
496 {
497 error = "encoding certificate failed";
498 goto end;
499 }
500 if (fwrite(encoding.ptr, encoding.len, 1, stdout) != 1)
501 {
502 error = "writing certificate key failed";
503 goto end;
504 }
505
506 end:
507 DESTROY_IF(id);
508 DESTROY_IF(cert_req);
509 DESTROY_IF(cert);
510 DESTROY_IF(ca);
511 DESTROY_IF(public);
512 DESTROY_IF(private);
513 san->destroy_offset(san, offsetof(identification_t, destroy));
514 permitted->destroy_offset(permitted, offsetof(identification_t, destroy));
515 excluded->destroy_offset(excluded, offsetof(identification_t, destroy));
516 policies->destroy_function(policies, (void*)destroy_cert_policy);
517 mappings->destroy_function(mappings, (void*)destroy_policy_mapping);
518 cdps->destroy_function(cdps, (void*)destroy_cdp);
519 ocsp->destroy(ocsp);
520 free(encoding.ptr);
521 free(serial.ptr);
522
523 if (error)
524 {
525 fprintf(stderr, "%s\n", error);
526 return 1;
527 }
528 return 0;
529
530 usage:
531 san->destroy_offset(san, offsetof(identification_t, destroy));
532 permitted->destroy_offset(permitted, offsetof(identification_t, destroy));
533 excluded->destroy_offset(excluded, offsetof(identification_t, destroy));
534 policies->destroy_function(policies, (void*)destroy_cert_policy);
535 mappings->destroy_function(mappings, (void*)destroy_policy_mapping);
536 cdps->destroy_function(cdps, (void*)destroy_cdp);
537 ocsp->destroy(ocsp);
538 return command_usage(error);
539 }
540
541 /**
542 * Register the command.
543 */
544 static void __attribute__ ((constructor))reg()
545 {
546 command_register((command_t) {
547 issue, 'i', "issue",
548 "issue a certificate using a CA certificate and key",
549 {"[--in file] [--type pub|pkcs10] --cakey file|--cakeyid hex",
550 " --cacert file [--dn subject-dn] [--san subjectAltName]+",
551 "[--lifetime days] [--serial hex] [--ca] [--pathlen len]",
552 "[--flag serverAuth|clientAuth|crlSign|ocspSigning]+",
553 "[--crl uri [--crlissuer i]]+ [--ocsp uri]+ [--nc-permitted name]",
554 "[--nc-excluded name] [--policy-mapping issuer-oid:subject-oid]",
555 "[--policy-explicit len] [--policy-inhibit len] [--policy-any len]",
556 "[--cert-policy oid [--cps-uri uri] [--user-notice text]]+",
557 "[--digest md5|sha1|sha224|sha256|sha384|sha512] [--outform der|pem]"},
558 {
559 {"help", 'h', 0, "show usage information"},
560 {"in", 'i', 1, "public key/request file to issue, default: stdin"},
561 {"type", 't', 1, "type of input, default: pub"},
562 {"cacert", 'c', 1, "CA certificate file"},
563 {"cakey", 'k', 1, "CA private key file"},
564 {"cakeyid", 'x', 1, "keyid on smartcard of CA private key"},
565 {"dn", 'd', 1, "distinguished name to include as subject"},
566 {"san", 'a', 1, "subjectAltName to include in certificate"},
567 {"lifetime", 'l', 1, "days the certificate is valid, default: 1095"},
568 {"not-before", 'F', 1, "date/time the validity of the cert starts"},
569 {"not-after", 'T', 1, "date/time the validity of the cert ends"},
570 {"dateform", 'D', 1, "strptime(3) input format, default: %d.%m.%y %T"},
571 {"serial", 's', 1, "serial number in hex, default: random"},
572 {"ca", 'b', 0, "include CA basicConstraint, default: no"},
573 {"pathlen", 'p', 1, "set path length constraint"},
574 {"nc-permitted", 'n', 1, "add permitted NameConstraint"},
575 {"nc-excluded", 'N', 1, "add excluded NameConstraint"},
576 {"cert-policy", 'P', 1, "certificatePolicy OID to include"},
577 {"cps-uri", 'C', 1, "Certification Practice statement URI for certificatePolicy"},
578 {"user-notice", 'U', 1, "user notice for certificatePolicy"},
579 {"policy-mapping", 'M', 1, "policyMapping from issuer to subject OID"},
580 {"policy-explicit", 'E', 1, "requireExplicitPolicy constraint"},
581 {"policy-inhibit", 'H', 1, "inhibitPolicyMapping constraint"},
582 {"policy-any", 'A', 1, "inhibitAnyPolicy constraint"},
583 {"flag", 'e', 1, "include extendedKeyUsage flag"},
584 {"crl", 'u', 1, "CRL distribution point URI to include"},
585 {"crlissuer", 'I', 1, "CRL Issuer for CRL at distribution point"},
586 {"ocsp", 'o', 1, "OCSP AuthorityInfoAccess URI to include"},
587 {"digest", 'g', 1, "digest for signature creation, default: sha1"},
588 {"outform", 'f', 1, "encoding of generated cert, default: der"},
589 }
590 });
591 }