Add and use and unlikely-to-be-eliminated memwipe()
[tor.git] / src / tools / tor-gencert.c
blobc7ab8dc615a3a535a6379bd906b1f90c11924774
1 /* Copyright (c) 2007-2012, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 #include "orconfig.h"
6 #include <stdio.h>
7 #include <string.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
12 #ifdef HAVE_UNISTD_H
13 #include <unistd.h>
14 #endif
16 #include <openssl/evp.h>
17 #include <openssl/pem.h>
18 #include <openssl/rsa.h>
19 #include <openssl/objects.h>
20 #include <openssl/obj_mac.h>
21 #include <openssl/err.h>
23 #include <errno.h>
24 #if 0
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <assert.h>
28 #endif
30 #define CRYPTO_PRIVATE
32 #include "compat.h"
33 #include "../common/util.h"
34 #include "../common/torlog.h"
35 #include "crypto.h"
36 #include "address.h"
38 #define IDENTITY_KEY_BITS 3072
39 #define SIGNING_KEY_BITS 1024
40 #define DEFAULT_LIFETIME 12
42 /* These globals are set via command line options. */
43 char *identity_key_file = NULL;
44 char *signing_key_file = NULL;
45 char *certificate_file = NULL;
46 int reuse_signing_key = 0;
47 int verbose = 0;
48 int make_new_id = 0;
49 int months_lifetime = DEFAULT_LIFETIME;
50 int passphrase_fd = -1;
51 char *address = NULL;
53 char *passphrase = NULL;
54 size_t passphrase_len = 0;
56 EVP_PKEY *identity_key = NULL;
57 EVP_PKEY *signing_key = NULL;
59 /** Write a usage message for tor-gencert to stderr. */
60 static void
61 show_help(void)
63 fprintf(stderr, "Syntax:\n"
64 "tor-gencert [-h|--help] [-v] [-r|--reuse] [--create-identity-key]\n"
65 " [-i identity_key_file] [-s signing_key_file] "
66 "[-c certificate_file]\n"
67 " [-m lifetime_in_months] [-a address:port] "
68 "[--passphrase-fd <fd>]\n");
71 /* XXXX copied from crypto.c */
72 static void
73 crypto_log_errors(int severity, const char *doing)
75 unsigned long err;
76 const char *msg, *lib, *func;
77 while ((err = ERR_get_error()) != 0) {
78 msg = (const char*)ERR_reason_error_string(err);
79 lib = (const char*)ERR_lib_error_string(err);
80 func = (const char*)ERR_func_error_string(err);
81 if (!msg) msg = "(null)";
82 if (!lib) lib = "(null)";
83 if (!func) func = "(null)";
84 if (doing) {
85 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
86 doing, msg, lib, func);
87 } else {
88 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
93 /** Read the passphrase from the passphrase fd. */
94 static int
95 load_passphrase(void)
97 char *cp;
98 char buf[1024]; /* "Ought to be enough for anybody." */
99 ssize_t n = read_all(passphrase_fd, buf, sizeof(buf), 0);
100 if (n < 0) {
101 log_err(LD_GENERAL, "Couldn't read from passphrase fd: %s",
102 strerror(errno));
103 return -1;
105 cp = memchr(buf, '\n', n);
106 passphrase_len = cp-buf;
107 passphrase = tor_strndup(buf, passphrase_len);
108 memwipe(buf, 0, sizeof(buf));
109 return 0;
112 static void
113 clear_passphrase(void)
115 if (passphrase) {
116 memwipe(passphrase, 0, passphrase_len);
117 tor_free(passphrase);
121 /** Read the command line options from <b>argc</b> and <b>argv</b>,
122 * setting global option vars as needed.
124 static int
125 parse_commandline(int argc, char **argv)
127 int i;
128 log_severity_list_t s;
129 for (i = 1; i < argc; ++i) {
130 if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
131 show_help();
132 return 1;
133 } else if (!strcmp(argv[i], "-i")) {
134 if (i+1>=argc) {
135 fprintf(stderr, "No argument to -i\n");
136 return 1;
138 identity_key_file = tor_strdup(argv[++i]);
139 } else if (!strcmp(argv[i], "-s")) {
140 if (i+1>=argc) {
141 fprintf(stderr, "No argument to -s\n");
142 return 1;
144 signing_key_file = tor_strdup(argv[++i]);
145 } else if (!strcmp(argv[i], "-c")) {
146 if (i+1>=argc) {
147 fprintf(stderr, "No argument to -c\n");
148 return 1;
150 certificate_file = tor_strdup(argv[++i]);
151 } else if (!strcmp(argv[i], "-m")) {
152 if (i+1>=argc) {
153 fprintf(stderr, "No argument to -m\n");
154 return 1;
156 months_lifetime = atoi(argv[++i]);
157 if (months_lifetime > 24 || months_lifetime < 0) {
158 fprintf(stderr, "Lifetime (in months) was out of range.\n");
159 return 1;
161 } else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--reuse")) {
162 reuse_signing_key = 1;
163 } else if (!strcmp(argv[i], "-v")) {
164 verbose = 1;
165 } else if (!strcmp(argv[i], "-a")) {
166 uint32_t addr;
167 uint16_t port;
168 char b[INET_NTOA_BUF_LEN];
169 struct in_addr in;
170 if (i+1>=argc) {
171 fprintf(stderr, "No argument to -a\n");
172 return 1;
174 if (addr_port_lookup(LOG_ERR, argv[++i], NULL, &addr, &port)<0)
175 return 1;
176 in.s_addr = htonl(addr);
177 tor_inet_ntoa(&in, b, sizeof(b));
178 address = tor_malloc(INET_NTOA_BUF_LEN+32);
179 tor_snprintf(address, INET_NTOA_BUF_LEN+32, "%s:%d", b, (int)port);
180 } else if (!strcmp(argv[i], "--create-identity-key")) {
181 make_new_id = 1;
182 } else if (!strcmp(argv[i], "--passphrase-fd")) {
183 if (i+1>=argc) {
184 fprintf(stderr, "No argument to --passphrase-fd\n");
185 return 1;
187 passphrase_fd = atoi(argv[++i]);
188 } else {
189 fprintf(stderr, "Unrecognized option %s\n", argv[i]);
190 return 1;
194 memwipe(&s, 0, sizeof(s));
195 if (verbose)
196 set_log_severity_config(LOG_DEBUG, LOG_ERR, &s);
197 else
198 set_log_severity_config(LOG_WARN, LOG_ERR, &s);
199 add_stream_log(&s, "<stderr>", fileno(stderr));
201 if (!identity_key_file) {
202 identity_key_file = tor_strdup("./authority_identity_key");
203 log_info(LD_GENERAL, "No identity key file given; defaulting to %s",
204 identity_key_file);
206 if (!signing_key_file) {
207 signing_key_file = tor_strdup("./authority_signing_key");
208 log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
209 signing_key_file);
211 if (!certificate_file) {
212 certificate_file = tor_strdup("./authority_certificate");
213 log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
214 certificate_file);
216 if (passphrase_fd >= 0) {
217 if (load_passphrase()<0)
218 return 1;
220 return 0;
223 static RSA *
224 generate_key(int bits)
226 RSA *rsa = NULL;
227 crypto_pk_t *env = crypto_pk_new();
228 if (crypto_pk_generate_key_with_bits(env,bits)<0)
229 goto done;
230 rsa = _crypto_pk_get_rsa(env);
231 rsa = RSAPrivateKey_dup(rsa);
232 done:
233 crypto_pk_free(env);
234 return rsa;
237 /** Try to read the identity key from <b>identity_key_file</b>. If no such
238 * file exists and create_identity_key is set, make a new identity key and
239 * store it. Return 0 on success, nonzero on failure.
241 static int
242 load_identity_key(void)
244 file_status_t status = file_status(identity_key_file);
245 FILE *f;
247 if (make_new_id) {
248 open_file_t *open_file = NULL;
249 RSA *key;
250 if (status != FN_NOENT) {
251 log_err(LD_GENERAL, "--create-identity-key was specified, but %s "
252 "already exists.", identity_key_file);
253 return 1;
255 log_notice(LD_GENERAL, "Generating %d-bit RSA identity key.",
256 IDENTITY_KEY_BITS);
257 if (!(key = generate_key(IDENTITY_KEY_BITS))) {
258 log_err(LD_GENERAL, "Couldn't generate identity key.");
259 crypto_log_errors(LOG_ERR, "Generating identity key");
260 return 1;
262 identity_key = EVP_PKEY_new();
263 if (!(EVP_PKEY_assign_RSA(identity_key, key))) {
264 log_err(LD_GENERAL, "Couldn't assign identity key.");
265 return 1;
268 if (!(f = start_writing_to_stdio_file(identity_key_file,
269 OPEN_FLAGS_REPLACE | O_TEXT, 0400,
270 &open_file)))
271 return 1;
273 /* Write the key to the file. If passphrase is not set, takes it from
274 * the terminal. */
275 if (!PEM_write_PKCS8PrivateKey_nid(f, identity_key,
276 NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
277 passphrase, (int)passphrase_len,
278 NULL, NULL)) {
279 log_err(LD_GENERAL, "Couldn't write identity key to %s",
280 identity_key_file);
281 crypto_log_errors(LOG_ERR, "Writing identity key");
282 abort_writing_to_file(open_file);
283 return 1;
285 finish_writing_to_file(open_file);
286 } else {
287 if (status != FN_FILE) {
288 log_err(LD_GENERAL,
289 "No identity key found in %s. To specify a location "
290 "for an identity key, use -i. To generate a new identity key, "
291 "use --create-identity-key.", identity_key_file);
292 return 1;
295 if (!(f = fopen(identity_key_file, "r"))) {
296 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
297 identity_key_file, strerror(errno));
298 return 1;
301 /* Read the key. If passphrase is not set, takes it from the terminal. */
302 identity_key = PEM_read_PrivateKey(f, NULL, NULL, passphrase);
303 if (!identity_key) {
304 log_err(LD_GENERAL, "Couldn't read identity key from %s",
305 identity_key_file);
306 return 1;
308 fclose(f);
310 return 0;
313 /** Load a saved signing key from disk. Return 0 on success, nonzero on
314 * failure. */
315 static int
316 load_signing_key(void)
318 FILE *f;
319 if (!(f = fopen(signing_key_file, "r"))) {
320 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
321 signing_key_file, strerror(errno));
322 return 1;
324 if (!(signing_key = PEM_read_PrivateKey(f, NULL, NULL, NULL))) {
325 log_err(LD_GENERAL, "Couldn't read siging key from %s", signing_key_file);
326 return 1;
328 fclose(f);
329 return 0;
332 /** Generate a new signing key and write it to disk. Return 0 on success,
333 * nonzero on failure. */
334 static int
335 generate_signing_key(void)
337 open_file_t *open_file;
338 FILE *f;
339 RSA *key;
340 log_notice(LD_GENERAL, "Generating %d-bit RSA signing key.",
341 SIGNING_KEY_BITS);
342 if (!(key = generate_key(SIGNING_KEY_BITS))) {
343 log_err(LD_GENERAL, "Couldn't generate signing key.");
344 crypto_log_errors(LOG_ERR, "Generating signing key");
345 return 1;
347 signing_key = EVP_PKEY_new();
348 if (!(EVP_PKEY_assign_RSA(signing_key, key))) {
349 log_err(LD_GENERAL, "Couldn't assign signing key.");
350 return 1;
353 if (!(f = start_writing_to_stdio_file(signing_key_file,
354 OPEN_FLAGS_REPLACE | O_TEXT, 0600,
355 &open_file)))
356 return 1;
358 /* Write signing key with no encryption. */
359 if (!PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL)) {
360 crypto_log_errors(LOG_WARN, "writing signing key");
361 abort_writing_to_file(open_file);
362 return 1;
365 finish_writing_to_file(open_file);
367 return 0;
370 /** Encode <b>key</b> in the format used in directory documents; return
371 * a newly allocated string holding the result or NULL on failure. */
372 static char *
373 key_to_string(EVP_PKEY *key)
375 BUF_MEM *buf;
376 BIO *b;
377 RSA *rsa = EVP_PKEY_get1_RSA(key);
378 char *result;
379 if (!rsa)
380 return NULL;
382 b = BIO_new(BIO_s_mem());
383 if (!PEM_write_bio_RSAPublicKey(b, rsa)) {
384 crypto_log_errors(LOG_WARN, "writing public key to string");
385 return NULL;
388 BIO_get_mem_ptr(b, &buf);
389 (void) BIO_set_close(b, BIO_NOCLOSE);
390 BIO_free(b);
391 result = tor_malloc(buf->length + 1);
392 memcpy(result, buf->data, buf->length);
393 result[buf->length] = 0;
394 BUF_MEM_free(buf);
396 return result;
399 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
400 static int
401 get_fingerprint(EVP_PKEY *pkey, char *out)
403 int r = 1;
404 crypto_pk_t *pk = _crypto_new_pk_from_rsa(EVP_PKEY_get1_RSA(pkey));
405 if (pk) {
406 r = crypto_pk_get_fingerprint(pk, out, 0);
407 crypto_pk_free(pk);
409 return r;
412 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
413 static int
414 get_digest(EVP_PKEY *pkey, char *out)
416 int r = 1;
417 crypto_pk_t *pk = _crypto_new_pk_from_rsa(EVP_PKEY_get1_RSA(pkey));
418 if (pk) {
419 r = crypto_pk_get_digest(pk, out);
420 crypto_pk_free(pk);
422 return r;
425 /** Generate a new certificate for our loaded or generated keys, and write it
426 * to disk. Return 0 on success, nonzero on failure. */
427 static int
428 generate_certificate(void)
430 char buf[8192];
431 time_t now = time(NULL);
432 struct tm tm;
433 char published[ISO_TIME_LEN+1];
434 char expires[ISO_TIME_LEN+1];
435 char id_digest[DIGEST_LEN];
436 char fingerprint[FINGERPRINT_LEN+1];
437 char *ident = key_to_string(identity_key);
438 char *signing = key_to_string(signing_key);
439 FILE *f;
440 size_t signed_len;
441 char digest[DIGEST_LEN];
442 char signature[1024]; /* handles up to 8192-bit keys. */
443 int r;
445 get_fingerprint(identity_key, fingerprint);
446 get_digest(identity_key, id_digest);
448 tor_localtime_r(&now, &tm);
449 tm.tm_mon += months_lifetime;
451 format_iso_time(published, now);
452 format_iso_time(expires, mktime(&tm));
454 tor_snprintf(buf, sizeof(buf),
455 "dir-key-certificate-version 3"
456 "%s%s"
457 "\nfingerprint %s\n"
458 "dir-key-published %s\n"
459 "dir-key-expires %s\n"
460 "dir-identity-key\n%s"
461 "dir-signing-key\n%s"
462 "dir-key-crosscert\n"
463 "-----BEGIN ID SIGNATURE-----\n",
464 address?"\ndir-address ":"", address?address:"",
465 fingerprint, published, expires, ident, signing
467 tor_free(ident);
468 tor_free(signing);
470 /* Append a cross-certification */
471 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)id_digest,
472 (unsigned char*)signature,
473 EVP_PKEY_get1_RSA(signing_key),
474 RSA_PKCS1_PADDING);
475 signed_len = strlen(buf);
476 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
478 strlcat(buf,
479 "-----END ID SIGNATURE-----\n"
480 "dir-key-certification\n", sizeof(buf));
482 signed_len = strlen(buf);
483 SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest);
485 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest,
486 (unsigned char*)signature,
487 EVP_PKEY_get1_RSA(identity_key),
488 RSA_PKCS1_PADDING);
489 strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf));
490 signed_len = strlen(buf);
491 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
492 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
494 if (!(f = fopen(certificate_file, "w"))) {
495 log_err(LD_GENERAL, "Couldn't open %s for writing: %s",
496 certificate_file, strerror(errno));
497 return 1;
500 if (fputs(buf, f) < 0) {
501 log_err(LD_GENERAL, "Couldn't write to %s: %s",
502 certificate_file, strerror(errno));
503 fclose(f);
504 return 1;
506 fclose(f);
507 return 0;
510 /** Entry point to tor-gencert */
512 main(int argc, char **argv)
514 int r = 1;
515 init_logging();
517 /* Don't bother using acceleration. */
518 if (crypto_global_init(0, NULL, NULL)) {
519 fprintf(stderr, "Couldn't initialize crypto library.\n");
520 return 1;
522 if (crypto_seed_rng(1)) {
523 fprintf(stderr, "Couldn't seed RNG.\n");
524 goto done;
526 /* Make sure that files are made private. */
527 umask(0077);
529 if (parse_commandline(argc, argv))
530 goto done;
531 if (load_identity_key())
532 goto done;
533 if (reuse_signing_key) {
534 if (load_signing_key())
535 goto done;
536 } else {
537 if (generate_signing_key())
538 goto done;
540 if (generate_certificate())
541 goto done;
543 r = 0;
544 done:
545 clear_passphrase();
546 if (identity_key)
547 EVP_PKEY_free(identity_key);
548 if (signing_key)
549 EVP_PKEY_free(signing_key);
550 tor_free(address);
552 crypto_global_cleanup();
553 return r;