pki: Choose default digest based on the signature key
[strongswan.git] / src / pki / commands / self.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 <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, "bliss"))
94 {
95 type = KEY_BLISS;
96 }
97 else
98 {
99 error = "invalid input type";
100 goto usage;
101 }
102 continue;
103 case 'g':
104 if (!enum_from_name(hash_algorithm_short_names, arg, &digest))
105 {
106 error = "invalid --digest type";
107 goto usage;
108 }
109 continue;
110 case 'i':
111 file = arg;
112 continue;
113 case 'x':
114 keyid = arg;
115 continue;
116 case 'd':
117 dn = arg;
118 continue;
119 case 'a':
120 san->insert_last(san, identification_create_from_string(arg));
121 continue;
122 case 'l':
123 lifetime = atoi(arg) * 24 * 60 * 60;
124 if (!lifetime)
125 {
126 error = "invalid --lifetime value";
127 goto usage;
128 }
129 continue;
130 case 'D':
131 dateform = arg;
132 continue;
133 case 'F':
134 datenb = arg;
135 continue;
136 case 'T':
137 datena = arg;
138 continue;
139 case 's':
140 hex = arg;
141 continue;
142 case 'b':
143 flags |= X509_CA;
144 continue;
145 case 'p':
146 pathlen = atoi(arg);
147 continue;
148 case 'n':
149 permitted->insert_last(permitted,
150 identification_create_from_string(arg));
151 continue;
152 case 'N':
153 excluded->insert_last(excluded,
154 identification_create_from_string(arg));
155 continue;
156 case 'P':
157 {
158 chunk_t oid;
159
160 oid = asn1_oid_from_string(arg);
161 if (!oid.len)
162 {
163 error = "--cert-policy OID invalid";
164 goto usage;
165 }
166 INIT(policy,
167 .oid = oid,
168 );
169 policies->insert_last(policies, policy);
170 continue;
171 }
172 case 'C':
173 if (!policy)
174 {
175 error = "--cps-uri must follow a --cert-policy";
176 goto usage;
177 }
178 policy->cps_uri = arg;
179 continue;
180 case 'U':
181 if (!policy)
182 {
183 error = "--user-notice must follow a --cert-policy";
184 goto usage;
185 }
186 policy->unotice_text = arg;
187 continue;
188 case 'M':
189 {
190 char *pos = strchr(arg, ':');
191 x509_policy_mapping_t *mapping;
192 chunk_t subject_oid, issuer_oid;
193
194 if (pos)
195 {
196 *pos++ = '\0';
197 issuer_oid = asn1_oid_from_string(arg);
198 subject_oid = asn1_oid_from_string(pos);
199 }
200 if (!pos || !issuer_oid.len || !subject_oid.len)
201 {
202 error = "--policy-map OIDs invalid";
203 goto usage;
204 }
205 INIT(mapping,
206 .issuer = issuer_oid,
207 .subject = subject_oid,
208 );
209 mappings->insert_last(mappings, mapping);
210 continue;
211 }
212 case 'E':
213 require_explicit = atoi(arg);
214 continue;
215 case 'H':
216 inhibit_mapping = atoi(arg);
217 continue;
218 case 'A':
219 inhibit_any = atoi(arg);
220 continue;
221 case 'e':
222 if (streq(arg, "serverAuth"))
223 {
224 flags |= X509_SERVER_AUTH;
225 }
226 else if (streq(arg, "clientAuth"))
227 {
228 flags |= X509_CLIENT_AUTH;
229 }
230 else if (streq(arg, "ikeIntermediate"))
231 {
232 flags |= X509_IKE_INTERMEDIATE;
233 }
234 else if (streq(arg, "crlSign"))
235 {
236 flags |= X509_CRL_SIGN;
237 }
238 else if (streq(arg, "ocspSigning"))
239 {
240 flags |= X509_OCSP_SIGNER;
241 }
242 else if (streq(arg, "msSmartcardLogon"))
243 {
244 flags |= X509_MS_SMARTCARD_LOGON;
245 }
246 continue;
247 case 'f':
248 if (!get_form(arg, &form, CRED_CERTIFICATE))
249 {
250 error = "invalid output format";
251 goto usage;
252 }
253 continue;
254 case 'o':
255 ocsp->insert_last(ocsp, arg);
256 continue;
257 case EOF:
258 break;
259 default:
260 error = "invalid --self option";
261 goto usage;
262 }
263 break;
264 }
265
266 if (!dn)
267 {
268 error = "--dn is required";
269 goto usage;
270 }
271 if (!calculate_lifetime(dateform, datenb, datena, lifetime,
272 &not_before, &not_after))
273 {
274 error = "invalid --not-before/after datetime";
275 goto usage;
276 }
277 id = identification_create_from_string(dn);
278 if (id->get_type(id) != ID_DER_ASN1_DN)
279 {
280 error = "supplied --dn is not a distinguished name";
281 goto end;
282 }
283 if (file)
284 {
285 private = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, type,
286 BUILD_FROM_FILE, file, BUILD_END);
287 }
288 else if (keyid)
289 {
290 chunk_t chunk;
291
292 chunk = chunk_from_hex(chunk_create(keyid, strlen(keyid)), NULL);
293 private = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_ANY,
294 BUILD_PKCS11_KEYID, chunk, BUILD_END);
295 free(chunk.ptr);
296 }
297 else
298 {
299 chunk_t chunk;
300
301 set_file_mode(stdin, CERT_ASN1_DER);
302 if (!chunk_from_fd(0, &chunk))
303 {
304 fprintf(stderr, "%s: ", strerror(errno));
305 error = "reading private key failed";
306 goto end;
307 }
308 private = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, type,
309 BUILD_BLOB, chunk, BUILD_END);
310 free(chunk.ptr);
311 }
312 if (!private)
313 {
314 error = "loading private key failed";
315 goto end;
316 }
317 if (digest == HASH_UNKNOWN)
318 {
319 digest = get_default_digest(private);
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: key-specific"},
455 {"outform", 'f', 1, "encoding of generated cert, default: der"},
456 }
457 });
458 }