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