Possible fix for broken country settings in ExcludeExitNodes.
[tor/rransom.git] / src / tools / tor-gencert.c
blobcbb8826e489820a821f47b3585c26e0ed345f73a
1 /* Copyright (c) 2007-2008 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/objects.h>
17 #include <openssl/obj_mac.h>
18 #include <openssl/err.h>
20 #include <errno.h>
21 #if 0
22 #include <stdlib.h>
23 #include <stdarg.h>
24 #include <assert.h>
25 #endif
27 #define CRYPTO_PRIVATE
29 #include "compat.h"
30 #include "util.h"
31 #include "log.h"
32 #include "crypto.h"
33 #include "address.h"
35 #define IDENTITY_KEY_BITS 3072
36 #define SIGNING_KEY_BITS 1024
37 #define DEFAULT_LIFETIME 12
39 /* These globals are set via command line options. */
40 char *identity_key_file = NULL;
41 char *signing_key_file = NULL;
42 char *certificate_file = NULL;
43 int reuse_signing_key = 0;
44 int verbose = 0;
45 int make_new_id = 0;
46 int months_lifetime = DEFAULT_LIFETIME;
47 int passphrase_fd = -1;
48 char *address = NULL;
50 char *passphrase = NULL;
51 size_t passphrase_len = 0;
53 EVP_PKEY *identity_key = NULL;
54 EVP_PKEY *signing_key = NULL;
56 /** Write a usage message for tor-gencert to stderr. */
57 static void
58 show_help(void)
60 fprintf(stderr, "Syntax:\n"
61 "tor-gencert [-h|--help] [-v] [-r|--reuse] [--create-identity-key]\n"
62 " [-i identity_key_file] [-s signing_key_file] "
63 "[-c certificate_file]\n"
64 " [-m lifetime_in_months] [-a address:port] "
65 "[--passphrase-fd <fd>]\n");
69 /* XXXX copied from crypto.c */
70 static void
71 crypto_log_errors(int severity, const char *doing)
73 unsigned int 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 int 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 /** Try to read the identity key from <b>identity_key_file</b>. If no such
222 * file exists and create_identity_key is set, make a new identity key and
223 * store it. Return 0 on success, nonzero on failure.
225 static int
226 load_identity_key(void)
228 file_status_t status = file_status(identity_key_file);
229 FILE *f;
231 if (make_new_id) {
232 open_file_t *open_file = NULL;
233 RSA *key;
234 if (status != FN_NOENT) {
235 log_err(LD_GENERAL, "--create-identity-key was specified, but %s "
236 "already exists.", identity_key_file);
237 return 1;
239 log_notice(LD_GENERAL, "Generating %d-bit RSA identity key.",
240 IDENTITY_KEY_BITS);
241 if (!(key = RSA_generate_key(IDENTITY_KEY_BITS, 65537, NULL, NULL))) {
242 log_err(LD_GENERAL, "Couldn't generate identity key.");
243 crypto_log_errors(LOG_ERR, "Generating identity key");
244 return 1;
246 identity_key = EVP_PKEY_new();
247 if (!(EVP_PKEY_assign_RSA(identity_key, key))) {
248 log_err(LD_GENERAL, "Couldn't assign identity key.");
249 return 1;
252 if (!(f = start_writing_to_stdio_file(identity_key_file,
253 OPEN_FLAGS_REPLACE, 0400,
254 &open_file)))
255 return 1;
257 /* Write the key to the file. If passphrase is not set, takes it from
258 * the terminal. */
259 if (!PEM_write_PKCS8PrivateKey_nid(f, identity_key,
260 NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
261 passphrase, (int)passphrase_len,
262 NULL, NULL)) {
263 log_err(LD_GENERAL, "Couldn't write identity key to %s",
264 identity_key_file);
265 crypto_log_errors(LOG_ERR, "Writing identity key");
266 abort_writing_to_file(open_file);
267 return 1;
269 finish_writing_to_file(open_file);
270 } else {
271 if (status != FN_FILE) {
272 log_err(LD_GENERAL,
273 "No identity key found in %s. To specify a location "
274 "for an identity key, use -i. To generate a new identity key, "
275 "use --create-identity-key.", identity_key_file);
276 return 1;
279 if (!(f = fopen(identity_key_file, "r"))) {
280 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
281 identity_key_file, strerror(errno));
282 return 1;
285 /* Read the key. If passphrase is not set, takes it from the terminal. */
286 identity_key = PEM_read_PrivateKey(f, NULL, NULL, passphrase);
287 if (!identity_key) {
288 log_err(LD_GENERAL, "Couldn't read identity key from %s",
289 identity_key_file);
290 return 1;
292 fclose(f);
294 return 0;
297 /** Load a saved signing key from disk. Return 0 on success, nonzero on
298 * failure. */
299 static int
300 load_signing_key(void)
302 FILE *f;
303 if (!(f = fopen(signing_key_file, "r"))) {
304 log_err(LD_GENERAL, "Couldn't open %s for reading: %s",
305 signing_key_file, strerror(errno));
306 return 1;
308 if (!(signing_key = PEM_read_PrivateKey(f, NULL, NULL, NULL))) {
309 log_err(LD_GENERAL, "Couldn't read siging key from %s", signing_key_file);
310 return 1;
312 fclose(f);
313 return 0;
316 /** Generate a new signing key and write it to disk. Return 0 on success,
317 * nonzero on failure. */
318 static int
319 generate_signing_key(void)
321 open_file_t *open_file;
322 FILE *f;
323 RSA *key;
324 log_notice(LD_GENERAL, "Generating %d-bit RSA signing key.",
325 SIGNING_KEY_BITS);
326 if (!(key = RSA_generate_key(SIGNING_KEY_BITS, 65537, NULL, NULL))) {
327 log_err(LD_GENERAL, "Couldn't generate signing key.");
328 crypto_log_errors(LOG_ERR, "Generating signing key");
329 return 1;
331 signing_key = EVP_PKEY_new();
332 if (!(EVP_PKEY_assign_RSA(signing_key, key))) {
333 log_err(LD_GENERAL, "Couldn't assign signing key.");
334 return 1;
337 if (!(f = start_writing_to_stdio_file(signing_key_file,
338 OPEN_FLAGS_REPLACE, 0600,
339 &open_file)))
340 return 1;
342 /* Write signing key with no encryption. */
343 if (!PEM_write_RSAPrivateKey(f, key, NULL, NULL, 0, NULL, NULL)) {
344 crypto_log_errors(LOG_WARN, "writing signing key");
345 abort_writing_to_file(open_file);
346 return 1;
349 finish_writing_to_file(open_file);
351 return 0;
354 /** Encode <b>key</b> in the format used in directory documents; return
355 * a newly allocated string holding the result or NULL on failure. */
356 static char *
357 key_to_string(EVP_PKEY *key)
359 BUF_MEM *buf;
360 BIO *b;
361 RSA *rsa = EVP_PKEY_get1_RSA(key);
362 char *result;
363 if (!rsa)
364 return NULL;
366 b = BIO_new(BIO_s_mem());
367 if (!PEM_write_bio_RSAPublicKey(b, rsa)) {
368 crypto_log_errors(LOG_WARN, "writing public key to string");
369 return NULL;
372 BIO_get_mem_ptr(b, &buf);
373 (void) BIO_set_close(b, BIO_NOCLOSE);
374 BIO_free(b);
375 result = tor_malloc(buf->length + 1);
376 memcpy(result, buf->data, buf->length);
377 result[buf->length] = 0;
378 BUF_MEM_free(buf);
380 return result;
383 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
384 static int
385 get_fingerprint(EVP_PKEY *pkey, char *out)
387 int r = 1;
388 crypto_pk_env_t *pk = _crypto_new_pk_env_rsa(EVP_PKEY_get1_RSA(pkey));
389 if (pk) {
390 r = crypto_pk_get_fingerprint(pk, out, 0);
391 crypto_free_pk_env(pk);
393 return r;
397 /** Set <b>out</b> to the hex-encoded fingerprint of <b>pkey</b>. */
398 static int
399 get_digest(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_digest(pk, out);
405 crypto_free_pk_env(pk);
407 return r;
410 /** Generate a new certificate for our loaded or generated keys, and write it
411 * to disk. Return 0 on success, nonzero on failure. */
412 static int
413 generate_certificate(void)
415 char buf[8192];
416 time_t now = time(NULL);
417 struct tm tm;
418 char published[ISO_TIME_LEN+1];
419 char expires[ISO_TIME_LEN+1];
420 char id_digest[DIGEST_LEN];
421 char fingerprint[FINGERPRINT_LEN+1];
422 char *ident = key_to_string(identity_key);
423 char *signing = key_to_string(signing_key);
424 FILE *f;
425 size_t signed_len;
426 char digest[DIGEST_LEN];
427 char signature[1024]; /* handles up to 8192-bit keys. */
428 int r;
430 get_fingerprint(identity_key, fingerprint);
431 get_digest(identity_key, id_digest);
433 tor_localtime_r(&now, &tm);
434 tm.tm_mon += months_lifetime;
436 format_iso_time(published, now);
437 format_iso_time(expires, mktime(&tm));
439 tor_snprintf(buf, sizeof(buf),
440 "dir-key-certificate-version 3"
441 "%s%s"
442 "\nfingerprint %s\n"
443 "dir-key-published %s\n"
444 "dir-key-expires %s\n"
445 "dir-identity-key\n%s"
446 "dir-signing-key\n%s"
447 "dir-key-crosscert\n"
448 "-----BEGIN ID SIGNATURE-----\n",
449 address?"\ndir-address ":"", address?address:"",
450 fingerprint, published, expires, ident, signing
452 tor_free(ident);
453 tor_free(signing);
455 /* Append a cross-certification */
456 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)id_digest,
457 (unsigned char*)signature,
458 EVP_PKEY_get1_RSA(signing_key),
459 RSA_PKCS1_PADDING);
460 signed_len = strlen(buf);
461 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
463 strlcat(buf,
464 "-----END ID SIGNATURE-----\n"
465 "dir-key-certification\n", sizeof(buf));
467 signed_len = strlen(buf);
468 SHA1((const unsigned char*)buf,signed_len,(unsigned char*)digest);
470 r = RSA_private_encrypt(DIGEST_LEN, (unsigned char*)digest,
471 (unsigned char*)signature,
472 EVP_PKEY_get1_RSA(identity_key),
473 RSA_PKCS1_PADDING);
474 strlcat(buf, "-----BEGIN SIGNATURE-----\n", sizeof(buf));
475 signed_len = strlen(buf);
476 base64_encode(buf+signed_len, sizeof(buf)-signed_len, signature, r);
477 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
479 if (!(f = fopen(certificate_file, "w"))) {
480 log_err(LD_GENERAL, "Couldn't open %s for writing: %s",
481 certificate_file, strerror(errno));
482 return 1;
485 fputs(buf, f);
486 fclose(f);
487 return 0;
491 /** Entry point to tor-gencert */
493 main(int argc, char **argv)
495 int r = 1;
496 init_logging();
498 /* Don't bother using acceleration. */
499 if (crypto_global_init(0)) {
500 fprintf(stderr, "Couldn't initialize crypto library.\n");
501 return 1;
503 if (crypto_seed_rng(1)) {
504 fprintf(stderr, "Couldn't seed RNG.\n");
505 goto done;
507 /* Make sure that files are made private. */
508 umask(0077);
510 if (parse_commandline(argc, argv))
511 goto done;
512 if (load_identity_key())
513 goto done;
514 if (reuse_signing_key) {
515 if (load_signing_key())
516 goto done;
517 } else {
518 if (generate_signing_key())
519 goto done;
521 if (generate_certificate())
522 goto done;
524 r = 0;
525 done:
526 clear_passphrase();
527 if (identity_key)
528 EVP_PKEY_free(identity_key);
529 if (signing_key)
530 EVP_PKEY_free(signing_key);
531 tor_free(address);
533 crypto_global_cleanup();
534 return r;