Don't use log_err for non-criticial warnings.
[tor/rransom.git] / src / tools / tor-gencert.c
blobbc99c24bd7d4c5e43c4d6e80dfc48b329b10701c
1 /* Copyright (c) 2007-2010 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 #include <unistd.h>
14 #include <openssl/evp.h>
15 #include <openssl/pem.h>
16 #include <openssl/rsa.h>
17 #include <openssl/objects.h>
18 #include <openssl/obj_mac.h>
19 #include <openssl/err.h>
21 #include <errno.h>
22 #if 0
23 #include <stdlib.h>
24 #include <stdarg.h>
25 #include <assert.h>
26 #endif
28 #define CRYPTO_PRIVATE
30 #include "compat.h"
31 #include "../common/util.h"
32 #include "../common/torlog.h"
33 #include "crypto.h"
34 #include "address.h"
36 #define IDENTITY_KEY_BITS 3072
37 #define SIGNING_KEY_BITS 1024
38 #define DEFAULT_LIFETIME 12
40 /* These globals are set via command line options. */
41 char *identity_key_file = NULL;
42 char *signing_key_file = NULL;
43 char *certificate_file = NULL;
44 int reuse_signing_key = 0;
45 int verbose = 0;
46 int make_new_id = 0;
47 int months_lifetime = DEFAULT_LIFETIME;
48 int passphrase_fd = -1;
49 char *address = NULL;
51 char *passphrase = NULL;
52 size_t passphrase_len = 0;
54 EVP_PKEY *identity_key = NULL;
55 EVP_PKEY *signing_key = NULL;
57 /** Write a usage message for tor-gencert to stderr. */
58 static void
59 show_help(void)
61 fprintf(stderr, "Syntax:\n"
62 "tor-gencert [-h|--help] [-v] [-r|--reuse] [--create-identity-key]\n"
63 " [-i identity_key_file] [-s signing_key_file] "
64 "[-c certificate_file]\n"
65 " [-m lifetime_in_months] [-a address:port] "
66 "[--passphrase-fd <fd>]\n");
69 /* XXXX copied from crypto.c */
70 static void
71 crypto_log_errors(int severity, const char *doing)
73 unsigned long err;
74 const char *msg, *lib, *func;
75 while ((err = ERR_get_error()) != 0) {
76 msg = (const char*)ERR_reason_error_string(err);
77 lib = (const char*)ERR_lib_error_string(err);
78 func = (const char*)ERR_func_error_string(err);
79 if (!msg) msg = "(null)";
80 if (!lib) lib = "(null)";
81 if (!func) func = "(null)";
82 if (doing) {
83 log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
84 doing, msg, lib, func);
85 } else {
86 log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
91 /** Read the passphrase from the passphrase fd. */
92 static int
93 load_passphrase(void)
95 char *cp;
96 char buf[1024]; /* "Ought to be enough for anybody." */
97 ssize_t n = read_all(passphrase_fd, buf, sizeof(buf), 0);
98 if (n < 0) {
99 log_err(LD_GENERAL, "Couldn't read from passphrase fd: %s",
100 strerror(errno));
101 return -1;
103 cp = memchr(buf, '\n', n);
104 passphrase_len = cp-buf;
105 passphrase = tor_strndup(buf, passphrase_len);
106 memset(buf, 0, sizeof(buf));
107 return 0;
110 static void
111 clear_passphrase(void)
113 if (passphrase) {
114 memset(passphrase, 0, passphrase_len);
115 tor_free(passphrase);
119 /** Read the command line options from <b>argc</b> and <b>argv</b>,
120 * setting global option vars as needed.
122 static int
123 parse_commandline(int argc, char **argv)
125 int i;
126 log_severity_list_t s;
127 for (i = 1; i < argc; ++i) {
128 if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
129 show_help();
130 return 1;
131 } else if (!strcmp(argv[i], "-i")) {
132 if (i+1>=argc) {
133 fprintf(stderr, "No argument to -i\n");
134 return 1;
136 identity_key_file = tor_strdup(argv[++i]);
137 } else if (!strcmp(argv[i], "-s")) {
138 if (i+1>=argc) {
139 fprintf(stderr, "No argument to -s\n");
140 return 1;
142 signing_key_file = tor_strdup(argv[++i]);
143 } else if (!strcmp(argv[i], "-c")) {
144 if (i+1>=argc) {
145 fprintf(stderr, "No argument to -c\n");
146 return 1;
148 certificate_file = tor_strdup(argv[++i]);
149 } else if (!strcmp(argv[i], "-m")) {
150 if (i+1>=argc) {
151 fprintf(stderr, "No argument to -m\n");
152 return 1;
154 months_lifetime = atoi(argv[++i]);
155 if (months_lifetime > 24 || months_lifetime < 0) {
156 fprintf(stderr, "Lifetime (in months) was out of range.");
157 return 1;
159 } else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--reuse")) {
160 reuse_signing_key = 1;
161 } else if (!strcmp(argv[i], "-v")) {
162 verbose = 1;
163 } else if (!strcmp(argv[i], "-a")) {
164 uint32_t addr;
165 uint16_t port;
166 char b[INET_NTOA_BUF_LEN];
167 struct in_addr in;
168 if (i+1>=argc) {
169 fprintf(stderr, "No argument to -a\n");
170 return 1;
172 if (parse_addr_port(LOG_ERR, argv[++i], NULL, &addr, &port)<0)
173 return 1;
174 in.s_addr = htonl(addr);
175 tor_inet_ntoa(&in, b, sizeof(b));
176 address = tor_malloc(INET_NTOA_BUF_LEN+32);
177 tor_snprintf(address, INET_NTOA_BUF_LEN+32, "%s:%d", b, (int)port);
178 } else if (!strcmp(argv[i], "--create-identity-key")) {
179 make_new_id = 1;
180 } else if (!strcmp(argv[i], "--passphrase-fd")) {
181 if (i+1>=argc) {
182 fprintf(stderr, "No argument to --passphrase-fd\n");
183 return 1;
185 passphrase_fd = atoi(argv[++i]);
186 } else {
187 fprintf(stderr, "Unrecognized option %s\n", argv[i]);
188 return 1;
192 memset(&s, 0, sizeof(s));
193 if (verbose)
194 set_log_severity_config(LOG_DEBUG, LOG_ERR, &s);
195 else
196 set_log_severity_config(LOG_WARN, LOG_ERR, &s);
197 add_stream_log(&s, "<stderr>", fileno(stderr));
199 if (!identity_key_file) {
200 identity_key_file = tor_strdup("./authority_identity_key");
201 log_info(LD_GENERAL, "No identity key file given; defaulting to %s",
202 identity_key_file);
204 if (!signing_key_file) {
205 signing_key_file = tor_strdup("./authority_signing_key");
206 log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
207 signing_key_file);
209 if (!certificate_file) {
210 certificate_file = tor_strdup("./authority_certificate");
211 log_info(LD_GENERAL, "No signing key file given; defaulting to %s",
212 certificate_file);
214 if (passphrase_fd >= 0) {
215 if (load_passphrase()<0)
216 return 1;
218 return 0;
221 static RSA *
222 generate_key(int bits)
224 RSA *rsa = NULL;
225 crypto_pk_env_t *env = crypto_new_pk_env();
226 if (crypto_pk_generate_key_with_bits(env,bits)<0)
227 goto done;
228 rsa = _crypto_pk_env_get_rsa(env);
229 rsa = RSAPrivateKey_dup(rsa);
230 done:
231 crypto_free_pk_env(env);
232 return rsa;
235 /** Try to read the identity key from <b>identity_key_file</b>. If no such
236 * file exists and create_identity_key is set, make a new identity key and
237 * store it. Return 0 on success, nonzero on failure.
239 static int
240 load_identity_key(void)
242 file_status_t status = file_status(identity_key_file);
243 FILE *f;
245 if (make_new_id) {
246 open_file_t *open_file = NULL;
247 RSA *key;
248 if (status != FN_NOENT) {
249 log_err(LD_GENERAL, "--create-identity-key was specified, but %s "
250 "already exists.", identity_key_file);
251 return 1;
253 log_notice(LD_GENERAL, "Generating %d-bit RSA identity key.",
254 IDENTITY_KEY_BITS);
255 if (!(key = generate_key(IDENTITY_KEY_BITS))) {
256 log_err(LD_GENERAL, "Couldn't generate identity key.");
257 crypto_log_errors(LOG_ERR, "Generating identity key");
258 return 1;
260 identity_key = EVP_PKEY_new();
261 if (!(EVP_PKEY_assign_RSA(identity_key, key))) {
262 log_err(LD_GENERAL, "Couldn't assign identity key.");
263 return 1;
266 if (!(f = start_writing_to_stdio_file(identity_key_file,
267 OPEN_FLAGS_REPLACE, 0400,
268 &open_file)))
269 return 1;
271 /* Write the key to the file. If passphrase is not set, takes it from
272 * the terminal. */
273 if (!PEM_write_PKCS8PrivateKey_nid(f, identity_key,
274 NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
275 passphrase, (int)passphrase_len,
276 NULL, NULL)) {
277 log_err(LD_GENERAL, "Couldn't write identity key to %s",
278 identity_key_file);
279 crypto_log_errors(LOG_ERR, "Writing identity key");
280 abort_writing_to_file(open_file);
281 return 1;
283 finish_writing_to_file(open_file);
284 } else {
285 if (status != FN_FILE) {
286 log_err(LD_GENERAL,
287 "No identity key found in %s. To specify a location "
288 "for an identity key, use -i. To generate a new identity key, "
289 "use --create-identity-key.", identity_key_file);
290 return 1;
293 if (!(f = fopen(identity_key_file, "r"))) {
294 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
295 identity_key_file, strerror(errno));
296 return 1;
299 /* Read the key. If passphrase is not set, takes it from the terminal. */
300 identity_key = PEM_read_PrivateKey(f, NULL, NULL, passphrase);
301 if (!identity_key) {
302 log_err(LD_GENERAL, "Couldn't read identity key from %s",
303 identity_key_file);
304 return 1;
306 fclose(f);
308 return 0;
311 /** Load a saved signing key from disk. Return 0 on success, nonzero on
312 * failure. */
313 static int
314 load_signing_key(void)
316 FILE *f;
317 if (!(f = fopen(signing_key_file, "r"))) {
318 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
319 signing_key_file, strerror(errno));
320 return 1;
322 if (!(signing_key = PEM_read_PrivateKey(f, NULL, NULL, NULL))) {
323 log_err(LD_GENERAL, "Couldn't read siging key from %s", signing_key_file);
324 return 1;
326 fclose(f);
327 return 0;
330 /** Generate a new signing key and write it to disk. Return 0 on success,
331 * nonzero on failure. */
332 static int
333 generate_signing_key(void)
335 open_file_t *open_file;
336 FILE *f;
337 RSA *key;
338 log_notice(LD_GENERAL, "Generating %d-bit RSA signing key.",
339 SIGNING_KEY_BITS);
340 if (!(key = generate_key(SIGNING_KEY_BITS))) {
341 log_err(LD_GENERAL, "Couldn't generate signing key.");
342 crypto_log_errors(LOG_ERR, "Generating signing key");
343 return 1;
345 signing_key = EVP_PKEY_new();
346 if (!(EVP_PKEY_assign_RSA(signing_key, key))) {
347 log_err(LD_GENERAL, "Couldn't assign signing key.");
348 return 1;
351 if (!(f = start_writing_to_stdio_file(signing_key_file,
352 OPEN_FLAGS_REPLACE, 0600,
353 &open_file)))
354 return 1;
356 /* Write signing key with no encryption. */
357 if (!PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL)) {
358 crypto_log_errors(LOG_WARN, "writing signing key");
359 abort_writing_to_file(open_file);
360 return 1;
363 finish_writing_to_file(open_file);
365 return 0;
368 /** Encode <b>key</b> in the format used in directory documents; return
369 * a newly allocated string holding the result or NULL on failure. */
370 static char *
371 key_to_string(EVP_PKEY *key)
373 BUF_MEM *buf;
374 BIO *b;
375 RSA *rsa = EVP_PKEY_get1_RSA(key);
376 char *result;
377 if (!rsa)
378 return NULL;
380 b = BIO_new(BIO_s_mem());
381 if (!PEM_write_bio_RSAPublicKey(b, rsa)) {
382 crypto_log_errors(LOG_WARN, "writing public key to string");
383 return NULL;
386 BIO_get_mem_ptr(b, &buf);
387 (void) BIO_set_close(b, BIO_NOCLOSE);
388 BIO_free(b);
389 result = tor_malloc(buf->length + 1);
390 memcpy(result, buf->data, buf->length);
391 result[buf->length] = 0;
392 BUF_MEM_free(buf);
394 return result;
397 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
398 static int
399 get_fingerprint(EVP_PKEY *pkey, char *out)
401 int r = 1;
402 crypto_pk_env_t *pk = _crypto_new_pk_env_rsa(EVP_PKEY_get1_RSA(pkey));
403 if (pk) {
404 r = crypto_pk_get_fingerprint(pk, out, 0);
405 crypto_free_pk_env(pk);
407 return r;
410 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
411 static int
412 get_digest(EVP_PKEY *pkey, char *out)
414 int r = 1;
415 crypto_pk_env_t *pk = _crypto_new_pk_env_rsa(EVP_PKEY_get1_RSA(pkey));
416 if (pk) {
417 r = crypto_pk_get_digest(pk, out);
418 crypto_free_pk_env(pk);
420 return r;
423 /** Generate a new certificate for our loaded or generated keys, and write it
424 * to disk. Return 0 on success, nonzero on failure. */
425 static int
426 generate_certificate(void)
428 char buf[8192];
429 time_t now = time(NULL);
430 struct tm tm;
431 char published[ISO_TIME_LEN+1];
432 char expires[ISO_TIME_LEN+1];
433 char id_digest[DIGEST_LEN];
434 char fingerprint[FINGERPRINT_LEN+1];
435 char *ident = key_to_string(identity_key);
436 char *signing = key_to_string(signing_key);
437 FILE *f;
438 size_t signed_len;
439 char digest[DIGEST_LEN];
440 char signature[1024]; /* handles up to 8192-bit keys. */
441 int r;
443 get_fingerprint(identity_key, fingerprint);
444 get_digest(identity_key, id_digest);
446 tor_localtime_r(&now, &tm);
447 tm.tm_mon += months_lifetime;
449 format_iso_time(published, now);
450 format_iso_time(expires, mktime(&tm));
452 tor_snprintf(buf, sizeof(buf),
453 "dir-key-certificate-version 3"
454 "%s%s"
455 "\nfingerprint %s\n"
456 "dir-key-published %s\n"
457 "dir-key-expires %s\n"
458 "dir-identity-key\n%s"
459 "dir-signing-key\n%s"
460 "dir-key-crosscert\n"
461 "-----BEGIN ID SIGNATURE-----\n",
462 address?"\ndir-address ":"", address?address:"",
463 fingerprint, published, expires, ident, signing
465 tor_free(ident);
466 tor_free(signing);
468 /* Append a cross-certification */
469 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)id_digest,
470 (unsigned char*)signature,
471 EVP_PKEY_get1_RSA(signing_key),
472 RSA_PKCS1_PADDING);
473 signed_len = strlen(buf);
474 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
476 strlcat(buf,
477 "-----END ID SIGNATURE-----\n"
478 "dir-key-certification\n", sizeof(buf));
480 signed_len = strlen(buf);
481 SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest);
483 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest,
484 (unsigned char*)signature,
485 EVP_PKEY_get1_RSA(identity_key),
486 RSA_PKCS1_PADDING);
487 strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf));
488 signed_len = strlen(buf);
489 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
490 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
492 if (!(f = fopen(certificate_file, "w"))) {
493 log_err(LD_GENERAL, "Couldn't open %s for writing: %s",
494 certificate_file, strerror(errno));
495 return 1;
498 fputs(buf, f);
499 fclose(f);
500 return 0;
503 /** Entry point to tor-gencert */
505 main(int argc, char **argv)
507 int r = 1;
508 init_logging();
510 /* Don't bother using acceleration. */
511 if (crypto_global_init(0, NULL, NULL)) {
512 fprintf(stderr, "Couldn't initialize crypto library.\n");
513 return 1;
515 if (crypto_seed_rng(1)) {
516 fprintf(stderr, "Couldn't seed RNG.\n");
517 goto done;
519 /* Make sure that files are made private. */
520 umask(0077);
522 if (parse_commandline(argc, argv))
523 goto done;
524 if (load_identity_key())
525 goto done;
526 if (reuse_signing_key) {
527 if (load_signing_key())
528 goto done;
529 } else {
530 if (generate_signing_key())
531 goto done;
533 if (generate_certificate())
534 goto done;
536 r = 0;
537 done:
538 clear_passphrase();
539 if (identity_key)
540 EVP_PKEY_free(identity_key);
541 if (signing_key)
542 EVP_PKEY_free(signing_key);
543 tor_free(address);
545 crypto_global_cleanup();
546 return r;