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