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