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