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