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