2 * Copyright (C) 2012 Tobias Brunner
3 * Copyright (C) 2005 Jan Hutter, Martin Willi
4 * HSR Hochschule fuer Technik Rapperswil
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>.
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
30 #include <utils/debug.h>
31 #include <asn1/asn1.h>
33 #include <utils/optionsfrom.h>
34 #include <collections/enumerator.h>
35 #include <collections/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 <credentials/sets/mem_cred.h>
45 #include <plugins/plugin.h>
50 * definition of some defaults
54 #define REQ_PATH IPSEC_CONFDIR "/ipsec.d/reqs"
55 #define HOST_CERT_PATH IPSEC_CONFDIR "/ipsec.d/certs"
56 #define CA_CERT_PATH IPSEC_CONFDIR "/ipsec.d/cacerts"
57 #define PRIVATE_KEY_PATH IPSEC_CONFDIR "/ipsec.d/private"
59 /* default name of DER-encoded PKCS#1 private key file */
60 #define DEFAULT_FILENAME_PKCS1 "myKey.der"
62 /* default name of DER-encoded PKCS#10 certificate request file */
63 #define DEFAULT_FILENAME_PKCS10 "myReq.der"
65 /* default name of DER-encoded PKCS#7 file */
66 #define DEFAULT_FILENAME_PKCS7 "pkcs7.der"
68 /* default name of DER-encoded self-signed X.509 certificate file */
69 #define DEFAULT_FILENAME_CERT_SELF "selfCert.der"
71 /* default name of DER-encoded X.509 certificate file */
72 #define DEFAULT_FILENAME_CERT "myCert.der"
74 /* default name of DER-encoded CA cert file used for key encipherment */
75 #define DEFAULT_FILENAME_CACERT_ENC "caCert.der"
77 /* default name of the der encoded CA cert file used for signature verification */
78 #define DEFAULT_FILENAME_CACERT_SIG "caCert.der"
80 /* default prefix of the der encoded CA certificates received from the SCEP server */
81 #define DEFAULT_FILENAME_PREFIX_CACERT "caCert.der"
83 /* default certificate validity */
84 #define DEFAULT_CERT_VALIDITY 5 * 3600 * 24 * 365 /* seconds */
86 /* default polling time interval in SCEP manual mode */
87 #define DEFAULT_POLL_INTERVAL 20 /* seconds */
89 /* default key length for self-generated RSA keys */
90 #define DEFAULT_RSA_KEY_LENGTH 2048 /* bits */
92 /* default distinguished name */
93 #define DEFAULT_DN "C=CH, O=Linux strongSwan, CN="
95 /* minimum RSA key size */
96 #define RSA_MIN_OCTETS (512 / BITS_PER_BYTE)
98 /* challenge password buffer size */
99 #define MAX_PASSWORD_LENGTH 256
101 /* Max length of filename for tempfile */
102 #define MAX_TEMP_FILENAME_LENGTH 256
105 /* current scepclient version */
106 static const char *scepclient_version
= "1.0";
108 /* by default the CRL policy is lenient */
109 bool strict_crl_policy
= FALSE
;
111 /* by default pluto does not check crls dynamically */
112 long crl_check_interval
= 0;
114 /* by default pluto logs out after every smartcard use */
115 bool pkcs11_keep_state
= FALSE
;
117 /* by default HTTP fetch timeout is 30s */
118 static u_int http_timeout
= 30;
120 /* address to bind for HTTP fetches */
121 static char* http_bind
= NULL
;
123 /* options read by optionsfrom */
131 chunk_t challengePassword
;
132 chunk_t serialNumber
;
136 chunk_t pkcs10_encoding
;
137 chunk_t issuerAndSubject
;
138 chunk_t getCertInitial
;
139 chunk_t scep_response
;
141 linked_list_t
*subjectAltNames
;
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
;
151 mem_cred_t
*creds
= NULL
;
154 static bool log_to_stderr
= TRUE
;
155 static bool log_to_syslog
= TRUE
;
156 static level_t default_loglevel
= 1;
159 * logging function for scepclient
161 static void scepclient_dbg(debug_t group
, level_t level
, char *fmt
, ...)
164 char *current
= buffer
, *next
;
167 if (level
<= default_loglevel
)
172 vfprintf(stderr
, fmt
, args
);
174 fprintf(stderr
, "\n");
178 /* write in memory buffer first */
180 vsnprintf(buffer
, sizeof(buffer
), fmt
, args
);
183 /* do a syslog with every line */
186 next
= strchr(current
, '\n');
191 syslog(LOG_INFO
, "%s\n", current
);
199 * Initialize logging to stderr/syslog
201 static void init_log(const char *program
)
203 dbg
= scepclient_dbg
;
207 setbuf(stderr
, NULL
);
211 openlog(program
, LOG_CONS
| LOG_NDELAY
| LOG_PID
, LOG_AUTHPRIV
);
216 * join two paths if filename is not absolute
218 static void join_paths(char *target
, size_t target_size
, char *parent
,
221 if (*filename
== '/' || *filename
== '.')
223 snprintf(target
, target_size
, "%s", filename
);
227 snprintf(target
, target_size
, "%s/%s", parent
, filename
);
232 * add a suffix to a given filename, properly handling extensions like '.der'
234 static void add_path_suffix(char *target
, size_t target_size
, char *filename
,
235 char *suffix_fmt
, ...)
237 char suffix
[PATH_MAX
], *start
, *dot
;
240 va_start(args
, suffix_fmt
);
241 vsnprintf(suffix
, sizeof(suffix
), suffix_fmt
, args
);
244 start
= strrchr(filename
, '/');
245 start
= start ?
: filename
;
246 dot
= strrchr(start
, '.');
248 if (!dot
|| dot
== start
|| dot
[1] == '\0')
249 { /* no extension add suffix at the end */
250 snprintf(target
, target_size
, "%s%s", filename
, suffix
);
253 { /* add the suffix between the filename and the extension */
254 snprintf(target
, target_size
, "%.*s%s%s", (int)(dot
- filename
),
255 filename
, suffix
, dot
);
260 * @brief exit scepclient
262 * @param status 0 = OK, 1 = general discomfort
264 static void exit_scepclient(err_t message
, ...)
270 lib
->credmgr
->remove_set(lib
->credmgr
, &creds
->set
);
271 creds
->destroy(creds
);
275 DESTROY_IF(private_key
);
276 DESTROY_IF(public_key
);
277 DESTROY_IF(x509_signer
);
278 DESTROY_IF(x509_ca_enc
);
279 DESTROY_IF(x509_ca_sig
);
280 DESTROY_IF(pkcs10_req
);
281 subjectAltNames
->destroy_offset(subjectAltNames
,
282 offsetof(identification_t
, destroy
));
285 free(serialNumber
.ptr
);
287 free(fingerprint
.ptr
);
289 free(pkcs10_encoding
.ptr
);
290 free(issuerAndSubject
.ptr
);
291 free(getCertInitial
.ptr
);
292 free(scep_response
.ptr
);
293 options
->destroy(options
);
295 /* print any error message to stderr */
296 if (message
!= NULL
&& *message
!= '\0')
301 va_start(args
, message
);
302 vsnprintf(m
, sizeof(m
), message
, args
);
305 fprintf(stderr
, "error: %s\n", m
);
313 * @brief prints the program version and exits
316 static void version(void)
318 printf("scepclient %s\n", scepclient_version
);
319 exit_scepclient(NULL
);
323 * @brief prints the usage of the program to the stderr output
325 * If message is set, program is exitet with 1 (error)
326 * @param message message in case of an error
328 static void usage(const char *message
)
331 "Usage: scepclient\n"
332 " --help (-h) show usage and exit\n"
333 " --version (-v) show version and exit\n"
334 " --quiet (-q) do not write log output to stderr\n"
335 " --in (-i) <type>[=<filename>] use <filename> of <type> for input\n"
336 " <type> = pkcs1 | pkcs10 | cert-self\n"
337 " cacert-enc | cacert-sig\n"
338 " - if no pkcs1 input is defined, an RSA\n"
339 " key will be generated\n"
340 " - if no pkcs10 input is defined, a\n"
341 " PKCS#10 request will be generated\n"
342 " - if no cert-self input is defined, a\n"
343 " self-signed certificate will be generated\n"
344 " - if no filename is given, default is used\n"
345 " --out (-o) <type>[=<filename>] write output of <type> to <filename>\n"
346 " multiple outputs are allowed\n"
347 " <type> = pkcs1 | pkcs10 | pkcs7 | cert-self |\n"
349 " - type cacert defines filename prefix of\n"
350 " received CA certificate(s)\n"
351 " - if no filename is given, default is used\n"
352 " --optionsfrom (-+) <filename> reads additional options from given file\n"
353 " --force (-f) force existing file(s)\n"
354 " --httptimeout (-T) timeout for HTTP operations (default: 30s)\n"
355 " --bind (-b) source address to bind for HTTP operations\n"
357 "Options for key generation (pkcs1):\n"
358 " --keylength (-k) <bits> key length for RSA key generation\n"
359 " (default: 2048 bits)\n"
361 "Options for validity:\n"
362 " --days (-D) <days> validity in days\n"
363 " --startdate (-S) <YYMMDDHHMMSS>Z not valid before date\n"
364 " --enddate (-E) <YYMMDDHHMMSS>Z not valid after date\n"
366 "Options for request generation (pkcs10):\n"
367 " --dn (-d) <dn> comma separated list of distinguished names\n"
368 " --subjectAltName (-s) <t>=<v> include subjectAltName in certificate request\n"
369 " <t> = email | dns | ip \n"
370 " --password (-p) <pw> challenge password\n"
371 " - use '%%prompt' as pw for a password prompt\n"
372 " --algorithm (-a) [<type>=]<algo> algorithm to be used for PKCS#7 encryption,\n"
373 " PKCS#7 digest or PKCS#10 signature\n"
374 " <type> = enc | dgst | sig\n"
375 " - if no type is given enc is assumed\n"
376 " <algo> = des (default) | 3des | aes128 |\n"
377 " aes192 | aes256 | camellia128 |\n"
378 " camellia192 | camellia256\n"
379 " <algo> = md5 (default) | sha1 | sha256 |\n"
382 "Options for CA certificate acquisition:\n"
383 " --caname (-c) <name> name of CA to fetch CA certificate(s)\n"
384 " (default: CAIdentifier)\n"
385 "Options for enrollment (cert):\n"
386 " --url (-u) <url> url of the SCEP server\n"
387 " --method (-m) post | get http request type\n"
388 " --interval (-t) <seconds> poll interval in seconds (default 20s)\n"
389 " --maxpolltime (-x) <seconds> max poll time in seconds when in manual mode\n"
390 " (default: unlimited)\n"
392 "Debugging output:\n"
393 " --debug (-l) <level> changes the log level (-1..4, default: 1)\n"
395 exit_scepclient(message
);
399 * @brief main of scepclient
401 * @param argc number of arguments
402 * @param argv pointer to the argument values
404 int main(int argc
, char **argv
)
406 /* external values */
407 extern char * optarg
;
410 /* type of input and output files */
421 /* filetype to read from, defaults to "generate a key" */
422 scep_filetype_t filetype_in
= 0;
424 /* filetype to write to, no default here */
425 scep_filetype_t filetype_out
= 0;
428 char *file_in_pkcs1
= DEFAULT_FILENAME_PKCS1
;
429 char *file_in_pkcs10
= DEFAULT_FILENAME_PKCS10
;
430 char *file_in_cert_self
= DEFAULT_FILENAME_CERT_SELF
;
431 char *file_in_cacert_enc
= DEFAULT_FILENAME_CACERT_ENC
;
432 char *file_in_cacert_sig
= DEFAULT_FILENAME_CACERT_SIG
;
435 char *file_out_pkcs1
= DEFAULT_FILENAME_PKCS1
;
436 char *file_out_pkcs10
= DEFAULT_FILENAME_PKCS10
;
437 char *file_out_pkcs7
= DEFAULT_FILENAME_PKCS7
;
438 char *file_out_cert_self
= DEFAULT_FILENAME_CERT_SELF
;
439 char *file_out_cert
= DEFAULT_FILENAME_CERT
;
440 char *file_out_ca_cert
= DEFAULT_FILENAME_CACERT_ENC
;
442 /* by default user certificate is requested */
443 bool request_ca_certificate
= FALSE
;
445 /* by default existing files are not overwritten */
448 /* length of RSA key in bits */
449 u_int rsa_keylength
= DEFAULT_RSA_KEY_LENGTH
;
451 /* validity of self-signed certificate */
452 time_t validity
= DEFAULT_CERT_VALIDITY
;
453 time_t notBefore
= 0;
456 /* distinguished name for requested certificate, ASCII format */
457 char *distinguishedName
= NULL
;
458 char default_distinguished_name
[BUF_LEN
];
460 /* challenge password */
461 char challenge_password_buffer
[MAX_PASSWORD_LENGTH
];
463 /* symmetric encryption algorithm used by pkcs7, default is DES */
464 encryption_algorithm_t pkcs7_symmetric_cipher
= ENCR_DES
;
465 size_t pkcs7_key_size
= 0;
467 /* digest algorithm used by pkcs7, default is MD5 */
468 hash_algorithm_t pkcs7_digest_alg
= HASH_MD5
;
470 /* signature algorithm used by pkcs10, default is MD5 */
471 hash_algorithm_t pkcs10_signature_alg
= HASH_MD5
;
473 /* URL of the SCEP-Server */
474 char *scep_url
= NULL
;
476 /* Name of CA to fetch CA certs for */
477 char *ca_name
= "CAIdentifier";
479 /* http request method, default is GET */
480 bool http_get_request
= TRUE
;
482 /* poll interval time in manual mode in seconds */
483 u_int poll_interval
= DEFAULT_POLL_INTERVAL
;
485 /* maximum poll time */
486 u_int max_poll_time
= 0;
490 /* initialize library */
491 if (!library_init(NULL
, "scepclient"))
494 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY
);
496 if (lib
->integrity
&&
497 !lib
->integrity
->check_file(lib
->integrity
, "scepclient", argv
[0]))
499 fprintf(stderr
, "integrity check of scepclient failed\n");
501 exit(SS_RC_DAEMON_INTEGRITY
);
504 /* initialize global variables */
507 serialNumber
= chunk_empty
;
508 transID
= chunk_empty
;
509 fingerprint
= chunk_empty
;
510 encoding
= chunk_empty
;
511 pkcs10_encoding
= chunk_empty
;
512 issuerAndSubject
= chunk_empty
;
513 challengePassword
= chunk_empty
;
514 getCertInitial
= chunk_empty
;
515 scep_response
= chunk_empty
;
516 subjectAltNames
= linked_list_create();
517 options
= options_create();
521 static const struct option long_opts
[] = {
522 /* name, has_arg, flag, val */
523 { "help", no_argument
, NULL
, 'h' },
524 { "version", no_argument
, NULL
, 'v' },
525 { "optionsfrom", required_argument
, NULL
, '+' },
526 { "quiet", no_argument
, NULL
, 'q' },
527 { "debug", required_argument
, NULL
, 'l' },
528 { "in", required_argument
, NULL
, 'i' },
529 { "out", required_argument
, NULL
, 'o' },
530 { "force", no_argument
, NULL
, 'f' },
531 { "httptimeout", required_argument
, NULL
, 'T' },
532 { "bind", required_argument
, NULL
, 'b' },
533 { "keylength", required_argument
, NULL
, 'k' },
534 { "dn", required_argument
, NULL
, 'd' },
535 { "days", required_argument
, NULL
, 'D' },
536 { "startdate", required_argument
, NULL
, 'S' },
537 { "enddate", required_argument
, NULL
, 'E' },
538 { "subjectAltName", required_argument
, NULL
, 's' },
539 { "password", required_argument
, NULL
, 'p' },
540 { "algorithm", required_argument
, NULL
, 'a' },
541 { "url", required_argument
, NULL
, 'u' },
542 { "caname", required_argument
, NULL
, 'c'},
543 { "method", required_argument
, NULL
, 'm' },
544 { "interval", required_argument
, NULL
, 't' },
545 { "maxpolltime", required_argument
, NULL
, 'x' },
549 /* parse next option */
550 int c
= getopt_long(argc
, argv
, "hv+:ql:i:o:fT:k:d:s:p:a:u:c:m:t:x:APRCMS", long_opts
, NULL
);
554 case EOF
: /* end of flags */
557 case 'h': /* --help */
560 case 'v': /* --version */
563 case 'q': /* --quiet */
564 log_to_stderr
= FALSE
;
567 case 'l': /* --debug <level> */
568 default_loglevel
= atoi(optarg
);
571 case 'i': /* --in <type> [= <filename>] */
573 char *filename
= strstr(optarg
, "=");
577 /* replace '=' by '\0' */
579 /* set pointer to start of filename */
582 if (strcaseeq("pkcs1", optarg
))
584 filetype_in
|= PKCS1
;
586 file_in_pkcs1
= filename
;
588 else if (strcaseeq("pkcs10", optarg
))
590 filetype_in
|= PKCS10
;
592 file_in_pkcs10
= filename
;
594 else if (strcaseeq("cacert-enc", optarg
))
596 filetype_in
|= CACERT_ENC
;
598 file_in_cacert_enc
= filename
;
600 else if (strcaseeq("cacert-sig", optarg
))
602 filetype_in
|= CACERT_SIG
;
604 file_in_cacert_sig
= filename
;
606 else if (strcaseeq("cert-self", optarg
))
608 filetype_in
|= CERT_SELF
;
610 file_in_cert_self
= filename
;
614 usage("invalid --in file type");
619 case 'o': /* --out <type> [= <filename>] */
621 char *filename
= strstr(optarg
, "=");
625 /* replace '=' by '\0' */
627 /* set pointer to start of filename */
630 if (strcaseeq("pkcs1", optarg
))
632 filetype_out
|= PKCS1
;
634 file_out_pkcs1
= filename
;
636 else if (strcaseeq("pkcs10", optarg
))
638 filetype_out
|= PKCS10
;
640 file_out_pkcs10
= filename
;
642 else if (strcaseeq("pkcs7", optarg
))
644 filetype_out
|= PKCS7
;
646 file_out_pkcs7
= filename
;
648 else if (strcaseeq("cert-self", optarg
))
650 filetype_out
|= CERT_SELF
;
652 file_out_cert_self
= filename
;
654 else if (strcaseeq("cert", optarg
))
656 filetype_out
|= CERT
;
658 file_out_cert
= filename
;
660 else if (strcaseeq("cacert", optarg
))
662 request_ca_certificate
= TRUE
;
664 file_out_ca_cert
= filename
;
668 usage("invalid --out file type");
673 case 'f': /* --force */
677 case 'T': /* --httptimeout */
678 http_timeout
= atoi(optarg
);
679 if (http_timeout
<= 0)
681 usage("invalid httptimeout specified");
685 case 'b': /* --bind */
689 case '+': /* --optionsfrom <filename> */
690 if (!options
->from(options
, optarg
, &argc
, &argv
, optind
))
692 exit_scepclient("optionsfrom failed");
696 case 'k': /* --keylength <length> */
700 rsa_keylength
= atoi(optarg
);
701 if (rsa_keylength
== 0)
702 usage("invalid keylength");
704 /* check if key length is a multiple of 8 bits */
705 q
= div(rsa_keylength
, 2*BITS_PER_BYTE
);
708 exit_scepclient("keylength is not a multiple of %d bits!"
714 case 'D': /* --days */
715 if (optarg
== NULL
|| !isdigit(optarg
[0]))
717 usage("missing number of days");
722 long days
= strtol(optarg
, &endptr
, 0);
724 if (*endptr
!= '\0' || endptr
== optarg
726 usage("<days> must be a positive number");
727 validity
= 24*3600*days
;
731 case 'S': /* --startdate */
732 if (optarg
== NULL
|| strlen(optarg
) != 13 || optarg
[12] != 'Z')
734 usage("date format must be YYMMDDHHMMSSZ");
738 chunk_t date
= { optarg
, 13 };
739 notBefore
= asn1_to_time(&date
, ASN1_UTCTIME
);
743 case 'E': /* --enddate */
744 if (optarg
== NULL
|| strlen(optarg
) != 13 || optarg
[12] != 'Z')
746 usage("date format must be YYMMDDHHMMSSZ");
750 chunk_t date
= { optarg
, 13 };
751 notAfter
= asn1_to_time(&date
, ASN1_UTCTIME
);
756 if (distinguishedName
)
758 usage("only one distinguished name allowed");
760 distinguishedName
= optarg
;
763 case 's': /* --subjectAltName */
765 char *value
= strstr(optarg
, "=");
769 /* replace '=' by '\0' */
771 /* set pointer to start of value */
775 if (strcaseeq("email", optarg
) ||
776 strcaseeq("dns", optarg
) ||
777 strcaseeq("ip", optarg
))
779 subjectAltNames
->insert_last(subjectAltNames
,
780 identification_create_from_string(value
));
785 usage("invalid --subjectAltName type");
790 case 'p': /* --password */
791 if (challengePassword
.len
> 0)
793 usage("only one challenge password allowed");
795 if (strcaseeq("%prompt", optarg
))
797 printf("Challenge password: ");
798 if (fgets(challenge_password_buffer
,
799 sizeof(challenge_password_buffer
) - 1, stdin
))
801 challengePassword
.ptr
= challenge_password_buffer
;
802 /* discard the terminating '\n' from the input */
803 challengePassword
.len
= strlen(challenge_password_buffer
) - 1;
807 usage("challenge password could not be read");
812 challengePassword
.ptr
= optarg
;
813 challengePassword
.len
= strlen(optarg
);
817 case 'u': /* -- url */
820 usage("only one URL argument allowed");
825 case 'c': /* -- caname */
829 case 'm': /* --method */
830 if (strcaseeq("get", optarg
))
832 http_get_request
= TRUE
;
834 else if (strcaseeq("post", optarg
))
836 http_get_request
= FALSE
;
840 usage("invalid http request method specified");
844 case 't': /* --interval */
845 poll_interval
= atoi(optarg
);
846 if (poll_interval
<= 0)
848 usage("invalid interval specified");
852 case 'x': /* --maxpolltime */
853 max_poll_time
= atoi(optarg
);
856 case 'a': /*--algorithm [<type>=]algo */
858 const proposal_token_t
*token
;
860 char *algo
= strstr(optarg
, "=");
873 if (strcaseeq("enc", type
))
875 token
= lib
->proposal
->get_token(lib
->proposal
, algo
);
876 if (token
== NULL
|| token
->type
!= ENCRYPTION_ALGORITHM
)
878 usage("invalid algorithm specified");
880 pkcs7_symmetric_cipher
= token
->algorithm
;
881 pkcs7_key_size
= token
->keysize
;
882 if (encryption_algorithm_to_oid(token
->algorithm
,
883 token
->keysize
) == OID_UNKNOWN
)
885 usage("unsupported encryption algorithm specified");
888 else if (strcaseeq("dgst", type
) ||
889 strcaseeq("sig", type
))
891 hash_algorithm_t hash
;
893 token
= lib
->proposal
->get_token(lib
->proposal
, algo
);
894 if (token
== NULL
|| token
->type
!= INTEGRITY_ALGORITHM
)
896 usage("invalid algorithm specified");
898 hash
= hasher_algorithm_from_integrity(token
->algorithm
,
900 if (hash
== (hash_algorithm_t
)OID_UNKNOWN
)
902 usage("invalid algorithm specified");
904 if (strcaseeq("dgst", type
))
906 pkcs7_digest_alg
= hash
;
910 pkcs10_signature_alg
= hash
;
915 usage("invalid --algorithm type");
920 usage("unknown option");
922 /* break from loop */
926 init_log("scepclient");
928 /* load plugins, further infrastructure may need it */
929 if (!lib
->plugins
->load(lib
->plugins
,
930 lib
->settings
->get_str(lib
->settings
, "scepclient.load", PLUGINS
)))
932 exit_scepclient("plugin loading failed");
934 lib
->plugins
->status(lib
->plugins
, LEVEL_DIAG
);
936 if ((filetype_out
== 0) && (!request_ca_certificate
))
938 usage("--out filetype required");
940 if (request_ca_certificate
&& (filetype_out
> 0 || filetype_in
> 0))
942 usage("in CA certificate request, no other --in or --out option allowed");
945 /* check if url is given, if cert output defined */
946 if (((filetype_out
& CERT
) || request_ca_certificate
) && !scep_url
)
948 usage("URL of SCEP server required");
951 /* check for sanity of --in/--out */
952 if (!filetype_in
&& (filetype_in
> filetype_out
))
954 usage("cannot generate --out of given --in!");
958 if (request_ca_certificate
)
960 char ca_path
[PATH_MAX
];
961 container_t
*container
;
964 if (!scep_http_request(scep_url
, chunk_create(ca_name
, strlen(ca_name
)),
965 SCEP_GET_CA_CERT
, http_get_request
,
966 http_timeout
, http_bind
, &scep_response
))
968 exit_scepclient("did not receive a valid scep response");
971 join_paths(ca_path
, sizeof(ca_path
), CA_CERT_PATH
, file_out_ca_cert
);
973 pkcs7
= lib
->creds
->create(lib
->creds
, CRED_CONTAINER
, CONTAINER_PKCS7
,
974 BUILD_BLOB_ASN1_DER
, scep_response
, BUILD_END
);
977 { /* no PKCS#7 encoded CA+RA certificates, assume simple CA cert */
979 DBG1(DBG_APP
, "unable to parse PKCS#7, assuming plain CA cert");
980 if (!chunk_write(scep_response
, ca_path
, 0022, force
))
982 exit_scepclient("could not write ca cert file '%s': %s",
983 ca_path
, strerror(errno
));
988 enumerator_t
*enumerator
;
990 int ra_certs
= 0, ca_certs
= 0;
991 int ra_index
= 1, ca_index
= 1;
993 enumerator
= pkcs7
->create_cert_enumerator(pkcs7
);
994 while (enumerator
->enumerate(enumerator
, &cert
))
996 x509_t
*x509
= (x509_t
*)cert
;
997 if (x509
->get_flags(x509
) & X509_CA
)
1006 enumerator
->destroy(enumerator
);
1008 enumerator
= pkcs7
->create_cert_enumerator(pkcs7
);
1009 while (enumerator
->enumerate(enumerator
, &cert
))
1011 x509_t
*x509
= (x509_t
*)cert
;
1012 bool ca_cert
= x509
->get_flags(x509
) & X509_CA
;
1013 char cert_path
[PATH_MAX
], *path
= ca_path
;
1015 if (ca_cert
&& ca_certs
> 1)
1017 add_path_suffix(cert_path
, sizeof(cert_path
), ca_path
,
1018 "-%.1d", ca_index
++);
1022 { /* use CA name as base for RA certs */
1025 add_path_suffix(cert_path
, sizeof(cert_path
), ca_path
,
1026 "-ra-%.1d", ra_index
++);
1030 add_path_suffix(cert_path
, sizeof(cert_path
), ca_path
,
1036 if (!cert
->get_encoding(cert
, CERT_ASN1_DER
, &encoding
) ||
1037 !chunk_write(encoding
, path
, 0022, force
))
1039 exit_scepclient("could not write cert file '%s': %s",
1040 path
, strerror(errno
));
1042 chunk_free(&encoding
);
1044 enumerator
->destroy(enumerator
);
1045 container
= &pkcs7
->container
;
1046 container
->destroy(container
);
1048 exit_scepclient(NULL
); /* no further output required */
1051 creds
= mem_cred_create();
1052 lib
->credmgr
->add_set(lib
->credmgr
, &creds
->set
);
1055 * input of PKCS#1 file
1057 if (filetype_in
& PKCS1
) /* load an RSA key pair from file */
1059 char path
[PATH_MAX
];
1061 join_paths(path
, sizeof(path
), PRIVATE_KEY_PATH
, file_in_pkcs1
);
1063 private_key
= lib
->creds
->create(lib
->creds
, CRED_PRIVATE_KEY
, KEY_RSA
,
1064 BUILD_FROM_FILE
, path
, BUILD_END
);
1066 else /* generate an RSA key pair */
1068 private_key
= lib
->creds
->create(lib
->creds
, CRED_PRIVATE_KEY
, KEY_RSA
,
1069 BUILD_KEY_SIZE
, rsa_keylength
,
1072 if (private_key
== NULL
)
1074 exit_scepclient("no RSA private key available");
1076 creds
->add_key(creds
, private_key
->get_ref(private_key
));
1077 public_key
= private_key
->get_public_key(private_key
);
1079 /* check for minimum key length */
1080 if (private_key
->get_keysize(private_key
) < RSA_MIN_OCTETS
/ BITS_PER_BYTE
)
1082 exit_scepclient("length of RSA key has to be at least %d bits",
1083 RSA_MIN_OCTETS
* BITS_PER_BYTE
);
1087 * input of PKCS#10 file
1089 if (filetype_in
& PKCS10
)
1091 char path
[PATH_MAX
];
1093 join_paths(path
, sizeof(path
), REQ_PATH
, file_in_pkcs10
);
1095 pkcs10_req
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
,
1096 CERT_PKCS10_REQUEST
, BUILD_FROM_FILE
,
1100 exit_scepclient("could not read certificate request '%s'", path
);
1102 subject
= pkcs10_req
->get_subject(pkcs10_req
);
1103 subject
= subject
->clone(subject
);
1107 if (distinguishedName
== NULL
)
1109 int n
= sprintf(default_distinguished_name
, DEFAULT_DN
);
1111 /* set the common name to the hostname */
1112 if (gethostname(default_distinguished_name
+ n
, BUF_LEN
- n
) ||
1113 strlen(default_distinguished_name
) == n
)
1115 exit_scepclient("no hostname defined, use "
1116 "--dn <distinguished name> option");
1118 distinguishedName
= default_distinguished_name
;
1121 DBG2(DBG_APP
, "dn: '%s'", distinguishedName
);
1122 subject
= identification_create_from_string(distinguishedName
);
1123 if (subject
->get_type(subject
) != ID_DER_ASN1_DN
)
1125 exit_scepclient("parsing of distinguished name failed");
1128 DBG2(DBG_APP
, "building pkcs10 object:");
1129 pkcs10_req
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
,
1130 CERT_PKCS10_REQUEST
,
1131 BUILD_SIGNING_KEY
, private_key
,
1132 BUILD_SUBJECT
, subject
,
1133 BUILD_SUBJECT_ALTNAMES
, subjectAltNames
,
1134 BUILD_CHALLENGE_PWD
, challengePassword
,
1135 BUILD_DIGEST_ALG
, pkcs10_signature_alg
,
1139 exit_scepclient("generating pkcs10 request failed");
1142 pkcs10_req
->get_encoding(pkcs10_req
, CERT_ASN1_DER
, &pkcs10_encoding
);
1143 fingerprint
= scep_generate_pkcs10_fingerprint(pkcs10_encoding
);
1144 DBG1(DBG_APP
, " fingerprint: %s", fingerprint
.ptr
);
1147 * output of PKCS#10 file
1149 if (filetype_out
& PKCS10
)
1151 char path
[PATH_MAX
];
1153 join_paths(path
, sizeof(path
), REQ_PATH
, file_out_pkcs10
);
1155 if (!chunk_write(pkcs10_encoding
, path
, 0022, force
))
1157 exit_scepclient("could not write pkcs10 file '%s': %s",
1158 path
, strerror(errno
));
1160 filetype_out
&= ~PKCS10
; /* delete PKCS10 flag */
1165 exit_scepclient(NULL
); /* no further output required */
1169 * output of PKCS#1 file
1171 if (filetype_out
& PKCS1
)
1173 char path
[PATH_MAX
];
1175 join_paths(path
, sizeof(path
), PRIVATE_KEY_PATH
, file_out_pkcs1
);
1177 DBG2(DBG_APP
, "building pkcs1 object:");
1178 if (!private_key
->get_encoding(private_key
, PRIVKEY_ASN1_DER
, &pkcs1
) ||
1179 !chunk_write(pkcs1
, path
, 0066, force
))
1181 exit_scepclient("could not write pkcs1 file '%s': %s",
1182 path
, strerror(errno
));
1184 filetype_out
&= ~PKCS1
; /* delete PKCS1 flag */
1189 exit_scepclient(NULL
); /* no further output required */
1192 scep_generate_transaction_id(public_key
, &transID
, &serialNumber
);
1193 DBG1(DBG_APP
, " transaction ID: %.*s", (int)transID
.len
, transID
.ptr
);
1196 * read or generate self-signed X.509 certificate
1198 if (filetype_in
& CERT_SELF
)
1200 char path
[PATH_MAX
];
1202 join_paths(path
, sizeof(path
), HOST_CERT_PATH
, file_in_cert_self
);
1204 x509_signer
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1205 BUILD_FROM_FILE
, path
, BUILD_END
);
1208 exit_scepclient("could not read certificate file '%s'", path
);
1213 notBefore
= notBefore ? notBefore
: time(NULL
);
1214 notAfter
= notAfter ? notAfter
: (notBefore
+ validity
);
1215 x509_signer
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1216 BUILD_SIGNING_KEY
, private_key
,
1217 BUILD_PUBLIC_KEY
, public_key
,
1218 BUILD_SUBJECT
, subject
,
1219 BUILD_NOT_BEFORE_TIME
, notBefore
,
1220 BUILD_NOT_AFTER_TIME
, notAfter
,
1221 BUILD_SERIAL
, serialNumber
,
1222 BUILD_SUBJECT_ALTNAMES
, subjectAltNames
,
1226 exit_scepclient("generating certificate failed");
1229 creds
->add_cert(creds
, TRUE
, x509_signer
->get_ref(x509_signer
));
1232 * output of self-signed X.509 certificate file
1234 if (filetype_out
& CERT_SELF
)
1236 char path
[PATH_MAX
];
1238 join_paths(path
, sizeof(path
), HOST_CERT_PATH
, file_out_cert_self
);
1240 if (!x509_signer
->get_encoding(x509_signer
, CERT_ASN1_DER
, &encoding
))
1242 exit_scepclient("encoding certificate failed");
1244 if (!chunk_write(encoding
, path
, 0022, force
))
1246 exit_scepclient("could not write self-signed cert file '%s': %s",
1247 path
, strerror(errno
));
1249 chunk_free(&encoding
);
1250 filetype_out
&= ~CERT_SELF
; /* delete CERT_SELF flag */
1255 exit_scepclient(NULL
); /* no further output required */
1259 * load ca encryption certificate
1262 char path
[PATH_MAX
];
1264 join_paths(path
, sizeof(path
), CA_CERT_PATH
, file_in_cacert_enc
);
1266 x509_ca_enc
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1267 BUILD_FROM_FILE
, path
, BUILD_END
);
1270 exit_scepclient("could not load encryption cacert file '%s'", path
);
1275 * input of PKCS#7 file
1277 if (filetype_in
& PKCS7
)
1279 /* user wants to load a pkcs7 encrypted request
1280 * operation is not yet supported!
1281 * would require additional parsing of transaction-id
1283 pkcs7 = pkcs7_read_from_file(file_in_pkcs7);
1289 DBG2(DBG_APP
, "building pkcs7 request");
1290 pkcs7
= scep_build_request(pkcs10_encoding
,
1291 transID
, SCEP_PKCSReq_MSG
, x509_ca_enc
,
1292 pkcs7_symmetric_cipher
, pkcs7_key_size
,
1293 x509_signer
, pkcs7_digest_alg
, private_key
);
1296 exit_scepclient("failed to build pkcs7 request");
1301 * output pkcs7 encrypted and signed certificate request
1303 if (filetype_out
& PKCS7
)
1305 char path
[PATH_MAX
];
1307 join_paths(path
, sizeof(path
), REQ_PATH
, file_out_pkcs7
);
1309 if (!chunk_write(pkcs7
, path
, 0022, force
))
1311 exit_scepclient("could not write pkcs7 file '%s': %s",
1312 path
, strerror(errno
));
1314 filetype_out
&= ~PKCS7
; /* delete PKCS7 flag */
1319 exit_scepclient(NULL
); /* no further output required */
1323 * output certificate fetch from SCEP server
1325 if (filetype_out
& CERT
)
1327 bool stored
= FALSE
;
1328 certificate_t
*cert
;
1329 enumerator_t
*enumerator
;
1330 char path
[PATH_MAX
];
1331 time_t poll_start
= 0;
1333 container_t
*container
= NULL
;
1335 scep_attributes_t attrs
= empty_scep_attributes
;
1337 join_paths(path
, sizeof(path
), CA_CERT_PATH
, file_in_cacert_sig
);
1339 x509_ca_sig
= lib
->creds
->create(lib
->creds
, CRED_CERTIFICATE
, CERT_X509
,
1340 BUILD_FROM_FILE
, path
, BUILD_END
);
1343 exit_scepclient("could not load signature cacert file '%s'", path
);
1346 creds
->add_cert(creds
, TRUE
, x509_ca_sig
->get_ref(x509_ca_sig
));
1348 if (!scep_http_request(scep_url
, pkcs7
, SCEP_PKI_OPERATION
,
1349 http_get_request
, http_timeout
, http_bind
, &scep_response
))
1351 exit_scepclient("did not receive a valid scep response");
1353 ugh
= scep_parse_response(scep_response
, transID
, &container
, &attrs
);
1356 exit_scepclient(ugh
);
1359 /* in case of manual mode, we are going into a polling loop */
1360 if (attrs
.pkiStatus
== SCEP_PENDING
)
1362 identification_t
*issuer
= x509_ca_sig
->get_subject(x509_ca_sig
);
1364 DBG1(DBG_APP
, " scep request pending, polling every %d seconds",
1366 poll_start
= time_monotonic(NULL
);
1367 issuerAndSubject
= asn1_wrap(ASN1_SEQUENCE
, "cc",
1368 issuer
->get_encoding(issuer
),
1369 subject
->get_encoding(subject
));
1371 while (attrs
.pkiStatus
== SCEP_PENDING
)
1373 if (max_poll_time
> 0 &&
1374 (time_monotonic(NULL
) - poll_start
>= max_poll_time
))
1376 exit_scepclient("maximum poll time reached: %d seconds"
1379 DBG2(DBG_APP
, "going to sleep for %d seconds", poll_interval
);
1380 sleep(poll_interval
);
1381 free(scep_response
.ptr
);
1382 container
->destroy(container
);
1384 DBG2(DBG_APP
, "fingerprint: %.*s",
1385 (int)fingerprint
.len
, fingerprint
.ptr
);
1386 DBG2(DBG_APP
, "transaction ID: %.*s",
1387 (int)transID
.len
, transID
.ptr
);
1389 chunk_free(&getCertInitial
);
1390 getCertInitial
= scep_build_request(issuerAndSubject
,
1391 transID
, SCEP_GetCertInitial_MSG
, x509_ca_enc
,
1392 pkcs7_symmetric_cipher
, pkcs7_key_size
,
1393 x509_signer
, pkcs7_digest_alg
, private_key
);
1394 if (!getCertInitial
.ptr
)
1396 exit_scepclient("failed to build scep request");
1398 if (!scep_http_request(scep_url
, getCertInitial
, SCEP_PKI_OPERATION
,
1399 http_get_request
, http_timeout
, http_bind
, &scep_response
))
1401 exit_scepclient("did not receive a valid scep response");
1403 ugh
= scep_parse_response(scep_response
, transID
, &container
, &attrs
);
1406 exit_scepclient(ugh
);
1410 if (attrs
.pkiStatus
!= SCEP_SUCCESS
)
1412 container
->destroy(container
);
1413 exit_scepclient("reply status is not 'SUCCESS'");
1416 if (!container
->get_data(container
, &chunk
))
1418 container
->destroy(container
);
1419 exit_scepclient("extracting signed-data failed");
1421 container
->destroy(container
);
1423 /* decrypt enveloped-data container */
1424 container
= lib
->creds
->create(lib
->creds
,
1425 CRED_CONTAINER
, CONTAINER_PKCS7
,
1426 BUILD_BLOB_ASN1_DER
, chunk
,
1431 exit_scepclient("could not decrypt envelopedData");
1434 if (!container
->get_data(container
, &chunk
))
1436 container
->destroy(container
);
1437 exit_scepclient("extracting encrypted-data failed");
1439 container
->destroy(container
);
1441 /* parse signed-data container */
1442 container
= lib
->creds
->create(lib
->creds
,
1443 CRED_CONTAINER
, CONTAINER_PKCS7
,
1444 BUILD_BLOB_ASN1_DER
, chunk
,
1449 exit_scepclient("could not parse singed-data");
1451 /* no need to verify the signed-data container, the signature does NOT
1452 * cover the contained certificates */
1454 /* store the end entity certificate */
1455 join_paths(path
, sizeof(path
), HOST_CERT_PATH
, file_out_cert
);
1457 p7
= (pkcs7_t
*)container
;
1458 enumerator
= p7
->create_cert_enumerator(p7
);
1459 while (enumerator
->enumerate(enumerator
, &cert
))
1461 x509_t
*x509
= (x509_t
*)cert
;
1463 if (!(x509
->get_flags(x509
) & X509_CA
))
1467 exit_scepclient("multiple certs received, only first stored");
1469 if (!cert
->get_encoding(cert
, CERT_ASN1_DER
, &encoding
) ||
1470 !chunk_write(encoding
, path
, 0022, force
))
1472 exit_scepclient("could not write cert file '%s': %s",
1473 path
, strerror(errno
));
1475 chunk_free(&encoding
);
1479 enumerator
->destroy(enumerator
);
1480 container
->destroy(container
);
1481 chunk_free(&attrs
.transID
);
1482 chunk_free(&attrs
.senderNonce
);
1483 chunk_free(&attrs
.recipientNonce
);
1485 filetype_out
&= ~CERT
; /* delete CERT flag */
1488 exit_scepclient(NULL
);
1489 return -1; /* should never be reached */