pki: Properly clean up if output format for --pkcs12 is wrong
[strongswan.git] / src / pki / commands / self.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 <collections/linked_list.h>
22 #include <credentials/certificates/certificate.h>
23 #include <credentials/certificates/x509.h>
24 #include <asn1/asn1.h>
25
26 /**
27 * Free cert policy with OID
28 */
29 static void destroy_cert_policy(x509_cert_policy_t *policy)
30 {
31 free(policy->oid.ptr);
32 free(policy);
33 }
34
35 /**
36 * Free policy mapping
37 */
38 static void destroy_policy_mapping(x509_policy_mapping_t *mapping)
39 {
40 free(mapping->issuer.ptr);
41 free(mapping->subject.ptr);
42 free(mapping);
43 }
44
45 /**
46 * Create a self signed certificate.
47 */
48 static int self()
49 {
50 cred_encoding_type_t form = CERT_ASN1_DER;
51 key_type_t type = KEY_RSA;
52 hash_algorithm_t digest = HASH_SHA1;
53 certificate_t *cert = NULL;
54 private_key_t *private = NULL;
55 public_key_t *public = NULL;
56 char *file = NULL, *dn = NULL, *hex = NULL, *error = NULL, *keyid = NULL;
57 identification_t *id = NULL;
58 linked_list_t *san, *ocsp, *permitted, *excluded, *policies, *mappings;
59 int pathlen = X509_NO_CONSTRAINT, inhibit_any = X509_NO_CONSTRAINT;
60 int inhibit_mapping = X509_NO_CONSTRAINT;
61 int require_explicit = X509_NO_CONSTRAINT;
62 chunk_t serial = chunk_empty;
63 chunk_t encoding = chunk_empty;
64 time_t not_before, not_after, lifetime = 1095 * 24 * 60 * 60;
65 char *datenb = NULL, *datena = NULL, *dateform = NULL;
66 x509_flag_t flags = 0;
67 x509_cert_policy_t *policy = NULL;
68 char *arg;
69
70 san = linked_list_create();
71 ocsp = linked_list_create();
72 permitted = linked_list_create();
73 excluded = linked_list_create();
74 policies = linked_list_create();
75 mappings = linked_list_create();
76
77 while (TRUE)
78 {
79 switch (command_getopt(&arg))
80 {
81 case 'h':
82 goto usage;
83 case 't':
84 if (streq(arg, "rsa"))
85 {
86 type = KEY_RSA;
87 }
88 else if (streq(arg, "ecdsa"))
89 {
90 type = KEY_ECDSA;
91 }
92 else if (streq(arg, "bliss"))
93 {
94 type = KEY_BLISS;
95 }
96 else
97 {
98 error = "invalid input type";
99 goto usage;
100 }
101 continue;
102 case 'g':
103 if (!enum_from_name(hash_algorithm_short_names, arg, &digest))
104 {
105 error = "invalid --digest type";
106 goto usage;
107 }
108 continue;
109 case 'i':
110 file = arg;
111 continue;
112 case 'x':
113 keyid = arg;
114 continue;
115 case 'd':
116 dn = arg;
117 continue;
118 case 'a':
119 san->insert_last(san, identification_create_from_string(arg));
120 continue;
121 case 'l':
122 lifetime = atoi(arg) * 24 * 60 * 60;
123 if (!lifetime)
124 {
125 error = "invalid --lifetime value";
126 goto usage;
127 }
128 continue;
129 case 'D':
130 dateform = arg;
131 continue;
132 case 'F':
133 datenb = arg;
134 continue;
135 case 'T':
136 datena = arg;
137 continue;
138 case 's':
139 hex = arg;
140 continue;
141 case 'b':
142 flags |= X509_CA;
143 continue;
144 case 'p':
145 pathlen = atoi(arg);
146 continue;
147 case 'n':
148 permitted->insert_last(permitted,
149 identification_create_from_string(arg));
150 continue;
151 case 'N':
152 excluded->insert_last(excluded,
153 identification_create_from_string(arg));
154 continue;
155 case 'P':
156 {
157 chunk_t oid;
158
159 oid = asn1_oid_from_string(arg);
160 if (!oid.len)
161 {
162 error = "--cert-policy OID invalid";
163 goto usage;
164 }
165 INIT(policy,
166 .oid = oid,
167 );
168 policies->insert_last(policies, policy);
169 continue;
170 }
171 case 'C':
172 if (!policy)
173 {
174 error = "--cps-uri must follow a --cert-policy";
175 goto usage;
176 }
177 policy->cps_uri = arg;
178 continue;
179 case 'U':
180 if (!policy)
181 {
182 error = "--user-notice must follow a --cert-policy";
183 goto usage;
184 }
185 policy->unotice_text = arg;
186 continue;
187 case 'M':
188 {
189 char *pos = strchr(arg, ':');
190 x509_policy_mapping_t *mapping;
191 chunk_t subject_oid, issuer_oid;
192
193 if (pos)
194 {
195 *pos++ = '\0';
196 issuer_oid = asn1_oid_from_string(arg);
197 subject_oid = asn1_oid_from_string(pos);
198 }
199 if (!pos || !issuer_oid.len || !subject_oid.len)
200 {
201 error = "--policy-map OIDs invalid";
202 goto usage;
203 }
204 INIT(mapping,
205 .issuer = issuer_oid,
206 .subject = subject_oid,
207 );
208 mappings->insert_last(mappings, mapping);
209 continue;
210 }
211 case 'E':
212 require_explicit = atoi(arg);
213 continue;
214 case 'H':
215 inhibit_mapping = atoi(arg);
216 continue;
217 case 'A':
218 inhibit_any = atoi(arg);
219 continue;
220 case 'e':
221 if (streq(arg, "serverAuth"))
222 {
223 flags |= X509_SERVER_AUTH;
224 }
225 else if (streq(arg, "clientAuth"))
226 {
227 flags |= X509_CLIENT_AUTH;
228 }
229 else if (streq(arg, "ikeIntermediate"))
230 {
231 flags |= X509_IKE_INTERMEDIATE;
232 }
233 else if (streq(arg, "crlSign"))
234 {
235 flags |= X509_CRL_SIGN;
236 }
237 else if (streq(arg, "ocspSigning"))
238 {
239 flags |= X509_OCSP_SIGNER;
240 }
241 else if (streq(arg, "msSmartcardLogon"))
242 {
243 flags |= X509_MS_SMARTCARD_LOGON;
244 }
245 continue;
246 case 'f':
247 if (!get_form(arg, &form, CRED_CERTIFICATE))
248 {
249 error = "invalid output format";
250 goto usage;
251 }
252 continue;
253 case 'o':
254 ocsp->insert_last(ocsp, arg);
255 continue;
256 case EOF:
257 break;
258 default:
259 error = "invalid --self option";
260 goto usage;
261 }
262 break;
263 }
264
265 if (type == KEY_BLISS)
266 {
267 /* currently only SHA-512 is supported */
268 digest = HASH_SHA512;
269 }
270 if (!dn)
271 {
272 error = "--dn is required";
273 goto usage;
274 }
275 if (!calculate_lifetime(dateform, datenb, datena, lifetime,
276 &not_before, &not_after))
277 {
278 error = "invalid --not-before/after datetime";
279 goto usage;
280 }
281 id = identification_create_from_string(dn);
282 if (id->get_type(id) != ID_DER_ASN1_DN)
283 {
284 error = "supplied --dn is not a distinguished name";
285 goto end;
286 }
287 if (file)
288 {
289 private = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, type,
290 BUILD_FROM_FILE, file, BUILD_END);
291 }
292 else if (keyid)
293 {
294 chunk_t chunk;
295
296 chunk = chunk_from_hex(chunk_create(keyid, strlen(keyid)), NULL);
297 private = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_ANY,
298 BUILD_PKCS11_KEYID, chunk, BUILD_END);
299 free(chunk.ptr);
300 }
301 else
302 {
303 chunk_t chunk;
304
305 set_file_mode(stdin, CERT_ASN1_DER);
306 if (!chunk_from_fd(0, &chunk))
307 {
308 fprintf(stderr, "%s: ", strerror(errno));
309 error = "reading private key failed";
310 goto end;
311 }
312 private = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, type,
313 BUILD_BLOB, chunk, BUILD_END);
314 free(chunk.ptr);
315 }
316 if (!private)
317 {
318 error = "loading private key failed";
319 goto end;
320 }
321 public = private->get_public_key(private);
322 if (!public)
323 {
324 error = "extracting public key failed";
325 goto end;
326 }
327 if (hex)
328 {
329 serial = chunk_from_hex(chunk_create(hex, strlen(hex)), NULL);
330 }
331 else
332 {
333 rng_t *rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK);
334
335 if (!rng)
336 {
337 error = "no random number generator found";
338 goto end;
339 }
340 if (!rng_allocate_bytes_not_zero(rng, 8, &serial, FALSE))
341 {
342 error = "failed to generate serial number";
343 rng->destroy(rng);
344 goto end;
345 }
346 serial.ptr[0] &= 0x7F;
347 rng->destroy(rng);
348 }
349 cert = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
350 BUILD_SIGNING_KEY, private, BUILD_PUBLIC_KEY, public,
351 BUILD_SUBJECT, id, BUILD_NOT_BEFORE_TIME, not_before,
352 BUILD_NOT_AFTER_TIME, not_after, BUILD_SERIAL, serial,
353 BUILD_DIGEST_ALG, digest, BUILD_X509_FLAG, flags,
354 BUILD_PATHLEN, pathlen, BUILD_SUBJECT_ALTNAMES, san,
355 BUILD_OCSP_ACCESS_LOCATIONS, ocsp,
356 BUILD_PERMITTED_NAME_CONSTRAINTS, permitted,
357 BUILD_EXCLUDED_NAME_CONSTRAINTS, excluded,
358 BUILD_CERTIFICATE_POLICIES, policies,
359 BUILD_POLICY_MAPPINGS, mappings,
360 BUILD_POLICY_REQUIRE_EXPLICIT, require_explicit,
361 BUILD_POLICY_INHIBIT_MAPPING, inhibit_mapping,
362 BUILD_POLICY_INHIBIT_ANY, inhibit_any,
363 BUILD_END);
364 if (!cert)
365 {
366 error = "generating certificate failed";
367 goto end;
368 }
369 if (!cert->get_encoding(cert, form, &encoding))
370 {
371 error = "encoding certificate failed";
372 goto end;
373 }
374 set_file_mode(stdout, form);
375 if (fwrite(encoding.ptr, encoding.len, 1, stdout) != 1)
376 {
377 error = "writing certificate key failed";
378 goto end;
379 }
380
381 end:
382 DESTROY_IF(id);
383 DESTROY_IF(cert);
384 DESTROY_IF(public);
385 DESTROY_IF(private);
386 san->destroy_offset(san, offsetof(identification_t, destroy));
387 permitted->destroy_offset(permitted, offsetof(identification_t, destroy));
388 excluded->destroy_offset(excluded, offsetof(identification_t, destroy));
389 policies->destroy_function(policies, (void*)destroy_cert_policy);
390 mappings->destroy_function(mappings, (void*)destroy_policy_mapping);
391 ocsp->destroy(ocsp);
392 free(encoding.ptr);
393 free(serial.ptr);
394
395 if (error)
396 {
397 fprintf(stderr, "%s\n", error);
398 return 1;
399 }
400 return 0;
401
402 usage:
403 san->destroy_offset(san, offsetof(identification_t, destroy));
404 permitted->destroy_offset(permitted, offsetof(identification_t, destroy));
405 excluded->destroy_offset(excluded, offsetof(identification_t, destroy));
406 policies->destroy_function(policies, (void*)destroy_cert_policy);
407 mappings->destroy_function(mappings, (void*)destroy_policy_mapping);
408 ocsp->destroy(ocsp);
409 return command_usage(error);
410 }
411
412 /**
413 * Register the command.
414 */
415 static void __attribute__ ((constructor))reg()
416 {
417 command_register((command_t) {
418 self, 's', "self",
419 "create a self signed certificate",
420 {" [--in file|--keyid hex] [--type rsa|ecdsa|bliss]",
421 " --dn distinguished-name [--san subjectAltName]+",
422 "[--lifetime days] [--serial hex] [--ca] [--ocsp uri]+",
423 "[--flag serverAuth|clientAuth|crlSign|ocspSigning|msSmartcardLogon]+",
424 "[--nc-permitted name] [--nc-excluded name]",
425 "[--policy-map issuer-oid:subject-oid]",
426 "[--policy-explicit len] [--policy-inhibit len] [--policy-any len]",
427 "[--cert-policy oid [--cps-uri uri] [--user-notice text]]+",
428 "[--digest md5|sha1|sha224|sha256|sha384|sha512] [--outform der|pem]"},
429 {
430 {"help", 'h', 0, "show usage information"},
431 {"in", 'i', 1, "private key input file, default: stdin"},
432 {"keyid", 'x', 1, "keyid on smartcard of private key"},
433 {"type", 't', 1, "type of input key, default: rsa"},
434 {"dn", 'd', 1, "subject and issuer distinguished name"},
435 {"san", 'a', 1, "subjectAltName to include in certificate"},
436 {"lifetime", 'l', 1, "days the certificate is valid, default: 1095"},
437 {"not-before", 'F', 1, "date/time the validity of the cert starts"},
438 {"not-after", 'T', 1, "date/time the validity of the cert ends"},
439 {"dateform", 'D', 1, "strptime(3) input format, default: %d.%m.%y %T"},
440 {"serial", 's', 1, "serial number in hex, default: random"},
441 {"ca", 'b', 0, "include CA basicConstraint, default: no"},
442 {"pathlen", 'p', 1, "set path length constraint"},
443 {"nc-permitted", 'n', 1, "add permitted NameConstraint"},
444 {"nc-excluded", 'N', 1, "add excluded NameConstraint"},
445 {"cert-policy", 'P', 1, "certificatePolicy OID to include"},
446 {"cps-uri", 'C', 1, "Certification Practice statement URI for certificatePolicy"},
447 {"user-notice", 'U', 1, "user notice for certificatePolicy"},
448 {"policy-mapping", 'M', 1, "policyMapping from issuer to subject OID"},
449 {"policy-explicit", 'E', 1, "requireExplicitPolicy constraint"},
450 {"policy-inhibit", 'H', 1, "inhibitPolicyMapping constraint"},
451 {"policy-any", 'A', 1, "inhibitAnyPolicy constraint"},
452 {"flag", 'e', 1, "include extendedKeyUsage flag"},
453 {"ocsp", 'o', 1, "OCSP AuthorityInfoAccess URI to include"},
454 {"digest", 'g', 1, "digest for signature creation, default: sha1"},
455 {"outform", 'f', 1, "encoding of generated cert, default: der"},
456 }
457 });
458 }