9c352c2ca92fffe56c68d048d7394eba38708a47
[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 <string.h>
31 #include <getopt.h>
32 #include <ctype.h>
33 #include <unistd.h>
34 #include <time.h>
35 #include <gmp.h>
36
37 #include <freeswan.h>
38 #include <library.h>
39 #include <debug.h>
40 #include <asn1/asn1.h>
41 #include <asn1/oid.h>
42 #include <utils/optionsfrom.h>
43 #include <utils/enumerator.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 /**
276 * Log loaded plugins
277 */
278 static void print_plugins()
279 {
280 char buf[BUF_LEN], *plugin;
281 int len = 0;
282 enumerator_t *enumerator;
283
284 enumerator = lib->plugins->create_plugin_enumerator(lib->plugins);
285 while (len < BUF_LEN && enumerator->enumerate(enumerator, &plugin))
286 {
287 len += snprintf(&buf[len], BUF_LEN-len, "%s ", plugin);
288 }
289 enumerator->destroy(enumerator);
290 DBG1(" loaded plugins: %s", buf);
291 }
292
293 /**
294 * @brief main of scepclient
295 *
296 * @param argc number of arguments
297 * @param argv pointer to the argument values
298 */
299 int main(int argc, char **argv)
300 {
301 /* external values */
302 extern char * optarg;
303 extern int optind;
304
305 /* type of input and output files */
306 typedef enum {
307 PKCS1 = 0x01,
308 PKCS10 = 0x02,
309 PKCS7 = 0x04,
310 CERT_SELF = 0x08,
311 CERT = 0x10,
312 CACERT_ENC = 0x20,
313 CACERT_SIG = 0x40
314 } scep_filetype_t;
315
316 /* filetype to read from, defaults to "generate a key" */
317 scep_filetype_t filetype_in = 0;
318
319 /* filetype to write to, no default here */
320 scep_filetype_t filetype_out = 0;
321
322 /* input files */
323 char *file_in_pkcs1 = DEFAULT_FILENAME_PKCS1;
324 char *file_in_cacert_enc = DEFAULT_FILENAME_CACERT_ENC;
325 char *file_in_cacert_sig = DEFAULT_FILENAME_CACERT_SIG;
326
327 /* output files */
328 char *file_out_pkcs1 = DEFAULT_FILENAME_PKCS1;
329 char *file_out_pkcs10 = DEFAULT_FILENAME_PKCS10;
330 char *file_out_pkcs7 = DEFAULT_FILENAME_PKCS7;
331 char *file_out_cert_self = DEFAULT_FILENAME_CERT_SELF;
332 char *file_out_cert = DEFAULT_FILENAME_CERT;
333 char *file_out_prefix_cacert = DEFAULT_FILENAME_PREFIX_CACERT;
334
335 /* by default user certificate is requested */
336 bool request_ca_certificate = FALSE;
337
338 /* by default existing files are not overwritten */
339 bool force = FALSE;
340
341 /* length of RSA key in bits */
342 u_int rsa_keylength = DEFAULT_RSA_KEY_LENGTH;
343
344 /* validity of self-signed certificate */
345 time_t validity = DEFAULT_CERT_VALIDITY;
346 time_t notBefore = 0;
347 time_t notAfter = 0;
348
349 /* distinguished name for requested certificate, ASCII format */
350 char *distinguishedName = NULL;
351
352 /* challenge password */
353 char challenge_password_buffer[MAX_PASSWORD_LENGTH];
354
355 /* symmetric encryption algorithm used by pkcs7, default is 3DES */
356 int pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;
357
358 /* digest algorithm used by pkcs7, default is MD5 */
359 int pkcs7_digest_alg = OID_MD5;
360
361 /* signature algorithm used by pkcs10, default is MD5 with RSA encryption */
362 int pkcs10_signature_alg = OID_MD5;
363
364 /* URL of the SCEP-Server */
365 char *scep_url = NULL;
366
367 /* http request method, default is GET */
368 fetch_request_t request_type = FETCH_GET;
369
370 /* poll interval time in manual mode in seconds */
371 u_int poll_interval = DEFAULT_POLL_INTERVAL;
372
373 /* maximum poll time */
374 u_int max_poll_time = 0;
375
376 err_t ugh = NULL;
377
378 /* initialize global variables */
379 pkcs1 = chunk_empty;
380 pkcs7 = chunk_empty;
381 serialNumber = chunk_empty;
382 transID = chunk_empty;
383 fingerprint = chunk_empty;
384 issuerAndSubject = chunk_empty;
385 challengePassword = chunk_empty;
386 getCertInitial = chunk_empty;
387 scep_response = chunk_empty;
388 log_to_stderr = TRUE;
389
390 /* initialize library and optionsfrom */
391 library_init(STRONGSWAN_CONF);
392 options = options_create();
393
394 for (;;)
395 {
396 static const struct option long_opts[] = {
397 /* name, has_arg, flag, val */
398 { "help", no_argument, NULL, 'h' },
399 { "version", no_argument, NULL, 'v' },
400 { "optionsfrom", required_argument, NULL, '+' },
401 { "quiet", no_argument, NULL, 'q' },
402 { "in", required_argument, NULL, 'i' },
403 { "out", required_argument, NULL, 'o' },
404 { "force", no_argument, NULL, 'f' },
405 { "keylength", required_argument, NULL, 'k' },
406 { "dn", required_argument, NULL, 'd' },
407 { "days", required_argument, NULL, 'D' },
408 { "startdate", required_argument, NULL, 'S' },
409 { "enddate", required_argument, NULL, 'E' },
410 { "subjectAltName", required_argument, NULL, 's' },
411 { "password", required_argument, NULL, 'p' },
412 { "algorithm", required_argument, NULL, 'a' },
413 { "url", required_argument, NULL, 'u' },
414 { "method", required_argument, NULL, 'm' },
415 { "interval", required_argument, NULL, 't' },
416 { "maxpolltime", required_argument, NULL, 'x' },
417 #ifdef DEBUG
418 { "debug-all", no_argument, NULL, 'A' },
419 { "debug-parsing", no_argument, NULL, 'P'},
420 { "debug-raw", no_argument, NULL, 'R'},
421 { "debug-control", no_argument, NULL, 'C'},
422 { "debug-controlmore", no_argument, NULL, 'M'},
423 { "debug-private", no_argument, NULL, 'X'},
424 #endif
425 { 0,0,0,0 }
426 };
427
428 /* parse next option */
429 int c = getopt_long(argc, argv, "hv+:qi:o:fk:d:s:p:a:u:m:t:x:APRCMS", long_opts, NULL);
430
431 switch (c)
432 {
433 case EOF: /* end of flags */
434 break;
435
436 case 'h': /* --help */
437 usage(NULL);
438
439 case 'v': /* --version */
440 version();
441
442 case 'q': /* --quiet */
443 log_to_stderr = FALSE;
444 continue;
445
446 case 'i': /* --in <type> [= <filename>] */
447 {
448 char *filename = strstr(optarg, "=");
449
450 if (filename)
451 {
452 /* replace '=' by '\0' */
453 *filename = '\0';
454 /* set pointer to start of filename */
455 filename++;
456 }
457 if (strcaseeq("pkcs1", optarg))
458 {
459 filetype_in |= PKCS1;
460 if (filename)
461 file_in_pkcs1 = filename;
462 }
463 else if (strcaseeq("cacert-enc", optarg))
464 {
465 filetype_in |= CACERT_ENC;
466 if (filename)
467 file_in_cacert_enc = filename;
468 }
469 else if (strcaseeq("cacert-sig", optarg))
470 {
471 filetype_in |= CACERT_SIG;
472 if (filename)
473 file_in_cacert_sig = filename;
474 }
475 else
476 {
477 usage("invalid --in file type");
478 }
479 continue;
480 }
481
482 case 'o': /* --out <type> [= <filename>] */
483 {
484 char *filename = strstr(optarg, "=");
485
486 if (filename)
487 {
488 /* replace '=' by '\0' */
489 *filename = '\0';
490 /* set pointer to start of filename */
491 filename++;
492 }
493 if (strcaseeq("pkcs1", optarg))
494 {
495 filetype_out |= PKCS1;
496 if (filename)
497 file_out_pkcs1 = filename;
498 }
499 else if (strcaseeq("pkcs10", optarg))
500 {
501 filetype_out |= PKCS10;
502 if (filename)
503 file_out_pkcs10 = filename;
504 }
505 else if (strcaseeq("pkcs7", optarg))
506 {
507 filetype_out |= PKCS7;
508 if (filename)
509 file_out_pkcs7 = filename;
510 }
511 else if (strcaseeq("cert-self", optarg))
512 {
513 filetype_out |= CERT_SELF;
514 if (filename)
515 file_out_cert_self = filename;
516 }
517 else if (strcaseeq("cert", optarg))
518 {
519 filetype_out |= CERT;
520 if (filename)
521 file_out_cert = filename;
522 }
523 else if (strcaseeq("cacert", optarg))
524 {
525 request_ca_certificate = TRUE;
526 if (filename)
527 file_out_prefix_cacert = filename;
528 }
529 else
530 {
531 usage("invalid --out file type");
532 }
533 continue;
534 }
535
536 case 'f': /* --force */
537 force = TRUE;
538 continue;
539
540 case '+': /* --optionsfrom <filename> */
541 if (!options->from(options, optarg, &argc, &argv, optind))
542 {
543 exit_scepclient("optionsfrom failed");
544 }
545 continue;
546
547 case 'k': /* --keylength <length> */
548 {
549 div_t q;
550
551 rsa_keylength = atoi(optarg);
552 if (rsa_keylength == 0)
553 usage("invalid keylength");
554
555 /* check if key length is a multiple of 8 bits */
556 q = div(rsa_keylength, 2*BITS_PER_BYTE);
557 if (q.rem != 0)
558 {
559 exit_scepclient("keylength is not a multiple of %d bits!"
560 , 2*BITS_PER_BYTE);
561 }
562 continue;
563 }
564
565 case 'D': /* --days */
566 if (optarg == NULL || !isdigit(optarg[0]))
567 usage("missing number of days");
568 {
569 char *endptr;
570 long days = strtol(optarg, &endptr, 0);
571
572 if (*endptr != '\0' || endptr == optarg
573 || days <= 0)
574 usage("<days> must be a positive number");
575 validity = 24*3600*days;
576 }
577 continue;
578
579 case 'S': /* --startdate */
580 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
581 usage("date format must be YYMMDDHHMMSSZ");
582 {
583 chunk_t date = { optarg, 13 };
584 notBefore = asn1_to_time(&date, ASN1_UTCTIME);
585 }
586 continue;
587
588 case 'E': /* --enddate */
589 if (optarg == NULL || strlen(optarg) != 13 || optarg[12] != 'Z')
590 usage("date format must be YYMMDDHHMMSSZ");
591 {
592 chunk_t date = { optarg, 13 };
593 notAfter = asn1_to_time(&date, ASN1_UTCTIME);
594 }
595 continue;
596
597 case 'd': /* --dn */
598 if (distinguishedName)
599 usage("only one distinguished name allowed");
600 distinguishedName = optarg;
601 continue;
602
603 case 's': /* --subjectAltName */
604 {
605 generalNames_t kind;
606 char *value = strstr(optarg, "=");
607
608 if (value)
609 {
610 /* replace '=' by '\0' */
611 *value = '\0';
612 /* set pointer to start of value */
613 value++;
614 }
615
616 if (strcaseeq("email", optarg))
617 {
618 kind = GN_RFC822_NAME;
619 }
620 else if (strcaseeq("dns", optarg))
621 {
622 kind = GN_DNS_NAME;
623 }
624 else if (strcaseeq("ip", optarg))
625 {
626 kind = GN_IP_ADDRESS;
627 }
628 else
629 {
630 usage("invalid --subjectAltName type");
631 continue;
632 }
633 pkcs10_add_subjectAltName(&subjectAltNames, kind, value);
634 continue;
635 }
636
637 case 'p': /* --password */
638 if (challengePassword.len > 0)
639 {
640 usage("only one challenge password allowed");
641 }
642 if (strcaseeq("%prompt", optarg))
643 {
644 printf("Challenge password: ");
645 if (fgets(challenge_password_buffer, sizeof(challenge_password_buffer)-1, stdin))
646 {
647 challengePassword.ptr = challenge_password_buffer;
648 /* discard the terminating '\n' from the input */
649 challengePassword.len = strlen(challenge_password_buffer) - 1;
650 }
651 else
652 {
653 usage("challenge password could not be read");
654 }
655 }
656 else
657 {
658 challengePassword.ptr = optarg;
659 challengePassword.len = strlen(optarg);
660 }
661 continue;
662
663 case 'u': /* -- url */
664 if (scep_url)
665 {
666 usage("only one URL argument allowed");
667 }
668 scep_url = optarg;
669 continue;
670
671 case 'm': /* --method */
672 if (strcaseeq("post", optarg))
673 {
674 request_type = FETCH_POST;
675 }
676 else if (strcaseeq("get", optarg))
677 {
678 request_type = FETCH_GET;
679 }
680 else
681 {
682 usage("invalid http request method specified");
683 }
684 continue;
685
686 case 't': /* --interval */
687 poll_interval = atoi(optarg);
688 if (poll_interval <= 0)
689 {
690 usage("invalid interval specified");
691 }
692 continue;
693
694 case 'x': /* --maxpolltime */
695 max_poll_time = atoi(optarg);
696 if (max_poll_time < 0)
697 {
698 usage("invalid maxpolltime specified");
699 }
700 continue;
701
702 case 'a': /*--algorithm */
703 if (strcaseeq("des-cbc", optarg))
704 {
705 pkcs7_symmetric_cipher = OID_DES_CBC;
706 }
707 else if (strcaseeq("3des-cbc", optarg))
708 {
709 pkcs7_symmetric_cipher = OID_3DES_EDE_CBC;
710 }
711 else
712 {
713 usage("invalid encryption algorithm specified");
714 }
715 continue;
716 #ifdef DEBUG
717 case 'A': /* --debug-all */
718 base_debugging |= DBG_ALL;
719 continue;
720 case 'P': /* debug parsing */
721 base_debugging |= DBG_PARSING;
722 continue;
723 case 'R': /* debug raw */
724 base_debugging |= DBG_RAW;
725 continue;
726 case 'C': /* debug control */
727 base_debugging |= DBG_CONTROL;
728 continue;
729 case 'M': /* debug control more */
730 base_debugging |= DBG_CONTROLMORE;
731 continue;
732 case 'X': /* debug private */
733 base_debugging |= DBG_PRIVATE;
734 continue;
735 #endif
736 default:
737 usage("unknown option");
738 }
739 /* break from loop */
740 break;
741 }
742 cur_debugging = base_debugging;
743
744 init_log("scepclient");
745
746 /* load plugins, further infrastructure may need it */
747 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
748 lib->settings->get_str(lib->settings, "scepclient.load", ""));
749 print_plugins();
750
751 init_rnd_pool();
752 init_fetch();
753
754 if ((filetype_out == 0) && (!request_ca_certificate))
755 {
756 usage ("--out filetype required");
757 }
758 if (request_ca_certificate && (filetype_out > 0 || filetype_in > 0))
759 {
760 usage("in CA certificate request, no other --in or --out option allowed");
761 }
762
763 /* check if url is given, if cert output defined */
764 if (((filetype_out & CERT) || request_ca_certificate) && !scep_url)
765 {
766 usage("URL of SCEP server required");
767 }
768
769 /* check for sanity of --in/--out */
770 if (!filetype_in && (filetype_in > filetype_out))
771 {
772 usage("cannot generate --out of given --in!");
773 }
774
775 /*
776 * input of PKCS#1 file
777 */
778 private_key = malloc_thing(RSA_private_key_t);
779
780 if (filetype_in & PKCS1) /* load an RSA key pair from file */
781 {
782 prompt_pass_t pass = { "", FALSE, STDIN_FILENO };
783 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_in_pkcs1);
784
785 ugh = load_rsa_private_key(path, &pass, private_key);
786 }
787 else /* generate an RSA key pair */
788 {
789 ugh = generate_rsa_private_key(rsa_keylength, private_key);
790 }
791 if (ugh != NULL)
792 exit_scepclient(ugh);
793
794 /* check for minimum key length */
795 if ((private_key->pub.k) < RSA_MIN_OCTETS)
796 {
797 exit_scepclient("length of RSA key has to be at least %d bits"
798 ,RSA_MIN_OCTETS * BITS_PER_BYTE);
799 }
800
801 /*
802 * input of PKCS#10 file
803 */
804 if (filetype_in & PKCS10)
805 {
806 /* user wants to load a pkcs10 request
807 * operation is not yet supported
808 * would require a PKCS#10 parsing function
809
810 pkcs10 = pkcs10_read_from_file(file_in_pkcs10);
811
812 */
813 }
814 else
815 {
816 char buf[IDTOA_BUF];
817 chunk_t dn = chunk_empty;
818
819 dn.ptr = buf;
820
821 if (distinguishedName == NULL)
822 {
823 char buf[BUF_LEN];
824 int n = sprintf(buf, DEFAULT_DN);
825
826 /* set the common name to the hostname */
827 if (gethostname(buf + n, BUF_LEN - n) || strlen(buf) == n)
828 {
829 exit_scepclient("no hostname defined, use "
830 "--dn <distinguished name> option");
831 }
832 distinguishedName = buf;
833 }
834
835 DBG(DBG_CONTROL,
836 DBG_log("dn: '%s'", distinguishedName);
837 )
838 ugh = atodn(distinguishedName, &dn);
839 if (ugh != NULL)
840 {
841 exit_scepclient(ugh);
842 }
843
844 subject = chunk_clone(dn);
845
846 DBG(DBG_CONTROL,
847 DBG_log("building pkcs10 object:")
848 )
849 pkcs10 = pkcs10_build(private_key, subject, challengePassword
850 , subjectAltNames, pkcs10_signature_alg);
851 scep_generate_pkcs10_fingerprint(pkcs10->request, &fingerprint);
852 plog(" fingerprint: %.*s", (int)fingerprint.len, fingerprint.ptr);
853 }
854
855 /*
856 * output of PKCS#10 file
857 */
858 if (filetype_out & PKCS10)
859 {
860 char *path = concatenate_paths(REQ_PATH, file_out_pkcs10);
861
862 if (!chunk_write(pkcs10->request, path, "pkcs10", 0022, force))
863 exit_scepclient("could not write pkcs10 file '%s'", path);
864
865 filetype_out &= ~PKCS10; /* delete PKCS10 flag */
866 }
867
868 if (!filetype_out)
869 {
870 exit_scepclient(NULL); /* no further output required */
871 }
872
873 /*
874 * output of PKCS#1 file
875 */
876 if (filetype_out & PKCS1)
877 {
878 char *path = concatenate_paths(PRIVATE_KEY_PATH, file_out_pkcs1);
879
880 DBG(DBG_CONTROL,
881 DBG_log("building pkcs1 object:")
882 )
883 pkcs1 = pkcs1_build_private_key(private_key);
884
885 if (!chunk_write(pkcs1, path, "pkcs1", 0066, force))
886 exit_scepclient("could not write pkcs1 file '%s'", path);
887
888 filetype_out &= ~PKCS1; /* delete PKCS1 flag */
889 }
890
891 if (!filetype_out)
892 {
893 exit_scepclient(NULL); /* no further output required */
894 }
895
896 scep_generate_transaction_id((const RSA_public_key_t *)private_key
897 , &transID, &serialNumber);
898 plog(" transaction ID: %.*s", (int)transID.len, transID.ptr);
899
900 /* generate a self-signed X.509 certificate */
901 x509_signer = malloc_thing(x509cert_t);
902 *x509_signer = empty_x509cert;
903 x509_signer->serialNumber = serialNumber;
904 x509_signer->sigAlg = OID_SHA1_WITH_RSA;
905 x509_signer->issuer = subject;
906 x509_signer->notBefore = (notBefore)? notBefore
907 : time(NULL);
908 x509_signer->notAfter = (notAfter)? notAfter
909 : x509_signer->notBefore + validity;
910 x509_signer->subject = subject;
911 x509_signer->subjectAltName = subjectAltNames;
912
913 build_x509cert(x509_signer, (const RSA_public_key_t *)private_key
914 , private_key);
915
916 /*
917 * output of self-signed X.509 certificate file
918 */
919 if (filetype_out & CERT_SELF)
920 {
921 char *path = concatenate_paths(HOST_CERT_PATH, file_out_cert_self);
922
923 if (!chunk_write(x509_signer->certificate, path, "self-signed cert", 0022, force))
924 exit_scepclient("could not write self-signed cert file '%s'", path);
925 ;
926 filetype_out &= ~CERT_SELF; /* delete CERT_SELF flag */
927 }
928
929 if (!filetype_out)
930 {
931 exit_scepclient(NULL); /* no further output required */
932 }
933
934 /*
935 * load ca encryption certificate
936 */
937 {
938 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_enc);
939 cert_t cert;
940
941 if (!load_cert(path, "encryption cacert", &cert))
942 {
943 exit_scepclient("could not load encryption cacert file '%s'", path);
944 }
945 x509_ca_enc = cert.u.x509;
946 }
947
948 /*
949 * input of PKCS#7 file
950 */
951 if (filetype_in & PKCS7)
952 {
953 /* user wants to load a pkcs7 encrypted request
954 * operation is not yet supported!
955 * would require additional parsing of transaction-id
956
957 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
958
959 */
960 }
961 else
962 {
963 DBG(DBG_CONTROL,
964 DBG_log("building pkcs7 request")
965 )
966 pkcs7 = scep_build_request(pkcs10->request
967 , transID, SCEP_PKCSReq_MSG
968 , x509_ca_enc, pkcs7_symmetric_cipher
969 , x509_signer, pkcs7_digest_alg, private_key);
970 }
971
972 /*
973 * output pkcs7 encrypted and signed certificate request
974 */
975 if (filetype_out & PKCS7)
976 {
977 char *path = concatenate_paths(REQ_PATH, file_out_pkcs7);
978
979 if (!chunk_write(pkcs7, path, "pkcs7 encrypted request", 0022, force))
980 exit_scepclient("could not write pkcs7 file '%s'", path);
981 ;
982 filetype_out &= ~PKCS7; /* delete PKCS7 flag */
983 }
984
985 if (!filetype_out)
986 {
987 exit_scepclient(NULL); /* no further output required */
988 }
989
990 /*
991 * output certificate fetch from SCEP server
992 */
993 if (filetype_out & CERT)
994 {
995 char *path = concatenate_paths(CA_CERT_PATH, file_in_cacert_sig);
996 cert_t cert;
997 time_t poll_start;
998
999 x509cert_t *certs = NULL;
1000 chunk_t envelopedData = chunk_empty;
1001 chunk_t certData = chunk_empty;
1002 contentInfo_t data = empty_contentInfo;
1003 scep_attributes_t attrs = empty_scep_attributes;
1004
1005 if (!load_cert(path, "signature cacert", &cert))
1006 exit_scepclient("could not load signature cacert file '%s'", path);
1007 x509_ca_sig = cert.u.x509;
1008
1009 if (!scep_http_request(scep_url, pkcs7, SCEP_PKI_OPERATION
1010 , request_type, &scep_response))
1011 {
1012 exit_scepclient("did not receive a valid scep response");
1013 }
1014 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1015 , x509_ca_sig);
1016 if (ugh != NULL)
1017 {
1018 exit_scepclient(ugh);
1019 }
1020
1021 /* in case of manual mode, we are going into a polling loop */
1022 if (attrs.pkiStatus == SCEP_PENDING)
1023 {
1024 plog(" scep request pending, polling every %d seconds"
1025 , poll_interval);
1026 time(&poll_start);
1027 issuerAndSubject = asn1_wrap(ASN1_SEQUENCE, "cc"
1028 , x509_ca_sig->subject
1029 , subject);
1030 }
1031 while (attrs.pkiStatus == SCEP_PENDING)
1032 {
1033 if (max_poll_time > 0
1034 && (time(NULL) - poll_start >= max_poll_time))
1035 {
1036 exit_scepclient("maximum poll time reached: %d seconds"
1037 , max_poll_time);
1038 }
1039 DBG(DBG_CONTROL,
1040 DBG_log("going to sleep for %d seconds", poll_interval)
1041 )
1042 sleep(poll_interval);
1043 free(scep_response.ptr);
1044
1045 DBG(DBG_CONTROL,
1046 DBG_log("fingerprint: %.*s", (int)fingerprint.len, fingerprint.ptr);
1047 DBG_log("transaction ID: %.*s", (int)transID.len, transID.ptr)
1048 )
1049
1050 chunk_free(&getCertInitial);
1051 getCertInitial = scep_build_request(issuerAndSubject
1052 , transID, SCEP_GetCertInitial_MSG
1053 , x509_ca_enc, pkcs7_symmetric_cipher
1054 , x509_signer, pkcs7_digest_alg, private_key);
1055
1056 if (!scep_http_request(scep_url, getCertInitial, SCEP_PKI_OPERATION
1057 , request_type, &scep_response))
1058 {
1059 exit_scepclient("did not receive a valid scep response");
1060 }
1061 ugh = scep_parse_response(scep_response, transID, &data, &attrs
1062 , x509_ca_sig);
1063 if (ugh != NULL)
1064 {
1065 exit_scepclient(ugh);
1066 }
1067 }
1068
1069 if (attrs.pkiStatus != SCEP_SUCCESS)
1070 {
1071 exit_scepclient("reply status is not 'SUCCESS'");
1072 }
1073
1074 envelopedData = data.content;
1075
1076 if (data.type != OID_PKCS7_DATA
1077 || !asn1_parse_simple_object(&envelopedData, ASN1_OCTET_STRING, 0, "data"))
1078 {
1079 exit_scepclient("contentInfo is not of type 'data'");
1080 }
1081 if (!pkcs7_parse_envelopedData(envelopedData, &certData
1082 , serialNumber, private_key))
1083 {
1084 exit_scepclient("could not decrypt envelopedData");
1085 }
1086 if (!pkcs7_parse_signedData(certData, NULL, &certs, NULL, NULL))
1087 {
1088 exit_scepclient("error parsing the scep response");
1089 }
1090 chunk_free(&certData);
1091
1092 /* store the end entity certificate */
1093 path = concatenate_paths(HOST_CERT_PATH, file_out_cert);
1094 while (certs != NULL)
1095 {
1096 bool stored = FALSE;
1097 x509cert_t *cert = certs;
1098
1099 if (!cert->isCA)
1100 {
1101 if (stored)
1102 exit_scepclient("multiple certs received, only first stored");
1103 if (!chunk_write(cert->certificate, path, "requested cert", 0022, force))
1104 exit_scepclient("could not write cert file '%s'", path);
1105 stored = TRUE;
1106 }
1107 certs = certs->next;
1108 free_x509cert(cert);
1109 }
1110 filetype_out &= ~CERT; /* delete CERT flag */
1111 }
1112
1113 exit_scepclient(NULL);
1114 return -1; /* should never be reached */
1115 }
1116
1117