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