scepclient: Some code cleanup.
[strongswan.git] / src / scepclient / scepclient.c
1 /*
2 * Copyright (C) 2005 Jan Hutter, 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 <stdarg.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <getopt.h>
21 #include <ctype.h>
22 #include <unistd.h>
23 #include <time.h>
24
25 #include <freeswan.h>
26
27 #include <library.h>
28 #include <debug.h>
29 #include <asn1/asn1.h>
30 #include <asn1/oid.h>
31 #include <utils/optionsfrom.h>
32 #include <utils/enumerator.h>
33 #include <utils/linked_list.h>
34 #include <crypto/hashers/hasher.h>
35 #include <crypto/crypters/crypter.h>
36 #include <crypto/proposal/proposal_keywords.h>
37 #include <credentials/keys/private_key.h>
38 #include <credentials/keys/public_key.h>
39 #include <credentials/certificates/certificate.h>
40 #include <credentials/certificates/x509.h>
41 #include <credentials/certificates/pkcs10.h>
42 #include <plugins/plugin.h>
43
44 #include "../pluto/constants.h"
45 #include "../pluto/defs.h"
46 #include "../pluto/log.h"
47 #include "../pluto/certs.h"
48 #include "../pluto/pkcs7.h"
49
50 #include "scep.h"
51
52 /*
53 * definition of some defaults
54 */
55
56 /* default name of DER-encoded PKCS#1 private key file */
57 #define DEFAULT_FILENAME_PKCS1 "myKey.der"
58
59 /* default name of DER-encoded PKCS#10 certificate request file */
60 #define DEFAULT_FILENAME_PKCS10 "myReq.der"
61
62 /* default name of DER-encoded PKCS#7 file */
63 #define DEFAULT_FILENAME_PKCS7 "pkcs7.der"
64
65 /* default name of DER-encoded self-signed X.509 certificate file */
66 #define DEFAULT_FILENAME_CERT_SELF "selfCert.der"
67
68 /* default name of DER-encoded X.509 certificate file */
69 #define DEFAULT_FILENAME_CERT "myCert.der"
70
71 /* default name of DER-encoded CA cert file used for key encipherment */
72 #define DEFAULT_FILENAME_CACERT_ENC "caCert.der"
73
74 /* default name of the der encoded CA cert file used for signature verification */
75 #define DEFAULT_FILENAME_CACERT_SIG "caCert.der"
76
77 /* default prefix of the der encoded CA certificates received from the SCEP server */
78 #define DEFAULT_FILENAME_PREFIX_CACERT "caCert.der"
79
80 /* default certificate validity */
81 #define DEFAULT_CERT_VALIDITY 5 * 3600 * 24 * 365 /* seconds */
82
83 /* default polling time interval in SCEP manual mode */
84 #define DEFAULT_POLL_INTERVAL 20 /* seconds */
85
86 /* default key length for self-generated RSA keys */
87 #define DEFAULT_RSA_KEY_LENGTH 2048 /* bits */
88
89 /* default distinguished name */
90 #define DEFAULT_DN "C=CH, O=Linux strongSwan, CN="
91
92 /* challenge password buffer size */
93 #define MAX_PASSWORD_LENGTH 256
94
95 /* Max length of filename for tempfile */
96 #define MAX_TEMP_FILENAME_LENGTH 256
97
98
99 /* current scepclient version */
100 static const char *scepclient_version = "1.0";
101
102 /* by default the CRL policy is lenient */
103 bool strict_crl_policy = FALSE;
104
105 /* by default pluto does not check crls dynamically */
106 long crl_check_interval = 0;
107
108 /* by default pluto logs out after every smartcard use */
109 bool pkcs11_keep_state = FALSE;
110
111 /* options read by optionsfrom */
112 options_t *options;
113
114 /*
115 * Global variables
116 */
117
118 chunk_t pkcs1;
119 chunk_t pkcs7;
120 chunk_t challengePassword;
121 chunk_t serialNumber;
122 chunk_t transID;
123 chunk_t fingerprint;
124 chunk_t encoding;
125 chunk_t pkcs10_encoding;
126 chunk_t issuerAndSubject;
127 chunk_t getCertInitial;
128 chunk_t scep_response;
129
130 linked_list_t *subjectAltNames;
131
132 identification_t *subject = NULL;
133 private_key_t *private_key = NULL;
134 public_key_t *public_key = NULL;
135 certificate_t *x509_signer = NULL;
136 certificate_t *x509_ca_enc = NULL;
137 certificate_t *x509_ca_sig = NULL;
138 certificate_t *pkcs10_req = NULL;
139
140 /**
141 * @brief exit scepclient
142 *
143 * @param status 0 = OK, 1 = general discomfort
144 */
145 static void exit_scepclient(err_t message, ...)
146 {
147 int status = 0;
148
149 DESTROY_IF(subject);
150 DESTROY_IF(private_key);
151 DESTROY_IF(public_key);
152 DESTROY_IF(x509_signer);
153 DESTROY_IF(x509_ca_enc);
154 DESTROY_IF(x509_ca_sig);
155 DESTROY_IF(pkcs10_req);
156 subjectAltNames->destroy_offset(subjectAltNames,
157 offsetof(identification_t, destroy));
158 free(pkcs1.ptr);
159 free(pkcs7.ptr);
160 free(serialNumber.ptr);
161 free(transID.ptr);
162 free(fingerprint.ptr);
163 free(encoding.ptr);
164 free(pkcs10_encoding.ptr);
165 free(issuerAndSubject.ptr);
166 free(getCertInitial.ptr);
167 free(scep_response.ptr);
168 options->destroy(options);
169
170 /* print any error message to stderr */
171 if (message != NULL && *message != '\0')
172 {
173 va_list args;
174 char m[LOG_WIDTH]; /* longer messages will be truncated */
175
176 va_start(args, message);
177 vsnprintf(m, sizeof(m), message, args);
178 va_end(args);
179
180 fprintf(stderr, "error: %s\n", m);
181 status = -1;
182 }
183 library_deinit();
184 close_log();
185 exit(status);
186 }
187
188 /**
189 * @brief prints the program version and exits
190 *
191 */
192 static void version(void)
193 {
194 printf("scepclient %s\n", scepclient_version);
195 exit_scepclient(NULL);
196 }
197
198 /**
199 * @brief prints the usage of the program to the stderr output
200 *
201 * If message is set, program is exitet with 1 (error)
202 * @param message message in case of an error
203 */
204 static void usage(const char *message)
205 {
206 fprintf(stderr,
207 "Usage: scepclient\n"
208 " --help (-h) show usage and exit\n"
209 " --version (-v) show version and exit\n"
210 " --quiet (-q) do not write log output to stderr\n"
211 " --in (-i) <type>[=<filename>] use <filename> of <type> for input \n"
212 " <type> = pkcs1 | cacert-enc | cacert-sig\n"
213 " - if no pkcs1 input is defined, a \n"
214 " RSA key will be generated\n"
215 " - if no filename is given, default is used\n"
216 " --out (-o) <type>[=<filename>] write output of <type> to <filename>\n"
217 " multiple outputs are allowed\n"
218 " <type> = pkcs1 | pkcs10 | pkcs7 | cert-self | cert | cacert\n"
219 " - type cacert defines filename prefix of\n"
220 " received CA certificate(s)\n"
221 " - if no filename is given, default is used\n"
222 " --optionsfrom (-+) <filename> reads additional options from given file\n"
223 " --force (-f) force existing file(s)\n"
224 "\n"
225 "Options for key generation (pkcs1):\n"
226 " --keylength (-k) <bits> key length for RSA key generation\n"
227 "(default: 2048 bits)\n"
228 "\n"
229 "Options for validity:\n"
230 " --days (-D) <days> validity in days\n"
231 " --startdate (-S) <YYMMDDHHMMSS>Z not valid before date\n"
232 " --enddate (-E) <YYMMDDHHMMSS>Z not valid after date\n"
233 "\n"
234 "Options for request generation (pkcs10):\n"
235 " --dn (-d) <dn> comma separated list of distinguished names\n"
236 " --subjectAltName (-s) <t>=<v> include subjectAltName in certificate request\n"
237 " <t> = email | dns | ip \n"
238 " --password (-p) <pw> challenge password\n"
239 " - if pw is '%%prompt', password gets prompted for\n"
240 " --algorithm (-a) <algo> use specified algorithm for PKCS#7 encryption\n"
241 " <algo> = des | 3des (default) | aes128| aes192 | \n"
242 " aes256 | camellia128 | camellia192 | camellia256\n"
243 "\n"
244 "Options for enrollment (cert):\n"
245 " --url (-u) <url> url of the SCEP server\n"
246 " --method (-m) post | get http request type\n"
247 " --interval (-t) <seconds> manual mode poll interval in seconds (default 20s)\n"
248 " --maxpolltime (-x) <seconds> max poll time in seconds when in manual mode\n"
249 " (default: unlimited)\n"
250 #ifdef DEBUG
251 "\n"
252 "Debugging output:\n"
253 " --debug-all (-A) show everything except private\n"
254 " --debug-parsing (-P) show parsing relevant stuff\n"
255 " --debug-raw (-R) show raw hex dumps\n"
256 " --debug-control (-C) show control flow output\n"
257 " --debug-controlmore (-M) show more control flow\n"
258 " --debug-private (-X) show sensitive data (private keys, etc.)\n"
259 #endif
260 );
261 exit_scepclient(message);
262 }
263
264 /**
265 * @brief main of scepclient
266 *
267 * @param argc number of arguments
268 * @param argv pointer to the argument values
269 */
270 int main(int argc, char **argv)
271 {
272 /* external values */
273 extern char * optarg;
274 extern int optind;
275
276 /* type of input and output files */
277 typedef enum {
278 PKCS1 = 0x01,
279 PKCS10 = 0x02,
280 PKCS7 = 0x04,
281 CERT_SELF = 0x08,
282 CERT = 0x10,
283 CACERT_ENC = 0x20,
284 CACERT_SIG = 0x40
285 } scep_filetype_t;
286
287 /* filetype to read from, defaults to "generate a key" */
288 scep_filetype_t filetype_in = 0;
289
290 /* filetype to write to, no default here */
291 scep_filetype_t filetype_out = 0;
292
293 /* input files */
294 char *file_in_pkcs1 = DEFAULT_FILENAME_PKCS1;
295 char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
296 char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;
297
298 /* output files */
299 char *file_out_pkcs1 = DEFAULT_FILENAME_PKCS1;
300 char *file_out_pkcs10 = DEFAULT_FILENAME_PKCS10;
301 char *file_out_pkcs7 = DEFAULT_FILENAME_PKCS7;
302 char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
303 char *file_out_cert = DEFAULT_FILENAME_CERT;
304 char *file_out_ca_cert = DEFAULT_FILENAME_CACERT_ENC;
305
306 /* by default user certificate is requested */
307 bool request_ca_certificate = FALSE;
308
309 /* by default existing files are not overwritten */
310 bool force = FALSE;
311
312 /* length of RSA key in bits */
313 u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;
314
315 /* validity of self-signed certificate */
316 time_t validity = DEFAULT_CERT_VALIDITY;
317 time_t notBefore = 0;
318 time_t notAfter = 0;
319
320 /* distinguished name for requested certificate, ASCII format */
321 char *distinguishedName = NULL;
322
323 /* challenge password */
324 char challenge_password_buffer[MAX_PASSWORD_LENGTH];
325
326 /* symmetric encryption algorithm used by pkcs7, default is 3DES */
327 int pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;
328
329 /* digest algorithm used by pkcs7, default is SHA-1 */
330 int pkcs7_digest_alg = OID_SHA1;
331
332 /* signature algorithm used by pkcs10, default is SHA-1 */
333 hash_algorithm_t pkcs10_signature_alg = HASH_SHA1;
334
335 /* URL of the SCEP-Server */
336 char *scep_url = NULL;
337
338 /* http request method, default is GET */
339 bool http_get_request = TRUE;
340
341 /* poll interval time in manual mode in seconds */
342 u_int poll_interval = DEFAULT_POLL_INTERVAL;
343
344 /* maximum poll time */
345 u_int max_poll_time = 0;
346
347 err_t ugh = NULL;
348
349 /* initialize library */
350 if (!library_init(NULL))
351 {
352 library_deinit();
353 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY);
354 }
355 if (lib->integrity &&
356 !lib->integrity->check_file(lib->integrity, "scepclient", argv[0]))
357 {
358 fprintf(stderr, "integrity check of scepclient failed\n");
359 library_deinit();
360 exit(SS_RC_DAEMON_INTEGRITY);
361 }
362
363 /* initialize global variables */
364 pkcs1 = chunk_empty;
365 pkcs7 = chunk_empty;
366 serialNumber = chunk_empty;
367 transID = chunk_empty;
368 fingerprint = chunk_empty;
369 encoding = chunk_empty;
370 pkcs10_encoding = chunk_empty;
371 issuerAndSubject = chunk_empty;
372 challengePassword = chunk_empty;
373 getCertInitial = chunk_empty;
374 scep_response = chunk_empty;
375 subjectAltNames = linked_list_create();
376 options = options_create();
377 log_to_stderr = TRUE;
378
379 for (;;)
380 {
381 static const struct option long_opts[] = {
382 /* name, has_arg, flag, val */
383 { "help", no_argument, NULL, 'h' },
384 { "version", no_argument, NULL, 'v' },
385 { "optionsfrom", required_argument, NULL, '+' },
386 { "quiet", no_argument, NULL, 'q' },
387 { "in", required_argument, NULL, 'i' },
388 { "out", required_argument, NULL, 'o' },
389 { "force", no_argument, NULL, 'f' },
390 { "keylength", required_argument, NULL, 'k' },
391 { "dn", required_argument, NULL, 'd' },
392 { "days", required_argument, NULL, 'D' },
393 { "startdate", required_argument, NULL, 'S' },
394 { "enddate", required_argument, NULL, 'E' },
395 { "subjectAltName", required_argument, NULL, 's' },
396 { "password", required_argument, NULL, 'p' },
397 { "algorithm", required_argument, NULL, 'a' },
398 { "url", required_argument, NULL, 'u' },
399 { "method", required_argument, NULL, 'm' },
400 { "interval", required_argument, NULL, 't' },
401 { "maxpolltime", required_argument, NULL, 'x' },
402 #ifdef DEBUG
403 { "debug-all", no_argument, NULL, 'A' },
404 { "debug-parsing", no_argument, NULL, 'P'},
405 { "debug-raw", no_argument, NULL, 'R'},
406 { "debug-control", no_argument, NULL, 'C'},
407 { "debug-controlmore", no_argument, NULL, 'M'},
408 { "debug-private", no_argument, NULL, 'X'},
409 #endif
410 { 0,0,0,0 }
411 };
412
413 /* parse next option */
414 int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:m:t:x:APRCMS", long_opts, NULL);
415
416 switch (c)
417 {
418 case EOF: /* end of flags */
419 break;
420
421 case 'h': /* --help */
422 usage(NULL);
423
424 case 'v': /* --version */
425 version();
426
427 case 'q': /* --quiet */
428 log_to_stderr = FALSE;
429 continue;
430
431 case 'i': /* --in <type> [= <filename>] */
432 {
433 char *filename = strstr(optarg, "=");
434
435 if (filename)
436 {
437 /* replace '=' by '\0' */
438 *filename = '\0';
439 /* set pointer to start of filename */
440 filename++;
441 }
442 if (strcaseeq("pkcs1", optarg))
443 {
444 filetype_in |= PKCS1;
445 if (filename)
446 file_in_pkcs1 = filename;
447 }
448 else if (strcaseeq("cacert-enc", optarg))
449 {
450 filetype_in |= CACERT_ENC;
451 if (filename)
452 file_in_cacert_enc = filename;
453 }
454 else if (strcaseeq("cacert-sig", optarg))
455 {
456 filetype_in |= CACERT_SIG;
457 if (filename)
458 file_in_cacert_sig = filename;
459 }
460 else
461 {
462 usage("invalid --in file type");
463 }
464 continue;
465 }
466
467 case 'o': /* --out <type> [= <filename>] */
468 {
469 char *filename = strstr(optarg, "=");
470
471 if (filename)
472 {
473 /* replace '=' by '\0' */
474 *filename = '\0';
475 /* set pointer to start of filename */
476 filename++;
477 }
478 if (strcaseeq("pkcs1", optarg))
479 {
480 filetype_out |= PKCS1;
481 if (filename)
482 file_out_pkcs1 = filename;
483 }
484 else if (strcaseeq("pkcs10", optarg))
485 {
486 filetype_out |= PKCS10;
487 if (filename)
488 file_out_pkcs10 = filename;
489 }
490 else if (strcaseeq("pkcs7", optarg))
491 {
492 filetype_out |= PKCS7;
493 if (filename)
494 file_out_pkcs7 = filename;
495 }
496 else if (strcaseeq("cert-self", optarg))
497 {
498 filetype_out |= CERT_SELF;
499 if (filename)
500 file_out_cert_self = filename;
501 }
502 else if (strcaseeq("cert", optarg))
503 {
504 filetype_out |= CERT;
505 if (filename)
506 file_out_cert = filename;
507 }
508 else if (strcaseeq("cacert", optarg))
509 {
510 request_ca_certificate = TRUE;
511 if (filename)
512 file_out_ca_cert = filename;
513 }
514 else
515 {
516 usage("invalid --out file type");
517 }
518 continue;
519 }
520
521 case 'f': /* --force */
522 force = TRUE;
523 continue;
524
525 case '+': /* --optionsfrom <filename> */
526 if (!options->from(options, optarg, &argc, &argv, optind))
527 {
528 exit_scepclient("optionsfrom failed");
529 }
530 continue;
531
532 case 'k': /* --keylength <length> */
533 {
534 div_t q;
535
536 rsa_keylength = atoi(optarg);
537 if (rsa_keylength == 0)
538 usage("invalid keylength");
539
540 /* check if key length is a multiple of 8 bits */
541 q = div(rsa_keylength, 2*BITS_PER_BYTE);
542 if (q.rem != 0)
543 {
544 exit_scepclient("keylength is not a multiple of %d bits!"
545 , 2*BITS_PER_BYTE);
546 }
547 continue;
548 }
549
550 case 'D': /* --days */
551 if (optarg == NULL || !isdigit(optarg[0]))
552 {
553 usage("missing number of days");
554 }
555 else
556 {
557 char *endptr;
558 long days = strtol(optarg, &endptr, 0);
559
560 if (*endptr != '\0' || endptr == optarg
561 || days <= 0)
562 usage("<days> must be a positive number");
563 validity = 24*3600*days;
564 }
565 continue;
566
567 case 'S': /* --startdate */
568 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
569 {
570 usage("date format must be YYMMDDHHMMSSZ");
571 }
572 else
573 {
574 chunk_t date = { optarg, 13 };
575 notBefore = asn1_to_time(&date, ASN1_UTCTIME);
576 }
577 continue;
578
579 case 'E': /* --enddate */
580 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
581 {
582 usage("date format must be YYMMDDHHMMSSZ");
583 }
584 else
585 {
586 chunk_t date = { optarg, 13 };
587 notAfter = asn1_to_time(&date, ASN1_UTCTIME);
588 }
589 continue;
590
591 case 'd': /* --dn */
592 if (distinguishedName)
593 {
594 usage("only one distinguished name allowed");
595 }
596 distinguishedName = optarg;
597 continue;
598
599 case 's': /* --subjectAltName */
600 {
601 char *value = strstr(optarg, "=");
602
603 if (value)
604 {
605 /* replace '=' by '\0' */
606 *value = '\0';
607 /* set pointer to start of value */
608 value++;
609 }
610
611 if (strcaseeq("email", optarg) ||
612 strcaseeq("dns", optarg) ||
613 strcaseeq("ip", optarg))
614 {
615 subjectAltNames->insert_last(subjectAltNames,
616 identification_create_from_string(value));
617 continue;
618 }
619 else
620 {
621 usage("invalid --subjectAltName type");
622 continue;
623 }
624 }
625
626 case 'p': /* --password */
627 if (challengePassword.len > 0)
628 {
629 usage("only one challenge password allowed");
630 }
631 if (strcaseeq("%prompt", optarg))
632 {
633 printf("Challenge password: ");
634 if (fgets(challenge_password_buffer,
635 sizeof(challenge_password_buffer) - 1, stdin))
636 {
637 challengePassword.ptr = challenge_password_buffer;
638 /* discard the terminating '\n' from the input */
639 challengePassword.len = strlen(challenge_password_buffer) - 1;
640 }
641 else
642 {
643 usage("challenge password could not be read");
644 }
645 }
646 else
647 {
648 challengePassword.ptr = optarg;
649 challengePassword.len = strlen(optarg);
650 }
651 continue;
652
653 case 'u': /* -- url */
654 if (scep_url)
655 {
656 usage("only one URL argument allowed");
657 }
658 scep_url = optarg;
659 continue;
660
661 case 'm': /* --method */
662 if (strcaseeq("get", optarg))
663 {
664 http_get_request = TRUE;
665 }
666 else if (strcaseeq("post", optarg))
667 {
668 http_get_request = FALSE;
669 }
670 else
671 {
672 usage("invalid http request method specified");
673 }
674 continue;
675
676 case 't': /* --interval */
677 poll_interval = atoi(optarg);
678 if (poll_interval <= 0)
679 {
680 usage("invalid interval specified");
681 }
682 continue;
683
684 case 'x': /* --maxpolltime */
685 max_poll_time = atoi(optarg);
686 continue;
687
688 case 'a': /*--algorithm */
689 {
690 const proposal_token_t *token;
691
692 token = proposal_get_token(optarg, strlen(optarg));
693 if (token == NULL || token->type != ENCRYPTION_ALGORITHM)
694 {
695 usage("invalid algorithm specified");
696 }
697 pkcs7_symmetric_cipher = encryption_algorithm_to_oid(
698 token->algorithm, token->keysize);
699 if (pkcs7_symmetric_cipher == OID_UNKNOWN)
700 {
701 usage("unsupported encryption algorithm specified");
702 }
703 continue;
704 }
705 #ifdef DEBUG
706 case 'A': /* --debug-all */
707 base_debugging |= DBG_ALL;
708 continue;
709 case 'P': /* debug parsing */
710 base_debugging |= DBG_PARSING;
711 continue;
712 case 'R': /* debug raw */
713 base_debugging |= DBG_RAW;
714 continue;
715 case 'C': /* debug control */
716 base_debugging |= DBG_CONTROL;
717 continue;
718 case 'M': /* debug control more */
719 base_debugging |= DBG_CONTROLMORE;
720 continue;
721 case 'X': /* debug private */
722 base_debugging |= DBG_PRIVATE;
723 continue;
724 #endif
725 default:
726 usage("unknown option");
727 }
728 /* break from loop */
729 break;
730 }
731 cur_debugging = base_debugging;
732
733 init_log("scepclient");
734
735 /* load plugins, further infrastructure may need it */
736 if (!lib->plugins->load(lib->plugins, NULL,
737 lib->settings->get_str(lib->settings, "scepclient.load", PLUGINS)))
738 {
739 exit_scepclient("plugin loading failed");
740 }
741 DBG1(DBG_LIB, " loaded plugins: %s",
742 lib->plugins->loaded_plugins(lib->plugins));
743
744 if ((filetype_out == 0) && (!request_ca_certificate))
745 {
746 usage ("--out filetype required");
747 }
748 if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
749 {
750 usage("in CA certificate request, no other --in or --out option allowed");
751 }
752
753 /* check if url is given, if cert output defined */
754 if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
755 {
756 usage("URL of SCEP server required");
757 }
758
759 /* check for sanity of --in/--out */
760 if (!filetype_in && (filetype_in > filetype_out))
761 {
762 usage("cannot generate --out of given --in!");
763 }
764
765 /* get CA cert */
766 if (request_ca_certificate)
767 {
768 char *path = concatenate_paths(CA_CERT_PATH, file_out_ca_cert);
769
770 if (!scep_http_request(scep_url, chunk_empty, SCEP_GET_CA_CERT,
771 http_get_request, &scep_response))
772 {
773 exit_scepclient("did not receive a valid scep response");
774 }
775
776 if (!chunk_write(scep_response, path, "ca cert", 0022, force))
777 {
778 exit_scepclient("could not write ca cert file '%s'", path);
779 }
780 exit_scepclient(NULL); /* no further output required */
781 }
782
783 /*
784 * input of PKCS#1 file
785 */
786 if (filetype_in & PKCS1) /* load an RSA key pair from file */
787 {
788 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_in_pkcs1);
789
790 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
791 BUILD_FROM_FILE, path, BUILD_END);
792 }
793 else /* generate an RSA key pair */
794 {
795 private_key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, KEY_RSA,
796 BUILD_KEY_SIZE, rsa_keylength,
797 BUILD_END);
798 }
799 if (private_key == NULL)
800 {
801 exit_scepclient("no RSA private key available");
802 }
803 public_key = private_key->get_public_key(private_key);
804
805 /* check for minimum key length */
806 if (private_key->get_keysize(private_key) < RSA_MIN_OCTETS / BITS_PER_BYTE)
807 {
808 exit_scepclient("length of RSA key has to be at least %d bits",
809 RSA_MIN_OCTETS * BITS_PER_BYTE);
810 }
811
812 /*
813 * input of PKCS#10 file
814 */
815 if (filetype_in & PKCS10)
816 {
817 /* user wants to load a pkcs10 request
818 * operation is not yet supported
819 * would require a PKCS#10 parsing function
820
821 pkcs10 = pkcs10_read_from_file(file_in_pkcs10);
822
823 */
824 }
825 else
826 {
827 if (distinguishedName == NULL)
828 {
829 char buf[BUF_LEN];
830 int n = sprintf(buf, DEFAULT_DN);
831
832 /* set the common name to the hostname */
833 if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
834 {
835 exit_scepclient("no hostname defined, use "
836 "--dn <distinguished name> option");
837 }
838 distinguishedName = buf;
839 }
840
841 DBG(DBG_CONTROL,
842 DBG_log("dn: '%s'", distinguishedName);
843 )
844 subject = identification_create_from_string(distinguishedName);
845 if (subject->get_type(subject) != ID_DER_ASN1_DN)
846 {
847 exit_scepclient("parsing of distinguished name failed");
848 }
849
850 DBG(DBG_CONTROL,
851 DBG_log("building pkcs10 object:")
852 )
853 pkcs10_req = lib->creds->create(lib->creds, CRED_CERTIFICATE,
854 CERT_PKCS10_REQUEST,
855 BUILD_SIGNING_KEY, private_key,
856 BUILD_SUBJECT, subject,
857 BUILD_SUBJECT_ALTNAMES, subjectAltNames,
858 BUILD_CHALLENGE_PWD, challengePassword,
859 BUILD_DIGEST_ALG, pkcs10_signature_alg,
860 BUILD_END);
861 if (!pkcs10_req)
862 {
863 exit_scepclient("generating pkcs10 request failed");
864 }
865 pkcs10_req->get_encoding(pkcs10_req, CERT_ASN1_DER, &pkcs10_encoding);
866 fingerprint = scep_generate_pkcs10_fingerprint(pkcs10_encoding);
867 plog(" fingerprint: %s", fingerprint.ptr);
868 }
869
870 /*
871 * output of PKCS#10 file
872 */
873 if (filetype_out & PKCS10)
874 {
875 char *path = concatenate_paths(REQ_PATH, file_out_pkcs10);
876
877 if (!chunk_write(pkcs10_encoding, path, "pkcs10", 0022, force))
878 {
879 exit_scepclient("could not write pkcs10 file '%s'", path);
880 }
881 filetype_out &= ~PKCS10; /* delete PKCS10 flag */
882 }
883
884 if (!filetype_out)
885 {
886 exit_scepclient(NULL); /* no further output required */
887 }
888
889 /*
890 * output of PKCS#1 file
891 */
892 if (filetype_out & PKCS1)
893 {
894 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_out_pkcs1);
895
896 DBG(DBG_CONTROL,
897 DBG_log("building pkcs1 object:")
898 )
899 if (!private_key->get_encoding(private_key, PRIVKEY_ASN1_DER, &pkcs1) ||
900 !chunk_write(pkcs1, path, "pkcs1", 0066, force))
901 {
902 exit_scepclient("could not write pkcs1 file '%s'", path);
903 }
904 filetype_out &= ~PKCS1; /* delete PKCS1 flag */
905 }
906
907 if (!filetype_out)
908 {
909 exit_scepclient(NULL); /* no further output required */
910 }
911
912 scep_generate_transaction_id(public_key, &transID, &serialNumber);
913 plog(" transaction ID: %.*s", (int)transID.len, transID.ptr);
914
915 notBefore = notBefore ? notBefore : time(NULL);
916 notAfter = notAfter ? notAfter : (notBefore + validity);
917
918 /* generate a self-signed X.509 certificate */
919 x509_signer = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
920 BUILD_SIGNING_KEY, private_key,
921 BUILD_PUBLIC_KEY, public_key,
922 BUILD_SUBJECT, subject,
923 BUILD_NOT_BEFORE_TIME, notBefore,
924 BUILD_NOT_AFTER_TIME, notAfter,
925 BUILD_SERIAL, serialNumber,
926 BUILD_SUBJECT_ALTNAMES, subjectAltNames,
927 BUILD_END);
928 if (!x509_signer)
929 {
930 exit_scepclient("generating certificate failed");
931 }
932
933 /*
934 * output of self-signed X.509 certificate file
935 */
936 if (filetype_out & CERT_SELF)
937 {
938 char *path = concatenate_paths(HOST_CERT_PATH, file_out_cert_self);
939
940 if (!x509_signer->get_encoding(x509_signer, CERT_ASN1_DER, &encoding))
941 {
942 exit_scepclient("encoding certificate failed");
943 }
944 if (!chunk_write(encoding, path, "self-signed cert", 0022, force))
945 {
946 exit_scepclient("could not write self-signed cert file '%s'", path);
947 }
948 chunk_free(&encoding);
949 filetype_out &= ~CERT_SELF; /* delete CERT_SELF flag */
950 }
951
952 if (!filetype_out)
953 {
954 exit_scepclient(NULL); /* no further output required */
955 }
956
957 /*
958 * load ca encryption certificate
959 */
960 {
961 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_enc);
962
963 x509_ca_enc = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
964 BUILD_FROM_FILE, path, BUILD_END);
965 if (!x509_ca_enc)
966 {
967 exit_scepclient("could not load encryption cacert file '%s'", path);
968 }
969 }
970
971 /*
972 * input of PKCS#7 file
973 */
974 if (filetype_in & PKCS7)
975 {
976 /* user wants to load a pkcs7 encrypted request
977 * operation is not yet supported!
978 * would require additional parsing of transaction-id
979
980 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
981
982 */
983 }
984 else
985 {
986 DBG(DBG_CONTROL,
987 DBG_log("building pkcs7 request")
988 )
989 pkcs7 = scep_build_request(pkcs10_encoding,
990 transID, SCEP_PKCSReq_MSG,
991 x509_ca_enc, pkcs7_symmetric_cipher,
992 x509_signer, pkcs7_digest_alg, private_key);
993 }
994
995 /*
996 * output pkcs7 encrypted and signed certificate request
997 */
998 if (filetype_out & PKCS7)
999 {
1000 char *path = concatenate_paths(REQ_PATH, file_out_pkcs7);
1001
1002 if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
1003 {
1004 exit_scepclient("could not write pkcs7 file '%s'", path);
1005 }
1006 filetype_out &= ~PKCS7; /* delete PKCS7 flag */
1007 }
1008
1009 if (!filetype_out)
1010 {
1011 exit_scepclient(NULL); /* no further output required */
1012 }
1013
1014 /*
1015 * output certificate fetch from SCEP server
1016 */
1017 if (filetype_out & CERT)
1018 {
1019 bool stored = FALSE;
1020 certificate_t *cert;
1021 enumerator_t *enumerator;
1022 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_sig);
1023 time_t poll_start = 0;
1024
1025 linked_list_t *certs = linked_list_create();
1026 chunk_t envelopedData = chunk_empty;
1027 chunk_t certData = chunk_empty;
1028 contentInfo_t data = empty_contentInfo;
1029 scep_attributes_t attrs = empty_scep_attributes;
1030
1031 x509_ca_sig = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
1032 BUILD_FROM_FILE, path, BUILD_END);
1033 if (!x509_ca_sig)
1034 {
1035 exit_scepclient("could not load signature cacert file '%s'", path);
1036 }
1037
1038 if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION,
1039 http_get_request, &scep_response))
1040 {
1041 exit_scepclient("did not receive a valid scep response");
1042 }
1043 ugh = scep_parse_response(scep_response, transID, &data, &attrs,
1044 x509_ca_sig);
1045 if (ugh != NULL)
1046 {
1047 exit_scepclient(ugh);
1048 }
1049
1050 /* in case of manual mode, we are going into a polling loop */
1051 if (attrs.pkiStatus == SCEP_PENDING)
1052 {
1053 identification_t *issuer = x509_ca_sig->get_subject(x509_ca_sig);
1054
1055 plog(" scep request pending, polling every %d seconds",
1056 poll_interval);
1057 poll_start = time_monotonic(NULL);
1058 issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc",
1059 issuer->get_encoding(issuer),
1060 subject);
1061 }
1062 while (attrs.pkiStatus == SCEP_PENDING)
1063 {
1064 if (max_poll_time > 0 &&
1065 (time_monotonic(NULL) - poll_start >= max_poll_time))
1066 {
1067 exit_scepclient("maximum poll time reached: %d seconds"
1068 , max_poll_time);
1069 }
1070 DBG(DBG_CONTROL,
1071 DBG_log("going to sleep for %d seconds", poll_interval)
1072 )
1073 sleep(poll_interval);
1074 free(scep_response.ptr);
1075
1076 DBG(DBG_CONTROL,
1077 DBG_log("fingerprint: %.*s", (int)fingerprint.len, fingerprint.ptr);
1078 DBG_log("transaction ID: %.*s", (int)transID.len, transID.ptr)
1079 )
1080
1081 chunk_free(&getCertInitial);
1082 getCertInitial = scep_build_request(issuerAndSubject,
1083 transID, SCEP_GetCertInitial_MSG,
1084 x509_ca_enc, pkcs7_symmetric_cipher,
1085 x509_signer, pkcs7_digest_alg, private_key);
1086
1087 if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION,
1088 http_get_request, &scep_response))
1089 {
1090 exit_scepclient("did not receive a valid scep response");
1091 }
1092 ugh = scep_parse_response(scep_response, transID, &data, &attrs,
1093 x509_ca_sig);
1094 if (ugh != NULL)
1095 {
1096 exit_scepclient(ugh);
1097 }
1098 }
1099
1100 if (attrs.pkiStatus != SCEP_SUCCESS)
1101 {
1102 exit_scepclient("reply status is not 'SUCCESS'");
1103 }
1104
1105 envelopedData = data.content;
1106
1107 if (data.type != OID_PKCS7_DATA ||
1108 !asn1_parse_simple_object(&envelopedData, ASN1_OCTET_STRING, 0, "data"))
1109 {
1110 exit_scepclient("contentInfo is not of type 'data'");
1111 }
1112 if (!pkcs7_parse_envelopedData(envelopedData, &certData,
1113 serialNumber, private_key))
1114 {
1115 exit_scepclient("could not decrypt envelopedData");
1116 }
1117 if (!pkcs7_parse_signedData(certData, NULL, certs, NULL, NULL))
1118 {
1119 exit_scepclient("error parsing the scep response");
1120 }
1121 chunk_free(&certData);
1122
1123 /* store the end entity certificate */
1124 path = concatenate_paths(HOST_CERT_PATH, file_out_cert);
1125
1126 enumerator = certs->create_enumerator(certs);
1127 while (enumerator->enumerate(enumerator, &cert))
1128 {
1129 x509_t *x509 = (x509_t*)cert;
1130
1131 if (!(x509->get_flags(x509) & X509_CA))
1132 {
1133 if (stored)
1134 {
1135 exit_scepclient("multiple certs received, only first stored");
1136 }
1137 if (!cert->get_encoding(cert, CERT_ASN1_DER, &encoding) ||
1138 !chunk_write(encoding, path, "requested cert", 0022, force))
1139 {
1140 exit_scepclient("could not write cert file '%s'", path);
1141 }
1142 chunk_free(&encoding);
1143 stored = TRUE;
1144 }
1145 }
1146 certs->destroy_offset(certs, offsetof(certificate_t, destroy));
1147 filetype_out &= ~CERT; /* delete CERT flag */
1148 }
1149
1150 exit_scepclient(NULL);
1151 return -1; /* should never be reached */
1152 }
1153
1154