tor-commits
Threads by month
- ----- 2025 -----
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
May 2015
- 22 participants
- 990 discussions
commit a9720b90f860323781d37dbba6ce04f312ec3632
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Tue Sep 30 08:35:02 2014 -0400
Fix whitespace from tor_x509_cert rename
---
src/common/tortls.c | 4 ++--
src/common/tortls.h | 3 ++-
src/or/connection_or.c | 3 ++-
3 files changed, 6 insertions(+), 4 deletions(-)
diff --git a/src/common/tortls.c b/src/common/tortls.c
index b4d50cd..97dca4d 100644
--- a/src/common/tortls.c
+++ b/src/common/tortls.c
@@ -880,8 +880,8 @@ tor_x509_cert_new(X509 *x509_cert)
}
/** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
- * from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on success
- * and NULL on failure. */
+ * from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on
+ * success and NULL on failure. */
tor_x509_cert_t *
tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
{
diff --git a/src/common/tortls.h b/src/common/tortls.h
index 22b1a9e..28a73e9 100644
--- a/src/common/tortls.h
+++ b/src/common/tortls.h
@@ -132,7 +132,8 @@ int tor_tls_get_my_certs(int server,
const tor_x509_cert_t **id_cert_out);
crypto_pk_t *tor_tls_get_my_client_auth_key(void);
crypto_pk_t *tor_tls_cert_get_key(tor_x509_cert_t *cert);
-int tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_x509_cert_t *cert);
+int tor_tls_cert_matches_key(const tor_tls_t *tls,
+ const tor_x509_cert_t *cert);
int tor_tls_cert_is_valid(int severity,
const tor_x509_cert_t *cert,
const tor_x509_cert_t *signing_cert,
diff --git a/src/or/connection_or.c b/src/or/connection_or.c
index 6c584a5..4ab47f0 100644
--- a/src/or/connection_or.c
+++ b/src/or/connection_or.c
@@ -2348,7 +2348,8 @@ connection_or_compute_authenticate_cell_body(or_connection_t *conn,
if (tor_tls_get_my_certs(server, &link_cert, &id_cert))
return -1;
my_digests = tor_x509_cert_get_id_digests(id_cert);
- their_digests = tor_x509_cert_get_id_digests(conn->handshake_state->id_cert);
+ their_digests =
+ tor_x509_cert_get_id_digests(conn->handshake_state->id_cert);
tor_assert(my_digests);
tor_assert(their_digests);
my_id = (uint8_t*)my_digests->d[DIGEST_SHA256];
1
0
commit fe5d2477aabbf06c940c33a266d6ebb3a7b19fe1
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Tue Sep 30 23:36:47 2014 -0400
Implement ed25519-signed descriptors
Now that we have ed25519 keys, we can sign descriptors with them
and check those signatures as documented in proposal 220.
---
src/common/crypto.c | 82 +++++++++++++++++++++++++++++++++++++-
src/common/crypto.h | 10 +++++
src/common/crypto_ed25519.c | 11 ++++++
src/common/crypto_ed25519.h | 10 +++++
src/common/crypto_format.c | 39 +++++++++++++++++++
src/or/or.h | 2 +
src/or/router.c | 61 ++++++++++++++++++++++++++---
src/or/router.h | 3 +-
src/or/routerkeys.c | 2 +-
src/or/routerlist.c | 3 ++
src/or/routerparse.c | 91 +++++++++++++++++++++++++++++++++++++++++++
src/or/routerparse.h | 2 +
src/or/torcert.c | 10 +++++
src/or/torcert.h | 2 +
src/test/test_crypto.c | 20 +++++++++-
src/test/test_dir.c | 34 +++++++++++++---
src/test/test_routerkeys.c | 2 +
17 files changed, 370 insertions(+), 14 deletions(-)
diff --git a/src/common/crypto.c b/src/common/crypto.c
index 218c7be..06631e1 100644
--- a/src/common/crypto.c
+++ b/src/common/crypto.c
@@ -1724,7 +1724,24 @@ crypto_digest_assign(crypto_digest_t *into,
* <b>out_len</b> must be \<= DIGEST256_LEN. */
void
crypto_digest_smartlist(char *digest_out, size_t len_out,
- const smartlist_t *lst, const char *append,
+ const smartlist_t *lst,
+ const char *append,
+ digest_algorithm_t alg)
+{
+ crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
+}
+
+/** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
+ * at <b>digest_out</b> to the hash of the concatenation of: the
+ * optional string <b>prepend</b>, those strings,
+ * and the optional string <b>append</b>, computed with the algorithm
+ * <b>alg</b>.
+ * <b>out_len</b> must be \<= DIGEST256_LEN. */
+void
+crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
+ const char *prepend,
+ const smartlist_t *lst,
+ const char *append,
digest_algorithm_t alg)
{
crypto_digest_t *d;
@@ -1732,6 +1749,8 @@ crypto_digest_smartlist(char *digest_out, size_t len_out,
d = crypto_digest_new();
else
d = crypto_digest256_new(alg);
+ if (prepend)
+ crypto_digest_add_bytes(d, prepend, strlen(prepend));
SMARTLIST_FOREACH(lst, const char *, cp,
crypto_digest_add_bytes(d, cp, strlen(cp)));
if (append)
@@ -2692,6 +2711,8 @@ base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
return -1;
if (destlen > SIZE_T_CEILING)
return -1;
+ if (destlen)
+ *dest = 0; /* Ensure we always initialize the buffer */
EVP_EncodeInit(&ctx);
EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
@@ -2701,6 +2722,65 @@ base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
return ret;
}
+/** As base64_encode, but do not add any internal spaces or external padding
+ * to the output stream. */
+int
+base64_encode_nopad(char *dest, size_t destlen,
+ const uint8_t *src, size_t srclen)
+{
+ int n = base64_encode(dest, destlen, (const char*) src, srclen);
+ if (n <= 0)
+ return n;
+ tor_assert((size_t)n < destlen && dest[n] == 0);
+ char *in, *out;
+ in = out = dest;
+ while (*in) {
+ if (*in == '=' || *in == '\n') {
+ ++in;
+ } else {
+ *out++ = *in++;
+ }
+ }
+ *out = 0;
+
+ tor_assert(out - dest <= INT_MAX);
+
+ return (int)(out - dest);
+}
+
+/** As base64_decode, but do not require any padding on the input */
+int
+base64_decode_nopad(uint8_t *dest, size_t destlen,
+ const char *src, size_t srclen)
+{
+ if (srclen > SIZE_T_CEILING - 4)
+ return -1;
+ char *buf = tor_malloc(srclen + 4);
+ memcpy(buf, src, srclen+1);
+ size_t buflen;
+ switch (srclen % 4)
+ {
+ case 0:
+ default:
+ buflen = srclen;
+ break;
+ case 1:
+ tor_free(buf);
+ return -1;
+ case 2:
+ memcpy(buf+srclen, "==", 3);
+ buflen = srclen + 2;
+ break;
+ case 3:
+ memcpy(buf+srclen, "=", 2);
+ buflen = srclen + 1;
+ break;
+ }
+ int n = base64_decode((char*)dest, destlen, buf, buflen);
+ tor_free(buf);
+ return n;
+}
+
/** @{ */
/** Special values used for the base64_decode_table */
#define X 255
diff --git a/src/common/crypto.h b/src/common/crypto.h
index d305bc1..5266197 100644
--- a/src/common/crypto.h
+++ b/src/common/crypto.h
@@ -207,6 +207,11 @@ int crypto_digest256(char *digest, const char *m, size_t len,
digest_algorithm_t algorithm);
int crypto_digest_all(digests_t *ds_out, const char *m, size_t len);
struct smartlist_t;
+void crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
+ const char *prepend,
+ const struct smartlist_t *lst,
+ const char *append,
+ digest_algorithm_t alg);
void crypto_digest_smartlist(char *digest_out, size_t len_out,
const struct smartlist_t *lst, const char *append,
digest_algorithm_t alg);
@@ -270,6 +275,11 @@ void smartlist_shuffle(struct smartlist_t *sl);
int base64_encode(char *dest, size_t destlen, const char *src, size_t srclen);
int base64_decode(char *dest, size_t destlen, const char *src, size_t srclen);
+int base64_encode_nopad(char *dest, size_t destlen,
+ const uint8_t *src, size_t srclen);
+int base64_decode_nopad(uint8_t *dest, size_t destlen,
+ const char *src, size_t srclen);
+
/** Characters that can appear (case-insensitively) in a base32 encoding. */
#define BASE32_CHARS "abcdefghijklmnopqrstuvwxyz234567"
void base32_encode(char *dest, size_t destlen, const char *src, size_t srclen);
diff --git a/src/common/crypto_ed25519.c b/src/common/crypto_ed25519.c
index 7e8b00a..6b93751 100644
--- a/src/common/crypto_ed25519.c
+++ b/src/common/crypto_ed25519.c
@@ -351,6 +351,7 @@ ed25519_pubkey_read_from_file(ed25519_public_key_t *pubkey_out,
return 0;
}
+/** Release all storage held for <b>kp</b>. */
void
ed25519_keypair_free(ed25519_keypair_t *kp)
{
@@ -361,3 +362,13 @@ ed25519_keypair_free(ed25519_keypair_t *kp)
tor_free(kp);
}
+/** Return true iff <b>key1</b> and <b>key2</b> are the same public key. */
+int
+ed25519_pubkey_eq(const ed25519_public_key_t *key1,
+ const ed25519_public_key_t *key2)
+{
+ tor_assert(key1);
+ tor_assert(key2);
+ return tor_memeq(key1->pubkey, key2->pubkey, ED25519_PUBKEY_LEN);
+}
+
diff --git a/src/common/crypto_ed25519.h b/src/common/crypto_ed25519.h
index 8e06191..79b3db8 100644
--- a/src/common/crypto_ed25519.h
+++ b/src/common/crypto_ed25519.h
@@ -95,6 +95,13 @@ int ed25519_public_from_base64(ed25519_public_key_t *pkey,
int ed25519_public_to_base64(char *output,
const ed25519_public_key_t *pkey);
+#define ED25519_SIG_BASE64_LEN 86
+
+int ed25519_signature_from_base64(ed25519_signature_t *sig,
+ const char *input);
+int ed25519_signature_to_base64(char *output,
+ const ed25519_signature_t *sig);
+
/* XXXX read encrypted, write encrypted. */
int ed25519_seckey_write_to_file(const ed25519_secret_key_t *seckey,
@@ -112,5 +119,8 @@ int ed25519_pubkey_read_from_file(ed25519_public_key_t *pubkey_out,
void ed25519_keypair_free(ed25519_keypair_t *kp);
+int ed25519_pubkey_eq(const ed25519_public_key_t *key1,
+ const ed25519_public_key_t *key2);
+
#endif
diff --git a/src/common/crypto_format.c b/src/common/crypto_format.c
index 00e0e9e..503d1de 100644
--- a/src/common/crypto_format.c
+++ b/src/common/crypto_format.c
@@ -65,3 +65,42 @@ ed25519_public_to_base64(char *output,
return digest256_to_base64(output, (const char *)pkey->pubkey);
}
+/** Encode the signature <b>sig</b> into the buffer at <b>output</b>,
+ * which must have space for ED25519_SIG_BASE64_LEN bytes of encoded signature,
+ * plus one byte for a terminating NUL. Return 0 on success, -1 on failure.
+ */
+int
+ed25519_signature_to_base64(char *output,
+ const ed25519_signature_t *sig)
+{
+ char buf[256];
+ int n = base64_encode_nopad(buf, sizeof(buf), sig->sig, ED25519_SIG_LEN);
+ tor_assert(n == ED25519_SIG_BASE64_LEN);
+ memcpy(output, buf, ED25519_SIG_BASE64_LEN+1);
+ return 0;
+}
+
+/** Try to decode the string <b>input</b> into an ed25519 signature. On
+ * success, store the value in <b>sig</b> and return 0. Otherwise return
+ * -1. */
+int
+ed25519_signature_from_base64(ed25519_signature_t *sig,
+ const char *input)
+{
+
+ if (strlen(input) != ED25519_SIG_BASE64_LEN)
+ return -1;
+ char buf[ED25519_SIG_BASE64_LEN+3];
+ memcpy(buf, input, ED25519_SIG_BASE64_LEN);
+ buf[ED25519_SIG_BASE64_LEN+0] = '=';
+ buf[ED25519_SIG_BASE64_LEN+1] = '=';
+ buf[ED25519_SIG_BASE64_LEN+2] = 0;
+ char decoded[128];
+ int n = base64_decode(decoded, sizeof(decoded), buf, strlen(buf));
+ if (n < 0 || n != ED25519_SIG_LEN)
+ return -1;
+ memcpy(sig->sig, decoded, ED25519_SIG_LEN);
+
+ return 0;
+}
+
diff --git a/src/or/or.h b/src/or/or.h
index 2044e84..437183e 100644
--- a/src/or/or.h
+++ b/src/or/or.h
@@ -2021,6 +2021,8 @@ typedef struct {
crypto_pk_t *identity_pkey; /**< Public RSA key for signing. */
/** Public curve25519 key for onions */
curve25519_public_key_t *onion_curve25519_pkey;
+ /** Certificate for ed25519 signing key */
+ struct tor_cert_st *signing_key_cert;
char *platform; /**< What software/operating system is this OR using? */
diff --git a/src/or/router.c b/src/or/router.c
index 1355613..6b2a238 100644
--- a/src/or/router.c
+++ b/src/or/router.c
@@ -30,6 +30,7 @@
#include "routerlist.h"
#include "routerparse.h"
#include "statefile.h"
+#include "torcert.h"
#include "transports.h"
#include "routerset.h"
@@ -1881,6 +1882,8 @@ router_rebuild_descriptor(int force)
routerinfo_free(ri);
return -1;
}
+ ri->signing_key_cert = tor_cert_dup(get_master_signing_key_cert());
+
get_platform_str(platform, sizeof(platform));
ri->platform = tor_strdup(platform);
@@ -1995,8 +1998,9 @@ router_rebuild_descriptor(int force)
/* ri was allocated with tor_malloc_zero, so there is no need to
* zero ri->cache_info.extra_info_digest here. */
}
- if (! (ri->cache_info.signed_descriptor_body = router_dump_router_to_string(
- ri, get_server_identity_key()))) {
+ if (! (ri->cache_info.signed_descriptor_body =
+ router_dump_router_to_string(ri, get_server_identity_key(),
+ get_master_signing_keypair())) ) {
log_warn(LD_BUG, "Couldn't generate router descriptor.");
routerinfo_free(ri);
extrainfo_free(ei);
@@ -2302,12 +2306,13 @@ get_platform_str(char *platform, size_t len)
*/
char *
router_dump_router_to_string(routerinfo_t *router,
- crypto_pk_t *ident_key)
+ crypto_pk_t *ident_key,
+ const ed25519_keypair_t *signing_keypair)
{
char *address = NULL;
char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
- char digest[DIGEST_LEN];
+ char digest[DIGEST256_LEN];
char published[ISO_TIME_LEN+1];
char fingerprint[FINGERPRINT_LEN+1];
int has_extra_info_digest;
@@ -2318,6 +2323,8 @@ router_dump_router_to_string(routerinfo_t *router,
const or_options_t *options = get_options();
smartlist_t *chunks = NULL;
char *output = NULL;
+ const int emit_ed_sigs = signing_keypair && router->signing_key_cert;
+ char *ed_cert_line = NULL;
/* Make sure the identity key matches the one in the routerinfo. */
if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
@@ -2325,6 +2332,15 @@ router_dump_router_to_string(routerinfo_t *router,
"match router's public key!");
goto err;
}
+ if (emit_ed_sigs) {
+ if (!router->signing_key_cert->signing_key_included ||
+ !ed25519_pubkey_eq(&router->signing_key_cert->signed_key,
+ &signing_keypair->pubkey)) {
+ log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
+ "ed25519 key chain");
+ goto err;
+ }
+ }
/* record our fingerprint, so we can include it in the descriptor */
if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
@@ -2332,6 +2348,21 @@ router_dump_router_to_string(routerinfo_t *router,
goto err;
}
+ if (emit_ed_sigs) {
+ /* Encode ed25519 signing cert */
+ char ed_cert_base64[256];
+ if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
+ (const char*)router->signing_key_cert->encoded,
+ router->signing_key_cert->encoded_len) < 0) {
+ log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
+ goto err;
+ }
+ tor_asprintf(&ed_cert_line, "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "%s"
+ "-----END ED25519 CERT-----\n", ed_cert_base64);
+ }
+
/* PEM-encode the onion key */
if (crypto_pk_write_public_key_to_string(router->onion_pkey,
&onion_pkey,&onion_pkeylen)<0) {
@@ -2385,6 +2416,7 @@ router_dump_router_to_string(routerinfo_t *router,
smartlist_add_asprintf(chunks,
"router %s %s %d 0 %d\n"
"%s"
+ "%s"
"platform %s\n"
"protocols Link 1 2 Circuit 1\n"
"published %s\n"
@@ -2399,6 +2431,7 @@ router_dump_router_to_string(routerinfo_t *router,
address,
router->or_port,
decide_to_advertise_dirport(options, router->dir_port),
+ ed_cert_line ? ed_cert_line : "",
extra_or_address ? extra_or_address : "",
router->platform,
published,
@@ -2455,7 +2488,24 @@ router_dump_router_to_string(routerinfo_t *router,
tor_free(p6);
}
- /* Sign the descriptor */
+ /* Sign the descriptor with Ed25519 */
+ if (emit_ed_sigs) {
+ smartlist_add(chunks, tor_strdup("router-sig-ed25519 "));
+ crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
+ ED_DESC_SIGNATURE_PREFIX,
+ chunks, "", DIGEST_SHA256);
+ ed25519_signature_t sig;
+ char buf[ED25519_SIG_BASE64_LEN+1];
+ if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
+ signing_keypair) < 0)
+ goto err;
+ if (ed25519_signature_to_base64(buf, &sig) < 0)
+ goto err;
+
+ smartlist_add_asprintf(chunks, "%s\n", buf);
+ }
+
+ /* Sign the descriptor with RSA */
smartlist_add(chunks, tor_strdup("router-signature\n"));
crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
@@ -2507,6 +2557,7 @@ router_dump_router_to_string(routerinfo_t *router,
tor_free(onion_pkey);
tor_free(identity_pkey);
tor_free(extra_or_address);
+ tor_free(ed_cert_line);
return output;
}
diff --git a/src/or/router.h b/src/or/router.h
index 8108ffb..c53a104 100644
--- a/src/or/router.h
+++ b/src/or/router.h
@@ -91,7 +91,8 @@ int router_is_me(const routerinfo_t *router);
int router_pick_published_address(const or_options_t *options, uint32_t *addr);
int router_rebuild_descriptor(int force);
char *router_dump_router_to_string(routerinfo_t *router,
- crypto_pk_t *ident_key);
+ crypto_pk_t *ident_key,
+ const ed25519_keypair_t *signing_keypair);
char *router_dump_exit_policy_to_string(const routerinfo_t *router,
int include_ipv4,
int include_ipv6);
diff --git a/src/or/routerkeys.c b/src/or/routerkeys.c
index fb61c31..6609d89 100644
--- a/src/or/routerkeys.c
+++ b/src/or/routerkeys.c
@@ -300,7 +300,7 @@ load_ed_keys(const or_options_t *options, time_t now)
(void) options;
id = ed_key_init_from_file(
- options_get_datadir_fname2(options, "keys", "ed25519_master_id"),
+ options_get_datadir_fname2(options, "keys", "ed25519_master_id"),
(INIT_ED_KEY_CREATE|INIT_ED_KEY_SPLIT|
INIT_ED_KEY_MISSING_SECRET_OK|
INIT_ED_KEY_EXTRA_STRONG),
diff --git a/src/or/routerlist.c b/src/or/routerlist.c
index f4f6200..069f70d 100644
--- a/src/or/routerlist.c
+++ b/src/or/routerlist.c
@@ -13,6 +13,7 @@
#define ROUTERLIST_PRIVATE
#include "or.h"
+#include "crypto_ed25519.h"
#include "circuitstats.h"
#include "config.h"
#include "connection.h"
@@ -38,6 +39,7 @@
#include "routerparse.h"
#include "routerset.h"
#include "../common/sandbox.h"
+#include "torcert.h"
// #define DEBUG_ROUTERLIST
/****************************************************************************/
@@ -2663,6 +2665,7 @@ routerinfo_free(routerinfo_t *router)
tor_free(router->onion_curve25519_pkey);
if (router->identity_pkey)
crypto_pk_free(router->identity_pkey);
+ tor_cert_free(router->signing_key_cert);
if (router->declared_family) {
SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
smartlist_free(router->declared_family);
diff --git a/src/or/routerparse.c b/src/or/routerparse.c
index 5a9626f..dbd6fdd 100644
--- a/src/or/routerparse.c
+++ b/src/or/routerparse.c
@@ -26,6 +26,8 @@
#include "rephist.h"
#include "routerparse.h"
#include "entrynodes.h"
+#include "torcert.h"
+
#undef log
#include <math.h>
@@ -83,6 +85,8 @@ typedef enum {
K_HIDDEN_SERVICE_DIR,
K_ALLOW_SINGLE_HOP_EXITS,
K_IPV6_POLICY,
+ K_ROUTER_SIG_ED25519,
+ K_IDENTITY_ED25519,
K_DIRREQ_END,
K_DIRREQ_V2_IPS,
@@ -293,6 +297,9 @@ static token_rule_t routerdesc_token_table[] = {
T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
+ T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
+ T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
+
T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
T01("family", K_FAMILY, ARGS, NO_OBJ ),
@@ -506,6 +513,10 @@ static addr_policy_t *router_parse_addr_policy(directory_token_t *tok,
unsigned fmt_flags);
static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
+static int router_get_hash_impl_helper(const char *s, size_t s_len,
+ const char *start_str,
+ const char *end_str, char end_c,
+ const char **start_out, const char **end_out);
static int router_get_hash_impl(const char *s, size_t s_len, char *digest,
const char *start_str, const char *end_str,
char end_char,
@@ -1302,6 +1313,86 @@ router_parse_entry_from_string(const char *s, const char *end,
tor_memdup(&k, sizeof(curve25519_public_key_t));
}
+ {
+ directory_token_t *ed_sig_tok, *ed_cert_tok;
+ ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
+ ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
+ if (!ed_sig_tok != !ed_cert_tok) {
+ log_warn(LD_DIR, "Router descriptor with only partial ed25519 support");
+ goto err;
+ }
+ if (ed_sig_tok) {
+ tor_assert(ed_cert_tok);
+ if (ed_cert_tok != smartlist_get(tokens, 0) &&
+ ed_cert_tok != smartlist_get(tokens, 1)) {
+ log_warn(LD_DIR, "Ed25519 certificate in wrong position");
+ goto err;
+ }
+ if (ed_sig_tok != smartlist_get(tokens, smartlist_len(tokens)-2)) {
+ log_warn(LD_DIR, "Ed25519 signature in wrong position");
+ goto err;
+ }
+ if (strcmp(ed_cert_tok->object_type, "ED25519 CERT")) {
+ log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
+ goto err;
+ }
+
+ uint8_t d256[DIGEST256_LEN];
+ const char *signed_start, *signed_end;
+
+ tor_cert_t *cert = tor_cert_parse(
+ (const uint8_t*)ed_cert_tok->object_body,
+ ed_cert_tok->object_size);
+ if (! cert) {
+ log_warn(LD_DIR, "Couldn't parse ed25519 cert");
+ goto err;
+ }
+ router->signing_key_cert = cert;
+ if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
+ ! cert->signing_key_included) {
+ log_warn(LD_DIR, "Invalid form for ed25519 cert");
+ goto err;
+ }
+
+ if (router_get_hash_impl_helper(s, end-s, "router ",
+ "\nrouter-sig-ed25519",
+ ' ', &signed_start, &signed_end) < 0) {
+ log_warn(LD_DIR, "Can't find ed25519-signed portion of descriptor");
+ goto err;
+ }
+ crypto_digest_t *d = crypto_digest256_new(DIGEST_SHA256);
+ crypto_digest_add_bytes(d, ED_DESC_SIGNATURE_PREFIX,
+ strlen(ED_DESC_SIGNATURE_PREFIX));
+ crypto_digest_add_bytes(d, signed_start, signed_end-signed_start);
+ crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
+ crypto_digest_free(d);
+
+ ed25519_checkable_t check[2];
+ int check_ok[2];
+ if (tor_cert_get_checkable_sig(&check[0], cert, NULL) < 0) {
+ log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
+ goto err;
+ }
+ if (ed25519_signature_from_base64(&check[1].signature,
+ ed_sig_tok->args[0])<0) {
+ log_warn(LD_DIR, "Couldn't decode ed25519 signature");
+ goto err;
+ }
+ check[1].pubkey = &cert->signed_key;
+ check[1].msg = d256;
+ check[1].len = DIGEST256_LEN;
+
+ if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
+ log_warn(LD_DIR, "Incorrect ed25519 signatures");
+ goto err;
+ }
+ if (cert->valid_until < time(NULL)) {
+ log_warn(LD_DIR, "Expired ed25519 certificate in router descriptor");
+ goto err;
+ }
+ }
+ }
+
tok = find_by_keyword(tokens, K_SIGNING_KEY);
router->identity_pkey = tok->key;
tok->key = NULL; /* Prevent free */
diff --git a/src/or/routerparse.h b/src/or/routerparse.h
index fc21cb1..52e53a8 100644
--- a/src/or/routerparse.h
+++ b/src/or/routerparse.h
@@ -92,5 +92,7 @@ STATIC int routerstatus_parse_guardfraction(const char *guardfraction_str,
routerstatus_t *rs);
#endif
+#define ED_DESC_SIGNATURE_PREFIX "Tor router descriptor signature v1"
+
#endif
diff --git a/src/or/torcert.c b/src/or/torcert.c
index 478ec4d..8fe9c12 100644
--- a/src/or/torcert.c
+++ b/src/or/torcert.c
@@ -206,3 +206,13 @@ tor_cert_checksig(tor_cert_t *cert,
}
}
+/** Return a new copy of <b>cert</b> */
+tor_cert_t *
+tor_cert_dup(const tor_cert_t *cert)
+{
+ tor_cert_t *newcert = tor_memdup(cert, sizeof(tor_cert_t));
+ if (cert->encoded)
+ newcert->encoded = tor_memdup(cert->encoded, cert->encoded_len);
+ return newcert;
+}
+
diff --git a/src/or/torcert.h b/src/or/torcert.h
index 7e9c3f5..644cbf8 100644
--- a/src/or/torcert.h
+++ b/src/or/torcert.h
@@ -62,5 +62,7 @@ int tor_cert_get_checkable_sig(ed25519_checkable_t *checkable_out,
int tor_cert_checksig(tor_cert_t *cert,
const ed25519_public_key_t *pubkey, time_t now);
+tor_cert_t *tor_cert_dup(const tor_cert_t *cert);
+
#endif
diff --git a/src/test/test_crypto.c b/src/test/test_crypto.c
index e9fb8bf..15ba14b 100644
--- a/src/test/test_crypto.c
+++ b/src/test/test_crypto.c
@@ -620,9 +620,18 @@ test_crypto_formats(void *arg)
for (idx = 0; idx < 10; ++idx) {
i = base64_encode(data2, 1024, data1, idx);
tt_int_op(i, OP_GE, 0);
+ tt_int_op(i, OP_EQ, strlen(data2));
j = base64_decode(data3, 1024, data2, i);
tt_int_op(j,OP_EQ, idx);
tt_mem_op(data3,OP_EQ, data1, idx);
+
+ i = base64_encode_nopad(data2, 1024, (uint8_t*)data1, idx);
+ tt_int_op(i, OP_GE, 0);
+ tt_int_op(i, OP_EQ, strlen(data2));
+ tt_assert(! strchr(data2, '='));
+ j = base64_decode_nopad((uint8_t*)data3, 1024, data2, i);
+ tt_int_op(j, OP_EQ, idx);
+ tt_mem_op(data3,OP_EQ, data1, idx);
}
strlcpy(data1, "Test string that contains 35 chars.", 1024);
@@ -1172,6 +1181,8 @@ test_crypto_ed25519_simple(void *arg)
tt_int_op(0, OP_EQ, ed25519_public_key_generate(&pub2, &sec1));
tt_mem_op(pub1.pubkey, OP_EQ, pub2.pubkey, sizeof(pub1.pubkey));
+ tt_assert(ed25519_pubkey_eq(&pub1, &pub2));
+ tt_assert(ed25519_pubkey_eq(&pub1, &pub1));
memcpy(&kp1.pubkey, &pub1, sizeof(pub1));
memcpy(&kp1.seckey, &sec1, sizeof(sec1));
@@ -1191,6 +1202,7 @@ test_crypto_ed25519_simple(void *arg)
/* Wrong public key doesn't work. */
tt_int_op(0, OP_EQ, ed25519_public_key_generate(&pub2, &sec2));
tt_int_op(-1, OP_EQ, ed25519_checksig(&sig2, msg, msg_len, &pub2));
+ tt_assert(! ed25519_pubkey_eq(&pub1, &pub2));
/* Wrong message doesn't work. */
tt_int_op(0, OP_EQ, ed25519_checksig(&sig2, msg, msg_len, &pub1));
@@ -1329,9 +1341,10 @@ test_crypto_ed25519_test_vectors(void *arg)
static void
test_crypto_ed25519_encode(void *arg)
{
- char buf[ED25519_BASE64_LEN+1];
+ char buf[ED25519_SIG_BASE64_LEN+1];
ed25519_keypair_t kp;
ed25519_public_key_t pk;
+ ed25519_signature_t sig1, sig2;
char *mem_op_hex_tmp = NULL;
(void) arg;
@@ -1342,6 +1355,11 @@ test_crypto_ed25519_encode(void *arg)
tt_int_op(0, OP_EQ, ed25519_public_from_base64(&pk, buf));
tt_mem_op(kp.pubkey.pubkey, OP_EQ, pk.pubkey, ED25519_PUBKEY_LEN);
+ tt_int_op(0, OP_EQ, ed25519_sign(&sig1, (const uint8_t*)"ABC", 3, &kp));
+ tt_int_op(0, OP_EQ, ed25519_signature_to_base64(buf, &sig1));
+ tt_int_op(0, OP_EQ, ed25519_signature_from_base64(&sig2, buf));
+ tt_mem_op(sig1.sig, OP_EQ, sig2.sig, ED25519_SIG_LEN);
+
/* Test known value. */
tt_int_op(0, OP_EQ, ed25519_public_from_base64(&pk,
"lVIuIctLjbGZGU5wKMNXxXlSE3cW4kaqkqm04u6pxvM"));
diff --git a/src/test/test_dir.c b/src/test/test_dir.c
index a949f5d..85ca40f 100644
--- a/src/test/test_dir.c
+++ b/src/test/test_dir.c
@@ -14,6 +14,7 @@
#define NETWORKSTATUS_PRIVATE
#include "or.h"
#include "config.h"
+#include "crypto_ed25519.h"
#include "directory.h"
#include "dirserv.h"
#include "dirvote.h"
@@ -23,6 +24,7 @@
#include "routerlist.h"
#include "routerparse.h"
#include "test.h"
+#include "torcert.h"
static void
test_dir_nicknames(void *arg)
@@ -89,6 +91,7 @@ test_dir_formats(void *arg)
routerlist_t *dir1 = NULL, *dir2 = NULL;
or_options_t *options = get_options_mutable();
const addr_policy_t *p;
+ time_t now = time(NULL);
(void)arg;
pk1 = pk_generate(0);
@@ -127,6 +130,22 @@ test_dir_formats(void *arg)
ex2->prt_min = ex2->prt_max = 24;
r2 = tor_malloc_zero(sizeof(routerinfo_t));
r2->addr = 0x0a030201u; /* 10.3.2.1 */
+ ed25519_keypair_t kp1, kp2;
+ ed25519_secret_key_from_seed(&kp1.seckey,
+ (const uint8_t*)"YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY");
+ ed25519_public_key_generate(&kp1.pubkey, &kp1.seckey);
+ ed25519_secret_key_from_seed(&kp2.seckey,
+ (const uint8_t*)"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
+ ed25519_public_key_generate(&kp2.pubkey, &kp2.seckey);
+ r2->signing_key_cert = tor_cert_create(&kp1,
+ CERT_TYPE_ID_SIGNING,
+ &kp2.pubkey,
+ now, 86400,
+ CERT_FLAG_INCLUDE_SIGNING_KEY);
+ char cert_buf[256];
+ base64_encode(cert_buf, sizeof(cert_buf),
+ (const char*)r2->signing_key_cert->encoded,
+ r2->signing_key_cert->encoded_len);
r2->platform = tor_strdup(platform);
r2->cache_info.published_on = 5;
r2->or_port = 9005;
@@ -150,7 +169,7 @@ test_dir_formats(void *arg)
/* XXXX025 router_dump_to_string should really take this from ri.*/
options->ContactInfo = tor_strdup("Magri White "
"<magri(a)elsewhere.example.com>");
- buf = router_dump_router_to_string(r1, pk2);
+ buf = router_dump_router_to_string(r1, pk2, NULL);
tor_free(options->ContactInfo);
tt_assert(buf);
@@ -183,7 +202,7 @@ test_dir_formats(void *arg)
tt_str_op(buf,OP_EQ, buf2);
tor_free(buf);
- buf = router_dump_router_to_string(r1, pk2);
+ buf = router_dump_router_to_string(r1, pk2, NULL);
tt_assert(buf);
cp = buf;
rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL,NULL);
@@ -201,6 +220,10 @@ test_dir_formats(void *arg)
strlcpy(buf2,
"router Fred 10.3.2.1 9005 0 0\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n", sizeof(buf2));
+ strlcat(buf2, cert_buf, sizeof(buf2));
+ strlcat(buf2, "-----END ED25519 CERT-----\n"
"platform Tor "VERSION" on ", sizeof(buf2));
strlcat(buf2, get_uname(), sizeof(buf2));
strlcat(buf2, "\n"
@@ -219,15 +242,16 @@ test_dir_formats(void *arg)
strlcat(buf2, "ntor-onion-key "
"skyinAnvardNostarsNomoonNowindormistsorsnow=\n", sizeof(buf2));
strlcat(buf2, "accept *:80\nreject 18.0.0.0/8:24\n", sizeof(buf2));
- strlcat(buf2, "router-signature\n", sizeof(buf2));
+ strlcat(buf2, "router-sig-ed25519 ", sizeof(buf2));
- buf = router_dump_router_to_string(r2, pk1);
+ buf = router_dump_router_to_string(r2, pk1, &kp2);
+ tt_assert(buf);
buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
* twice */
tt_str_op(buf,OP_EQ, buf2);
tor_free(buf);
- buf = router_dump_router_to_string(r2, pk1);
+ buf = router_dump_router_to_string(r2, pk1, NULL);
cp = buf;
rp2 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL,NULL);
tt_assert(rp2);
diff --git a/src/test/test_routerkeys.c b/src/test/test_routerkeys.c
index 63284b7..8780213 100644
--- a/src/test/test_routerkeys.c
+++ b/src/test/test_routerkeys.c
@@ -90,6 +90,7 @@ test_routerkeys_ed_certs(void *args)
tor_cert_t *parsed_cert[2] = {NULL, NULL};
time_t now = 1412094534;
uint8_t *junk = NULL;
+ char *base64 = NULL;
tt_int_op(0,==,ed25519_keypair_generate(&kp1, 0));
tt_int_op(0,==,ed25519_keypair_generate(&kp2, 0));
@@ -186,6 +187,7 @@ test_routerkeys_ed_certs(void *args)
tor_cert_free(parsed_cert[0]);
tor_cert_free(parsed_cert[1]);
tor_free(junk);
+ tor_free(base64);
}
static void
1
0

[tor/master] Implement proposal 228: cross-certification with onion keys
by nickm@torproject.org 28 May '15
by nickm@torproject.org 28 May '15
28 May '15
commit a2f317913fc48975381696cc381d5f78e25e92b6
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Thu May 28 10:41:43 2015 -0400
Implement proposal 228: cross-certification with onion keys
Routers now use TAP and ntor onion keys to sign their identity keys,
and put these signatures in their descriptors. That allows other
parties to be confident that the onion keys are indeed controlled by
the router that generated the descriptor.
---
src/or/router.c | 2 ++
1 file changed, 2 insertions(+)
diff --git a/src/or/router.c b/src/or/router.c
index 2087a25..97c2b83 100644
--- a/src/or/router.c
+++ b/src/or/router.c
@@ -2628,6 +2628,8 @@ router_dump_router_to_string(routerinfo_t *router,
tor_free(identity_pkey);
tor_free(extra_or_address);
tor_free(ed_cert_line);
+ tor_free(rsa_tap_cc_line);
+ tor_free(ntor_cc_line);
return output;
}
1
0

28 May '15
commit f253aef14faf7640f94e9e76947b6a4461c3c1a4
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Tue Sep 30 08:31:08 2014 -0400
Mechanical rename: tor_cert_t -> tor_x509_cert_t
---
src/common/tortls.c | 66 ++++++++++++++++++++++++------------------------
src/common/tortls.h | 26 +++++++++----------
src/or/channeltls.c | 26 +++++++++----------
src/or/connection_or.c | 24 +++++++++---------
src/or/or.h | 4 +--
5 files changed, 73 insertions(+), 73 deletions(-)
diff --git a/src/common/tortls.c b/src/common/tortls.c
index 97a82bf..b4d50cd 100644
--- a/src/common/tortls.c
+++ b/src/common/tortls.c
@@ -122,7 +122,7 @@ static int use_unsafe_renegotiation_op = 0;
static int use_unsafe_renegotiation_flag = 0;
/** Structure that we use for a single certificate. */
-struct tor_cert_t {
+struct tor_x509_cert_t {
X509 *cert;
uint8_t *encoded;
size_t encoded_len;
@@ -137,9 +137,9 @@ struct tor_cert_t {
typedef struct tor_tls_context_t {
int refcnt;
SSL_CTX *ctx;
- tor_cert_t *my_link_cert;
- tor_cert_t *my_id_cert;
- tor_cert_t *my_auth_cert;
+ tor_x509_cert_t *my_link_cert;
+ tor_x509_cert_t *my_id_cert;
+ tor_x509_cert_t *my_auth_cert;
crypto_pk_t *link_key;
crypto_pk_t *auth_key;
} tor_tls_context_t;
@@ -821,7 +821,7 @@ static const int N_CLIENT_CIPHERS = ARRAY_LENGTH(CLIENT_CIPHER_INFO_LIST);
/** Free all storage held in <b>cert</b> */
void
-tor_cert_free(tor_cert_t *cert)
+tor_x509_cert_free(tor_x509_cert_t *cert)
{
if (! cert)
return;
@@ -833,14 +833,14 @@ tor_cert_free(tor_cert_t *cert)
}
/**
- * Allocate a new tor_cert_t to hold the certificate "x509_cert".
+ * Allocate a new tor_x509_cert_t to hold the certificate "x509_cert".
*
* Steals a reference to x509_cert.
*/
-static tor_cert_t *
-tor_cert_new(X509 *x509_cert)
+static tor_x509_cert_t *
+tor_x509_cert_new(X509 *x509_cert)
{
- tor_cert_t *cert;
+ tor_x509_cert_t *cert;
EVP_PKEY *pkey;
RSA *rsa;
int length;
@@ -850,7 +850,7 @@ tor_cert_new(X509 *x509_cert)
return NULL;
length = i2d_X509(x509_cert, &buf);
- cert = tor_malloc_zero(sizeof(tor_cert_t));
+ cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
if (length <= 0 || buf == NULL) {
tor_free(cert);
log_err(LD_CRYPTO, "Couldn't get length of encoded x509 certificate");
@@ -880,14 +880,14 @@ tor_cert_new(X509 *x509_cert)
}
/** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
- * from a <b>certificate</b>. Return a newly allocated tor_cert_t on success
+ * from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on success
* and NULL on failure. */
-tor_cert_t *
-tor_cert_decode(const uint8_t *certificate, size_t certificate_len)
+tor_x509_cert_t *
+tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
{
X509 *x509;
const unsigned char *cp = (const unsigned char *)certificate;
- tor_cert_t *newcert;
+ tor_x509_cert_t *newcert;
tor_assert(certificate);
check_no_tls_errors();
@@ -902,14 +902,14 @@ tor_cert_decode(const uint8_t *certificate, size_t certificate_len)
X509_free(x509);
goto err; /* Didn't use all the bytes */
}
- newcert = tor_cert_new(x509);
+ newcert = tor_x509_cert_new(x509);
if (!newcert) {
goto err;
}
if (newcert->encoded_len != certificate_len ||
fast_memneq(newcert->encoded, certificate, certificate_len)) {
/* Cert wasn't in DER */
- tor_cert_free(newcert);
+ tor_x509_cert_free(newcert);
goto err;
}
return newcert;
@@ -921,7 +921,7 @@ tor_cert_decode(const uint8_t *certificate, size_t certificate_len)
/** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
* representation and length, respectively. */
void
-tor_cert_get_der(const tor_cert_t *cert,
+tor_x509_cert_get_der(const tor_x509_cert_t *cert,
const uint8_t **encoded_out, size_t *size_out)
{
tor_assert(cert);
@@ -934,7 +934,7 @@ tor_cert_get_der(const tor_cert_t *cert,
/** Return a set of digests for the public key in <b>cert</b>, or NULL if this
* cert's public key is not one we know how to take the digest of. */
const digests_t *
-tor_cert_get_id_digests(const tor_cert_t *cert)
+tor_x509_cert_get_id_digests(const tor_x509_cert_t *cert)
{
if (cert->pkey_digests_set)
return &cert->pkey_digests;
@@ -944,7 +944,7 @@ tor_cert_get_id_digests(const tor_cert_t *cert)
/** Return a set of digests for the public key in <b>cert</b>. */
const digests_t *
-tor_cert_get_cert_digests(const tor_cert_t *cert)
+tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert)
{
return &cert->cert_digests;
}
@@ -957,9 +957,9 @@ tor_tls_context_decref(tor_tls_context_t *ctx)
tor_assert(ctx);
if (--ctx->refcnt == 0) {
SSL_CTX_free(ctx->ctx);
- tor_cert_free(ctx->my_link_cert);
- tor_cert_free(ctx->my_id_cert);
- tor_cert_free(ctx->my_auth_cert);
+ tor_x509_cert_free(ctx->my_link_cert);
+ tor_x509_cert_free(ctx->my_id_cert);
+ tor_x509_cert_free(ctx->my_auth_cert);
crypto_pk_free(ctx->link_key);
crypto_pk_free(ctx->auth_key);
tor_free(ctx);
@@ -973,8 +973,8 @@ tor_tls_context_decref(tor_tls_context_t *ctx)
* client mode. */
int
tor_tls_get_my_certs(int server,
- const tor_cert_t **link_cert_out,
- const tor_cert_t **id_cert_out)
+ const tor_x509_cert_t **link_cert_out,
+ const tor_x509_cert_t **id_cert_out)
{
tor_tls_context_t *ctx = server ? server_tls_context : client_tls_context;
if (! ctx)
@@ -1003,7 +1003,7 @@ tor_tls_get_my_client_auth_key(void)
* certifies. Return NULL if the cert's key is not RSA.
*/
crypto_pk_t *
-tor_tls_cert_get_key(tor_cert_t *cert)
+tor_tls_cert_get_key(tor_x509_cert_t *cert)
{
crypto_pk_t *result = NULL;
EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
@@ -1024,7 +1024,7 @@ tor_tls_cert_get_key(tor_cert_t *cert)
* the key certified in <b>cert</b> is the same as the key they used to do it.
*/
int
-tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_cert_t *cert)
+tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_x509_cert_t *cert)
{
X509 *peercert = SSL_get_peer_certificate(tls->ssl);
EVP_PKEY *link_key = NULL, *cert_key = NULL;
@@ -1053,8 +1053,8 @@ tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_cert_t *cert)
* we couldn't check it. */
int
tor_tls_cert_is_valid(int severity,
- const tor_cert_t *cert,
- const tor_cert_t *signing_cert,
+ const tor_x509_cert_t *cert,
+ const tor_x509_cert_t *signing_cert,
int check_rsa_1024)
{
check_no_tls_errors();
@@ -1265,9 +1265,9 @@ tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
result = tor_malloc_zero(sizeof(tor_tls_context_t));
result->refcnt = 1;
if (!is_client) {
- result->my_link_cert = tor_cert_new(X509_dup(cert));
- result->my_id_cert = tor_cert_new(X509_dup(idcert));
- result->my_auth_cert = tor_cert_new(X509_dup(authcert));
+ result->my_link_cert = tor_x509_cert_new(X509_dup(cert));
+ result->my_id_cert = tor_x509_cert_new(X509_dup(idcert));
+ result->my_auth_cert = tor_x509_cert_new(X509_dup(authcert));
if (!result->my_link_cert || !result->my_id_cert || !result->my_auth_cert)
goto error;
result->link_key = crypto_pk_dup_key(rsa);
@@ -2394,7 +2394,7 @@ tor_tls_peer_has_cert(tor_tls_t *tls)
}
/** Return the peer certificate, or NULL if there isn't one. */
-tor_cert_t *
+tor_x509_cert_t *
tor_tls_get_peer_cert(tor_tls_t *tls)
{
X509 *cert;
@@ -2402,7 +2402,7 @@ tor_tls_get_peer_cert(tor_tls_t *tls)
tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
if (!cert)
return NULL;
- return tor_cert_new(cert);
+ return tor_x509_cert_new(cert);
}
/** Warn that a certificate lifetime extends through a certain range. */
diff --git a/src/common/tortls.h b/src/common/tortls.h
index f8c6d59..22b1a9e 100644
--- a/src/common/tortls.h
+++ b/src/common/tortls.h
@@ -19,7 +19,7 @@
typedef struct tor_tls_t tor_tls_t;
/* Opaque structure to hold an X509 certificate. */
-typedef struct tor_cert_t tor_cert_t;
+typedef struct tor_x509_cert_t tor_x509_cert_t;
/* Possible return values for most tor_tls_* functions. */
#define MIN_TOR_TLS_ERROR_VAL_ -9
@@ -72,7 +72,7 @@ void tor_tls_set_renegotiate_callback(tor_tls_t *tls,
int tor_tls_is_server(tor_tls_t *tls);
void tor_tls_free(tor_tls_t *tls);
int tor_tls_peer_has_cert(tor_tls_t *tls);
-tor_cert_t *tor_tls_get_peer_cert(tor_tls_t *tls);
+tor_x509_cert_t *tor_tls_get_peer_cert(tor_tls_t *tls);
int tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity);
int tor_tls_check_lifetime(int severity,
tor_tls_t *tls, int past_tolerance,
@@ -120,22 +120,22 @@ struct bufferevent *tor_tls_init_bufferevent(tor_tls_t *tls,
int filter);
#endif
-void tor_cert_free(tor_cert_t *cert);
-tor_cert_t *tor_cert_decode(const uint8_t *certificate,
+void tor_x509_cert_free(tor_x509_cert_t *cert);
+tor_x509_cert_t *tor_x509_cert_decode(const uint8_t *certificate,
size_t certificate_len);
-void tor_cert_get_der(const tor_cert_t *cert,
+void tor_x509_cert_get_der(const tor_x509_cert_t *cert,
const uint8_t **encoded_out, size_t *size_out);
-const digests_t *tor_cert_get_id_digests(const tor_cert_t *cert);
-const digests_t *tor_cert_get_cert_digests(const tor_cert_t *cert);
+const digests_t *tor_x509_cert_get_id_digests(const tor_x509_cert_t *cert);
+const digests_t *tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert);
int tor_tls_get_my_certs(int server,
- const tor_cert_t **link_cert_out,
- const tor_cert_t **id_cert_out);
+ const tor_x509_cert_t **link_cert_out,
+ const tor_x509_cert_t **id_cert_out);
crypto_pk_t *tor_tls_get_my_client_auth_key(void);
-crypto_pk_t *tor_tls_cert_get_key(tor_cert_t *cert);
-int tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_cert_t *cert);
+crypto_pk_t *tor_tls_cert_get_key(tor_x509_cert_t *cert);
+int tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_x509_cert_t *cert);
int tor_tls_cert_is_valid(int severity,
- const tor_cert_t *cert,
- const tor_cert_t *signing_cert,
+ const tor_x509_cert_t *cert,
+ const tor_x509_cert_t *signing_cert,
int check_rsa_1024);
const char *tor_tls_get_ciphersuite_name(tor_tls_t *tls);
diff --git a/src/or/channeltls.c b/src/or/channeltls.c
index e194c1c..10fcb28 100644
--- a/src/or/channeltls.c
+++ b/src/or/channeltls.c
@@ -1747,9 +1747,9 @@ channel_tls_process_netinfo_cell(cell_t *cell, channel_tls_t *chan)
static void
channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
{
- tor_cert_t *link_cert = NULL;
- tor_cert_t *id_cert = NULL;
- tor_cert_t *auth_cert = NULL;
+ tor_x509_cert_t *link_cert = NULL;
+ tor_x509_cert_t *id_cert = NULL;
+ tor_x509_cert_t *auth_cert = NULL;
uint8_t *ptr;
int n_certs, i;
int send_netinfo = 0;
@@ -1803,7 +1803,7 @@ channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
if (cert_type == OR_CERT_TYPE_TLS_LINK ||
cert_type == OR_CERT_TYPE_ID_1024 ||
cert_type == OR_CERT_TYPE_AUTH_1024) {
- tor_cert_t *cert = tor_cert_decode(ptr + 3, cert_len);
+ tor_x509_cert_t *cert = tor_x509_cert_decode(ptr + 3, cert_len);
if (!cert) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Received undecodable certificate in CERTS cell from %s:%d",
@@ -1812,24 +1812,24 @@ channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
} else {
if (cert_type == OR_CERT_TYPE_TLS_LINK) {
if (link_cert) {
- tor_cert_free(cert);
+ tor_x509_cert_free(cert);
ERR("Too many TLS_LINK certificates");
}
link_cert = cert;
} else if (cert_type == OR_CERT_TYPE_ID_1024) {
if (id_cert) {
- tor_cert_free(cert);
+ tor_x509_cert_free(cert);
ERR("Too many ID_1024 certificates");
}
id_cert = cert;
} else if (cert_type == OR_CERT_TYPE_AUTH_1024) {
if (auth_cert) {
- tor_cert_free(cert);
+ tor_x509_cert_free(cert);
ERR("Too many AUTH_1024 certificates");
}
auth_cert = cert;
} else {
- tor_cert_free(cert);
+ tor_x509_cert_free(cert);
}
}
}
@@ -1864,7 +1864,7 @@ channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
chan->conn->handshake_state->authenticated = 1;
{
- const digests_t *id_digests = tor_cert_get_id_digests(id_cert);
+ const digests_t *id_digests = tor_x509_cert_get_id_digests(id_cert);
crypto_pk_t *identity_rcvd;
if (!id_digests)
ERR("Couldn't compute digests for key in ID cert");
@@ -1929,9 +1929,9 @@ channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
}
err:
- tor_cert_free(id_cert);
- tor_cert_free(link_cert);
- tor_cert_free(auth_cert);
+ tor_x509_cert_free(id_cert);
+ tor_x509_cert_free(link_cert);
+ tor_x509_cert_free(auth_cert);
#undef ERR
}
@@ -2151,7 +2151,7 @@ channel_tls_process_authenticate_cell(var_cell_t *cell, channel_tls_t *chan)
crypto_pk_t *identity_rcvd =
tor_tls_cert_get_key(chan->conn->handshake_state->id_cert);
const digests_t *id_digests =
- tor_cert_get_id_digests(chan->conn->handshake_state->id_cert);
+ tor_x509_cert_get_id_digests(chan->conn->handshake_state->id_cert);
/* This must exist; we checked key type when reading the cert. */
tor_assert(id_digests);
diff --git a/src/or/connection_or.c b/src/or/connection_or.c
index 85462d8..6c584a5 100644
--- a/src/or/connection_or.c
+++ b/src/or/connection_or.c
@@ -1878,8 +1878,8 @@ or_handshake_state_free(or_handshake_state_t *state)
return;
crypto_digest_free(state->digest_sent);
crypto_digest_free(state->digest_received);
- tor_cert_free(state->auth_cert);
- tor_cert_free(state->id_cert);
+ tor_x509_cert_free(state->auth_cert);
+ tor_x509_cert_free(state->id_cert);
memwipe(state, 0xBE, sizeof(or_handshake_state_t));
tor_free(state);
}
@@ -2227,7 +2227,7 @@ connection_or_send_netinfo(or_connection_t *conn)
int
connection_or_send_certs_cell(or_connection_t *conn)
{
- const tor_cert_t *link_cert = NULL, *id_cert = NULL;
+ const tor_x509_cert_t *link_cert = NULL, *id_cert = NULL;
const uint8_t *link_encoded = NULL, *id_encoded = NULL;
size_t link_len, id_len;
var_cell_t *cell;
@@ -2242,8 +2242,8 @@ connection_or_send_certs_cell(or_connection_t *conn)
server_mode = ! conn->handshake_state->started_here;
if (tor_tls_get_my_certs(server_mode, &link_cert, &id_cert) < 0)
return -1;
- tor_cert_get_der(link_cert, &link_encoded, &link_len);
- tor_cert_get_der(id_cert, &id_encoded, &id_len);
+ tor_x509_cert_get_der(link_cert, &link_encoded, &link_len);
+ tor_x509_cert_get_der(id_cert, &id_encoded, &id_len);
cell_len = 1 /* 1 byte: num certs in cell */ +
2 * ( 1 + 2 ) /* For each cert: 1 byte for type, 2 for length */ +
@@ -2342,13 +2342,13 @@ connection_or_compute_authenticate_cell_body(or_connection_t *conn,
ptr += 8;
{
- const tor_cert_t *id_cert=NULL, *link_cert=NULL;
+ const tor_x509_cert_t *id_cert=NULL, *link_cert=NULL;
const digests_t *my_digests, *their_digests;
const uint8_t *my_id, *their_id, *client_id, *server_id;
if (tor_tls_get_my_certs(server, &link_cert, &id_cert))
return -1;
- my_digests = tor_cert_get_id_digests(id_cert);
- their_digests = tor_cert_get_id_digests(conn->handshake_state->id_cert);
+ my_digests = tor_x509_cert_get_id_digests(id_cert);
+ their_digests = tor_x509_cert_get_id_digests(conn->handshake_state->id_cert);
tor_assert(my_digests);
tor_assert(their_digests);
my_id = (uint8_t*)my_digests->d[DIGEST_SHA256];
@@ -2387,8 +2387,8 @@ connection_or_compute_authenticate_cell_body(or_connection_t *conn,
{
/* Digest of cert used on TLS link : 32 octets. */
- const tor_cert_t *cert = NULL;
- tor_cert_t *freecert = NULL;
+ const tor_x509_cert_t *cert = NULL;
+ tor_x509_cert_t *freecert = NULL;
if (server) {
tor_tls_get_my_certs(1, &cert, NULL);
} else {
@@ -2397,10 +2397,10 @@ connection_or_compute_authenticate_cell_body(or_connection_t *conn,
}
if (!cert)
return -1;
- memcpy(ptr, tor_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
+ memcpy(ptr, tor_x509_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
if (freecert)
- tor_cert_free(freecert);
+ tor_x509_cert_free(freecert);
ptr += 32;
}
diff --git a/src/or/or.h b/src/or/or.h
index 6723f93..19694a0 100644
--- a/src/or/or.h
+++ b/src/or/or.h
@@ -1411,9 +1411,9 @@ typedef struct or_handshake_state_t {
* @{
*/
/** The cert for the key that's supposed to sign the AUTHENTICATE cell */
- tor_cert_t *auth_cert;
+ tor_x509_cert_t *auth_cert;
/** A self-signed identity certificate */
- tor_cert_t *id_cert;
+ tor_x509_cert_t *id_cert;
/**@}*/
} or_handshake_state_t;
1
0

[tor/master] prop220: Implement certificates and key storage/creation
by nickm@torproject.org 28 May '15
by nickm@torproject.org 28 May '15
28 May '15
commit 818e6f939d4bd241e762970da4c6360858993cd5
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Tue Sep 30 16:00:17 2014 -0400
prop220: Implement certificates and key storage/creation
For prop220, we have a new ed25519 certificate type. This patch
implements the code to create, parse, and validate those, along with
code for routers to maintain their own sets of certificates and
keys. (Some parts of master identity key encryption are done, but
the implementation of that isn't finished)
---
src/common/crypto_ed25519.c | 10 +
src/common/crypto_ed25519.h | 5 +-
src/or/config.h | 4 +
src/or/include.am | 13 +-
src/or/main.c | 2 +
src/or/or.h | 1 +
src/or/router.c | 5 +
src/or/routerkeys.c | 453 +++++++++++++++++++
src/or/routerkeys.h | 44 ++
src/or/torcert.c | 208 +++++++++
src/or/torcert.h | 66 +++
src/test/include.am | 2 +-
src/test/test_routerkeys.c | 444 ++++++++++++++++++-
src/trunnel/ed25519_cert.c | 887 ++++++++++++++++++++++++++++++++++++++
src/trunnel/ed25519_cert.h | 288 +++++++++++++
src/trunnel/ed25519_cert.trunnel | 76 ++++
src/trunnel/include.am | 18 +-
17 files changed, 2513 insertions(+), 13 deletions(-)
diff --git a/src/common/crypto_ed25519.c b/src/common/crypto_ed25519.c
index f2e6945..7e8b00a 100644
--- a/src/common/crypto_ed25519.c
+++ b/src/common/crypto_ed25519.c
@@ -351,3 +351,13 @@ ed25519_pubkey_read_from_file(ed25519_public_key_t *pubkey_out,
return 0;
}
+void
+ed25519_keypair_free(ed25519_keypair_t *kp)
+{
+ if (! kp)
+ return;
+
+ memwipe(kp, 0, sizeof(*kp));
+ tor_free(kp);
+}
+
diff --git a/src/common/crypto_ed25519.h b/src/common/crypto_ed25519.h
index 7efa74b..8e06191 100644
--- a/src/common/crypto_ed25519.h
+++ b/src/common/crypto_ed25519.h
@@ -6,6 +6,7 @@
#include "testsupport.h"
#include "torint.h"
+#include "crypto_curve25519.h"
#define ED25519_PUBKEY_LEN 32
#define ED25519_SECKEY_LEN 64
@@ -60,7 +61,7 @@ int ed25519_checksig(const ed25519_signature_t *signature,
*/
typedef struct {
/** The public key that supposedly generated the signature. */
- ed25519_public_key_t *pubkey;
+ const ed25519_public_key_t *pubkey;
/** The signature to check. */
ed25519_signature_t signature;
/** The message that the signature is supposed to have been applied to. */
@@ -109,5 +110,7 @@ int ed25519_pubkey_read_from_file(ed25519_public_key_t *pubkey_out,
char **tag_out,
const char *filename);
+void ed25519_keypair_free(ed25519_keypair_t *kp);
+
#endif
diff --git a/src/or/config.h b/src/or/config.h
index b064f05..e972485 100644
--- a/src/or/config.h
+++ b/src/or/config.h
@@ -61,6 +61,10 @@ char *options_get_datadir_fname2_suffix(const or_options_t *options,
* get_datadir_fname2_suffix. */
#define get_datadir_fname2(sub1,sub2) \
get_datadir_fname2_suffix((sub1), (sub2), NULL)
+/** Return a newly allocated string containing datadir/sub1/sub2 relative to
+ * opts. See get_datadir_fname2_suffix. */
+#define options_get_datadir_fname2(opts,sub1,sub2) \
+ options_get_datadir_fname2_suffix((opts),(sub1), (sub2), NULL)
/** Return a newly allocated string containing datadir/sub1suffix. See
* get_datadir_fname2_suffix. */
#define get_datadir_fname_suffix(sub1, suffix) \
diff --git a/src/or/include.am b/src/or/include.am
index b44e109..a85b0dd 100644
--- a/src/or/include.am
+++ b/src/or/include.am
@@ -71,12 +71,14 @@ LIBTOR_A_SOURCES = \
src/or/rephist.c \
src/or/replaycache.c \
src/or/router.c \
+ src/or/routerkeys.c \
src/or/routerlist.c \
src/or/routerparse.c \
src/or/routerset.c \
src/or/scheduler.c \
src/or/statefile.c \
src/or/status.c \
+ src/or/torcert.c \
src/or/onion_ntor.c \
$(evdns_source) \
$(tor_platform_source) \
@@ -87,7 +89,7 @@ src_or_libtor_testing_a_SOURCES = $(LIBTOR_A_SOURCES)
#libtor_a_LIBADD = ../common/libor.a ../common/libor-crypto.a \
# ../common/libor-event.a
-
+#src_or_libtor_a_LIBADD = src/trunnel/libor-trunnel.a
src_or_tor_SOURCES = src/or/tor_main.c
AM_CPPFLAGS += -I$(srcdir)/src/or -Isrc/or
@@ -109,7 +111,7 @@ src_or_libtor_testing_a_CFLAGS = $(AM_CFLAGS) $(TEST_CFLAGS)
src_or_tor_LDFLAGS = @TOR_LDFLAGS_zlib@ @TOR_LDFLAGS_openssl@ @TOR_LDFLAGS_libevent@
src_or_tor_LDADD = src/or/libtor.a src/common/libor.a \
src/common/libor-crypto.a $(LIBDONNA) \
- src/common/libor-event.a \
+ src/common/libor-event.a src/trunnel/libor-trunnel.a \
@TOR_ZLIB_LIBS@ @TOR_LIB_MATH@ @TOR_LIBEVENT_LIBS@ @TOR_OPENSSL_LIBS@ \
@TOR_LIB_WS32@ @TOR_LIB_GDI@ @CURVE25519_LIBS@ @TOR_SYSTEMD_LIBS@
@@ -120,7 +122,7 @@ src_or_tor_cov_CFLAGS = $(AM_CFLAGS) $(TEST_CFLAGS)
src_or_tor_cov_LDFLAGS = @TOR_LDFLAGS_zlib@ @TOR_LDFLAGS_openssl@ @TOR_LDFLAGS_libevent@
src_or_tor_cov_LDADD = src/or/libtor-testing.a src/common/libor-testing.a \
src/common/libor-crypto-testing.a $(LIBDONNA) \
- src/common/libor-event-testing.a \
+ src/common/libor-event-testing.a src/trunnel/libor-trunnel-testing.a \
@TOR_ZLIB_LIBS@ @TOR_LIB_MATH@ @TOR_LIBEVENT_LIBS@ @TOR_OPENSSL_LIBS@ \
@TOR_LIB_WS32@ @TOR_LIB_GDI@ @CURVE25519_LIBS@ @TOR_SYSTEMD_LIBS@
TESTING_TOR_BINARY = ./src/or/tor-cov
@@ -180,12 +182,15 @@ ORHEADERS = \
src/or/rephist.h \
src/or/replaycache.h \
src/or/router.h \
+ src/or/routerkeys.h \
src/or/routerlist.h \
+ src/or/routerkeys.h \
src/or/routerset.h \
src/or/routerparse.h \
src/or/scheduler.h \
src/or/statefile.h \
- src/or/status.h
+ src/or/status.h \
+ src/or/torcert.h
noinst_HEADERS+= $(ORHEADERS) micro-revision.i
diff --git a/src/or/main.c b/src/or/main.c
index bc89458..8b82a31 100644
--- a/src/or/main.c
+++ b/src/or/main.c
@@ -51,6 +51,7 @@
#include "rendservice.h"
#include "rephist.h"
#include "router.h"
+#include "routerkeys.h"
#include "routerlist.h"
#include "routerparse.h"
#include "scheduler.h"
@@ -2648,6 +2649,7 @@ tor_free_all(int postfork)
config_free_all();
or_state_free_all();
router_free_all();
+ routerkeys_free_all();
policies_free_all();
}
if (!postfork) {
diff --git a/src/or/or.h b/src/or/or.h
index 19694a0..2044e84 100644
--- a/src/or/or.h
+++ b/src/or/or.h
@@ -96,6 +96,7 @@
#include "ht.h"
#include "replaycache.h"
#include "crypto_curve25519.h"
+#include "crypto_ed25519.h"
#include "tor_queue.h"
/* These signals are defined to help handle_control_signal work.
diff --git a/src/or/router.c b/src/or/router.c
index 2ddaa89..1355613 100644
--- a/src/or/router.c
+++ b/src/or/router.c
@@ -26,6 +26,7 @@
#include "relay.h"
#include "rephist.h"
#include "router.h"
+#include "routerkeys.h"
#include "routerlist.h"
#include "routerparse.h"
#include "statefile.h"
@@ -861,6 +862,10 @@ init_keys(void)
set_client_identity_key(prkey);
}
+ /* 1d. Load all ed25519 keys */
+ if (load_ed_keys(options,now) < 0)
+ return -1;
+
/* 2. Read onion key. Make it if none is found. */
keydir = get_datadir_fname2("keys", "secret_onion_key");
log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
diff --git a/src/or/routerkeys.c b/src/or/routerkeys.c
new file mode 100644
index 0000000..fb61c31
--- /dev/null
+++ b/src/or/routerkeys.c
@@ -0,0 +1,453 @@
+/* Copyright (c) 2014, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "or.h"
+#include "config.h"
+#include "routerkeys.h"
+#include "torcert.h"
+
+/**
+ * Read an ed25519 key and associated certificates from files beginning with
+ * <b>fname</b>, with certificate type <b>cert_type</b>. On failure, return
+ * NULL; on success return the keypair.
+ *
+ * If INIT_ED_KEY_CREATE is set in <b>flags</b>, then create the key (and
+ * certificate if requested) if it doesn't exist, and save it to disk.
+ *
+ * If INIT_ED_KEY_NEEDCERT is set in <b>flags</b>, load/create a certificate
+ * too and store it in *<b>cert_out</b>. Fail if the cert can't be
+ * found/created. To create a certificate, <b>signing_key</b> must be set to
+ * the key that should sign it; <b>now</b> to the current time, and
+ * <b>lifetime</b> to the lifetime of the key.
+ *
+ * If INIT_ED_KEY_REPLACE is set in <b>flags</b>, then create and save new key
+ * whether we can read the old one or not.
+ *
+ * If INIT_ED_KEY_EXTRA_STRONG is set in <b>flags</b>, set the extra_strong
+ * flag when creating the secret key.
+ *
+ * If INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT is set in <b>flags</b>, and
+ * we create a new certificate, create it with the signing key embedded.
+ *
+ * If INIT_ED_KEY_SPLIT is set in <b>flags</b>, and we create a new key,
+ * store the public key in a separate file from the secret key.
+ *
+ * If INIT_ED_KEY_MISSING_SECRET_OK is set in <b>flags</b>, and we find a
+ * public key file but no secret key file, return successfully anyway.
+ */
+ed25519_keypair_t *
+ed_key_init_from_file(const char *fname, uint32_t flags,
+ int severity,
+ const ed25519_keypair_t *signing_key,
+ time_t now,
+ time_t lifetime,
+ uint8_t cert_type,
+ struct tor_cert_st **cert_out)
+{
+ char *secret_fname = NULL;
+ char *public_fname = NULL;
+ char *cert_fname = NULL;
+ int created_pk = 0, created_sk = 0, created_cert = 0;
+ const int try_to_load = ! (flags & INIT_ED_KEY_REPLACE);
+
+ char tag[8];
+ tor_snprintf(tag, sizeof(tag), "type%d", (int)cert_type);
+
+ tor_cert_t *cert = NULL;
+ char *got_tag = NULL;
+ ed25519_keypair_t *keypair = tor_malloc_zero(sizeof(ed25519_keypair_t));
+
+ tor_asprintf(&secret_fname, "%s_secret_key", fname);
+ tor_asprintf(&public_fname, "%s_public_key", fname);
+ tor_asprintf(&cert_fname, "%s_cert", fname);
+
+ /* Try to read the secret key. */
+ const int have_secret = try_to_load &&
+ ed25519_seckey_read_from_file(&keypair->seckey,
+ &got_tag, secret_fname) == 0;
+
+ if (have_secret) {
+ if (strcmp(got_tag, tag)) {
+ tor_log(severity, LD_OR, "%s has wrong tag", secret_fname);
+ goto err;
+ }
+ /* Derive the public key */
+ if (ed25519_public_key_generate(&keypair->pubkey, &keypair->seckey)<0) {
+ tor_log(severity, LD_OR, "%s can't produce a public key", secret_fname);
+ goto err;
+ }
+ }
+
+ /* If it's absent and that's okay, try to read the pubkey. */
+ int found_public = 0;
+ if (!have_secret && try_to_load && (flags & INIT_ED_KEY_MISSING_SECRET_OK)) {
+ tor_free(got_tag);
+ found_public = ed25519_pubkey_read_from_file(&keypair->pubkey,
+ &got_tag, public_fname) == 0;
+ if (found_public && strcmp(got_tag, tag)) {
+ tor_log(severity, LD_OR, "%s has wrong tag", public_fname);
+ goto err;
+ }
+ }
+
+ /* If it's absent, and we're not supposed to make a new keypair, fail. */
+ if (!have_secret && !found_public && !(flags & INIT_ED_KEY_CREATE))
+ goto err;
+
+ /* if it's absent, make a new keypair and save it. */
+ if (!have_secret && !found_public) {
+ const int split = !! (flags & INIT_ED_KEY_SPLIT);
+ tor_free(keypair);
+ keypair = ed_key_new(signing_key, flags, now, lifetime,
+ cert_type, &cert);
+ if (!keypair) {
+ tor_log(severity, LD_OR, "Couldn't create keypair");
+ goto err;
+ }
+
+ created_pk = created_sk = created_cert = 1;
+ if (ed25519_seckey_write_to_file(&keypair->seckey, secret_fname, tag) < 0
+ ||
+ (split &&
+ ed25519_pubkey_write_to_file(&keypair->pubkey, public_fname, tag) < 0)
+ ||
+ (cert &&
+ crypto_write_tagged_contents_to_file(cert_fname, "ed25519v1-cert",
+ tag, cert->encoded, cert->encoded_len) < 0)) {
+ tor_log(severity, LD_OR, "Couldn't write keys or cert to file.");
+ goto err;
+ }
+ goto done;
+ }
+
+ /* If we're not supposed to get a cert, we're done. */
+ if (! (flags & INIT_ED_KEY_NEEDCERT))
+ goto done;
+
+ /* Read a cert. */
+ uint8_t certbuf[256];
+ ssize_t cert_body_len = crypto_read_tagged_contents_from_file(
+ cert_fname, "ed25519v1-cert",
+ &got_tag, certbuf, sizeof(certbuf));
+ if (cert_body_len >= 0 && !strcmp(got_tag, tag))
+ cert = tor_cert_parse(certbuf, cert_body_len);
+
+ /* If we got it, check it to the extent we can. */
+ if (cert) {
+ int bad_cert = 0;
+
+ if (! cert) {
+ tor_log(severity, LD_OR, "Cert was unparseable");
+ bad_cert = 1;
+ } else if (!tor_memeq(cert->signed_key.pubkey, keypair->pubkey.pubkey,
+ ED25519_PUBKEY_LEN)) {
+ tor_log(severity, LD_OR, "Cert was for wrong key");
+ bad_cert = 1;
+ } else if (tor_cert_checksig(cert, &signing_key->pubkey, now) < 0 &&
+ (signing_key || cert->cert_expired)) {
+ tor_log(severity, LD_OR, "Can't check certificate");
+ bad_cert = 1;
+ }
+
+ if (bad_cert) {
+ tor_cert_free(cert);
+ cert = NULL;
+ }
+ }
+
+ /* If we got a cert, we're done. */
+ if (cert)
+ goto done;
+
+ /* If we didn't get a cert, and we're not supposed to make one, fail. */
+ if (!signing_key || !(flags & INIT_ED_KEY_CREATE))
+ goto err;
+
+ /* We have keys but not a certificate, so make one. */
+ uint32_t cert_flags = 0;
+ if (flags & INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT)
+ cert_flags |= CERT_FLAG_INCLUDE_SIGNING_KEY;
+ cert = tor_cert_create(signing_key, cert_type,
+ &keypair->pubkey,
+ now, lifetime,
+ cert_flags);
+
+ if (! cert)
+ goto err;
+
+ /* Write it to disk. */
+ created_cert = 1;
+ if (crypto_write_tagged_contents_to_file(cert_fname, "ed25519v1-cert",
+ tag, cert->encoded, cert->encoded_len) < 0) {
+ tor_log(severity, LD_OR, "Couldn't write cert to disk.");
+ goto err;
+ }
+
+ done:
+ if (cert_out)
+ *cert_out = cert;
+ else
+ tor_cert_free(cert);
+
+ goto cleanup;
+
+ err:
+ memwipe(keypair, 0, sizeof(*keypair));
+ tor_free(keypair);
+ tor_cert_free(cert);
+ if (cert_out)
+ *cert_out = NULL;
+ if (created_sk)
+ unlink(secret_fname);
+ if (created_pk)
+ unlink(public_fname);
+ if (created_cert)
+ unlink(cert_fname);
+
+ cleanup:
+ tor_free(secret_fname);
+ tor_free(public_fname);
+ tor_free(cert_fname);
+
+ return keypair;
+}
+
+/**
+ * Create a new signing key and (optionally) certficiate; do not read or write
+ * from disk. See ed_key_init_from_file() for more information.
+ */
+ed25519_keypair_t *
+ed_key_new(const ed25519_keypair_t *signing_key,
+ uint32_t flags,
+ time_t now,
+ time_t lifetime,
+ uint8_t cert_type,
+ struct tor_cert_st **cert_out)
+{
+ if (cert_out)
+ *cert_out = NULL;
+
+ const int extra_strong = !! (flags & INIT_ED_KEY_EXTRA_STRONG);
+ ed25519_keypair_t *keypair = tor_malloc_zero(sizeof(ed25519_keypair_t));
+ if (ed25519_keypair_generate(keypair, extra_strong) < 0)
+ goto err;
+
+ if (! (flags & INIT_ED_KEY_NEEDCERT))
+ return keypair;
+
+ tor_assert(signing_key);
+ tor_assert(cert_out);
+ uint32_t cert_flags = 0;
+ if (flags & INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT)
+ cert_flags |= CERT_FLAG_INCLUDE_SIGNING_KEY;
+ tor_cert_t *cert = tor_cert_create(signing_key, cert_type,
+ &keypair->pubkey,
+ now, lifetime,
+ cert_flags);
+ if (! cert)
+ goto err;
+
+ *cert_out = cert;
+ return keypair;
+
+ err:
+ tor_free(keypair);
+ return NULL;
+}
+
+static ed25519_keypair_t *master_identity_key = NULL;
+static ed25519_keypair_t *master_signing_key = NULL;
+static ed25519_keypair_t *current_link_key = NULL;
+static ed25519_keypair_t *current_auth_key = NULL;
+static tor_cert_t *signing_key_cert = NULL;
+static tor_cert_t *link_key_cert = NULL;
+static tor_cert_t *auth_key_cert = NULL;
+
+/**
+ * Running as a server: load, reload, or refresh our ed25519 keys and
+ * certificates, creating and saving new ones as needed.
+ */
+int
+load_ed_keys(const or_options_t *options, time_t now)
+{
+ ed25519_keypair_t *id = NULL;
+ ed25519_keypair_t *sign = NULL;
+ ed25519_keypair_t *link = NULL;
+ ed25519_keypair_t *auth = NULL;
+ const ed25519_keypair_t *use_signing = NULL;
+ tor_cert_t *sign_cert = NULL;
+ tor_cert_t *link_cert = NULL;
+ tor_cert_t *auth_cert = NULL;
+
+#define FAIL(msg) do { \
+ log_warn(LD_OR, (msg)); \
+ goto err; \
+ } while (0)
+#define SET_KEY(key, newval) do { \
+ ed25519_keypair_free(key); \
+ key = (newval); \
+ } while (0)
+#define SET_CERT(cert, newval) do { \
+ tor_cert_free(cert); \
+ cert = (newval); \
+ } while (0)
+#define EXPIRES_SOON(cert, interval) \
+ (!(cert) || (cert)->valid_until < now + (interval))
+
+ /* XXXX support encrypted identity keys fully */
+
+ /* XXXX use options. */
+ (void) options;
+
+ id = ed_key_init_from_file(
+ options_get_datadir_fname2(options, "keys", "ed25519_master_id"),
+ (INIT_ED_KEY_CREATE|INIT_ED_KEY_SPLIT|
+ INIT_ED_KEY_MISSING_SECRET_OK|
+ INIT_ED_KEY_EXTRA_STRONG),
+ LOG_WARN, NULL, 0, 0, 0, NULL);
+ if (!id)
+ FAIL("Missing identity key");
+
+ if (!master_signing_key || EXPIRES_SOON(signing_key_cert, 86400/*???*/)) {
+ uint32_t flags = (INIT_ED_KEY_CREATE|
+ INIT_ED_KEY_EXTRA_STRONG|
+ INIT_ED_KEY_NEEDCERT|
+ INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT);
+ const ed25519_keypair_t *sign_with_id = id;
+ if (master_signing_key) {
+ flags |= INIT_ED_KEY_REPLACE; /* it's expired, so force-replace it. */
+ }
+ if (tor_mem_is_zero((char*)id->seckey.seckey, sizeof(id->seckey))) {
+ sign_with_id = NULL;
+ flags &= ~INIT_ED_KEY_CREATE;
+ }
+ sign = ed_key_init_from_file(
+ options_get_datadir_fname2(options, "keys", "ed25519_signing"),
+ flags, LOG_WARN,
+ sign_with_id, now, 30*86400/*XXX option*/,
+ CERT_TYPE_ID_SIGNING, &sign_cert);
+ if (!sign)
+ FAIL("Missing signing key");
+ use_signing = sign;
+ } else {
+ use_signing = master_signing_key;
+ }
+
+ /* At this point we no longer need our secret identity key. So wipe
+ * it, if we loaded it in the first place. */
+ memwipe(id->seckey.seckey, 0, sizeof(id->seckey));
+
+ if (!current_link_key || EXPIRES_SOON(link_key_cert, 7200/*???*/)) {
+ link = ed_key_new(use_signing, INIT_ED_KEY_NEEDCERT,
+ now, 2*86400/*XXX option??*/,
+ CERT_TYPE_SIGNING_LINK, &link_cert);
+
+ if (!link)
+ FAIL("Can't create link key");
+ }
+
+ if (!current_auth_key || EXPIRES_SOON(auth_key_cert, 7200)/*???*/) {
+ auth = ed_key_new(use_signing, INIT_ED_KEY_NEEDCERT,
+ now, 2*86400/*XXX option??*/,
+ CERT_TYPE_SIGNING_AUTH, &auth_cert);
+
+ if (!auth)
+ FAIL("Can't create auth key");
+ }
+
+ /* We've generated or loaded everything. Put them in memory. */
+
+ if (! master_identity_key) {
+ SET_KEY(master_identity_key, id);
+ } else {
+ tor_free(id);
+ }
+ if (sign) {
+ SET_KEY(master_signing_key, sign);
+ SET_CERT(signing_key_cert, sign_cert);
+ }
+ if (link) {
+ SET_KEY(current_link_key, link);
+ SET_CERT(link_key_cert, link_cert);
+ }
+ if (auth) {
+ SET_KEY(current_auth_key, auth);
+ SET_CERT(auth_key_cert, auth_cert);
+ }
+
+ return 0;
+ err:
+ ed25519_keypair_free(id);
+ ed25519_keypair_free(sign);
+ ed25519_keypair_free(link);
+ ed25519_keypair_free(auth);
+ tor_cert_free(sign_cert);
+ tor_cert_free(link_cert);
+ tor_cert_free(auth_cert);
+ return -1;
+#undef FAIL
+#undef SET_KEY
+#undef SET_CERT
+#undef EXPIRES_SOON
+}
+
+const ed25519_public_key_t *
+get_master_identity_key(void)
+{
+ if (!master_identity_key)
+ return NULL;
+ return &master_identity_key->pubkey;
+}
+
+const ed25519_keypair_t *
+get_master_signing_keypair(void)
+{
+ return master_signing_key;
+}
+
+const struct tor_cert_st *
+get_master_signing_key_cert(void)
+{
+ return signing_key_cert;
+}
+
+const ed25519_keypair_t *
+get_current_link_keypair(void)
+{
+ return current_link_key;
+}
+
+const ed25519_keypair_t *
+get_current_auth_keypair(void)
+{
+ return current_auth_key;
+}
+
+const tor_cert_t *
+get_current_link_key_cert(void)
+{
+ return link_key_cert;
+}
+
+const tor_cert_t *
+get_current_auth_key_cert(void)
+{
+ return auth_key_cert;
+}
+
+void
+routerkeys_free_all(void)
+{
+ ed25519_keypair_free(master_identity_key);
+ ed25519_keypair_free(master_signing_key);
+ ed25519_keypair_free(current_link_key);
+ ed25519_keypair_free(current_auth_key);
+ tor_cert_free(signing_key_cert);
+ tor_cert_free(link_key_cert);
+ tor_cert_free(auth_key_cert);
+
+ master_identity_key = master_signing_key = NULL;
+ current_link_key = current_auth_key = NULL;
+ signing_key_cert = link_key_cert = auth_key_cert = NULL;
+}
+
diff --git a/src/or/routerkeys.h b/src/or/routerkeys.h
new file mode 100644
index 0000000..eb21401
--- /dev/null
+++ b/src/or/routerkeys.h
@@ -0,0 +1,44 @@
+/* Copyright (c) 2014, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#ifndef TOR_ROUTERKEYS_H
+#define TOR_ROUTERKEYS_H
+
+#include "crypto_ed25519.h"
+
+#define INIT_ED_KEY_CREATE (1u<<0)
+#define INIT_ED_KEY_REPLACE (1u<<1)
+#define INIT_ED_KEY_SPLIT (1u<<2)
+#define INIT_ED_KEY_MISSING_SECRET_OK (1u<<3)
+#define INIT_ED_KEY_NEEDCERT (1u<<4)
+#define INIT_ED_KEY_EXTRA_STRONG (1u<<5)
+#define INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT (1u<<6)
+
+struct tor_cert_st;
+ed25519_keypair_t *ed_key_init_from_file(const char *fname, uint32_t flags,
+ int severity,
+ const ed25519_keypair_t *signing_key,
+ time_t now,
+ time_t lifetime,
+ uint8_t cert_type,
+ struct tor_cert_st **cert_out);
+ed25519_keypair_t *ed_key_new(const ed25519_keypair_t *signing_key,
+ uint32_t flags,
+ time_t now,
+ time_t lifetime,
+ uint8_t cert_type,
+ struct tor_cert_st **cert_out);
+const ed25519_public_key_t *get_master_identity_key(void);
+const ed25519_keypair_t *get_master_signing_keypair(void);
+const struct tor_cert_st *get_master_signing_key_cert(void);
+
+const ed25519_keypair_t *get_current_link_keypair(void);
+const ed25519_keypair_t *get_current_auth_keypair(void);
+const struct tor_cert_st *get_current_link_key_cert(void);
+const struct tor_cert_st *get_current_auth_key_cert(void);
+
+int load_ed_keys(const or_options_t *options, time_t now);
+void routerkeys_free_all(void);
+
+#endif
+
diff --git a/src/or/torcert.c b/src/or/torcert.c
new file mode 100644
index 0000000..478ec4d
--- /dev/null
+++ b/src/or/torcert.c
@@ -0,0 +1,208 @@
+/* Copyright (c) 2014, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "torcert.h"
+#include "crypto.h"
+#include "ed25519_cert.h"
+#include "torlog.h"
+#include "util.h"
+#include "compat.h"
+
+/** Helper for tor_cert_create(): signs any 32 bytes, not just an ed25519
+ * key.
+ */
+static tor_cert_t *
+tor_cert_sign_impl(const ed25519_keypair_t *signing_key,
+ uint8_t cert_type,
+ uint8_t signed_key_type,
+ const uint8_t signed_key_info[32],
+ time_t now, time_t lifetime,
+ uint32_t flags)
+{
+ tor_cert_t *torcert = NULL;
+
+ ed25519_cert_t *cert = ed25519_cert_new();
+ cert->cert_type = cert_type;
+ cert->exp_field = (uint32_t) CEIL_DIV(now + lifetime, 3600);
+ cert->cert_key_type = signed_key_type;
+ memcpy(cert->certified_key, signed_key_info, 32);
+
+ if (flags & CERT_FLAG_INCLUDE_SIGNING_KEY) {
+ ed25519_cert_extension_t *ext = ed25519_cert_extension_new();
+ ext->ext_type = CERTEXT_SIGNED_WITH_KEY;
+ memcpy(ext->un_signing_key, signing_key->pubkey.pubkey, 32);
+ ed25519_cert_add_ext(cert, ext);
+ ++cert->n_extensions;
+ }
+
+ const ssize_t alloc_len = ed25519_cert_encoded_len(cert);
+ tor_assert(alloc_len > 0);
+ uint8_t *encoded = tor_malloc(alloc_len);
+ const ssize_t real_len = ed25519_cert_encode(encoded, alloc_len, cert);
+ if (real_len < 0)
+ goto err;
+ tor_assert(real_len == alloc_len);
+ tor_assert(real_len > ED25519_SIG_LEN);
+ uint8_t *sig = encoded + (real_len - ED25519_SIG_LEN);
+ tor_assert(tor_mem_is_zero((char*)sig, ED25519_SIG_LEN));
+
+ ed25519_signature_t signature;
+ if (ed25519_sign(&signature, encoded,
+ real_len-ED25519_SIG_LEN, signing_key)<0) {
+ log_warn(LD_BUG, "Can't sign certificate");
+ goto err;
+ }
+ memcpy(sig, signature.sig, ED25519_SIG_LEN);
+
+ torcert = tor_cert_parse(encoded, real_len);
+ if (! torcert) {
+ log_warn(LD_BUG, "Generated a certificate we cannot parse");
+ goto err;
+ }
+
+ if (tor_cert_checksig(torcert, &signing_key->pubkey, now) < 0) {
+ log_warn(LD_BUG, "Generated a certificate whose signature we can't check");
+ goto err;
+ }
+
+ tor_free(encoded);
+
+ return torcert;
+
+ err:
+ tor_cert_free(torcert);
+ ed25519_cert_free(cert);
+ tor_free(encoded);
+ return NULL;
+}
+
+/**
+ * Create and return a new new certificate of type <b>cert_type</b> to
+ * authenticate <b>signed_key</b> using the key <b>signing_key</b>. The
+ * certificate should remain valid for at least <b>lifetime</b> seconds after
+ * <b>now</b>.
+ *
+ * If CERT_FLAG_INCLUDE_SIGNING_KEY is set in <b>flags</b>, embed
+ * the public part of <b>signing_key</b> in the certificate.
+ */
+tor_cert_t *
+tor_cert_create(const ed25519_keypair_t *signing_key,
+ uint8_t cert_type,
+ const ed25519_public_key_t *signed_key,
+ time_t now, time_t lifetime,
+ uint32_t flags)
+{
+ return tor_cert_sign_impl(signing_key, cert_type,
+ SIGNED_KEY_TYPE_ED25519, signed_key->pubkey,
+ now, lifetime, flags);
+}
+
+/** Release all storage held for <b>cert</>. */
+void
+tor_cert_free(tor_cert_t *cert)
+{
+ if (! cert)
+ return;
+
+ if (cert->encoded)
+ memwipe(cert->encoded, 0, cert->encoded_len);
+ tor_free(cert->encoded);
+
+ memwipe(cert, 0, sizeof(tor_cert_t));
+ tor_free(cert);
+}
+
+/** Parse a certificate encoded with <b>len</b> bytes in <b>encoded</b>. */
+tor_cert_t *
+tor_cert_parse(const uint8_t *encoded, const size_t len)
+{
+ tor_cert_t *cert = NULL;
+ ed25519_cert_t *parsed = NULL;
+ ssize_t got_len = ed25519_cert_parse(&parsed, encoded, len);
+ if (got_len < 0 || (size_t) got_len != len)
+ goto err;
+
+ cert = tor_malloc_zero(sizeof(tor_cert_t));
+ cert->encoded = tor_memdup(encoded, len);
+ cert->encoded_len = len;
+
+ memcpy(cert->signed_key.pubkey, parsed->certified_key, 32);
+ cert->valid_until = parsed->exp_field * 3600;
+ cert->cert_type = parsed->cert_type;
+
+ for (unsigned i = 0; i < ed25519_cert_getlen_ext(parsed); ++i) {
+ ed25519_cert_extension_t *ext = ed25519_cert_get_ext(parsed, i);
+ if (ext->ext_type == CERTEXT_SIGNED_WITH_KEY) {
+ if (cert->signing_key_included)
+ goto err;
+
+ cert->signing_key_included = 1;
+ memcpy(cert->signing_key.pubkey, ext->un_signing_key, 32);
+ } else if (ext->ext_flags & CERTEXT_FLAG_AFFECTS_VALIDATION) {
+ /* Unrecognized extension with affects_validation set */
+ goto err;
+ }
+ }
+
+ return cert;
+ err:
+ ed25519_cert_free(parsed);
+ tor_cert_free(cert);
+ return NULL;
+}
+
+/** Fill in <b>checkable_out</b> with the information needed to check
+ * the signature on <b>cert</b> with <b>pubkey</b>. */
+int
+tor_cert_get_checkable_sig(ed25519_checkable_t *checkable_out,
+ const tor_cert_t *cert,
+ const ed25519_public_key_t *pubkey)
+{
+ if (! pubkey) {
+ if (cert->signing_key_included)
+ pubkey = &cert->signing_key;
+ else
+ return -1;
+ }
+
+ checkable_out->msg = cert->encoded;
+ checkable_out->pubkey = pubkey;
+ tor_assert(cert->encoded_len > ED25519_SIG_LEN);
+ const size_t signed_len = cert->encoded_len - ED25519_SIG_LEN;
+ checkable_out->len = signed_len;
+ memcpy(checkable_out->signature.sig,
+ cert->encoded + signed_len, ED25519_SIG_LEN);
+
+ return 0;
+}
+
+/** Validates the signature on <b>cert</b> with <b>pubkey</b> relative to
+ * the current time <b>now</b>. Return 0 on success, -1 on failure.
+ * Sets flags in <b>cert</b> as appropriate.
+ */
+int
+tor_cert_checksig(tor_cert_t *cert,
+ const ed25519_public_key_t *pubkey, time_t now)
+{
+ ed25519_checkable_t checkable;
+ int okay;
+
+ if (now > cert->valid_until) {
+ cert->cert_expired = 1;
+ return -1;
+ }
+
+ if (tor_cert_get_checkable_sig(&checkable, cert, pubkey) < 0)
+ return -1;
+
+ if (ed25519_checksig_batch(&okay, &checkable, 1) < 0) {
+ cert->sig_bad = 1;
+ return -1;
+ } else {
+ cert->sig_ok = 1;
+ memcpy(cert->signing_key.pubkey, checkable.pubkey->pubkey, 32);
+ cert->cert_valid = 1;
+ return 0;
+ }
+}
+
diff --git a/src/or/torcert.h b/src/or/torcert.h
new file mode 100644
index 0000000..7e9c3f5
--- /dev/null
+++ b/src/or/torcert.h
@@ -0,0 +1,66 @@
+/* Copyright (c) 2014, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#ifndef TORCERT_H_INCLUDED
+#define TORCERT_H_INCLUDED
+
+#include "crypto_ed25519.h"
+
+#define SIGNED_KEY_TYPE_ED25519 0x01
+
+#define CERT_TYPE_ID_SIGNING 0x04
+#define CERT_TYPE_SIGNING_LINK 0x05
+#define CERT_TYPE_SIGNING_AUTH 0x06
+
+#define CERT_FLAG_INCLUDE_SIGNING_KEY 0x1
+
+/** An ed25519-signed certificate as used throughout the Tor protocol.
+ **/
+typedef struct tor_cert_st {
+ /** The key authenticated by this certificate */
+ ed25519_public_key_t signed_key;
+ /** The key that signed this certificate. This value may be unset if the
+ * certificate has never been checked, and didn't include its own key. */
+ ed25519_public_key_t signing_key;
+ /** A time after which this certificate will no longer be valid. */
+ time_t valid_until;
+
+ /** The encoded representation of this certificate */
+ uint8_t *encoded;
+ /** The length of <b>encoded</b> */
+ size_t encoded_len;
+
+ /** One of CERT_TYPE_... */
+ uint8_t cert_type;
+ /** True iff we received a signing key embedded in this certificate */
+ unsigned signing_key_included : 1;
+ /** True iff we checked the signature and found it bad */
+ unsigned sig_bad : 1;
+ /** True iff we checked the signature and found it correct */
+ unsigned sig_ok : 1;
+ /** True iff we checked the signature and first found that the cert
+ * had expired */
+ unsigned cert_expired : 1;
+ /** True iff we checked the signature and found the whole cert valid */
+ unsigned cert_valid : 1;
+} tor_cert_t;
+
+tor_cert_t *tor_cert_create(const ed25519_keypair_t *signing_key,
+ uint8_t cert_type,
+ const ed25519_public_key_t *signed_key,
+ time_t now, time_t lifetime,
+ uint32_t flags);
+
+tor_cert_t *tor_cert_parse(const uint8_t *cert, size_t certlen);
+
+void tor_cert_free(tor_cert_t *cert);
+
+int tor_cert_get_checkable_sig(ed25519_checkable_t *checkable_out,
+ const tor_cert_t *out,
+ const ed25519_public_key_t *pubkey);
+
+int tor_cert_checksig(tor_cert_t *cert,
+ const ed25519_public_key_t *pubkey, time_t now);
+
+#endif
+
diff --git a/src/test/include.am b/src/test/include.am
index d20d2f6..44f63a7 100644
--- a/src/test/include.am
+++ b/src/test/include.am
@@ -104,7 +104,7 @@ src_test_bench_LDFLAGS = @TOR_LDFLAGS_zlib@ @TOR_LDFLAGS_openssl@ \
@TOR_LDFLAGS_libevent@
src_test_bench_LDADD = src/or/libtor.a src/common/libor.a \
src/common/libor-crypto.a $(LIBDONNA) \
- src/common/libor-event.a \
+ src/common/libor-event.a src/trunnel/libor-trunnel.a \
@TOR_ZLIB_LIBS@ @TOR_LIB_MATH@ @TOR_LIBEVENT_LIBS@ \
@TOR_OPENSSL_LIBS@ @TOR_LIB_WS32@ @TOR_LIB_GDI@ @CURVE25519_LIBS@ \
@TOR_SYSTEMD_LIBS@
diff --git a/src/test/test_routerkeys.c b/src/test/test_routerkeys.c
index 60b6bb5..63284b7 100644
--- a/src/test/test_routerkeys.c
+++ b/src/test/test_routerkeys.c
@@ -8,11 +8,17 @@
#include "or.h"
#include "config.h"
#include "router.h"
+#include "routerkeys.h"
#include "util.h"
#include "crypto.h"
-
+#include "torcert.h"
#include "test.h"
+#ifdef _WIN32
+/* For mkdir() */
+#include <direct.h>
+#endif
+
static void
test_routerkeys_write_fingerprint(void *arg)
{
@@ -75,11 +81,447 @@ test_routerkeys_write_fingerprint(void *arg)
tor_free(cp2);
}
+static void
+test_routerkeys_ed_certs(void *args)
+{
+ (void)args;
+ ed25519_keypair_t kp1, kp2;
+ tor_cert_t *cert[2] = {NULL, NULL};
+ tor_cert_t *parsed_cert[2] = {NULL, NULL};
+ time_t now = 1412094534;
+ uint8_t *junk = NULL;
+
+ tt_int_op(0,==,ed25519_keypair_generate(&kp1, 0));
+ tt_int_op(0,==,ed25519_keypair_generate(&kp2, 0));
+
+ for (int i = 0; i <= 1; ++i) {
+ uint32_t flags = i ? CERT_FLAG_INCLUDE_SIGNING_KEY : 0;
+
+ cert[i] = tor_cert_create(&kp1, 5, &kp2.pubkey, now, 10000, flags);
+ tt_assert(cert[i]);
+
+ tt_assert(cert[i]->sig_bad == 0);
+ tt_assert(cert[i]->sig_ok == 1);
+ tt_assert(cert[i]->cert_expired == 0);
+ tt_assert(cert[i]->cert_valid == 1);
+ tt_int_op(cert[i]->cert_type, ==, 5);
+ tt_mem_op(cert[i]->signed_key.pubkey, ==, &kp2.pubkey.pubkey, 32);
+ tt_mem_op(cert[i]->signing_key.pubkey, ==, &kp1.pubkey.pubkey, 32);
+ tt_int_op(cert[i]->signing_key_included, ==, i);
+
+ tt_assert(cert[i]->encoded);
+ tt_int_op(cert[i]->encoded_len, ==, 104 + 36 * i);
+ tt_int_op(cert[i]->encoded[0], ==, 1);
+ tt_int_op(cert[i]->encoded[1], ==, 5);
+
+ parsed_cert[i] = tor_cert_parse(cert[i]->encoded, cert[i]->encoded_len);
+ tt_assert(parsed_cert[i]);
+ tt_int_op(cert[i]->encoded_len, ==, parsed_cert[i]->encoded_len);
+ tt_mem_op(cert[i]->encoded, ==, parsed_cert[i]->encoded,
+ cert[i]->encoded_len);
+ tt_assert(parsed_cert[i]->sig_bad == 0);
+ tt_assert(parsed_cert[i]->sig_ok == 0);
+ tt_assert(parsed_cert[i]->cert_expired == 0);
+ tt_assert(parsed_cert[i]->cert_valid == 0);
+
+ /* Expired */
+ tt_int_op(tor_cert_checksig(parsed_cert[i], &kp1.pubkey, now + 30000),
+ <, 0);
+ tt_assert(parsed_cert[i]->cert_expired == 1);
+ parsed_cert[i]->cert_expired = 0;
+
+ /* Wrong key */
+ tt_int_op(tor_cert_checksig(parsed_cert[i], &kp2.pubkey, now), <, 0);
+ tt_assert(parsed_cert[i]->sig_bad== 1);
+ parsed_cert[i]->sig_bad = 0;
+
+ /* Missing key */
+ int ok = tor_cert_checksig(parsed_cert[i], NULL, now);
+ tt_int_op(ok < 0, ==, i == 0);
+ tt_assert(parsed_cert[i]->sig_bad == 0);
+ tt_assert(parsed_cert[i]->sig_ok == (i != 0));
+ tt_assert(parsed_cert[i]->cert_valid == (i != 0));
+ parsed_cert[i]->sig_bad = 0;
+ parsed_cert[i]->sig_ok = 0;
+ parsed_cert[i]->cert_valid = 0;
+
+ /* Right key */
+ tt_int_op(tor_cert_checksig(parsed_cert[i], &kp1.pubkey, now), ==, 0);
+ tt_assert(parsed_cert[i]->sig_bad == 0);
+ tt_assert(parsed_cert[i]->sig_ok == 1);
+ tt_assert(parsed_cert[i]->cert_expired == 0);
+ tt_assert(parsed_cert[i]->cert_valid == 1);
+ }
+
+ /* Now try some junky certs. */
+ /* - Truncated */
+ tt_ptr_op(NULL, ==,tor_cert_parse(cert[0]->encoded, cert[0]->encoded_len-1));
+
+ /* - First byte modified */
+ cert[0]->encoded[0] = 99;
+ tt_ptr_op(NULL, ==,tor_cert_parse(cert[0]->encoded, cert[0]->encoded_len));
+ cert[0]->encoded[0] = 1;
+
+ /* - Extra byte at the end*/
+ junk = tor_malloc_zero(cert[0]->encoded_len + 1);
+ memcpy(junk, cert[0]->encoded, cert[0]->encoded_len);
+ tt_ptr_op(NULL, ==, tor_cert_parse(junk, cert[0]->encoded_len+1));
+
+ /* - Multiple signing key instances */
+ tor_free(junk);
+ junk = tor_malloc_zero(104 + 36 * 2);
+ junk[0] = 1; /* version */
+ junk[1] = 5; /* cert type */
+ junk[6] = 1; /* key type */
+ junk[39] = 2; /* n_extensions */
+ junk[41] = 32; /* extlen */
+ junk[42] = 4; /* exttype */
+ junk[77] = 32; /* extlen */
+ junk[78] = 4; /* exttype */
+ tt_ptr_op(NULL, ==, tor_cert_parse(junk, 104 + 36 * 2));
+
+ done:
+ tor_cert_free(cert[0]);
+ tor_cert_free(cert[1]);
+ tor_cert_free(parsed_cert[0]);
+ tor_cert_free(parsed_cert[1]);
+ tor_free(junk);
+}
+
+static void
+test_routerkeys_ed_key_create(void *arg)
+{
+ (void)arg;
+ tor_cert_t *cert = NULL;
+ ed25519_keypair_t *kp1 = NULL, *kp2 = NULL;
+ time_t now = time(NULL);
+
+ /* This is a simple alias for 'make a new keypair' */
+ kp1 = ed_key_new(NULL, 0, 0, 0, 0, &cert);
+ tt_assert(kp1);
+
+ /* Create a new certificate signed by kp1. */
+ kp2 = ed_key_new(kp1, INIT_ED_KEY_NEEDCERT, now, 3600, 4, &cert);
+ tt_assert(kp2);
+ tt_assert(cert);
+ tt_mem_op(&cert->signed_key, ==, &kp2->pubkey, sizeof(ed25519_public_key_t));
+ tt_assert(! cert->signing_key_included);
+
+ tt_int_op(cert->valid_until, >=, now);
+ tt_int_op(cert->valid_until, <=, now+7200);
+
+ /* Create a new key-including certificate signed by kp1 */
+ ed25519_keypair_free(kp2);
+ tor_cert_free(cert);
+ cert = NULL; kp2 = NULL;
+ kp2 = ed_key_new(kp1, (INIT_ED_KEY_NEEDCERT|
+ INIT_ED_KEY_INCLUDE_SIGNING_KEY_IN_CERT),
+ now, 3600, 4, &cert);
+ tt_assert(kp2);
+ tt_assert(cert);
+ tt_assert(cert->signing_key_included);
+ tt_mem_op(&cert->signed_key, ==, &kp2->pubkey, sizeof(ed25519_public_key_t));
+ tt_mem_op(&cert->signing_key, ==, &kp1->pubkey,sizeof(ed25519_public_key_t));
+
+ done:
+ ed25519_keypair_free(kp1);
+ ed25519_keypair_free(kp2);
+ tor_cert_free(cert);
+}
+
+static void
+test_routerkeys_ed_key_init_basic(void *arg)
+{
+ (void) arg;
+
+ tor_cert_t *cert = NULL, *cert2 = NULL;
+ ed25519_keypair_t *kp1 = NULL, *kp2 = NULL, *kp3 = NULL;
+ time_t now = time(NULL);
+ char *fname1 = tor_strdup(get_fname("test_ed_key_1"));
+ char *fname2 = tor_strdup(get_fname("test_ed_key_2"));
+ struct stat st;
+
+ unlink(fname1);
+ unlink(fname2);
+
+ /* Fail to load a key that isn't there. */
+ kp1 = ed_key_init_from_file(fname1, 0, LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp1 == NULL);
+ tt_assert(cert == NULL);
+
+ /* Create the key if requested to do so. */
+ kp1 = ed_key_init_from_file(fname1, INIT_ED_KEY_CREATE, LOG_INFO,
+ NULL, now, 0, 7, &cert);
+ tt_assert(kp1 != NULL);
+ tt_assert(cert == NULL);
+ tt_int_op(stat(get_fname("test_ed_key_1_cert"), &st), <, 0);
+ tt_int_op(stat(get_fname("test_ed_key_1_secret_key"), &st), ==, 0);
+
+ /* Fail to load if we say we need a cert */
+ kp2 = ed_key_init_from_file(fname1, INIT_ED_KEY_NEEDCERT, LOG_INFO,
+ NULL, now, 0, 7, &cert);
+ tt_assert(kp2 == NULL);
+
+ /* Fail to load if we say the wrong key type */
+ kp2 = ed_key_init_from_file(fname1, 0, LOG_INFO,
+ NULL, now, 0, 6, &cert);
+ tt_assert(kp2 == NULL);
+
+ /* Load successfully if we're not picky, whether we say "create" or not. */
+ kp2 = ed_key_init_from_file(fname1, INIT_ED_KEY_CREATE, LOG_INFO,
+ NULL, now, 0, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert == NULL);
+ tt_mem_op(kp1, ==, kp2, sizeof(*kp1));
+ ed25519_keypair_free(kp2); kp2 = NULL;
+
+ kp2 = ed_key_init_from_file(fname1, 0, LOG_INFO,
+ NULL, now, 0, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert == NULL);
+ tt_mem_op(kp1, ==, kp2, sizeof(*kp1));
+ ed25519_keypair_free(kp2); kp2 = NULL;
+
+ /* Now create a key with a cert. */
+ kp2 = ed_key_init_from_file(fname2, (INIT_ED_KEY_CREATE|
+ INIT_ED_KEY_NEEDCERT),
+ LOG_INFO, kp1, now, 7200, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert != NULL);
+ tt_mem_op(kp1, !=, kp2, sizeof(*kp1));
+ tt_int_op(stat(get_fname("test_ed_key_2_cert"), &st), ==, 0);
+ tt_int_op(stat(get_fname("test_ed_key_2_secret_key"), &st), ==, 0);
+
+ tt_assert(cert->cert_valid == 1);
+ tt_mem_op(&cert->signed_key, ==, &kp2->pubkey, 32);
+
+ /* Now verify we can load the cert... */
+ kp3 = ed_key_init_from_file(fname2, (INIT_ED_KEY_CREATE|
+ INIT_ED_KEY_NEEDCERT),
+ LOG_INFO, kp1, now, 7200, 7, &cert2);
+ tt_mem_op(kp2, ==, kp3, sizeof(*kp2));
+ tt_mem_op(cert2->encoded, ==, cert->encoded, cert->encoded_len);
+ ed25519_keypair_free(kp3); kp3 = NULL;
+ tor_cert_free(cert2); cert2 = NULL;
+
+ /* ... even without create... */
+ kp3 = ed_key_init_from_file(fname2, INIT_ED_KEY_NEEDCERT,
+ LOG_INFO, kp1, now, 7200, 7, &cert2);
+ tt_mem_op(kp2, ==, kp3, sizeof(*kp2));
+ tt_mem_op(cert2->encoded, ==, cert->encoded, cert->encoded_len);
+ ed25519_keypair_free(kp3); kp3 = NULL;
+ tor_cert_free(cert2); cert2 = NULL;
+
+ /* ... but that we don't crash or anything if we say we don't want it. */
+ kp3 = ed_key_init_from_file(fname2, INIT_ED_KEY_NEEDCERT,
+ LOG_INFO, kp1, now, 7200, 7, NULL);
+ tt_mem_op(kp2, ==, kp3, sizeof(*kp2));
+ ed25519_keypair_free(kp3); kp3 = NULL;
+
+ /* Fail if we're told the wrong signing key */
+ kp3 = ed_key_init_from_file(fname2, INIT_ED_KEY_NEEDCERT,
+ LOG_INFO, kp2, now, 7200, 7, &cert2);
+ tt_assert(kp3 == NULL);
+ tt_assert(cert2 == NULL);
+
+ done:
+ ed25519_keypair_free(kp1);
+ ed25519_keypair_free(kp2);
+ ed25519_keypair_free(kp3);
+ tor_cert_free(cert);
+ tor_cert_free(cert2);
+ tor_free(fname1);
+ tor_free(fname2);
+}
+
+static void
+test_routerkeys_ed_key_init_split(void *arg)
+{
+ (void) arg;
+
+ tor_cert_t *cert = NULL;
+ ed25519_keypair_t *kp1 = NULL, *kp2 = NULL;
+ time_t now = time(NULL);
+ char *fname1 = tor_strdup(get_fname("test_ed_key_3"));
+ char *fname2 = tor_strdup(get_fname("test_ed_key_4"));
+ struct stat st;
+ const uint32_t flags = INIT_ED_KEY_SPLIT|INIT_ED_KEY_MISSING_SECRET_OK;
+
+ unlink(fname1);
+ unlink(fname2);
+
+ /* Can't load key that isn't there. */
+ kp1 = ed_key_init_from_file(fname1, flags, LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp1 == NULL);
+ tt_assert(cert == NULL);
+
+ /* Create a split key */
+ kp1 = ed_key_init_from_file(fname1, flags|INIT_ED_KEY_CREATE,
+ LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp1 != NULL);
+ tt_assert(cert == NULL);
+ tt_int_op(stat(get_fname("test_ed_key_3_cert"), &st), <, 0);
+ tt_int_op(stat(get_fname("test_ed_key_3_secret_key"), &st), ==, 0);
+ tt_int_op(stat(get_fname("test_ed_key_3_public_key"), &st), ==, 0);
+
+ /* Load it. */
+ kp2 = ed_key_init_from_file(fname1, flags|INIT_ED_KEY_CREATE,
+ LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert == NULL);
+ tt_mem_op(kp1, ==, kp2, sizeof(*kp2));
+ ed25519_keypair_free(kp2); kp2 = NULL;
+
+ /* Okay, try killing the secret key and loading it. */
+ unlink(get_fname("test_ed_key_3_secret_key"));
+ kp2 = ed_key_init_from_file(fname1, flags,
+ LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert == NULL);
+ tt_mem_op(&kp1->pubkey, ==, &kp2->pubkey, sizeof(kp2->pubkey));
+ tt_assert(tor_mem_is_zero((char*)kp2->seckey.seckey,
+ sizeof(kp2->seckey.seckey)));
+ ed25519_keypair_free(kp2); kp2 = NULL;
+
+ /* Even when we're told to "create", don't create if there's a public key */
+ kp2 = ed_key_init_from_file(fname1, flags|INIT_ED_KEY_CREATE,
+ LOG_INFO, NULL, now, 0, 7, &cert);
+ tt_assert(kp2 != NULL);
+ tt_assert(cert == NULL);
+ tt_mem_op(&kp1->pubkey, ==, &kp2->pubkey, sizeof(kp2->pubkey));
+ tt_assert(tor_mem_is_zero((char*)kp2->seckey.seckey,
+ sizeof(kp2->seckey.seckey)));
+ ed25519_keypair_free(kp2); kp2 = NULL;
+
+ /* Make sure we fail on a tag mismatch, though */
+ kp2 = ed_key_init_from_file(fname1, flags,
+ LOG_INFO, NULL, now, 0, 99, &cert);
+ tt_assert(kp2 == NULL);
+
+ done:
+ ed25519_keypair_free(kp1);
+ ed25519_keypair_free(kp2);
+ tor_cert_free(cert);
+ tor_free(fname1);
+ tor_free(fname2);
+}
+
+static void
+test_routerkeys_ed_keys_init_all(void *arg)
+{
+ (void)arg;
+ char *dir = tor_strdup(get_fname("test_ed_keys_init_all"));
+ or_options_t *options = tor_malloc_zero(sizeof(or_options_t));
+ time_t now = time(NULL);
+ ed25519_public_key_t id;
+ ed25519_keypair_t sign, link, auth;
+ // tor_cert_t *cert_is, *cert_sl, *cert_auth;
+
+#ifdef _WIN32
+ mkdir(dir);
+ mkdir(get_fname("test_ed_keys_init_all/keys"));
+#else
+ mkdir(dir, 0700);
+ mkdir(get_fname("test_ed_keys_init_all/keys"), 0700);
+#endif
+
+ options->DataDirectory = dir;
+
+ tt_int_op(0, ==, load_ed_keys(options, now));
+ tt_assert(get_master_identity_key());
+ tt_assert(get_master_identity_key());
+ tt_assert(get_master_signing_keypair());
+ tt_assert(get_current_link_keypair());
+ tt_assert(get_current_auth_keypair());
+ tt_assert(get_master_signing_key_cert());
+ tt_assert(get_current_link_key_cert());
+ tt_assert(get_current_auth_key_cert());
+ memcpy(&id, get_master_identity_key(), sizeof(id));
+ memcpy(&sign, get_master_signing_keypair(), sizeof(sign));
+ memcpy(&link, get_current_link_keypair(), sizeof(link));
+ memcpy(&auth, get_current_auth_keypair(), sizeof(auth));
+
+ /* Call load_ed_keys again, but nothing has changed. */
+ tt_int_op(0, ==, load_ed_keys(options, now));
+ tt_mem_op(&id, ==, get_master_identity_key(), sizeof(id));
+ tt_mem_op(&sign, ==, get_master_signing_keypair(), sizeof(sign));
+ tt_mem_op(&link, ==, get_current_link_keypair(), sizeof(link));
+ tt_mem_op(&auth, ==, get_current_auth_keypair(), sizeof(auth));
+
+ /* Force a reload: we make new link/auth keys. */
+ routerkeys_free_all();
+ tt_int_op(0, ==, load_ed_keys(options, now));
+ tt_mem_op(&id, ==, get_master_identity_key(), sizeof(id));
+ tt_mem_op(&sign, ==, get_master_signing_keypair(), sizeof(sign));
+ tt_mem_op(&link, !=, get_current_link_keypair(), sizeof(link));
+ tt_mem_op(&auth, !=, get_current_auth_keypair(), sizeof(auth));
+ tt_assert(get_master_signing_key_cert());
+ tt_assert(get_current_link_key_cert());
+ tt_assert(get_current_auth_key_cert());
+ memcpy(&link, get_current_link_keypair(), sizeof(link));
+ memcpy(&auth, get_current_auth_keypair(), sizeof(auth));
+
+ /* Force a link/auth-key regeneration by advancing time. */
+ tt_int_op(0, ==, load_ed_keys(options, now+3*86400));
+ tt_mem_op(&id, ==, get_master_identity_key(), sizeof(id));
+ tt_mem_op(&sign, ==, get_master_signing_keypair(), sizeof(sign));
+ tt_mem_op(&link, !=, get_current_link_keypair(), sizeof(link));
+ tt_mem_op(&auth, !=, get_current_auth_keypair(), sizeof(auth));
+ tt_assert(get_master_signing_key_cert());
+ tt_assert(get_current_link_key_cert());
+ tt_assert(get_current_auth_key_cert());
+ memcpy(&link, get_current_link_keypair(), sizeof(link));
+ memcpy(&auth, get_current_auth_keypair(), sizeof(auth));
+
+ /* Force a signing-key regeneration by advancing time. */
+ tt_int_op(0, ==, load_ed_keys(options, now+100*86400));
+ tt_mem_op(&id, ==, get_master_identity_key(), sizeof(id));
+ tt_mem_op(&sign, !=, get_master_signing_keypair(), sizeof(sign));
+ tt_mem_op(&link, !=, get_current_link_keypair(), sizeof(link));
+ tt_mem_op(&auth, !=, get_current_auth_keypair(), sizeof(auth));
+ tt_assert(get_master_signing_key_cert());
+ tt_assert(get_current_link_key_cert());
+ tt_assert(get_current_auth_key_cert());
+ memcpy(&sign, get_master_signing_keypair(), sizeof(sign));
+ memcpy(&link, get_current_link_keypair(), sizeof(link));
+ memcpy(&auth, get_current_auth_keypair(), sizeof(auth));
+
+ /* Demonstrate that we can start up with no secret identity key */
+ routerkeys_free_all();
+ unlink(get_fname("test_ed_keys_init_all/keys/"
+ "ed25519_master_id_secret_key"));
+ tt_int_op(0, ==, load_ed_keys(options, now));
+ tt_mem_op(&id, ==, get_master_identity_key(), sizeof(id));
+ tt_mem_op(&sign, ==, get_master_signing_keypair(), sizeof(sign));
+ tt_mem_op(&link, !=, get_current_link_keypair(), sizeof(link));
+ tt_mem_op(&auth, !=, get_current_auth_keypair(), sizeof(auth));
+ tt_assert(get_master_signing_key_cert());
+ tt_assert(get_current_link_key_cert());
+ tt_assert(get_current_auth_key_cert());
+
+ /* But we're in trouble if we have no id key and our signing key has
+ expired. */
+ log_global_min_severity_ = LOG_ERR; /* Suppress warnings.
+ * XXX (better way to do this)? */
+ routerkeys_free_all();
+ tt_int_op(-1, ==, load_ed_keys(options, now+200*86400));
+
+ done:
+ tor_free(dir);
+ tor_free(options);
+ routerkeys_free_all();
+}
+
#define TEST(name, flags) \
{ #name , test_routerkeys_ ## name, (flags), NULL, NULL }
struct testcase_t routerkeys_tests[] = {
TEST(write_fingerprint, TT_FORK),
+ TEST(ed_certs, TT_FORK),
+ TEST(ed_key_create, TT_FORK),
+ TEST(ed_key_init_basic, TT_FORK),
+ TEST(ed_key_init_split, TT_FORK),
+ TEST(ed_keys_init_all, TT_FORK),
END_OF_TESTCASES
};
diff --git a/src/trunnel/ed25519_cert.c b/src/trunnel/ed25519_cert.c
new file mode 100644
index 0000000..2a84e4b
--- /dev/null
+++ b/src/trunnel/ed25519_cert.c
@@ -0,0 +1,887 @@
+/* ed25519_cert.c -- generated by Trunnel v1.2.
+ * https://gitweb.torproject.org/trunnel.git
+ * You probably shouldn't edit this file.
+ */
+#include <stdlib.h>
+#include "trunnel-impl.h"
+
+#include "ed25519_cert.h"
+
+#define TRUNNEL_SET_ERROR_CODE(obj) \
+ do { \
+ (obj)->trunnel_error_code_ = 1; \
+ } while (0)
+
+#if defined(__COVERITY__) || defined(__clang_analyzer__)
+/* If we're runnning a static analysis tool, we don't want it to complain
+ * that some of our remaining-bytes checks are dead-code. */
+int edcert_deadcode_dummy__ = 0;
+#define OR_DEADCODE_DUMMY || edcert_deadcode_dummy__
+#else
+#define OR_DEADCODE_DUMMY
+#endif
+
+#define CHECK_REMAINING(nbytes, label) \
+ do { \
+ if (remaining < (nbytes) OR_DEADCODE_DUMMY) { \
+ goto label; \
+ } \
+ } while (0)
+
+ed25519_cert_extension_t *
+ed25519_cert_extension_new(void)
+{
+ ed25519_cert_extension_t *val = trunnel_calloc(1, sizeof(ed25519_cert_extension_t));
+ if (NULL == val)
+ return NULL;
+ return val;
+}
+
+/** Release all storage held inside 'obj', but do not free 'obj'.
+ */
+static void
+ed25519_cert_extension_clear(ed25519_cert_extension_t *obj)
+{
+ (void) obj;
+ TRUNNEL_DYNARRAY_WIPE(&obj->un_unparsed);
+ TRUNNEL_DYNARRAY_CLEAR(&obj->un_unparsed);
+}
+
+void
+ed25519_cert_extension_free(ed25519_cert_extension_t *obj)
+{
+ if (obj == NULL)
+ return;
+ ed25519_cert_extension_clear(obj);
+ trunnel_memwipe(obj, sizeof(ed25519_cert_extension_t));
+ trunnel_free_(obj);
+}
+
+uint16_t
+ed25519_cert_extension_get_ext_length(ed25519_cert_extension_t *inp)
+{
+ return inp->ext_length;
+}
+int
+ed25519_cert_extension_set_ext_length(ed25519_cert_extension_t *inp, uint16_t val)
+{
+ inp->ext_length = val;
+ return 0;
+}
+uint8_t
+ed25519_cert_extension_get_ext_type(ed25519_cert_extension_t *inp)
+{
+ return inp->ext_type;
+}
+int
+ed25519_cert_extension_set_ext_type(ed25519_cert_extension_t *inp, uint8_t val)
+{
+ inp->ext_type = val;
+ return 0;
+}
+uint8_t
+ed25519_cert_extension_get_ext_flags(ed25519_cert_extension_t *inp)
+{
+ return inp->ext_flags;
+}
+int
+ed25519_cert_extension_set_ext_flags(ed25519_cert_extension_t *inp, uint8_t val)
+{
+ inp->ext_flags = val;
+ return 0;
+}
+size_t
+ed25519_cert_extension_getlen_un_signing_key(const ed25519_cert_extension_t *inp)
+{
+ (void)inp; return 32;
+}
+
+uint8_t
+ed25519_cert_extension_get_un_signing_key(const ed25519_cert_extension_t *inp, size_t idx)
+{
+ trunnel_assert(idx < 32);
+ return inp->un_signing_key[idx];
+}
+
+int
+ed25519_cert_extension_set_un_signing_key(ed25519_cert_extension_t *inp, size_t idx, uint8_t elt)
+{
+ trunnel_assert(idx < 32);
+ inp->un_signing_key[idx] = elt;
+ return 0;
+}
+
+uint8_t *
+ed25519_cert_extension_getarray_un_signing_key(ed25519_cert_extension_t *inp)
+{
+ return inp->un_signing_key;
+}
+size_t
+ed25519_cert_extension_getlen_un_unparsed(const ed25519_cert_extension_t *inp)
+{
+ return TRUNNEL_DYNARRAY_LEN(&inp->un_unparsed);
+}
+
+uint8_t
+ed25519_cert_extension_get_un_unparsed(ed25519_cert_extension_t *inp, size_t idx)
+{
+ return TRUNNEL_DYNARRAY_GET(&inp->un_unparsed, idx);
+}
+
+int
+ed25519_cert_extension_set_un_unparsed(ed25519_cert_extension_t *inp, size_t idx, uint8_t elt)
+{
+ TRUNNEL_DYNARRAY_SET(&inp->un_unparsed, idx, elt);
+ return 0;
+}
+int
+ed25519_cert_extension_add_un_unparsed(ed25519_cert_extension_t *inp, uint8_t elt)
+{
+ TRUNNEL_DYNARRAY_ADD(uint8_t, &inp->un_unparsed, elt, {});
+ return 0;
+ trunnel_alloc_failed:
+ TRUNNEL_SET_ERROR_CODE(inp);
+ return -1;
+}
+
+uint8_t *
+ed25519_cert_extension_getarray_un_unparsed(ed25519_cert_extension_t *inp)
+{
+ return inp->un_unparsed.elts_;
+}
+int
+ed25519_cert_extension_setlen_un_unparsed(ed25519_cert_extension_t *inp, size_t newlen)
+{
+ uint8_t *newptr;
+ newptr = trunnel_dynarray_setlen(&inp->un_unparsed.allocated_,
+ &inp->un_unparsed.n_, inp->un_unparsed.elts_, newlen,
+ sizeof(inp->un_unparsed.elts_[0]), (trunnel_free_fn_t) NULL,
+ &inp->trunnel_error_code_);
+ if (newptr == NULL)
+ goto trunnel_alloc_failed;
+ inp->un_unparsed.elts_ = newptr;
+ return 0;
+ trunnel_alloc_failed:
+ TRUNNEL_SET_ERROR_CODE(inp);
+ return -1;
+}
+const char *
+ed25519_cert_extension_check(const ed25519_cert_extension_t *obj)
+{
+ if (obj == NULL)
+ return "Object was NULL";
+ if (obj->trunnel_error_code_)
+ return "A set function failed on this object";
+ switch (obj->ext_type) {
+
+ case CERTEXT_SIGNED_WITH_KEY:
+ break;
+
+ default:
+ break;
+ }
+ return NULL;
+}
+
+ssize_t
+ed25519_cert_extension_encoded_len(const ed25519_cert_extension_t *obj)
+{
+ ssize_t result = 0;
+
+ if (NULL != ed25519_cert_extension_check(obj))
+ return -1;
+
+
+ /* Length of u16 ext_length */
+ result += 2;
+
+ /* Length of u8 ext_type */
+ result += 1;
+
+ /* Length of u8 ext_flags */
+ result += 1;
+ switch (obj->ext_type) {
+
+ case CERTEXT_SIGNED_WITH_KEY:
+
+ /* Length of u8 un_signing_key[32] */
+ result += 32;
+ break;
+
+ default:
+
+ /* Length of u8 un_unparsed[] */
+ result += TRUNNEL_DYNARRAY_LEN(&obj->un_unparsed);
+ break;
+ }
+ return result;
+}
+int
+ed25519_cert_extension_clear_errors(ed25519_cert_extension_t *obj)
+{
+ int r = obj->trunnel_error_code_;
+ obj->trunnel_error_code_ = 0;
+ return r;
+}
+ssize_t
+ed25519_cert_extension_encode(uint8_t *output, const size_t avail, const ed25519_cert_extension_t *obj)
+{
+ ssize_t result = 0;
+ size_t written = 0;
+ uint8_t *ptr = output;
+ const char *msg;
+#ifdef TRUNNEL_CHECK_ENCODED_LEN
+ const ssize_t encoded_len = ed25519_cert_extension_encoded_len(obj);
+#endif
+
+ uint8_t *backptr_ext_length = NULL;
+
+ if (NULL != (msg = ed25519_cert_extension_check(obj)))
+ goto check_failed;
+
+#ifdef TRUNNEL_CHECK_ENCODED_LEN
+ trunnel_assert(encoded_len >= 0);
+#endif
+
+ /* Encode u16 ext_length */
+ backptr_ext_length = ptr;
+ trunnel_assert(written <= avail);
+ if (avail - written < 2)
+ goto truncated;
+ trunnel_set_uint16(ptr, trunnel_htons(obj->ext_length));
+ written += 2; ptr += 2;
+
+ /* Encode u8 ext_type */
+ trunnel_assert(written <= avail);
+ if (avail - written < 1)
+ goto truncated;
+ trunnel_set_uint8(ptr, (obj->ext_type));
+ written += 1; ptr += 1;
+
+ /* Encode u8 ext_flags */
+ trunnel_assert(written <= avail);
+ if (avail - written < 1)
+ goto truncated;
+ trunnel_set_uint8(ptr, (obj->ext_flags));
+ written += 1; ptr += 1;
+ {
+ size_t written_before_union = written;
+
+ /* Encode union un[ext_type] */
+ trunnel_assert(written <= avail);
+ switch (obj->ext_type) {
+
+ case CERTEXT_SIGNED_WITH_KEY:
+
+ /* Encode u8 un_signing_key[32] */
+ trunnel_assert(written <= avail);
+ if (avail - written < 32)
+ goto truncated;
+ memcpy(ptr, obj->un_signing_key, 32);
+ written += 32; ptr += 32;
+ break;
+
+ default:
+
+ /* Encode u8 un_unparsed[] */
+ {
+ size_t elt_len = TRUNNEL_DYNARRAY_LEN(&obj->un_unparsed);
+ trunnel_assert(written <= avail);
+ if (avail - written < elt_len)
+ goto truncated;
+ memcpy(ptr, obj->un_unparsed.elts_, elt_len);
+ written += elt_len; ptr += elt_len;
+ }
+ break;
+ }
+ /* Write the length field back to ext_length */
+ trunnel_assert(written >= written_before_union);
+#if UINT16_MAX < SIZE_MAX
+ if (written - written_before_union > UINT16_MAX)
+ goto check_failed;
+#endif
+ trunnel_set_uint16(backptr_ext_length, trunnel_htons(written - written_before_union));
+ }
+
+
+ trunnel_assert(ptr == output + written);
+#ifdef TRUNNEL_CHECK_ENCODED_LEN
+ {
+ trunnel_assert(encoded_len >= 0);
+ trunnel_assert((size_t)encoded_len == written);
+ }
+
+#endif
+
+ return written;
+
+ truncated:
+ result = -2;
+ goto fail;
+ check_failed:
+ (void)msg;
+ result = -1;
+ goto fail;
+ fail:
+ trunnel_assert(result < 0);
+ return result;
+}
+
+/** As ed25519_cert_extension_parse(), but do not allocate the output
+ * object.
+ */
+static ssize_t
+ed25519_cert_extension_parse_into(ed25519_cert_extension_t *obj, const uint8_t *input, const size_t len_in)
+{
+ const uint8_t *ptr = input;
+ size_t remaining = len_in;
+ ssize_t result = 0;
+ (void)result;
+
+ /* Parse u16 ext_length */
+ CHECK_REMAINING(2, truncated);
+ obj->ext_length = trunnel_ntohs(trunnel_get_uint16(ptr));
+ remaining -= 2; ptr += 2;
+
+ /* Parse u8 ext_type */
+ CHECK_REMAINING(1, truncated);
+ obj->ext_type = (trunnel_get_uint8(ptr));
+ remaining -= 1; ptr += 1;
+
+ /* Parse u8 ext_flags */
+ CHECK_REMAINING(1, truncated);
+ obj->ext_flags = (trunnel_get_uint8(ptr));
+ remaining -= 1; ptr += 1;
+ {
+ size_t remaining_after;
+ CHECK_REMAINING(obj->ext_length, truncated);
+ remaining_after = remaining - obj->ext_length;
+ remaining = obj->ext_length;
+
+ /* Parse union un[ext_type] */
+ switch (obj->ext_type) {
+
+ case CERTEXT_SIGNED_WITH_KEY:
+
+ /* Parse u8 un_signing_key[32] */
+ CHECK_REMAINING(32, fail);
+ memcpy(obj->un_signing_key, ptr, 32);
+ remaining -= 32; ptr += 32;
+ break;
+
+ default:
+
+ /* Parse u8 un_unparsed[] */
+ TRUNNEL_DYNARRAY_EXPAND(uint8_t, &obj->un_unparsed, remaining, {});
+ obj->un_unparsed.n_ = remaining;
+ memcpy(obj->un_unparsed.elts_, ptr, remaining);
+ ptr += remaining; remaining -= remaining;
+ break;
+ }
+ if (remaining != 0)
+ goto fail;
+ remaining = remaining_after;
+ }
+ trunnel_assert(ptr + remaining == input + len_in);
+ return len_in - remaining;
+
+ truncated:
+ return -2;
+ trunnel_alloc_failed:
+ return -1;
+ fail:
+ result = -1;
+ return result;
+}
+
+ssize_t
+ed25519_cert_extension_parse(ed25519_cert_extension_t **output, const uint8_t *input, const size_t len_in)
+{
+ ssize_t result;
+ *output = ed25519_cert_extension_new();
+ if (NULL == *output)
+ return -1;
+ result = ed25519_cert_extension_parse_into(*output, input, len_in);
+ if (result < 0) {
+ ed25519_cert_extension_free(*output);
+ *output = NULL;
+ }
+ return result;
+}
+ed25519_cert_t *
+ed25519_cert_new(void)
+{
+ ed25519_cert_t *val = trunnel_calloc(1, sizeof(ed25519_cert_t));
+ if (NULL == val)
+ return NULL;
+ val->version = 1;
+ return val;
+}
+
+/** Release all storage held inside 'obj', but do not free 'obj'.
+ */
+static void
+ed25519_cert_clear(ed25519_cert_t *obj)
+{
+ (void) obj;
+ {
+
+ unsigned idx;
+ for (idx = 0; idx < TRUNNEL_DYNARRAY_LEN(&obj->ext); ++idx) {
+ ed25519_cert_extension_free(TRUNNEL_DYNARRAY_GET(&obj->ext, idx));
+ }
+ }
+ TRUNNEL_DYNARRAY_WIPE(&obj->ext);
+ TRUNNEL_DYNARRAY_CLEAR(&obj->ext);
+}
+
+void
+ed25519_cert_free(ed25519_cert_t *obj)
+{
+ if (obj == NULL)
+ return;
+ ed25519_cert_clear(obj);
+ trunnel_memwipe(obj, sizeof(ed25519_cert_t));
+ trunnel_free_(obj);
+}
+
+uint8_t
+ed25519_cert_get_version(ed25519_cert_t *inp)
+{
+ return inp->version;
+}
+int
+ed25519_cert_set_version(ed25519_cert_t *inp, uint8_t val)
+{
+ if (! ((val == 1))) {
+ TRUNNEL_SET_ERROR_CODE(inp);
+ return -1;
+ }
+ inp->version = val;
+ return 0;
+}
+uint8_t
+ed25519_cert_get_cert_type(ed25519_cert_t *inp)
+{
+ return inp->cert_type;
+}
+int
+ed25519_cert_set_cert_type(ed25519_cert_t *inp, uint8_t val)
+{
+ inp->cert_type = val;
+ return 0;
+}
+uint32_t
+ed25519_cert_get_exp_field(ed25519_cert_t *inp)
+{
+ return inp->exp_field;
+}
+int
+ed25519_cert_set_exp_field(ed25519_cert_t *inp, uint32_t val)
+{
+ inp->exp_field = val;
+ return 0;
+}
+uint8_t
+ed25519_cert_get_cert_key_type(ed25519_cert_t *inp)
+{
+ return inp->cert_key_type;
+}
+int
+ed25519_cert_set_cert_key_type(ed25519_cert_t *inp, uint8_t val)
+{
+ inp->cert_key_type = val;
+ return 0;
+}
+size_t
+ed25519_cert_getlen_certified_key(const ed25519_cert_t *inp)
+{
+ (void)inp; return 32;
+}
+
+uint8_t
+ed25519_cert_get_certified_key(const ed25519_cert_t *inp, size_t idx)
+{
+ trunnel_assert(idx < 32);
+ return inp->certified_key[idx];
+}
+
+int
+ed25519_cert_set_certified_key(ed25519_cert_t *inp, size_t idx, uint8_t elt)
+{
+ trunnel_assert(idx < 32);
+ inp->certified_key[idx] = elt;
+ return 0;
+}
+
+uint8_t *
+ed25519_cert_getarray_certified_key(ed25519_cert_t *inp)
+{
+ return inp->certified_key;
+}
+uint8_t
+ed25519_cert_get_n_extensions(ed25519_cert_t *inp)
+{
+ return inp->n_extensions;
+}
+int
+ed25519_cert_set_n_extensions(ed25519_cert_t *inp, uint8_t val)
+{
+ inp->n_extensions = val;
+ return 0;
+}
+size_t
+ed25519_cert_getlen_ext(const ed25519_cert_t *inp)
+{
+ return TRUNNEL_DYNARRAY_LEN(&inp->ext);
+}
+
+struct ed25519_cert_extension_st *
+ed25519_cert_get_ext(ed25519_cert_t *inp, size_t idx)
+{
+ return TRUNNEL_DYNARRAY_GET(&inp->ext, idx);
+}
+
+int
+ed25519_cert_set_ext(ed25519_cert_t *inp, size_t idx, struct ed25519_cert_extension_st * elt)
+{
+ ed25519_cert_extension_t *oldval = TRUNNEL_DYNARRAY_GET(&inp->ext, idx);
+ if (oldval && oldval != elt)
+ ed25519_cert_extension_free(oldval);
+ return ed25519_cert_set0_ext(inp, idx, elt);
+}
+int
+ed25519_cert_set0_ext(ed25519_cert_t *inp, size_t idx, struct ed25519_cert_extension_st * elt)
+{
+ TRUNNEL_DYNARRAY_SET(&inp->ext, idx, elt);
+ return 0;
+}
+int
+ed25519_cert_add_ext(ed25519_cert_t *inp, struct ed25519_cert_extension_st * elt)
+{
+#if SIZE_MAX >= UINT8_MAX
+ if (inp->ext.n_ == UINT8_MAX)
+ goto trunnel_alloc_failed;
+#endif
+ TRUNNEL_DYNARRAY_ADD(struct ed25519_cert_extension_st *, &inp->ext, elt, {});
+ return 0;
+ trunnel_alloc_failed:
+ TRUNNEL_SET_ERROR_CODE(inp);
+ return -1;
+}
+
+struct ed25519_cert_extension_st * *
+ed25519_cert_getarray_ext(ed25519_cert_t *inp)
+{
+ return inp->ext.elts_;
+}
+int
+ed25519_cert_setlen_ext(ed25519_cert_t *inp, size_t newlen)
+{
+ struct ed25519_cert_extension_st * *newptr;
+#if UINT8_MAX < SIZE_MAX
+ if (newlen > UINT8_MAX)
+ goto trunnel_alloc_failed;
+#endif
+ newptr = trunnel_dynarray_setlen(&inp->ext.allocated_,
+ &inp->ext.n_, inp->ext.elts_, newlen,
+ sizeof(inp->ext.elts_[0]), (trunnel_free_fn_t) ed25519_cert_extension_free,
+ &inp->trunnel_error_code_);
+ if (newptr == NULL)
+ goto trunnel_alloc_failed;
+ inp->ext.elts_ = newptr;
+ return 0;
+ trunnel_alloc_failed:
+ TRUNNEL_SET_ERROR_CODE(inp);
+ return -1;
+}
+size_t
+ed25519_cert_getlen_signature(const ed25519_cert_t *inp)
+{
+ (void)inp; return 64;
+}
+
+uint8_t
+ed25519_cert_get_signature(const ed25519_cert_t *inp, size_t idx)
+{
+ trunnel_assert(idx < 64);
+ return inp->signature[idx];
+}
+
+int
+ed25519_cert_set_signature(ed25519_cert_t *inp, size_t idx, uint8_t elt)
+{
+ trunnel_assert(idx < 64);
+ inp->signature[idx] = elt;
+ return 0;
+}
+
+uint8_t *
+ed25519_cert_getarray_signature(ed25519_cert_t *inp)
+{
+ return inp->signature;
+}
+const char *
+ed25519_cert_check(const ed25519_cert_t *obj)
+{
+ if (obj == NULL)
+ return "Object was NULL";
+ if (obj->trunnel_error_code_)
+ return "A set function failed on this object";
+ if (! (obj->version == 1))
+ return "Integer out of bounds";
+ {
+ const char *msg;
+
+ unsigned idx;
+ for (idx = 0; idx < TRUNNEL_DYNARRAY_LEN(&obj->ext); ++idx) {
+ if (NULL != (msg = ed25519_cert_extension_check(TRUNNEL_DYNARRAY_GET(&obj->ext, idx))))
+ return msg;
+ }
+ }
+ if (TRUNNEL_DYNARRAY_LEN(&obj->ext) != obj->n_extensions)
+ return "Length mismatch for ext";
+ return NULL;
+}
+
+ssize_t
+ed25519_cert_encoded_len(const ed25519_cert_t *obj)
+{
+ ssize_t result = 0;
+
+ if (NULL != ed25519_cert_check(obj))
+ return -1;
+
+
+ /* Length of u8 version IN [1] */
+ result += 1;
+
+ /* Length of u8 cert_type */
+ result += 1;
+
+ /* Length of u32 exp_field */
+ result += 4;
+
+ /* Length of u8 cert_key_type */
+ result += 1;
+
+ /* Length of u8 certified_key[32] */
+ result += 32;
+
+ /* Length of u8 n_extensions */
+ result += 1;
+
+ /* Length of struct ed25519_cert_extension ext[n_extensions] */
+ {
+
+ unsigned idx;
+ for (idx = 0; idx < TRUNNEL_DYNARRAY_LEN(&obj->ext); ++idx) {
+ result += ed25519_cert_extension_encoded_len(TRUNNEL_DYNARRAY_GET(&obj->ext, idx));
+ }
+ }
+
+ /* Length of u8 signature[64] */
+ result += 64;
+ return result;
+}
+int
+ed25519_cert_clear_errors(ed25519_cert_t *obj)
+{
+ int r = obj->trunnel_error_code_;
+ obj->trunnel_error_code_ = 0;
+ return r;
+}
+ssize_t
+ed25519_cert_encode(uint8_t *output, const size_t avail, const ed25519_cert_t *obj)
+{
+ ssize_t result = 0;
+ size_t written = 0;
+ uint8_t *ptr = output;
+ const char *msg;
+#ifdef TRUNNEL_CHECK_ENCODED_LEN
+ const ssize_t encoded_len = ed25519_cert_encoded_len(obj);
+#endif
+
+ if (NULL != (msg = ed25519_cert_check(obj)))
+ goto check_failed;
+
+#ifdef TRUNNEL_CHECK_ENCODED_LEN
+ trunnel_assert(encoded_len >= 0);
+#endif
+
+ /* Encode u8 version IN [1] */
+ trunnel_assert(written <= avail);
+ if (avail - written < 1)
+ goto truncated;
+ trunnel_set_uint8(ptr, (obj->version));
+ written += 1; ptr += 1;
+
+ /* Encode u8 cert_type */
+ trunnel_assert(written <= avail);
+ if (avail - written < 1)
+ goto truncated;
+ trunnel_set_uint8(ptr, (obj->cert_type));
+ written += 1; ptr += 1;
+
+ /* Encode u32 exp_field */
+ trunnel_assert(written <= avail);
+ if (avail - written < 4)
+ goto truncated;
+ trunnel_set_uint32(ptr, trunnel_htonl(obj->exp_field));
+ written += 4; ptr += 4;
+
+ /* Encode u8 cert_key_type */
+ trunnel_assert(written <= avail);
+ if (avail - written < 1)
+ goto truncated;
+ trunnel_set_uint8(ptr, (obj->cert_key_type));
+ written += 1; ptr += 1;
+
+ /* Encode u8 certified_key[32] */
+ trunnel_assert(written <= avail);
+ if (avail - written < 32)
+ goto truncated;
+ memcpy(ptr, obj->certified_key, 32);
+ written += 32; ptr += 32;
+
+ /* Encode u8 n_extensions */
+ trunnel_assert(written <= avail);
+ if (avail - written < 1)
+ goto truncated;
+ trunnel_set_uint8(ptr, (obj->n_extensions));
+ written += 1; ptr += 1;
+
+ /* Encode struct ed25519_cert_extension ext[n_extensions] */
+ {
+
+ unsigned idx;
+ for (idx = 0; idx < TRUNNEL_DYNARRAY_LEN(&obj->ext); ++idx) {
+ trunnel_assert(written <= avail);
+ result = ed25519_cert_extension_encode(ptr, avail - written, TRUNNEL_DYNARRAY_GET(&obj->ext, idx));
+ if (result < 0)
+ goto fail; /* XXXXXXX !*/
+ written += result; ptr += result;
+ }
+ }
+
+ /* Encode u8 signature[64] */
+ trunnel_assert(written <= avail);
+ if (avail - written < 64)
+ goto truncated;
+ memcpy(ptr, obj->signature, 64);
+ written += 64; ptr += 64;
+
+
+ trunnel_assert(ptr == output + written);
+#ifdef TRUNNEL_CHECK_ENCODED_LEN
+ {
+ trunnel_assert(encoded_len >= 0);
+ trunnel_assert((size_t)encoded_len == written);
+ }
+
+#endif
+
+ return written;
+
+ truncated:
+ result = -2;
+ goto fail;
+ check_failed:
+ (void)msg;
+ result = -1;
+ goto fail;
+ fail:
+ trunnel_assert(result < 0);
+ return result;
+}
+
+/** As ed25519_cert_parse(), but do not allocate the output object.
+ */
+static ssize_t
+ed25519_cert_parse_into(ed25519_cert_t *obj, const uint8_t *input, const size_t len_in)
+{
+ const uint8_t *ptr = input;
+ size_t remaining = len_in;
+ ssize_t result = 0;
+ (void)result;
+
+ /* Parse u8 version IN [1] */
+ CHECK_REMAINING(1, truncated);
+ obj->version = (trunnel_get_uint8(ptr));
+ remaining -= 1; ptr += 1;
+ if (! (obj->version == 1))
+ goto fail;
+
+ /* Parse u8 cert_type */
+ CHECK_REMAINING(1, truncated);
+ obj->cert_type = (trunnel_get_uint8(ptr));
+ remaining -= 1; ptr += 1;
+
+ /* Parse u32 exp_field */
+ CHECK_REMAINING(4, truncated);
+ obj->exp_field = trunnel_ntohl(trunnel_get_uint32(ptr));
+ remaining -= 4; ptr += 4;
+
+ /* Parse u8 cert_key_type */
+ CHECK_REMAINING(1, truncated);
+ obj->cert_key_type = (trunnel_get_uint8(ptr));
+ remaining -= 1; ptr += 1;
+
+ /* Parse u8 certified_key[32] */
+ CHECK_REMAINING(32, truncated);
+ memcpy(obj->certified_key, ptr, 32);
+ remaining -= 32; ptr += 32;
+
+ /* Parse u8 n_extensions */
+ CHECK_REMAINING(1, truncated);
+ obj->n_extensions = (trunnel_get_uint8(ptr));
+ remaining -= 1; ptr += 1;
+
+ /* Parse struct ed25519_cert_extension ext[n_extensions] */
+ TRUNNEL_DYNARRAY_EXPAND(ed25519_cert_extension_t *, &obj->ext, obj->n_extensions, {});
+ {
+ ed25519_cert_extension_t * elt;
+ unsigned idx;
+ for (idx = 0; idx < obj->n_extensions; ++idx) {
+ result = ed25519_cert_extension_parse(&elt, ptr, remaining);
+ if (result < 0)
+ goto relay_fail;
+ trunnel_assert((size_t)result <= remaining);
+ remaining -= result; ptr += result;
+ TRUNNEL_DYNARRAY_ADD(ed25519_cert_extension_t *, &obj->ext, elt, {ed25519_cert_extension_free(elt);});
+ }
+ }
+
+ /* Parse u8 signature[64] */
+ CHECK_REMAINING(64, truncated);
+ memcpy(obj->signature, ptr, 64);
+ remaining -= 64; ptr += 64;
+ trunnel_assert(ptr + remaining == input + len_in);
+ return len_in - remaining;
+
+ truncated:
+ return -2;
+ relay_fail:
+ if (result >= 0) result = -1;
+ return result;
+ trunnel_alloc_failed:
+ return -1;
+ fail:
+ result = -1;
+ return result;
+}
+
+ssize_t
+ed25519_cert_parse(ed25519_cert_t **output, const uint8_t *input, const size_t len_in)
+{
+ ssize_t result;
+ *output = ed25519_cert_new();
+ if (NULL == *output)
+ return -1;
+ result = ed25519_cert_parse_into(*output, input, len_in);
+ if (result < 0) {
+ ed25519_cert_free(*output);
+ *output = NULL;
+ }
+ return result;
+}
diff --git a/src/trunnel/ed25519_cert.h b/src/trunnel/ed25519_cert.h
new file mode 100644
index 0000000..3ddf95e
--- /dev/null
+++ b/src/trunnel/ed25519_cert.h
@@ -0,0 +1,288 @@
+/* ed25519_cert.h -- generated by by Trunnel v1.2.
+ * https://gitweb.torproject.org/trunnel.git
+ * You probably shouldn't edit this file.
+ */
+#ifndef TRUNNEL_ED25519_CERT_H
+#define TRUNNEL_ED25519_CERT_H
+
+#include <stdint.h>
+#include "trunnel.h"
+
+#define CERTEXT_SIGNED_WITH_KEY 4
+#define CERTEXT_FLAG_AFFECTS_VALIDATION 1
+#if !defined(TRUNNEL_OPAQUE) && !defined(TRUNNEL_OPAQUE_ED25519_CERT_EXTENSION)
+struct ed25519_cert_extension_st {
+ uint16_t ext_length;
+ uint8_t ext_type;
+ uint8_t ext_flags;
+ uint8_t un_signing_key[32];
+ TRUNNEL_DYNARRAY_HEAD(, uint8_t) un_unparsed;
+ uint8_t trunnel_error_code_;
+};
+#endif
+typedef struct ed25519_cert_extension_st ed25519_cert_extension_t;
+#if !defined(TRUNNEL_OPAQUE) && !defined(TRUNNEL_OPAQUE_ED25519_CERT)
+struct ed25519_cert_st {
+ uint8_t version;
+ uint8_t cert_type;
+ uint32_t exp_field;
+ uint8_t cert_key_type;
+ uint8_t certified_key[32];
+ uint8_t n_extensions;
+ TRUNNEL_DYNARRAY_HEAD(, struct ed25519_cert_extension_st *) ext;
+ uint8_t signature[64];
+ uint8_t trunnel_error_code_;
+};
+#endif
+typedef struct ed25519_cert_st ed25519_cert_t;
+/** Return a newly allocated ed25519_cert_extension with all elements
+ * set to zero.
+ */
+ed25519_cert_extension_t *ed25519_cert_extension_new(void);
+/** Release all storage held by the ed25519_cert_extension in
+ * 'victim'. (Do nothing if 'victim' is NULL.)
+ */
+void ed25519_cert_extension_free(ed25519_cert_extension_t *victim);
+/** Try to parse a ed25519_cert_extension from the buffer in 'input',
+ * using up to 'len_in' bytes from the input buffer. On success,
+ * return the number of bytes consumed and set *output to the newly
+ * allocated ed25519_cert_extension_t. On failure, return -2 if the
+ * input appears truncated, and -1 if the input is otherwise invalid.
+ */
+ssize_t ed25519_cert_extension_parse(ed25519_cert_extension_t **output, const uint8_t *input, const size_t len_in);
+/** Return the number of bytes we expect to need to encode the
+ * ed25519_cert_extension in 'obj'. On failure, return a negative
+ * value. Note that this value may be an overestimate, and can even be
+ * an underestimate for certain unencodeable objects.
+ */
+ssize_t ed25519_cert_extension_encoded_len(const ed25519_cert_extension_t *obj);
+/** Try to encode the ed25519_cert_extension from 'input' into the
+ * buffer at 'output', using up to 'avail' bytes of the output buffer.
+ * On success, return the number of bytes used. On failure, return -2
+ * if the buffer was not long enough, and -1 if the input was invalid.
+ */
+ssize_t ed25519_cert_extension_encode(uint8_t *output, const size_t avail, const ed25519_cert_extension_t *input);
+/** Check whether the internal state of the ed25519_cert_extension in
+ * 'obj' is consistent. Return NULL if it is, and a short message if
+ * it is not.
+ */
+const char *ed25519_cert_extension_check(const ed25519_cert_extension_t *obj);
+/** Clear any errors that were set on the object 'obj' by its setter
+ * functions. Return true iff errors were cleared.
+ */
+int ed25519_cert_extension_clear_errors(ed25519_cert_extension_t *obj);
+/** Return the value of the ext_length field of the
+ * ed25519_cert_extension_t in 'inp'
+ */
+uint16_t ed25519_cert_extension_get_ext_length(ed25519_cert_extension_t *inp);
+/** Set the value of the ext_length field of the
+ * ed25519_cert_extension_t in 'inp' to 'val'. Return 0 on success;
+ * return -1 and set the error code on 'inp' on failure.
+ */
+int ed25519_cert_extension_set_ext_length(ed25519_cert_extension_t *inp, uint16_t val);
+/** Return the value of the ext_type field of the
+ * ed25519_cert_extension_t in 'inp'
+ */
+uint8_t ed25519_cert_extension_get_ext_type(ed25519_cert_extension_t *inp);
+/** Set the value of the ext_type field of the
+ * ed25519_cert_extension_t in 'inp' to 'val'. Return 0 on success;
+ * return -1 and set the error code on 'inp' on failure.
+ */
+int ed25519_cert_extension_set_ext_type(ed25519_cert_extension_t *inp, uint8_t val);
+/** Return the value of the ext_flags field of the
+ * ed25519_cert_extension_t in 'inp'
+ */
+uint8_t ed25519_cert_extension_get_ext_flags(ed25519_cert_extension_t *inp);
+/** Set the value of the ext_flags field of the
+ * ed25519_cert_extension_t in 'inp' to 'val'. Return 0 on success;
+ * return -1 and set the error code on 'inp' on failure.
+ */
+int ed25519_cert_extension_set_ext_flags(ed25519_cert_extension_t *inp, uint8_t val);
+/** Return the (constant) length of the array holding the
+ * un_signing_key field of the ed25519_cert_extension_t in 'inp'.
+ */
+size_t ed25519_cert_extension_getlen_un_signing_key(const ed25519_cert_extension_t *inp);
+/** Return the element at position 'idx' of the fixed array field
+ * un_signing_key of the ed25519_cert_extension_t in 'inp'.
+ */
+uint8_t ed25519_cert_extension_get_un_signing_key(const ed25519_cert_extension_t *inp, size_t idx);
+/** Change the element at position 'idx' of the fixed array field
+ * un_signing_key of the ed25519_cert_extension_t in 'inp', so that it
+ * will hold the value 'elt'.
+ */
+int ed25519_cert_extension_set_un_signing_key(ed25519_cert_extension_t *inp, size_t idx, uint8_t elt);
+/** Return a pointer to the 32-element array field un_signing_key of
+ * 'inp'.
+ */
+uint8_t * ed25519_cert_extension_getarray_un_signing_key(ed25519_cert_extension_t *inp);
+/** Return the length of the dynamic array holding the un_unparsed
+ * field of the ed25519_cert_extension_t in 'inp'.
+ */
+size_t ed25519_cert_extension_getlen_un_unparsed(const ed25519_cert_extension_t *inp);
+/** Return the element at position 'idx' of the dynamic array field
+ * un_unparsed of the ed25519_cert_extension_t in 'inp'.
+ */
+uint8_t ed25519_cert_extension_get_un_unparsed(ed25519_cert_extension_t *inp, size_t idx);
+/** Change the element at position 'idx' of the dynamic array field
+ * un_unparsed of the ed25519_cert_extension_t in 'inp', so that it
+ * will hold the value 'elt'.
+ */
+int ed25519_cert_extension_set_un_unparsed(ed25519_cert_extension_t *inp, size_t idx, uint8_t elt);
+/** Append a new element 'elt' to the dynamic array field un_unparsed
+ * of the ed25519_cert_extension_t in 'inp'.
+ */
+int ed25519_cert_extension_add_un_unparsed(ed25519_cert_extension_t *inp, uint8_t elt);
+/** Return a pointer to the variable-length array field un_unparsed of
+ * 'inp'.
+ */
+uint8_t * ed25519_cert_extension_getarray_un_unparsed(ed25519_cert_extension_t *inp);
+/** Change the length of the variable-length array field un_unparsed
+ * of 'inp' to 'newlen'.Fill extra elements with 0. Return 0 on
+ * success; return -1 and set the error code on 'inp' on failure.
+ */
+int ed25519_cert_extension_setlen_un_unparsed(ed25519_cert_extension_t *inp, size_t newlen);
+/** Return a newly allocated ed25519_cert with all elements set to
+ * zero.
+ */
+ed25519_cert_t *ed25519_cert_new(void);
+/** Release all storage held by the ed25519_cert in 'victim'. (Do
+ * nothing if 'victim' is NULL.)
+ */
+void ed25519_cert_free(ed25519_cert_t *victim);
+/** Try to parse a ed25519_cert from the buffer in 'input', using up
+ * to 'len_in' bytes from the input buffer. On success, return the
+ * number of bytes consumed and set *output to the newly allocated
+ * ed25519_cert_t. On failure, return -2 if the input appears
+ * truncated, and -1 if the input is otherwise invalid.
+ */
+ssize_t ed25519_cert_parse(ed25519_cert_t **output, const uint8_t *input, const size_t len_in);
+/** Return the number of bytes we expect to need to encode the
+ * ed25519_cert in 'obj'. On failure, return a negative value. Note
+ * that this value may be an overestimate, and can even be an
+ * underestimate for certain unencodeable objects.
+ */
+ssize_t ed25519_cert_encoded_len(const ed25519_cert_t *obj);
+/** Try to encode the ed25519_cert from 'input' into the buffer at
+ * 'output', using up to 'avail' bytes of the output buffer. On
+ * success, return the number of bytes used. On failure, return -2 if
+ * the buffer was not long enough, and -1 if the input was invalid.
+ */
+ssize_t ed25519_cert_encode(uint8_t *output, const size_t avail, const ed25519_cert_t *input);
+/** Check whether the internal state of the ed25519_cert in 'obj' is
+ * consistent. Return NULL if it is, and a short message if it is not.
+ */
+const char *ed25519_cert_check(const ed25519_cert_t *obj);
+/** Clear any errors that were set on the object 'obj' by its setter
+ * functions. Return true iff errors were cleared.
+ */
+int ed25519_cert_clear_errors(ed25519_cert_t *obj);
+/** Return the value of the version field of the ed25519_cert_t in
+ * 'inp'
+ */
+uint8_t ed25519_cert_get_version(ed25519_cert_t *inp);
+/** Set the value of the version field of the ed25519_cert_t in 'inp'
+ * to 'val'. Return 0 on success; return -1 and set the error code on
+ * 'inp' on failure.
+ */
+int ed25519_cert_set_version(ed25519_cert_t *inp, uint8_t val);
+/** Return the value of the cert_type field of the ed25519_cert_t in
+ * 'inp'
+ */
+uint8_t ed25519_cert_get_cert_type(ed25519_cert_t *inp);
+/** Set the value of the cert_type field of the ed25519_cert_t in
+ * 'inp' to 'val'. Return 0 on success; return -1 and set the error
+ * code on 'inp' on failure.
+ */
+int ed25519_cert_set_cert_type(ed25519_cert_t *inp, uint8_t val);
+/** Return the value of the exp_field field of the ed25519_cert_t in
+ * 'inp'
+ */
+uint32_t ed25519_cert_get_exp_field(ed25519_cert_t *inp);
+/** Set the value of the exp_field field of the ed25519_cert_t in
+ * 'inp' to 'val'. Return 0 on success; return -1 and set the error
+ * code on 'inp' on failure.
+ */
+int ed25519_cert_set_exp_field(ed25519_cert_t *inp, uint32_t val);
+/** Return the value of the cert_key_type field of the ed25519_cert_t
+ * in 'inp'
+ */
+uint8_t ed25519_cert_get_cert_key_type(ed25519_cert_t *inp);
+/** Set the value of the cert_key_type field of the ed25519_cert_t in
+ * 'inp' to 'val'. Return 0 on success; return -1 and set the error
+ * code on 'inp' on failure.
+ */
+int ed25519_cert_set_cert_key_type(ed25519_cert_t *inp, uint8_t val);
+/** Return the (constant) length of the array holding the
+ * certified_key field of the ed25519_cert_t in 'inp'.
+ */
+size_t ed25519_cert_getlen_certified_key(const ed25519_cert_t *inp);
+/** Return the element at position 'idx' of the fixed array field
+ * certified_key of the ed25519_cert_t in 'inp'.
+ */
+uint8_t ed25519_cert_get_certified_key(const ed25519_cert_t *inp, size_t idx);
+/** Change the element at position 'idx' of the fixed array field
+ * certified_key of the ed25519_cert_t in 'inp', so that it will hold
+ * the value 'elt'.
+ */
+int ed25519_cert_set_certified_key(ed25519_cert_t *inp, size_t idx, uint8_t elt);
+/** Return a pointer to the 32-element array field certified_key of
+ * 'inp'.
+ */
+uint8_t * ed25519_cert_getarray_certified_key(ed25519_cert_t *inp);
+/** Return the value of the n_extensions field of the ed25519_cert_t
+ * in 'inp'
+ */
+uint8_t ed25519_cert_get_n_extensions(ed25519_cert_t *inp);
+/** Set the value of the n_extensions field of the ed25519_cert_t in
+ * 'inp' to 'val'. Return 0 on success; return -1 and set the error
+ * code on 'inp' on failure.
+ */
+int ed25519_cert_set_n_extensions(ed25519_cert_t *inp, uint8_t val);
+/** Return the length of the dynamic array holding the ext field of
+ * the ed25519_cert_t in 'inp'.
+ */
+size_t ed25519_cert_getlen_ext(const ed25519_cert_t *inp);
+/** Return the element at position 'idx' of the dynamic array field
+ * ext of the ed25519_cert_t in 'inp'.
+ */
+struct ed25519_cert_extension_st * ed25519_cert_get_ext(ed25519_cert_t *inp, size_t idx);
+/** Change the element at position 'idx' of the dynamic array field
+ * ext of the ed25519_cert_t in 'inp', so that it will hold the value
+ * 'elt'. Free the previous value, if any.
+ */
+int ed25519_cert_set_ext(ed25519_cert_t *inp, size_t idx, struct ed25519_cert_extension_st * elt);
+/** As ed25519_cert_set_ext, but does not free the previous value.
+ */
+int ed25519_cert_set0_ext(ed25519_cert_t *inp, size_t idx, struct ed25519_cert_extension_st * elt);
+/** Append a new element 'elt' to the dynamic array field ext of the
+ * ed25519_cert_t in 'inp'.
+ */
+int ed25519_cert_add_ext(ed25519_cert_t *inp, struct ed25519_cert_extension_st * elt);
+/** Return a pointer to the variable-length array field ext of 'inp'.
+ */
+struct ed25519_cert_extension_st * * ed25519_cert_getarray_ext(ed25519_cert_t *inp);
+/** Change the length of the variable-length array field ext of 'inp'
+ * to 'newlen'.Fill extra elements with NULL; free removed elements.
+ * Return 0 on success; return -1 and set the error code on 'inp' on
+ * failure.
+ */
+int ed25519_cert_setlen_ext(ed25519_cert_t *inp, size_t newlen);
+/** Return the (constant) length of the array holding the signature
+ * field of the ed25519_cert_t in 'inp'.
+ */
+size_t ed25519_cert_getlen_signature(const ed25519_cert_t *inp);
+/** Return the element at position 'idx' of the fixed array field
+ * signature of the ed25519_cert_t in 'inp'.
+ */
+uint8_t ed25519_cert_get_signature(const ed25519_cert_t *inp, size_t idx);
+/** Change the element at position 'idx' of the fixed array field
+ * signature of the ed25519_cert_t in 'inp', so that it will hold the
+ * value 'elt'.
+ */
+int ed25519_cert_set_signature(ed25519_cert_t *inp, size_t idx, uint8_t elt);
+/** Return a pointer to the 64-element array field signature of 'inp'.
+ */
+uint8_t * ed25519_cert_getarray_signature(ed25519_cert_t *inp);
+
+
+#endif
diff --git a/src/trunnel/ed25519_cert.trunnel b/src/trunnel/ed25519_cert.trunnel
new file mode 100644
index 0000000..c46f1b6
--- /dev/null
+++ b/src/trunnel/ed25519_cert.trunnel
@@ -0,0 +1,76 @@
+
+struct ed25519_cert {
+ u8 version IN [1];
+ u8 cert_type;
+ u32 exp_field;
+ u8 cert_key_type;
+ u8 certified_key[32];
+ u8 n_extensions;
+ struct ed25519_cert_extension ext[n_extensions];
+ u8 signature[64];
+}
+
+const CERTEXT_SIGNED_WITH_KEY = 4;
+const CERTEXT_FLAG_AFFECTS_VALIDATION = 1;
+
+struct ed25519_cert_extension {
+ u16 ext_length;
+ u8 ext_type;
+ u8 ext_flags;
+ union un[ext_type] with length ext_length {
+ CERTEXT_SIGNED_WITH_KEY : u8 signing_key[32];
+ default: u8 unparsed[];
+ };
+}
+
+/*
+struct cert_revocation {
+ u8 prefix[8];
+ u8 version IN [1];
+ u8 keytype;
+ u8 identity_key[32];
+ u8 revoked_key[32];
+ u64 published;
+ u8 n_extensions;
+ struct cert_extension ext[n_extensions];
+ u8 signature[64];
+}
+
+struct crosscert_ed_rsa {
+ u8 ed_key[32];
+ u32 expiration_date;
+ u8 signature[128];
+}
+
+struct auth02_cell {
+ u8 type[8];
+ u8 cid[32];
+ u8 sid[32];
+ u8 cid_ed[32];
+ u8 sid_ed[32];
+ u8 slog[32];
+ u8 clog[32];
+ u8 scert[32];
+ u8 tlssecrets[32];
+ u8 rand[24];
+ u8 sig[64];
+}
+
+const LS_IPV4 = 0x00;
+const LS_IPV6 = 0x01;
+const LS_LEGACY_ID = 0x02;
+const LS_ED25519_ID = 0x03;
+
+// amended from tor.trunnel
+struct link_specifier {
+ u8 ls_type;
+ u8 ls_len;
+ union un[ls_type] with length ls_len {
+ LS_IPV4: u32 ipv4_addr; u16 ipv4_port;
+ LS_IPV6: u8 ipv6_addr[16]; u16 ipv6_port;
+ LS_LEGACY_ID: u8 legacy_id[20];
+ LS_ED25519_ID: u8 ed25519_id[32];
+ default: u8 unrecognized[];
+ };
+}
+*/
\ No newline at end of file
diff --git a/src/trunnel/include.am b/src/trunnel/include.am
index c7ac167..6e7851a 100644
--- a/src/trunnel/include.am
+++ b/src/trunnel/include.am
@@ -9,15 +9,21 @@ endif
AM_CPPFLAGS += -I$(srcdir)/src/ext/trunnel -I$(srcdir)/src/trunnel
+TRUNNELINPUTS = \
+ src/trunnel/ed25519_cert.trunnel \
+ src/trunnel/pwbox.trunnel
+
TRUNNELSOURCES = \
- src/ext/trunnel/trunnel.c \
- src/trunnel/pwbox.c
+ src/ext/trunnel/trunnel.c \
+ src/trunnel/ed25519_cert.c \
+ src/trunnel/pwbox.c
TRUNNELHEADERS = \
- src/ext/trunnel/trunnel.h \
- src/ext/trunnel/trunnel-impl.h \
- src/trunnel/trunnel-local.h \
- src/trunnel/pwbox.h
+ src/ext/trunnel/trunnel.h \
+ src/ext/trunnel/trunnel-impl.h \
+ src/trunnel/trunnel-local.h \
+ src/trunnel/ed25519_cert.h \
+ src/trunnel/pwbox.h
src_trunnel_libor_trunnel_a_SOURCES = $(TRUNNELSOURCES)
src_trunnel_libor_trunnel_a_CPPFLAGS = -DTRUNNEL_LOCAL_H $(AM_CPPFLAGS)
1
0

[tor/master] Implement proposal 228: cross-certification with onion keys
by nickm@torproject.org 28 May '15
by nickm@torproject.org 28 May '15
28 May '15
commit efa21bb94188863e4ff5d8a288144cd93db00fe3
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Wed Oct 1 11:54:07 2014 -0400
Implement proposal 228: cross-certification with onion keys
Routers now use TAP and ntor onion keys to sign their identity keys,
and put these signatures in their descriptors. That allows other
parties to be confident that the onion keys are indeed controlled by
the router that generated the descriptor.
---
src/common/crypto.c | 16 +++---
src/common/crypto.h | 10 ++--
src/or/or.h | 5 ++
src/or/router.c | 72 +++++++++++++++++++++++++-
src/or/router.h | 4 +-
src/or/routerkeys.c | 87 +++++++++++++++++++++++++++++++
src/or/routerkeys.h | 16 ++++++
src/or/routerlist.c | 5 ++
src/or/routerlist.h | 7 ++-
src/or/routerparse.c | 122 ++++++++++++++++++++++++++++++++++----------
src/or/routerparse.h | 2 +-
src/or/torcert.h | 1 +
src/test/test_dir.c | 54 ++++++++++++++++----
src/test/test_routerkeys.c | 70 +++++++++++++++++++++++++
14 files changed, 417 insertions(+), 54 deletions(-)
diff --git a/src/common/crypto.c b/src/common/crypto.c
index 06631e1..05dc432 100644
--- a/src/common/crypto.c
+++ b/src/common/crypto.c
@@ -830,7 +830,7 @@ crypto_pk_public_exponent_ok(crypto_pk_t *env)
* Note that this may leak information about the keys through timing.
*/
int
-crypto_pk_cmp_keys(crypto_pk_t *a, crypto_pk_t *b)
+crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
{
int result;
char a_is_non_null = (a != NULL) && (a->key != NULL);
@@ -856,19 +856,19 @@ crypto_pk_cmp_keys(crypto_pk_t *a, crypto_pk_t *b)
* Note that this may leak information about the keys through timing.
*/
int
-crypto_pk_eq_keys(crypto_pk_t *a, crypto_pk_t *b)
+crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
{
return (crypto_pk_cmp_keys(a, b) == 0);
}
/** Return the size of the public key modulus in <b>env</b>, in bytes. */
size_t
-crypto_pk_keysize(crypto_pk_t *env)
+crypto_pk_keysize(const crypto_pk_t *env)
{
tor_assert(env);
tor_assert(env->key);
- return (size_t) RSA_size(env->key);
+ return (size_t) RSA_size((RSA*)env->key);
}
/** Return the size of the public key modulus of <b>env</b>, in bits. */
@@ -997,7 +997,7 @@ crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
* at least the length of the modulus of <b>env</b>.
*/
int
-crypto_pk_public_checksig(crypto_pk_t *env, char *to,
+crypto_pk_public_checksig(const crypto_pk_t *env, char *to,
size_t tolen,
const char *from, size_t fromlen)
{
@@ -1069,7 +1069,7 @@ crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
* at least the length of the modulus of <b>env</b>.
*/
int
-crypto_pk_private_sign(crypto_pk_t *env, char *to, size_t tolen,
+crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
const char *from, size_t fromlen)
{
int r;
@@ -1084,7 +1084,7 @@ crypto_pk_private_sign(crypto_pk_t *env, char *to, size_t tolen,
r = RSA_private_encrypt((int)fromlen,
(unsigned char*)from, (unsigned char*)to,
- env->key, RSA_PKCS1_PADDING);
+ (RSA*)env->key, RSA_PKCS1_PADDING);
if (r<0) {
crypto_log_errors(LOG_WARN, "generating RSA signature");
return -1;
@@ -1298,7 +1298,7 @@ crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
unsigned char *buf = NULL;
int len;
- len = i2d_RSAPublicKey(pk->key, &buf);
+ len = i2d_RSAPublicKey((RSA*)pk->key, &buf);
if (len < 0 || buf == NULL)
return -1;
if (crypto_digest(digest_out, (char*)buf, len) < 0) {
diff --git a/src/common/crypto.h b/src/common/crypto.h
index 5266197..15d1f6e 100644
--- a/src/common/crypto.h
+++ b/src/common/crypto.h
@@ -147,9 +147,9 @@ int crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
const char *fname);
int crypto_pk_check_key(crypto_pk_t *env);
-int crypto_pk_cmp_keys(crypto_pk_t *a, crypto_pk_t *b);
-int crypto_pk_eq_keys(crypto_pk_t *a, crypto_pk_t *b);
-size_t crypto_pk_keysize(crypto_pk_t *env);
+int crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b);
+int crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b);
+size_t crypto_pk_keysize(const crypto_pk_t *env);
int crypto_pk_num_bits(crypto_pk_t *env);
crypto_pk_t *crypto_pk_dup_key(crypto_pk_t *orig);
crypto_pk_t *crypto_pk_copy_full(crypto_pk_t *orig);
@@ -161,11 +161,11 @@ int crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
int crypto_pk_private_decrypt(crypto_pk_t *env, char *to, size_t tolen,
const char *from, size_t fromlen,
int padding, int warnOnFailure);
-int crypto_pk_public_checksig(crypto_pk_t *env, char *to, size_t tolen,
+int crypto_pk_public_checksig(const crypto_pk_t *env, char *to, size_t tolen,
const char *from, size_t fromlen);
int crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
size_t datalen, const char *sig, size_t siglen);
-int crypto_pk_private_sign(crypto_pk_t *env, char *to, size_t tolen,
+int crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
const char *from, size_t fromlen);
int crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
const char *from, size_t fromlen);
diff --git a/src/or/or.h b/src/or/or.h
index 437183e..d030189 100644
--- a/src/or/or.h
+++ b/src/or/or.h
@@ -2023,6 +2023,9 @@ typedef struct {
curve25519_public_key_t *onion_curve25519_pkey;
/** Certificate for ed25519 signing key */
struct tor_cert_st *signing_key_cert;
+ /** What's the earliest expiration time on all the certs in this
+ * routerinfo? */
+ time_t cert_expiration_time;
char *platform; /**< What software/operating system is this OR using? */
@@ -5043,6 +5046,8 @@ typedef enum was_router_added_t {
/* Router descriptor was rejected because it was older than
* OLD_ROUTER_DESC_MAX_AGE. */
ROUTER_WAS_TOO_OLD = -7, /* note contrast with 'NOT_NEW' */
+ /* DOCDOC */
+ ROUTER_CERTS_EXPIRED = -8
} was_router_added_t;
/********************************* routerparse.c ************************/
diff --git a/src/or/router.c b/src/or/router.c
index 6b2a238..2087a25 100644
--- a/src/or/router.c
+++ b/src/or/router.c
@@ -2000,6 +2000,8 @@ router_rebuild_descriptor(int force)
}
if (! (ri->cache_info.signed_descriptor_body =
router_dump_router_to_string(ri, get_server_identity_key(),
+ get_onion_key(),
+ get_current_curve25519_keypair(),
get_master_signing_keypair())) ) {
log_warn(LD_BUG, "Couldn't generate router descriptor.");
routerinfo_free(ri);
@@ -2306,7 +2308,9 @@ get_platform_str(char *platform, size_t len)
*/
char *
router_dump_router_to_string(routerinfo_t *router,
- crypto_pk_t *ident_key,
+ const crypto_pk_t *ident_key,
+ const crypto_pk_t *tap_key,
+ const curve25519_keypair_t *ntor_keypair,
const ed25519_keypair_t *signing_keypair)
{
char *address = NULL;
@@ -2325,6 +2329,8 @@ router_dump_router_to_string(routerinfo_t *router,
char *output = NULL;
const int emit_ed_sigs = signing_keypair && router->signing_key_cert;
char *ed_cert_line = NULL;
+ char *rsa_tap_cc_line = NULL;
+ char *ntor_cc_line = NULL;
/* Make sure the identity key matches the one in the routerinfo. */
if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
@@ -2377,6 +2383,67 @@ router_dump_router_to_string(routerinfo_t *router,
goto err;
}
+ /* Cross-certify with RSA key */
+ if (tap_key && router->signing_key_cert &&
+ router->signing_key_cert->signing_key_included) {
+ char buf[256];
+ int tap_cc_len = 0;
+ uint8_t *tap_cc =
+ make_tap_onion_key_crosscert(tap_key,
+ &router->signing_key_cert->signing_key,
+ router->identity_pkey,
+ &tap_cc_len);
+ if (!tap_cc) {
+ log_warn(LD_BUG,"make_tap_onion_key_crosscert failed!");
+ goto err;
+ }
+
+ if (base64_encode(buf, sizeof(buf), (const char*)tap_cc, tap_cc_len) < 0) {
+ log_warn(LD_BUG,"base64_encode(rsa_crosscert) failed!");
+ tor_free(tap_cc);
+ goto err;
+ }
+ tor_free(tap_cc);
+
+ tor_asprintf(&rsa_tap_cc_line,
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "%s"
+ "-----END CROSSCERT-----\n", buf);
+ }
+
+ /* Cross-certify with onion keys */
+ if (ntor_keypair && router->signing_key_cert &&
+ router->signing_key_cert->signing_key_included) {
+ int sign = 0;
+ char buf[256];
+ /* XXXX Base the expiration date on the actual onion key expiration time?*/
+ tor_cert_t *cert =
+ make_ntor_onion_key_crosscert(ntor_keypair,
+ &router->signing_key_cert->signing_key,
+ router->cache_info.published_on,
+ MIN_ONION_KEY_LIFETIME, &sign);
+ if (!cert) {
+ log_warn(LD_BUG,"make_ntor_onion_key_crosscert failed!");
+ goto err;
+ }
+ tor_assert(sign == 0 || sign == 1);
+
+ if (base64_encode(buf, sizeof(buf),
+ (const char*)cert->encoded, cert->encoded_len)<0) {
+ log_warn(LD_BUG,"base64_encode(ntor_crosscert) failed!");
+ tor_cert_free(cert);
+ goto err;
+ }
+ tor_cert_free(cert);
+
+ tor_asprintf(&ntor_cc_line,
+ "ntor-onion-key-crosscert %d\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "%s"
+ "-----END ED25519 CERT-----\n", sign, buf);
+ }
+
/* Encode the publication time. */
format_iso_time(published, router->cache_info.published_on);
@@ -2426,6 +2493,7 @@ router_dump_router_to_string(routerinfo_t *router,
"%s%s%s%s"
"onion-key\n%s"
"signing-key\n%s"
+ "%s%s"
"%s%s%s%s",
router->nickname,
address,
@@ -2446,6 +2514,8 @@ router_dump_router_to_string(routerinfo_t *router,
(options->DownloadExtraInfo || options->V3AuthoritativeDir) ?
"caches-extra-info\n" : "",
onion_pkey, identity_pkey,
+ rsa_tap_cc_line ? rsa_tap_cc_line : "",
+ ntor_cc_line ? ntor_cc_line : "",
family_line,
we_are_hibernating() ? "hibernating 1\n" : "",
options->HidServDirectoryV2 ? "hidden-service-dir\n" : "",
diff --git a/src/or/router.h b/src/or/router.h
index c53a104..cb813c6 100644
--- a/src/or/router.h
+++ b/src/or/router.h
@@ -91,7 +91,9 @@ int router_is_me(const routerinfo_t *router);
int router_pick_published_address(const or_options_t *options, uint32_t *addr);
int router_rebuild_descriptor(int force);
char *router_dump_router_to_string(routerinfo_t *router,
- crypto_pk_t *ident_key,
+ const crypto_pk_t *ident_key,
+ const crypto_pk_t *tap_key,
+ const curve25519_keypair_t *ntor_keypair,
const ed25519_keypair_t *signing_keypair);
char *router_dump_exit_policy_to_string(const routerinfo_t *router,
int include_ipv4,
diff --git a/src/or/routerkeys.c b/src/or/routerkeys.c
index 6609d89..9ad5a89 100644
--- a/src/or/routerkeys.c
+++ b/src/or/routerkeys.c
@@ -435,6 +435,93 @@ get_current_auth_key_cert(void)
return auth_key_cert;
}
+/** Construct cross-certification for the master identity key with
+ * the ntor onion key. Store the sign of the corresponding ed25519 public key
+ * in *<b>sign_out</b>. */
+tor_cert_t *
+make_ntor_onion_key_crosscert(const curve25519_keypair_t *onion_key,
+ const ed25519_public_key_t *master_id_key, time_t now, time_t lifetime,
+ int *sign_out)
+{
+ tor_cert_t *cert = NULL;
+ ed25519_keypair_t ed_onion_key;
+
+ if (ed25519_keypair_from_curve25519_keypair(&ed_onion_key, sign_out,
+ onion_key) < 0)
+ goto end;
+
+ cert = tor_cert_create(&ed_onion_key, CERT_TYPE_ONION_ID, master_id_key,
+ now, lifetime, 0);
+
+ end:
+ memwipe(&ed_onion_key, 0, sizeof(ed_onion_key));
+ return cert;
+}
+
+/** Construct and return an RSA signature for the TAP onion key to
+ * cross-certify the RSA and Ed25519 identity keys. Set <b>len_out</b> to its
+ * length. */
+uint8_t *
+make_tap_onion_key_crosscert(const crypto_pk_t *onion_key,
+ const ed25519_public_key_t *master_id_key,
+ const crypto_pk_t *rsa_id_key,
+ int *len_out)
+{
+ uint8_t signature[PK_BYTES];
+ uint8_t signed_data[DIGEST_LEN + ED25519_PUBKEY_LEN];
+
+ *len_out = 0;
+ crypto_pk_get_digest(rsa_id_key, (char*)signed_data);
+ memcpy(signed_data + DIGEST_LEN, master_id_key->pubkey, ED25519_PUBKEY_LEN);
+
+ int r = crypto_pk_private_sign(onion_key,
+ (char*)signature, sizeof(signature),
+ (const char*)signed_data, sizeof(signed_data));
+ if (r < 0)
+ return NULL;
+
+ *len_out = r;
+
+ return tor_memdup(signature, r);
+}
+
+/** Check whether an RSA-TAP cross-certification is correct. Return 0 if it
+ * is, -1 if it isn't. */
+int
+check_tap_onion_key_crosscert(const uint8_t *crosscert,
+ int crosscert_len,
+ const crypto_pk_t *onion_pkey,
+ const ed25519_public_key_t *master_id_pkey,
+ const uint8_t *rsa_id_digest)
+{
+ uint8_t *cc = tor_malloc(crypto_pk_keysize(onion_pkey));
+ int cc_len =
+ crypto_pk_public_checksig(onion_pkey,
+ (char*)cc,
+ crypto_pk_keysize(onion_pkey),
+ (const char*)crosscert,
+ crosscert_len);
+ if (cc_len < 0) {
+ goto err;
+ }
+ if (cc_len < DIGEST_LEN + ED25519_PUBKEY_LEN) {
+ log_warn(LD_DIR, "Short signature on cross-certification with TAP key");
+ goto err;
+ }
+ if (tor_memneq(cc, rsa_id_digest, DIGEST_LEN) ||
+ tor_memneq(cc + DIGEST_LEN, master_id_pkey->pubkey,
+ ED25519_PUBKEY_LEN)) {
+ log_warn(LD_DIR, "Incorrect cross-certification with TAP key");
+ goto err;
+ }
+
+ tor_free(cc);
+ return 0;
+ err:
+ tor_free(cc);
+ return -1;
+}
+
void
routerkeys_free_all(void)
{
diff --git a/src/or/routerkeys.h b/src/or/routerkeys.h
index eb21401..5e2ef45 100644
--- a/src/or/routerkeys.h
+++ b/src/or/routerkeys.h
@@ -37,6 +37,22 @@ const ed25519_keypair_t *get_current_auth_keypair(void);
const struct tor_cert_st *get_current_link_key_cert(void);
const struct tor_cert_st *get_current_auth_key_cert(void);
+struct tor_cert_st *make_ntor_onion_key_crosscert(
+ const curve25519_keypair_t *onion_key,
+ const ed25519_public_key_t *master_id_key,
+ time_t now, time_t lifetime,
+ int *sign_out);
+uint8_t *make_tap_onion_key_crosscert(const crypto_pk_t *onion_key,
+ const ed25519_public_key_t *master_id_key,
+ const crypto_pk_t *rsa_id_key,
+ int *len_out);
+
+int check_tap_onion_key_crosscert(const uint8_t *crosscert,
+ int crosscert_len,
+ const crypto_pk_t *onion_pkey,
+ const ed25519_public_key_t *master_id_pkey,
+ const uint8_t *rsa_id_digest);
+
int load_ed_keys(const or_options_t *options, time_t now);
void routerkeys_free_all(void);
diff --git a/src/or/routerlist.c b/src/or/routerlist.c
index 069f70d..dbb93e4 100644
--- a/src/or/routerlist.c
+++ b/src/or/routerlist.c
@@ -3294,6 +3294,11 @@ router_add_to_routerlist(routerinfo_t *router, const char **msg,
old_router = router_get_mutable_by_digest(id_digest);
+ /* Make sure that it isn't expired. */
+ if (router->cert_expiration_time < approx_time()) {
+ return ROUTER_CERTS_EXPIRED;
+ }
+
/* Make sure that we haven't already got this exact descriptor. */
if (sdmap_get(routerlist->desc_digest_map,
router->cache_info.signed_descriptor_digest)) {
diff --git a/src/or/routerlist.h b/src/or/routerlist.h
index 78c3fbb..200533f 100644
--- a/src/or/routerlist.h
+++ b/src/or/routerlist.h
@@ -118,13 +118,15 @@ WRA_WAS_ADDED(was_router_added_t s) {
* - not in the consensus
* - neither in the consensus nor in any networkstatus document
* - it was outdated.
+ * - its certificates were expired.
*/
static INLINE int WRA_WAS_OUTDATED(was_router_added_t s)
{
return (s == ROUTER_WAS_TOO_OLD ||
s == ROUTER_IS_ALREADY_KNOWN ||
s == ROUTER_NOT_IN_CONSENSUS ||
- s == ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS);
+ s == ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS ||
+ s == ROUTER_CERTS_EXPIRED);
}
/** Return true iff the outcome code in <b>s</b> indicates that the descriptor
* was flat-out rejected. */
@@ -138,7 +140,8 @@ static INLINE int WRA_NEVER_DOWNLOADABLE(was_router_added_t s)
{
return (s == ROUTER_AUTHDIR_REJECTS ||
s == ROUTER_BAD_EI ||
- s == ROUTER_WAS_TOO_OLD);
+ s == ROUTER_WAS_TOO_OLD ||
+ s == ROUTER_CERTS_EXPIRED);
}
was_router_added_t router_add_to_routerlist(routerinfo_t *router,
const char **msg,
diff --git a/src/or/routerparse.c b/src/or/routerparse.c
index dbd6fdd..b3bb565 100644
--- a/src/or/routerparse.c
+++ b/src/or/routerparse.c
@@ -24,6 +24,7 @@
#include "microdesc.h"
#include "networkstatus.h"
#include "rephist.h"
+#include "routerkeys.h"
#include "routerparse.h"
#include "entrynodes.h"
#include "torcert.h"
@@ -87,6 +88,8 @@ typedef enum {
K_IPV6_POLICY,
K_ROUTER_SIG_ED25519,
K_IDENTITY_ED25519,
+ K_ONION_KEY_CROSSCERT,
+ K_NTOR_ONION_KEY_CROSSCERT,
K_DIRREQ_END,
K_DIRREQ_V2_IPS,
@@ -299,6 +302,9 @@ static token_rule_t routerdesc_token_table[] = {
T01("hidden-service-dir", K_HIDDEN_SERVICE_DIR, NO_ARGS, NO_OBJ ),
T01("identity-ed25519", K_IDENTITY_ED25519, NO_ARGS, NEED_OBJ ),
T01("router-sig-ed25519", K_ROUTER_SIG_ED25519, GE(1), NO_OBJ ),
+ T01("onion-key-crosscert", K_ONION_KEY_CROSSCERT, NO_ARGS, NEED_OBJ ),
+ T01("ntor-onion-key-crosscert", K_NTOR_ONION_KEY_CROSSCERT,
+ EQ(1), NEED_OBJ ),
T01("allow-single-hop-exits",K_ALLOW_SINGLE_HOP_EXITS, NO_ARGS, NO_OBJ ),
@@ -648,7 +654,7 @@ router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
char *
router_get_dirobj_signature(const char *digest,
size_t digest_len,
- crypto_pk_t *private_key)
+ const crypto_pk_t *private_key)
{
char *signature;
size_t i, keysize;
@@ -868,8 +874,8 @@ check_signature_token(const char *digest,
tor_free(signed_digest);
return -1;
}
-// log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
-// hex_str(signed_digest,4));
+ // log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
+ // hex_str(signed_digest,4));
if (tor_memneq(digest, signed_digest, digest_len)) {
log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
tor_free(signed_digest);
@@ -1116,6 +1122,7 @@ router_parse_entry_from_string(const char *s, const char *end,
size_t prepend_len = prepend_annotations ? strlen(prepend_annotations) : 0;
int ok = 1;
memarea_t *area = NULL;
+ tor_cert_t *ntor_cc_cert = NULL;
/* Do not set this to '1' until we have parsed everything that we intend to
* parse that's covered by the hash. */
int can_dl_again = 0;
@@ -1191,6 +1198,7 @@ router_parse_entry_from_string(const char *s, const char *end,
tor_assert(tok->n_args >= 5);
router = tor_malloc_zero(sizeof(routerinfo_t));
+ router->cert_expiration_time = TIME_MAX;
router->cache_info.routerlist_index = -1;
router->cache_info.annotations_len = s-start_of_annotations + prepend_len;
router->cache_info.signed_descriptor_len = end-s;
@@ -1313,16 +1321,30 @@ router_parse_entry_from_string(const char *s, const char *end,
tor_memdup(&k, sizeof(curve25519_public_key_t));
}
+ tok = find_by_keyword(tokens, K_SIGNING_KEY);
+ router->identity_pkey = tok->key;
+ tok->key = NULL; /* Prevent free */
+ if (crypto_pk_get_digest(router->identity_pkey,
+ router->cache_info.identity_digest)) {
+ log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
+ }
+
{
- directory_token_t *ed_sig_tok, *ed_cert_tok;
+ directory_token_t *ed_sig_tok, *ed_cert_tok, *cc_tap_tok, *cc_ntor_tok;
ed_sig_tok = find_opt_by_keyword(tokens, K_ROUTER_SIG_ED25519);
ed_cert_tok = find_opt_by_keyword(tokens, K_IDENTITY_ED25519);
- if (!ed_sig_tok != !ed_cert_tok) {
- log_warn(LD_DIR, "Router descriptor with only partial ed25519 support");
+ cc_tap_tok = find_opt_by_keyword(tokens, K_ONION_KEY_CROSSCERT);
+ cc_ntor_tok = find_opt_by_keyword(tokens, K_NTOR_ONION_KEY_CROSSCERT);
+ int n_ed_toks = !!ed_sig_tok + !!ed_cert_tok +
+ !!cc_tap_tok + !!cc_ntor_tok;
+ if ((n_ed_toks != 0 && n_ed_toks != 4) ||
+ (n_ed_toks == 4 && !router->onion_curve25519_pkey)) {
+ log_warn(LD_DIR, "Router descriptor with only partial ed25519/"
+ "cross-certification support");
goto err;
}
if (ed_sig_tok) {
- tor_assert(ed_cert_tok);
+ tor_assert(ed_cert_tok && cc_tap_tok && cc_ntor_tok);
if (ed_cert_tok != smartlist_get(tokens, 0) &&
ed_cert_tok != smartlist_get(tokens, 1)) {
log_warn(LD_DIR, "Ed25519 certificate in wrong position");
@@ -1336,10 +1358,25 @@ router_parse_entry_from_string(const char *s, const char *end,
log_warn(LD_DIR, "Wrong object type on identity-ed25519 in decriptor");
goto err;
}
+ if (strcmp(cc_ntor_tok->object_type, "ED25519 CERT")) {
+ log_warn(LD_DIR, "Wrong object type on ntor-onion-key-crosscert "
+ "in decriptor");
+ goto err;
+ }
+ if (strcmp(cc_tap_tok->object_type, "CROSSCERT")) {
+ log_warn(LD_DIR, "Wrong object type on onion-key-crosscert "
+ "in decriptor");
+ goto err;
+ }
+ if (strcmp(cc_ntor_tok->args[0], "0") &&
+ strcmp(cc_ntor_tok->args[0], "1")) {
+ log_warn(LD_DIR, "Bad sign bit on ntor-onion-key-crosscert");
+ goto err;
+ }
+ int ntor_cc_sign_bit = !strcmp(cc_ntor_tok->args[0], "1");
uint8_t d256[DIGEST256_LEN];
const char *signed_start, *signed_end;
-
tor_cert_t *cert = tor_cert_parse(
(const uint8_t*)ed_cert_tok->object_body,
ed_cert_tok->object_size);
@@ -1347,13 +1384,33 @@ router_parse_entry_from_string(const char *s, const char *end,
log_warn(LD_DIR, "Couldn't parse ed25519 cert");
goto err;
}
- router->signing_key_cert = cert;
+ router->signing_key_cert = cert; /* makes sure it gets freed. */
if (cert->cert_type != CERT_TYPE_ID_SIGNING ||
! cert->signing_key_included) {
log_warn(LD_DIR, "Invalid form for ed25519 cert");
goto err;
}
+ ntor_cc_cert = tor_cert_parse((const uint8_t*)cc_ntor_tok->object_body,
+ cc_ntor_tok->object_size);
+ if (!cc_ntor_tok) {
+ log_warn(LD_DIR, "Couldn't parse ntor-onion-key-crosscert cert");
+ goto err;
+ }
+ if (ntor_cc_cert->cert_type != CERT_TYPE_ONION_ID ||
+ ! ed25519_pubkey_eq(&ntor_cc_cert->signed_key, &cert->signing_key)) {
+ log_warn(LD_DIR, "Invalid contents for ntor-onion-key-crosscert cert");
+ goto err;
+ }
+
+ ed25519_public_key_t ntor_cc_pk;
+ if (ed25519_public_key_from_curve25519_public_key(&ntor_cc_pk,
+ router->onion_curve25519_pkey,
+ ntor_cc_sign_bit)<0) {
+ log_warn(LD_DIR, "Error converting onion key to ed25519");
+ goto err;
+ }
+
if (router_get_hash_impl_helper(s, end-s, "router ",
"\nrouter-sig-ed25519",
' ', &signed_start, &signed_end) < 0) {
@@ -1367,38 +1424,48 @@ router_parse_entry_from_string(const char *s, const char *end,
crypto_digest_get_digest(d, (char*)d256, sizeof(d256));
crypto_digest_free(d);
- ed25519_checkable_t check[2];
- int check_ok[2];
+ ed25519_checkable_t check[3];
+ int check_ok[3];
if (tor_cert_get_checkable_sig(&check[0], cert, NULL) < 0) {
log_err(LD_BUG, "Couldn't create 'checkable' for cert.");
goto err;
}
- if (ed25519_signature_from_base64(&check[1].signature,
+ if (tor_cert_get_checkable_sig(&check[1],
+ ntor_cc_cert, &ntor_cc_pk) < 0) {
+ log_err(LD_BUG, "Couldn't create 'checkable' for ntor_cc_cert.");
+ goto err;
+ }
+
+ if (ed25519_signature_from_base64(&check[2].signature,
ed_sig_tok->args[0])<0) {
log_warn(LD_DIR, "Couldn't decode ed25519 signature");
goto err;
}
- check[1].pubkey = &cert->signed_key;
- check[1].msg = d256;
- check[1].len = DIGEST256_LEN;
+ check[2].pubkey = &cert->signed_key;
+ check[2].msg = d256;
+ check[2].len = DIGEST256_LEN;
- if (ed25519_checksig_batch(check_ok, check, 2) < 0) {
- log_warn(LD_DIR, "Incorrect ed25519 signatures");
+ if (ed25519_checksig_batch(check_ok, check, 3) < 0) {
+ log_warn(LD_DIR, "Incorrect ed25519 signature(s)");
goto err;
}
- if (cert->valid_until < time(NULL)) {
- log_warn(LD_DIR, "Expired ed25519 certificate in router descriptor");
+
+ if (check_tap_onion_key_crosscert(
+ (const uint8_t*)cc_tap_tok->object_body,
+ (int)cc_tap_tok->object_size,
+ router->onion_pkey,
+ &cert->signing_key,
+ (const uint8_t*)router->cache_info.identity_digest)<0) {
+ log_warn(LD_DIR, "Incorrect TAP cross-verification");
goto err;
}
- }
- }
- tok = find_by_keyword(tokens, K_SIGNING_KEY);
- router->identity_pkey = tok->key;
- tok->key = NULL; /* Prevent free */
- if (crypto_pk_get_digest(router->identity_pkey,
- router->cache_info.identity_digest)) {
- log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
+ /* We check this before adding it to the routerlist. */
+ if (cert->valid_until < ntor_cc_cert->valid_until)
+ router->cert_expiration_time = cert->valid_until;
+ else
+ router->cert_expiration_time = ntor_cc_cert->valid_until;
+ }
}
if ((tok = find_opt_by_keyword(tokens, K_FINGERPRINT))) {
@@ -1527,6 +1594,7 @@ router_parse_entry_from_string(const char *s, const char *end,
routerinfo_free(router);
router = NULL;
done:
+ tor_cert_free(ntor_cc_cert);
if (tokens) {
SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_clear(t));
smartlist_free(tokens);
diff --git a/src/or/routerparse.h b/src/or/routerparse.h
index 52e53a8..7776063 100644
--- a/src/or/routerparse.h
+++ b/src/or/routerparse.h
@@ -19,7 +19,7 @@ int router_get_extrainfo_hash(const char *s, size_t s_len, char *digest);
#define DIROBJ_MAX_SIG_LEN 256
char *router_get_dirobj_signature(const char *digest,
size_t digest_len,
- crypto_pk_t *private_key);
+ const crypto_pk_t *private_key);
int router_append_dirobj_signature(char *buf, size_t buf_len,
const char *digest,
size_t digest_len,
diff --git a/src/or/torcert.h b/src/or/torcert.h
index 644cbf8..ae9361f 100644
--- a/src/or/torcert.h
+++ b/src/or/torcert.h
@@ -11,6 +11,7 @@
#define CERT_TYPE_ID_SIGNING 0x04
#define CERT_TYPE_SIGNING_LINK 0x05
#define CERT_TYPE_SIGNING_AUTH 0x06
+#define CERT_TYPE_ONION_ID 0x0A
#define CERT_FLAG_INCLUDE_SIGNING_KEY 0x1
diff --git a/src/test/test_dir.c b/src/test/test_dir.c
index 85ca40f..d7b5e1b 100644
--- a/src/test/test_dir.c
+++ b/src/test/test_dir.c
@@ -21,6 +21,7 @@
#include "hibernate.h"
#include "networkstatus.h"
#include "router.h"
+#include "routerkeys.h"
#include "routerlist.h"
#include "routerparse.h"
#include "test.h"
@@ -89,6 +90,8 @@ test_dir_formats(void *arg)
routerinfo_t *rp1 = NULL, *rp2 = NULL;
addr_policy_t *ex1, *ex2;
routerlist_t *dir1 = NULL, *dir2 = NULL;
+ uint8_t *rsa_cc = NULL;
+ tor_cert_t *ntor_cc = NULL;
or_options_t *options = get_options_mutable();
const addr_policy_t *p;
time_t now = time(NULL);
@@ -152,8 +155,10 @@ test_dir_formats(void *arg)
r2->dir_port = 0;
r2->onion_pkey = crypto_pk_dup_key(pk2);
r2->onion_curve25519_pkey = tor_malloc_zero(sizeof(curve25519_public_key_t));
- curve25519_public_from_base64(r2->onion_curve25519_pkey,
- "skyinAnvardNostarsNomoonNowindormistsorsnow");
+ curve25519_keypair_t r2_onion_keypair;
+ curve25519_keypair_generate(&r2_onion_keypair, 0);
+ r2->onion_curve25519_pkey = tor_memdup(&r2_onion_keypair.pubkey,
+ sizeof(curve25519_public_key_t));
r2->identity_pkey = crypto_pk_dup_key(pk1);
r2->bandwidthrate = r2->bandwidthburst = r2->bandwidthcapacity = 3000;
r2->exit_policy = smartlist_new();
@@ -169,7 +174,7 @@ test_dir_formats(void *arg)
/* XXXX025 router_dump_to_string should really take this from ri.*/
options->ContactInfo = tor_strdup("Magri White "
"<magri(a)elsewhere.example.com>");
- buf = router_dump_router_to_string(r1, pk2, NULL);
+ buf = router_dump_router_to_string(r1, pk2, NULL, NULL, NULL);
tor_free(options->ContactInfo);
tt_assert(buf);
@@ -202,7 +207,7 @@ test_dir_formats(void *arg)
tt_str_op(buf,OP_EQ, buf2);
tor_free(buf);
- buf = router_dump_router_to_string(r1, pk2, NULL);
+ buf = router_dump_router_to_string(r1, pk2, NULL, NULL, NULL);
tt_assert(buf);
cp = buf;
rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL,NULL);
@@ -238,20 +243,49 @@ test_dir_formats(void *arg)
strlcat(buf2, pk2_str, sizeof(buf2));
strlcat(buf2, "signing-key\n", sizeof(buf2));
strlcat(buf2, pk1_str, sizeof(buf2));
+ int rsa_cc_len;
+ rsa_cc = make_tap_onion_key_crosscert(pk2,
+ &kp1.pubkey,
+ pk1,
+ &rsa_cc_len);
+ tt_assert(rsa_cc);
+ base64_encode(cert_buf, sizeof(cert_buf), (char*)rsa_cc, rsa_cc_len);
+ strlcat(buf2, "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n", sizeof(buf2));
+ strlcat(buf2, cert_buf, sizeof(buf2));
+ strlcat(buf2, "-----END CROSSCERT-----\n", sizeof(buf2));
+ int ntor_cc_sign;
+ ntor_cc = make_ntor_onion_key_crosscert(&r2_onion_keypair,
+ &kp1.pubkey,
+ r2->cache_info.published_on,
+ MIN_ONION_KEY_LIFETIME,
+ &ntor_cc_sign);
+ tt_assert(ntor_cc);
+ base64_encode(cert_buf, sizeof(cert_buf),
+ (char*)ntor_cc->encoded, ntor_cc->encoded_len);
+ tor_snprintf(buf2+strlen(buf2), sizeof(buf2)-strlen(buf2),
+ "ntor-onion-key-crosscert %d\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "%s"
+ "-----END ED25519 CERT-----\n", ntor_cc_sign, cert_buf);
+
strlcat(buf2, "hidden-service-dir\n", sizeof(buf2));
- strlcat(buf2, "ntor-onion-key "
- "skyinAnvardNostarsNomoonNowindormistsorsnow=\n", sizeof(buf2));
+ strlcat(buf2, "ntor-onion-key ", sizeof(buf2));
+ base64_encode(cert_buf, sizeof(cert_buf),
+ (const char*)r2_onion_keypair.pubkey.public_key, 32);
+ strlcat(buf2, cert_buf, sizeof(buf2));
strlcat(buf2, "accept *:80\nreject 18.0.0.0/8:24\n", sizeof(buf2));
strlcat(buf2, "router-sig-ed25519 ", sizeof(buf2));
- buf = router_dump_router_to_string(r2, pk1, &kp2);
+ buf = router_dump_router_to_string(r2, pk1, pk2, &r2_onion_keypair, &kp2);
tt_assert(buf);
buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
* twice */
- tt_str_op(buf,OP_EQ, buf2);
+
+ tt_str_op(buf, OP_EQ, buf2);
tor_free(buf);
- buf = router_dump_router_to_string(r2, pk1, NULL);
+ buf = router_dump_router_to_string(r2, pk1, NULL, NULL, NULL);
cp = buf;
rp2 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL,NULL);
tt_assert(rp2);
@@ -304,6 +338,7 @@ test_dir_formats(void *arg)
if (rp2)
routerinfo_free(rp2);
+ tor_free(rsa_cc);
tor_free(buf);
tor_free(pk1_str);
tor_free(pk2_str);
@@ -1418,6 +1453,7 @@ generate_ri_from_rs(const vote_routerstatus_t *vrs)
static time_t published = 0;
r = tor_malloc_zero(sizeof(routerinfo_t));
+ r->cert_expiration_time = TIME_MAX;
memcpy(r->cache_info.identity_digest, rs->identity_digest, DIGEST_LEN);
memcpy(r->cache_info.signed_descriptor_digest, rs->descriptor_digest,
DIGEST_LEN);
diff --git a/src/test/test_routerkeys.c b/src/test/test_routerkeys.c
index 8780213..2434255 100644
--- a/src/test/test_routerkeys.c
+++ b/src/test/test_routerkeys.c
@@ -514,6 +514,74 @@ test_routerkeys_ed_keys_init_all(void *arg)
routerkeys_free_all();
}
+static void
+test_routerkeys_cross_certify_ntor(void *args)
+{
+ (void) args;
+
+ tor_cert_t *cert = NULL;
+ curve25519_keypair_t onion_keys;
+ ed25519_public_key_t master_key;
+ ed25519_public_key_t onion_check_key;
+ time_t now = time(NULL);
+ int sign;
+
+ tt_int_op(0, ==, ed25519_public_from_base64(&master_key,
+ "IamwritingthesetestsOnARainyAfternoonin2014"));
+ tt_int_op(0, ==, curve25519_keypair_generate(&onion_keys, 0));
+ cert = make_ntor_onion_key_crosscert(&onion_keys,
+ &master_key,
+ now, 10000,
+ &sign);
+ tt_assert(cert);
+ tt_assert(sign == 0 || sign == 1);
+ tt_int_op(cert->cert_type, ==, CERT_TYPE_ONION_ID);
+ tt_int_op(1, ==, ed25519_pubkey_eq(&cert->signed_key, &master_key));
+ tt_int_op(0, ==, ed25519_public_key_from_curve25519_public_key(
+ &onion_check_key, &onion_keys.pubkey, sign));
+ tt_int_op(0, ==, tor_cert_checksig(cert, &onion_check_key, now));
+
+ done:
+ tor_cert_free(cert);
+}
+
+static void
+test_routerkeys_cross_certify_tap(void *args)
+{
+ (void)args;
+ uint8_t *cc = NULL;
+ int cc_len;
+ ed25519_public_key_t master_key;
+ crypto_pk_t *onion_key = pk_generate(2), *id_key = pk_generate(1);
+ char digest[20];
+ char buf[128];
+ int n;
+
+ tt_int_op(0, ==, ed25519_public_from_base64(&master_key,
+ "IAlreadyWroteTestsForRouterdescsUsingTheseX"));
+
+ cc = make_tap_onion_key_crosscert(onion_key,
+ &master_key,
+ id_key, &cc_len);
+ tt_assert(cc);
+ tt_assert(cc_len);
+
+ n = crypto_pk_public_checksig(onion_key, buf, sizeof(buf),
+ (char*)cc, cc_len);
+ tt_int_op(n,>,0);
+ tt_int_op(n,==,52);
+
+ crypto_pk_get_digest(id_key, digest);
+ tt_mem_op(buf,==,digest,20);
+ tt_mem_op(buf+20,==,master_key.pubkey,32);
+
+ tt_int_op(0, ==, check_tap_onion_key_crosscert(cc, cc_len,
+ onion_key, &master_key, (uint8_t*)digest));
+
+ done:
+ tor_free(cc);
+}
+
#define TEST(name, flags) \
{ #name , test_routerkeys_ ## name, (flags), NULL, NULL }
@@ -524,6 +592,8 @@ struct testcase_t routerkeys_tests[] = {
TEST(ed_key_init_basic, TT_FORK),
TEST(ed_key_init_split, TT_FORK),
TEST(ed_keys_init_all, TT_FORK),
+ TEST(cross_certify_ntor, 0),
+ TEST(cross_certify_tap, 0),
END_OF_TESTCASES
};
1
0

[tor/master] Tie key-pinning logic into directory authority operation
by nickm@torproject.org 28 May '15
by nickm@torproject.org 28 May '15
28 May '15
commit 592a43910706a67048c7d05e45d35dc79712820a
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Wed Oct 8 08:32:00 2014 -0400
Tie key-pinning logic into directory authority operation
With this patch:
* Authorities load the key-pinning log at startup.
* Authorities open a key-pinning log for writing at startup.
* Authorities reject any router with an ed25519 key where they have
previously seen that ed25519 key with a different RSA key, or vice
versa.
* Authorities warn about, but *do not* reject, RSA-only descriptors
when the RSA key has previously gone along with an Ed25519 key.
(We should make this a 'reject' too, but we can't do that until we're
sure there's no legit reason to downgrade to 0.2.5.)
---
src/or/dirserv.c | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
src/or/keypin.c | 28 ++++++++++++++++++++++++
src/or/keypin.h | 2 ++
src/or/main.c | 19 ++++++++++++++++
src/or/router.c | 3 ++-
5 files changed, 115 insertions(+), 1 deletion(-)
diff --git a/src/or/dirserv.c b/src/or/dirserv.c
index e5a5b54..f26a6bb 100644
--- a/src/or/dirserv.c
+++ b/src/or/dirserv.c
@@ -18,6 +18,7 @@
#include "dirserv.h"
#include "dirvote.h"
#include "hibernate.h"
+#include "keypin.h"
#include "microdesc.h"
#include "networkstatus.h"
#include "nodelist.h"
@@ -27,6 +28,7 @@
#include "routerlist.h"
#include "routerparse.h"
#include "routerset.h"
+#include "torcert.h"
/**
* \file dirserv.c
@@ -225,6 +227,16 @@ dirserv_load_fingerprint_file(void)
return 0;
}
+/* If this is set, then we don't allow routers that have advertised an Ed25519
+ * identity to stop doing so. This is going to be essential for good identity
+ * security: otherwise anybody who can attack RSA-1024 but not Ed25519 could
+ * just sign fake descriptors missing the Ed25519 key. But we won't actually
+ * be able to prevent that kind of thing until we're confident that there
+ * isn't actually a legit reason to downgrade to 0.2.5. So for now, we have
+ * to leave this #undef.
+ */
+#undef DISABLE_DISABLING_ED25519
+
/** Check whether <b>router</b> has a nickname/identity key combination that
* we recognize from the fingerprint list, or an IP we automatically act on
* according to our configuration. Return the appropriate router status.
@@ -243,6 +255,36 @@ dirserv_router_get_status(const routerinfo_t *router, const char **msg)
return FP_REJECT;
}
+ if (router->signing_key_cert) {
+ /* This has an ed25519 identity key. */
+ if (KEYPIN_MISMATCH ==
+ keypin_check((const uint8_t*)router->cache_info.identity_digest,
+ router->signing_key_cert->signing_key.pubkey)) {
+ if (msg) {
+ *msg = "Ed25519 identity key or RSA identity key has changed.";
+ }
+ log_warn(LD_DIR, "Router %s uploaded a descriptor with a Ed25519 key "
+ "but the <rsa,ed25519> keys don't match what they were before.",
+ router_describe(router));
+ return FP_REJECT;
+ }
+ } else {
+ /* No ed25519 key */
+ if (KEYPIN_MISMATCH == keypin_check_lone_rsa(
+ (const uint8_t*)router->cache_info.identity_digest)) {
+ log_warn(LD_DIR, "Router %s uploaded a descriptor with no Ed25519 key, "
+ "when we previously knew an Ed25519 for it. Ignoring for now, "
+ "since Tor 0.2.6 is under development.",
+ router_describe(router));
+#ifdef DISABLE_DISABLING_ED25519
+ if (msg) {
+ *msg = "Ed25519 identity key has disappeared.";
+ }
+ return FP_REJECT;
+#endif
+ }
+ }
+
return dirserv_get_status_impl(d, router->nickname,
router->addr, router->or_port,
router->platform, msg, 1);
@@ -578,6 +620,28 @@ dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
return ROUTER_IS_ALREADY_KNOWN;
}
+ /* Do keypinning again ... this time, to add the pin if appropriate */
+ int keypin_status;
+ if (ri->signing_key_cert) {
+ keypin_status = keypin_check_and_add(
+ (const uint8_t*)ri->cache_info.identity_digest,
+ ri->signing_key_cert->signing_key.pubkey);
+ } else {
+ keypin_status = keypin_check_lone_rsa(
+ (const uint8_t*)ri->cache_info.identity_digest);
+#ifndef DISABLE_DISABLING_ED25519
+ if (keypin_status == KEYPIN_MISMATCH)
+ keypin_status = KEYPIN_NOT_FOUND;
+#endif
+ }
+ if (keypin_status == KEYPIN_MISMATCH) {
+ log_info(LD_DIRSERV, "Dropping descriptor from %s (source: %s) because "
+ "its key did not match an older RSA/Ed25519 keypair",
+ router_describe(ri), source);
+ *msg = "Looks like your keypair does not match its older value.";
+ return ROUTER_AUTHDIR_REJECTS;
+ }
+
/* Make a copy of desc, since router_add_to_routerlist might free
* ri and its associated signed_descriptor_t. */
desc = tor_strndup(ri->cache_info.signed_descriptor_body, desclen);
diff --git a/src/or/keypin.c b/src/or/keypin.c
index 87e49cd..7b0c0c7 100644
--- a/src/or/keypin.c
+++ b/src/or/keypin.c
@@ -44,6 +44,9 @@
static int keypin_journal_append_entry(const uint8_t *rsa_id_digest,
const uint8_t *ed25519_id_key);
+static int keypin_check_and_add_impl(const uint8_t *rsa_id_digest,
+ const uint8_t *ed25519_id_key,
+ int do_not_add);
static HT_HEAD(rsamap, keypin_ent_st) the_rsa_map = HT_INITIALIZER();
static HT_HEAD(edmap, keypin_ent_st) the_ed_map = HT_INITIALIZER();
@@ -100,6 +103,28 @@ int
keypin_check_and_add(const uint8_t *rsa_id_digest,
const uint8_t *ed25519_id_key)
{
+ return keypin_check_and_add_impl(rsa_id_digest, ed25519_id_key, 0);
+}
+
+/**
+ * As keypin_check_and_add, but do not add. Return KEYPIN_NOT_FOUND if
+ * we would add.
+ */
+int
+keypin_check(const uint8_t *rsa_id_digest,
+ const uint8_t *ed25519_id_key)
+{
+ return keypin_check_and_add_impl(rsa_id_digest, ed25519_id_key, 1);
+}
+
+/**
+ * Helper: implements keypin_check and keypin_check_and_add.
+ */
+static int
+keypin_check_and_add_impl(const uint8_t *rsa_id_digest,
+ const uint8_t *ed25519_id_key,
+ int do_not_add)
+{
keypin_ent_t search, *ent;
memset(&search, 0, sizeof(search));
memcpy(search.rsa_id, rsa_id_digest, sizeof(search.rsa_id));
@@ -127,6 +152,9 @@ keypin_check_and_add(const uint8_t *rsa_id_digest,
}
/* Okay, this one is new to us. */
+ if (do_not_add)
+ return KEYPIN_NOT_FOUND;
+
ent = tor_memdup(&search, sizeof(search));
keypin_add_entry_to_map(ent);
keypin_journal_append_entry(rsa_id_digest, ed25519_id_key);
diff --git a/src/or/keypin.h b/src/or/keypin.h
index 16a0775..2a5b3f1 100644
--- a/src/or/keypin.h
+++ b/src/or/keypin.h
@@ -8,6 +8,8 @@
int keypin_check_and_add(const uint8_t *rsa_id_digest,
const uint8_t *ed25519_id_key);
+int keypin_check(const uint8_t *rsa_id_digest,
+ const uint8_t *ed25519_id_key);
int keypin_open_journal(const char *fname);
int keypin_close_journal(void);
diff --git a/src/or/main.c b/src/or/main.c
index 8b82a31..70d075f 100644
--- a/src/or/main.c
+++ b/src/or/main.c
@@ -37,6 +37,7 @@
#include "entrynodes.h"
#include "geoip.h"
#include "hibernate.h"
+#include "keypin.h"
#include "main.h"
#include "microdesc.h"
#include "networkstatus.h"
@@ -1998,6 +1999,23 @@ do_main_loop(void)
/* initialize the bootstrap status events to know we're starting up */
control_event_bootstrap(BOOTSTRAP_STATUS_STARTING, 0);
+ /* Initialize the keypinning log. */
+ if (authdir_mode_v3(get_options())) {
+ char *fname = get_datadir_fname("key-pinning-entries");
+ int r = 0;
+ if (keypin_load_journal(fname)<0) {
+ log_err(LD_DIR, "Error loading key-pinning journal: %s",strerror(errno));
+ r = -1;
+ }
+ if (keypin_open_journal(fname)<0) {
+ log_err(LD_DIR, "Error opening key-pinning journal: %s",strerror(errno));
+ r = -1;
+ }
+ tor_free(fname);
+ if (r)
+ return r;
+ }
+
if (trusted_dirs_reload_certs()) {
log_warn(LD_DIR,
"Couldn't load all cached v3 certificates. Starting anyway.");
@@ -2707,6 +2725,7 @@ tor_cleanup(void)
or_state_save(now);
if (authdir_mode_tests_reachability(options))
rep_hist_record_mtbf_data(now, 0);
+ keypin_close_journal();
}
#ifdef USE_DMALLOC
dmalloc_log_stats();
diff --git a/src/or/router.c b/src/or/router.c
index 97c2b83..242ec05 100644
--- a/src/or/router.c
+++ b/src/or/router.c
@@ -2343,7 +2343,8 @@ router_dump_router_to_string(routerinfo_t *router,
!ed25519_pubkey_eq(&router->signing_key_cert->signed_key,
&signing_keypair->pubkey)) {
log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
- "ed25519 key chain");
+ "ed25519 key chain %d",
+ router->signing_key_cert->signing_key_included);
goto err;
}
}
1
0

28 May '15
commit 24b720a984cc6c05ebc51d0c699a36119c518ee4
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Wed Oct 8 11:33:59 2014 -0400
Include ed25519 keys in microdescriptors.
---
src/or/dirvote.c | 19 +++++++--
src/or/dirvote.h | 6 ++-
src/or/microdesc.c | 1 +
src/or/or.h | 2 +
src/or/routerparse.c | 22 +++++++++++
src/test/test_microdesc.c | 93 +++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 138 insertions(+), 5 deletions(-)
diff --git a/src/or/dirvote.c b/src/or/dirvote.c
index 7a5154d..94b4e51 100644
--- a/src/or/dirvote.c
+++ b/src/or/dirvote.c
@@ -17,6 +17,7 @@
#include "routerlist.h"
#include "routerparse.h"
#include "entrynodes.h" /* needed for guardfraction methods */
+#include "torcert.h"
/**
* \file dirvote.c
@@ -3486,9 +3487,18 @@ dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
}
if (consensus_method >= MIN_METHOD_FOR_ID_HASH_IN_MD) {
- char idbuf[BASE64_DIGEST_LEN+1];
- digest_to_base64(idbuf, ri->cache_info.identity_digest);
- smartlist_add_asprintf(chunks, "id rsa1024 %s\n", idbuf);
+ char idbuf[ED25519_BASE64_LEN+1];
+ const char *keytype;
+ if (consensus_method >= MIN_METHOD_FOR_ED25519_ID_IN_MD &&
+ ri->signing_key_cert &&
+ ri->signing_key_cert->signing_key_included) {
+ keytype = "ed25519";
+ ed25519_public_to_base64(idbuf, &ri->signing_key_cert->signing_key);
+ } else {
+ keytype = "rsa1024";
+ digest_to_base64(idbuf, ri->cache_info.identity_digest);
+ }
+ smartlist_add_asprintf(chunks, "id %s %s\n", keytype, idbuf);
}
output = smartlist_join_strings(chunks, "", 0, NULL);
@@ -3561,7 +3571,8 @@ static const struct consensus_method_range_t {
{MIN_METHOD_FOR_A_LINES, MIN_METHOD_FOR_P6_LINES - 1},
{MIN_METHOD_FOR_P6_LINES, MIN_METHOD_FOR_NTOR_KEY - 1},
{MIN_METHOD_FOR_NTOR_KEY, MIN_METHOD_FOR_ID_HASH_IN_MD - 1},
- {MIN_METHOD_FOR_ID_HASH_IN_MD, MAX_SUPPORTED_CONSENSUS_METHOD},
+ {MIN_METHOD_FOR_ID_HASH_IN_MD, MIN_METHOD_FOR_ED25519_ID_IN_MD - 1},
+ {MIN_METHOD_FOR_ED25519_ID_IN_MD, MAX_SUPPORTED_CONSENSUS_METHOD},
{-1, -1}
};
diff --git a/src/or/dirvote.h b/src/or/dirvote.h
index 542563b..edd5751 100644
--- a/src/or/dirvote.h
+++ b/src/or/dirvote.h
@@ -55,7 +55,7 @@
#define MIN_SUPPORTED_CONSENSUS_METHOD 13
/** The highest consensus method that we currently support. */
-#define MAX_SUPPORTED_CONSENSUS_METHOD 20
+#define MAX_SUPPORTED_CONSENSUS_METHOD 21
/** Lowest consensus method where microdesc consensuses omit any entry
* with no microdesc. */
@@ -86,6 +86,10 @@
* GuardFraction information in microdescriptors. */
#define MIN_METHOD_FOR_GUARDFRACTION 20
+/** Lowest consensus method where authorities may include an "id" line for
+ * ed25519 identities in microdescriptors. */
+#define MIN_METHOD_FOR_ED25519_ID_IN_MD 21
+
/** Default bandwidth to clip unmeasured bandwidths to using method >=
* MIN_METHOD_TO_CLIP_UNMEASURED_BW. (This is not a consensus method; do not
* get confused with the above macros.) */
diff --git a/src/or/microdesc.c b/src/or/microdesc.c
index 0511e87..ee48f6a 100644
--- a/src/or/microdesc.c
+++ b/src/or/microdesc.c
@@ -738,6 +738,7 @@ microdesc_free_(microdesc_t *md, const char *fname, int lineno)
if (md->onion_pkey)
crypto_pk_free(md->onion_pkey);
tor_free(md->onion_curve25519_pkey);
+ tor_free(md->ed25519_identity_pkey);
if (md->body && md->saved_location != SAVED_IN_CACHE)
tor_free(md->body);
diff --git a/src/or/or.h b/src/or/or.h
index d030189..ba36ad8 100644
--- a/src/or/or.h
+++ b/src/or/or.h
@@ -2234,6 +2234,8 @@ typedef struct microdesc_t {
crypto_pk_t *onion_pkey;
/** As routerinfo_t.onion_curve25519_pkey */
curve25519_public_key_t *onion_curve25519_pkey;
+ /** Ed25519 identity key, if included. */
+ ed25519_public_key_t *ed25519_identity_pkey;
/** As routerinfo_t.ipv6_add */
tor_addr_t ipv6_addr;
/** As routerinfo_t.ipv6_orport */
diff --git a/src/or/routerparse.c b/src/or/routerparse.c
index 98104f4..e1bc295 100644
--- a/src/or/routerparse.c
+++ b/src/or/routerparse.c
@@ -72,6 +72,7 @@ typedef enum {
K_CLIENT_VERSIONS,
K_SERVER_VERSIONS,
K_OR_ADDRESS,
+ K_ID,
K_P,
K_P6,
K_R,
@@ -503,6 +504,7 @@ static token_rule_t networkstatus_detached_signature_token_table[] = {
static token_rule_t microdesc_token_table[] = {
T1_START("onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024),
T01("ntor-onion-key", K_ONION_KEY_NTOR, GE(1), NO_OBJ ),
+ T0N("id", K_ID, GE(2), NO_OBJ ),
T0N("a", K_A, GE(1), NO_OBJ ),
T01("family", K_FAMILY, ARGS, NO_OBJ ),
T01("p", K_P, CONCAT_ARGS, NO_OBJ ),
@@ -4372,6 +4374,26 @@ microdescs_parse_from_string(const char *s, const char *eos,
tor_memdup(&k, sizeof(curve25519_public_key_t));
}
+ smartlist_t *id_lines = find_all_by_keyword(tokens, K_ID);
+ if (id_lines) {
+ SMARTLIST_FOREACH_BEGIN(id_lines, directory_token_t *, t) {
+ tor_assert(t->n_args >= 2);
+ if (!strcmp(t->args[0], "ed25519")) {
+ if (md->ed25519_identity_pkey) {
+ log_warn(LD_DIR, "Extra ed25519 key in microdesc");
+ goto next;
+ }
+ ed25519_public_key_t k;
+ if (ed25519_public_from_base64(&k, t->args[1])<0) {
+ log_warn(LD_DIR, "Bogus ed25519 key in microdesc");
+ goto next;
+ }
+ md->ed25519_identity_pkey = tor_memdup(&k, sizeof(k));
+ }
+ } SMARTLIST_FOREACH_END(t);
+ smartlist_free(id_lines);
+ }
+
{
smartlist_t *a_lines = find_all_by_keyword(tokens, K_A);
if (a_lines) {
diff --git a/src/test/test_microdesc.c b/src/test/test_microdesc.c
index fb3df77..3c22e18 100644
--- a/src/test/test_microdesc.c
+++ b/src/test/test_microdesc.c
@@ -10,6 +10,7 @@
#include "networkstatus.h"
#include "routerlist.h"
#include "routerparse.h"
+#include "torcert.h"
#include "test.h"
@@ -335,6 +336,59 @@ static const char test_ri[] =
"t0xkIE39ss/EwmQr7iIgkdVH4oRIMsjYnFFJBG26nYY=\n"
"-----END SIGNATURE-----\n";
+static const char test_ri2[] =
+ "router test001a 127.0.0.1 5001 0 7001\n"
+ "identity-ed25519\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQQABf/FAf5iDuKCZP2VxnAaQWdklilAh6kaEeFX4z8261Yx2T1/AQAgBADCp8vO\n"
+ "B8K1F9g2DzwuwvVCnPFLSK1qknVqPpNucHLH9DY7fuIYogBAdz4zHv1qC7RKaMNG\n"
+ "Jux/tMO2tzPcm62Ky5PjClMQplKUOnZNQ+RIpA3wYCIfUDy/cQnY7XWgNQ0=\n"
+ "-----END ED25519 CERT-----\n"
+ "platform Tor 0.2.6.0-alpha-dev on Darwin\n"
+ "protocols Link 1 2 Circuit 1\n"
+ "published 2014-10-08 12:58:04\n"
+ "fingerprint B7E2 7F10 4213 C36F 13E7 E982 9182 845E 4959 97A0\n"
+ "uptime 0\n"
+ "bandwidth 1073741824 1073741824 0\n"
+ "extra-info-digest 568F27331B6D8C73E7024F1EF5D097B90DFC7CDB\n"
+ "caches-extra-info\n"
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL2R8EfubUcahxha4u02P4VAR0llQIMwFAmrHPjzcK7apcQgDOf2ovOA\n"
+ "+YQnJFxlpBmCoCZC6ssCi+9G0mqo650lFuTMP5I90BdtjotfzESfTykHLiChyvhd\n"
+ "l0dlqclb2SU/GKem/fLRXH16aNi72CdSUu/1slKs/70ILi34QixRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "signing-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAN8+78KUVlgHXdMMkYJxcwh1Zv2y+Gb5eWUyltUaQRajhrT9ij2T5JZs\n"
+ "M0g85xTcuM3jNVVpV79+33hiTohdC6UZ+Bk4USQ7WBFzRbVFSXoVKLBJFkCOIexg\n"
+ "SMGNd5WEDtHWrXl58mizmPFu1eG6ZxHzt7RuLSol5cwBvawXPNkFAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "onion-key-crosscert\n"
+ "-----BEGIN CROSSCERT-----\n"
+ "ETFDzU49bvNfoZnKK1j6JeBP2gDirgj6bBCgWpUYs663OO9ypbZRO0JwWANssKl6\n"
+ "oaq9vKTsKGRsaNnqnz/JGMhehymakjjNtqg7crWwsahe8+7Pw9GKmW+YjFtcOkUf\n"
+ "KfOn2bmKBa1FoJb4yW3oXzHcdlLSRuCciKqPn+Hky5o=\n"
+ "-----END CROSSCERT-----\n"
+ "ntor-onion-key-crosscert 0\n"
+ "-----BEGIN ED25519 CERT-----\n"
+ "AQoABf2dAcKny84HwrUX2DYPPC7C9UKc8UtIrWqSdWo+k25wcsf0AFohutG+xI06\n"
+ "Ef21c5Zl1j8Hw6DzHDjYyJevXLFuOneaL3zcH2Ldn4sjrG3kc5UuVvRfTvV120UO\n"
+ "xk4f5s5LGwY=\n"
+ "-----END ED25519 CERT-----\n"
+ "hidden-service-dir\n"
+ "contact auth1(a)test.test\n"
+ "ntor-onion-key hbxdRnfVUJJY7+KcT4E3Rs7/zuClbN3hJrjSBiEGMgI=\n"
+ "reject *:*\n"
+ "router-sig-ed25519 5aQXyTif7PExIuL2di37UvktmJECKnils2OWz2vDi"
+ "hFxi+5TTAAPxYkS5clhc/Pjvw34itfjGmTKFic/8httAQ\n"
+ "router-signature\n"
+ "-----BEGIN SIGNATURE-----\n"
+ "BaUB+aFPQbb3BwtdzKsKqV3+6cRlSqJF5bI3UTmwRoJk+Z5Pz+W5NWokNI0xArHM\n"
+ "T4T5FZCCP9350jXsUCIvzyIyktU6aVRCGFt76rFlo1OETpN8GWkMnQU0w18cxvgS\n"
+ "cf34GXHv61XReJF3AlzNHFpbrPOYmowmhrTULKyMqow=\n"
+ "-----END SIGNATURE-----\n";
+
static const char test_md_8[] =
"onion-key\n"
"-----BEGIN RSA PUBLIC KEY-----\n"
@@ -365,6 +419,26 @@ static const char test_md_18[] =
"p reject 25,119,135-139,445,563,1214,4661-4666,6346-6429,6699,6881-6999\n"
"id rsa1024 Cd47okjCHD83YGzThGBDptXs9Z4\n";
+static const char test_md2_18[] =
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL2R8EfubUcahxha4u02P4VAR0llQIMwFAmrHPjzcK7apcQgDOf2ovOA\n"
+ "+YQnJFxlpBmCoCZC6ssCi+9G0mqo650lFuTMP5I90BdtjotfzESfTykHLiChyvhd\n"
+ "l0dlqclb2SU/GKem/fLRXH16aNi72CdSUu/1slKs/70ILi34QixRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key hbxdRnfVUJJY7+KcT4E3Rs7/zuClbN3hJrjSBiEGMgI=\n"
+ "id rsa1024 t+J/EEITw28T5+mCkYKEXklZl6A\n";
+
+static const char test_md2_21[] =
+ "onion-key\n"
+ "-----BEGIN RSA PUBLIC KEY-----\n"
+ "MIGJAoGBAL2R8EfubUcahxha4u02P4VAR0llQIMwFAmrHPjzcK7apcQgDOf2ovOA\n"
+ "+YQnJFxlpBmCoCZC6ssCi+9G0mqo650lFuTMP5I90BdtjotfzESfTykHLiChyvhd\n"
+ "l0dlqclb2SU/GKem/fLRXH16aNi72CdSUu/1slKs/70ILi34QixRAgMBAAE=\n"
+ "-----END RSA PUBLIC KEY-----\n"
+ "ntor-onion-key hbxdRnfVUJJY7+KcT4E3Rs7/zuClbN3hJrjSBiEGMgI=\n"
+ "id ed25519 wqfLzgfCtRfYNg88LsL1QpzxS0itapJ1aj6TbnByx/Q\n";
+
static void
test_md_generate(void *arg)
{
@@ -391,6 +465,25 @@ test_md_generate(void *arg)
md = dirvote_create_microdescriptor(ri, 18);
tt_str_op(md->body, OP_EQ, test_md_18);
+ microdesc_free(md);
+ md = NULL;
+ md = dirvote_create_microdescriptor(ri, 21);
+ tt_str_op(md->body, ==, test_md_18);
+
+ ri = router_parse_entry_from_string(test_ri2, NULL, 0, 0, NULL, NULL);
+
+ microdesc_free(md);
+ md = NULL;
+ md = dirvote_create_microdescriptor(ri, 18);
+ tt_str_op(md->body, ==, test_md2_18);
+
+ microdesc_free(md);
+ md = NULL;
+ md = dirvote_create_microdescriptor(ri, 21);
+ tt_str_op(md->body, ==, test_md2_21);
+ tt_assert(ed25519_pubkey_eq(md->ed25519_identity_pkey,
+ &ri->signing_key_cert->signing_key));
+
done:
microdesc_free(md);
routerinfo_free(ri);
1
0

28 May '15
commit eacbe03c71a9ddc7c3745ef8da88580a60021201
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Thu Oct 2 15:34:23 2014 -0400
Key-pinning back-end for directory authorities.
This module implements a key-pinning mechanism to ensure that it's
safe to use RSA keys as identitifers even as we migrate to Ed25519
keys. It remembers, for every Ed25519 key we've seen, what the
associated Ed25519 key is. This way, if we see a different Ed25519
key with that RSA key, we'll know that there's a mismatch.
We persist these entries to disk using a simple format, where each
line has a base64-encoded RSA SHA1 hash, then a base64-endoded
Ed25519 key. Empty lines, misformed lines, and lines beginning with
a # are ignored. Lines beginning with @ are reserved for future
extensions.
---
src/or/include.am | 2 +
src/or/keypin.c | 391 ++++++++++++++++++++++++++++++++++++++++++++++++
src/or/keypin.h | 44 ++++++
src/test/include.am | 1 +
src/test/test.c | 2 +
src/test/test_keypin.c | 255 +++++++++++++++++++++++++++++++
6 files changed, 695 insertions(+)
diff --git a/src/or/include.am b/src/or/include.am
index a85b0dd..68f091b 100644
--- a/src/or/include.am
+++ b/src/or/include.am
@@ -53,6 +53,7 @@ LIBTOR_A_SOURCES = \
src/or/entrynodes.c \
src/or/ext_orport.c \
src/or/hibernate.c \
+ src/or/keypin.c \
src/or/main.c \
src/or/microdesc.c \
src/or/networkstatus.c \
@@ -161,6 +162,7 @@ ORHEADERS = \
src/or/geoip.h \
src/or/entrynodes.h \
src/or/hibernate.h \
+ src/or/keypin.h \
src/or/main.h \
src/or/microdesc.h \
src/or/networkstatus.h \
diff --git a/src/or/keypin.c b/src/or/keypin.c
new file mode 100644
index 0000000..87e49cd
--- /dev/null
+++ b/src/or/keypin.c
@@ -0,0 +1,391 @@
+/* Copyright (c) 2014, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#define KEYPIN_PRIVATE
+
+#include "orconfig.h"
+#include "compat.h"
+#include "crypto.h"
+#include "di_ops.h"
+#include "ht.h"
+#include "keypin.h"
+#include "siphash.h"
+#include "torint.h"
+#include "torlog.h"
+#include "util.h"
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#ifdef _WIN32
+#include <io.h>
+#endif
+
+/**
+ * @file keypin.c
+ * @brief Key-pinning for RSA and Ed25519 identity keys at directory
+ * authorities.
+ *
+ * This module implements a key-pinning mechanism to ensure that it's safe
+ * to use RSA keys as identitifers even as we migrate to Ed25519 keys. It
+ * remembers, for every Ed25519 key we've seen, what the associated Ed25519
+ * key is. This way, if we see a different Ed25519 key with that RSA key,
+ * we'll know that there's a mismatch.
+ *
+ * We persist these entries to disk using a simple format, where each line
+ * has a base64-encoded RSA SHA1 hash, then a base64-endoded Ed25519 key.
+ * Empty lines, misformed lines, and lines beginning with # are
+ * ignored. Lines beginning with @ are reserved for future extensions.
+ */
+
+static int keypin_journal_append_entry(const uint8_t *rsa_id_digest,
+ const uint8_t *ed25519_id_key);
+
+static HT_HEAD(rsamap, keypin_ent_st) the_rsa_map = HT_INITIALIZER();
+static HT_HEAD(edmap, keypin_ent_st) the_ed_map = HT_INITIALIZER();
+
+/** Hashtable helper: compare two keypin table entries and return true iff
+ * they have the same RSA key IDs. */
+static INLINE int
+keypin_ents_eq_rsa(const keypin_ent_t *a, const keypin_ent_t *b)
+{
+ return tor_memeq(a->rsa_id, b->rsa_id, sizeof(a->rsa_id));
+}
+
+/** Hashtable helper: hash a keypin table entries based on its RSA key ID */
+static INLINE unsigned
+keypin_ent_hash_rsa(const keypin_ent_t *a)
+{
+return (unsigned) siphash24g(a->rsa_id, sizeof(a->rsa_id));
+}
+
+/** Hashtable helper: compare two keypin table entries and return true iff
+ * they have the same ed25519 keys */
+static INLINE int
+keypin_ents_eq_ed(const keypin_ent_t *a, const keypin_ent_t *b)
+{
+ return tor_memeq(a->ed25519_key, b->ed25519_key, sizeof(a->ed25519_key));
+}
+
+/** Hashtable helper: hash a keypin table entries based on its ed25519 key */
+static INLINE unsigned
+keypin_ent_hash_ed(const keypin_ent_t *a)
+{
+return (unsigned) siphash24g(a->ed25519_key, sizeof(a->ed25519_key));
+}
+
+HT_PROTOTYPE(rsamap, keypin_ent_st, rsamap_node, keypin_ent_hash_rsa,
+ keypin_ents_eq_rsa);
+HT_GENERATE2(rsamap, keypin_ent_st, rsamap_node, keypin_ent_hash_rsa,
+ keypin_ents_eq_rsa, 0.6, tor_reallocarray, tor_free_);
+
+HT_PROTOTYPE(edmap, keypin_ent_st, edmap_node, keypin_ent_hash_ed,
+ keypin_ents_eq_ed);
+HT_GENERATE2(edmap, keypin_ent_st, edmap_node, keypin_ent_hash_ed,
+ keypin_ents_eq_ed, 0.6, tor_reallocarray, tor_free_);
+
+/**
+ * Check whether we already have an entry in the key pinning table for a
+ * router with RSA ID digest <b>rsa_id_digest</b> or for ed25519 key
+ * <b>ed25519_id_key</b>. If we have an entry that matches both keys,
+ * return KEYPIN_FOUND. If we find an entry that matches one key but
+ * not the other, return KEYPIN_MISMATCH. If we have no entry for either
+ * key, add such an entry to the table and return KEYPIN_ADDED.
+ */
+int
+keypin_check_and_add(const uint8_t *rsa_id_digest,
+ const uint8_t *ed25519_id_key)
+{
+ keypin_ent_t search, *ent;
+ memset(&search, 0, sizeof(search));
+ memcpy(search.rsa_id, rsa_id_digest, sizeof(search.rsa_id));
+ memcpy(search.ed25519_key, ed25519_id_key, sizeof(search.ed25519_key));
+
+ /* Search by RSA key digest first */
+ ent = HT_FIND(rsamap, &the_rsa_map, &search);
+ if (ent) {
+ tor_assert(fast_memeq(ent->rsa_id, rsa_id_digest, sizeof(ent->rsa_id)));
+ if (tor_memeq(ent->ed25519_key, ed25519_id_key,sizeof(ent->ed25519_key))) {
+ return KEYPIN_FOUND; /* Match on both keys. Great. */
+ } else {
+ return KEYPIN_MISMATCH; /* Found RSA with different Ed key */
+ }
+ }
+
+ /* See if we know a different RSA key for this ed key */
+ ent = HT_FIND(edmap, &the_ed_map, &search);
+ if (ent) {
+ /* If we got here, then the ed key matches and the RSA doesn't */
+ tor_assert(fast_memeq(ent->ed25519_key, ed25519_id_key,
+ sizeof(ent->ed25519_key)));
+ tor_assert(fast_memneq(ent->rsa_id, rsa_id_digest, sizeof(ent->rsa_id)));
+ return KEYPIN_MISMATCH;
+ }
+
+ /* Okay, this one is new to us. */
+ ent = tor_memdup(&search, sizeof(search));
+ keypin_add_entry_to_map(ent);
+ keypin_journal_append_entry(rsa_id_digest, ed25519_id_key);
+ return KEYPIN_ADDED;
+}
+
+/**
+ * Helper: add <b>ent</b> to the hash tables.
+ */
+MOCK_IMPL(STATIC void,
+keypin_add_entry_to_map, (keypin_ent_t *ent))
+{
+ HT_INSERT(rsamap, &the_rsa_map, ent);
+ HT_INSERT(edmap, &the_ed_map, ent);
+}
+
+/**
+ * Check whether we already have an entry in the key pinning table for a
+ * router with RSA ID digest <b>rsa_id_digest</b>. If we have no such entry,
+ * return KEYPIN_NOT_FOUND. If we find an entry that matches the RSA key but
+ * which has an ed25519 key, return KEYPIN_MISMATCH.
+ */
+int
+keypin_check_lone_rsa(const uint8_t *rsa_id_digest)
+{
+ keypin_ent_t search, *ent;
+ memset(&search, 0, sizeof(search));
+ memcpy(search.rsa_id, rsa_id_digest, sizeof(search.rsa_id));
+
+ /* Search by RSA key digest first */
+ ent = HT_FIND(rsamap, &the_rsa_map, &search);
+ if (ent) {
+ return KEYPIN_MISMATCH;
+ } else {
+ return KEYPIN_NOT_FOUND;
+ }
+}
+
+/** Open fd to the keypinning journal file. */
+static int keypin_journal_fd = -1;
+
+/** Open the key-pinning journal to append to <b>fname</b>. Return 0 on
+ * success, -1 on failure. */
+int
+keypin_open_journal(const char *fname)
+{
+ /* O_SYNC ??*/
+ int fd = tor_open_cloexec(fname, O_WRONLY|O_CREAT, 0600);
+ if (fd < 0)
+ goto err;
+
+ if (tor_fd_seekend(fd) < 0)
+ goto err;
+
+ /* Add a newline in case the last line was only partially written */
+ if (write(fd, "\n", 1) < 1)
+ goto err;
+
+ /* Add something about when we opened this file. */
+ char buf[80];
+ char tbuf[ISO_TIME_LEN+1];
+ format_iso_time(tbuf, approx_time());
+ tor_snprintf(buf, sizeof(buf), "@opened-at %s\n", tbuf);
+ if (write_all(fd, buf, strlen(buf), 0) < 0)
+ goto err;
+
+ keypin_journal_fd = fd;
+ return 0;
+ err:
+ if (fd >= 0)
+ close(fd);
+ return -1;
+}
+
+/** Close the keypinning journal file. */
+int
+keypin_close_journal(void)
+{
+ if (keypin_journal_fd >= 0)
+ close(keypin_journal_fd);
+ keypin_journal_fd = -1;
+ return 0;
+}
+
+/** Length of a keypinning journal line, including terminating newline. */
+#define JOURNAL_LINE_LEN (BASE64_DIGEST_LEN + BASE64_DIGEST256_LEN + 2)
+
+/** Add an entry to the keypinning journal to map <b>rsa_id_digest</b> and
+ * <b>ed25519_id_key</b>. */
+static int
+keypin_journal_append_entry(const uint8_t *rsa_id_digest,
+ const uint8_t *ed25519_id_key)
+{
+ if (keypin_journal_fd == -1)
+ return -1;
+ char line[JOURNAL_LINE_LEN];
+ digest_to_base64(line, (const char*)rsa_id_digest);
+ line[BASE64_DIGEST_LEN] = ' ';
+ digest256_to_base64(line + BASE64_DIGEST_LEN + 1,
+ (const char*)ed25519_id_key);
+ line[BASE64_DIGEST_LEN+1+BASE64_DIGEST256_LEN] = '\n';
+
+ if (write_all(keypin_journal_fd, line, JOURNAL_LINE_LEN, 0)<0) {
+ log_warn(LD_DIRSERV, "Error while adding a line to the key-pinning "
+ "journal: %s", strerror(errno));
+ keypin_close_journal();
+ return -1;
+ }
+
+ return 0;
+}
+
+/** Load a journal from the <b>size</b>-byte region at <b>data</b>. Return 0
+ * on success, -1 on failure. */
+STATIC int
+keypin_load_journal_impl(const char *data, size_t size)
+{
+ const char *start = data, *end = data + size, *next;
+
+ int n_corrupt_lines = 0;
+ int n_entries = 0;
+ int n_duplicates = 0;
+ int n_conflicts = 0;
+
+ for (const char *cp = start; cp < end; cp = next) {
+ const char *eol = memchr(cp, '\n', end-cp);
+ const char *eos = eol ? eol : end;
+ const size_t len = eos - cp;
+
+ next = eol ? eol + 1 : end;
+
+ if (len == 0) {
+ continue;
+ }
+
+ if (*cp == '@') {
+ /* Lines that start with @ are reserved. Ignore for now. */
+ continue;
+ }
+ if (*cp == '#') {
+ /* Lines that start with # are comments. */
+ continue;
+ }
+
+ /* Is it the right length? (The -1 here is for the newline.) */
+ if (len != JOURNAL_LINE_LEN - 1) {
+ /* Lines with a bad length are corrupt unless they are empty.
+ * Ignore them either way */
+ for (const char *s = cp; s < eos; ++s) {
+ if (! TOR_ISSPACE(*s)) {
+ ++n_corrupt_lines;
+ break;
+ }
+ }
+ continue;
+ }
+
+ keypin_ent_t *ent = keypin_parse_journal_line(cp);
+
+ if (ent == NULL) {
+ ++n_corrupt_lines;
+ continue;
+ }
+
+ const keypin_ent_t *ent2;
+ if ((ent2 = HT_FIND(rsamap, &the_rsa_map, ent))) {
+ if (fast_memeq(ent2->ed25519_key, ent->ed25519_key, DIGEST256_LEN)) {
+ ++n_duplicates;
+ } else {
+ ++n_conflicts;
+ }
+ tor_free(ent);
+ continue;
+ } else if (HT_FIND(edmap, &the_ed_map, ent)) {
+ tor_free(ent);
+ ++n_conflicts;
+ continue;
+ }
+
+ keypin_add_entry_to_map(ent);
+ ++n_entries;
+ }
+
+ int severity = (n_corrupt_lines || n_duplicates) ? LOG_WARN : LOG_INFO;
+ tor_log(severity, LD_DIRSERV,
+ "Loaded %d entries from keypin journal. "
+ "Found %d corrupt lines, %d duplicates, and %d conflicts.",
+ n_entries, n_corrupt_lines, n_duplicates, n_conflicts);
+
+ return 0;
+}
+
+/**
+ * Load a journal from the file called <b>fname</b>. Return 0 on success,
+ * -1 on failure.
+ */
+int
+keypin_load_journal(const char *fname)
+{
+ tor_mmap_t *map = tor_mmap_file(fname);
+ if (!map) {
+ if (errno == ENOENT)
+ return 0;
+ else
+ return -1;
+ }
+ int r = keypin_load_journal_impl(map->data, map->size);
+ tor_munmap_file(map);
+ return r;
+}
+
+/** Parse a single keypinning journal line entry from <b>cp</b>. The input
+ * does not need to be NUL-terminated, but it <em>does</em> need to have
+ * KEYPIN_JOURNAL_LINE_LEN -1 bytes available to read. Return a new entry
+ * on success, and NULL on failure.
+ */
+STATIC keypin_ent_t *
+keypin_parse_journal_line(const char *cp)
+{
+ /* XXXX assumes !USE_OPENSSL_BASE64 */
+ keypin_ent_t *ent = tor_malloc_zero(sizeof(keypin_ent_t));
+
+ if (base64_decode((char*)ent->rsa_id, sizeof(ent->rsa_id),
+ cp, BASE64_DIGEST_LEN) != DIGEST_LEN ||
+ cp[BASE64_DIGEST_LEN] != ' ' ||
+ base64_decode((char*)ent->ed25519_key, sizeof(ent->ed25519_key),
+ cp+BASE64_DIGEST_LEN+1, BASE64_DIGEST256_LEN) != DIGEST256_LEN) {
+ tor_free(ent);
+ return NULL;
+ } else {
+ return ent;
+ }
+}
+
+/** Remove all entries from the keypinning table.*/
+void
+keypin_clear(void)
+{
+ int bad_entries = 0;
+ {
+ keypin_ent_t **ent, **next, *this;
+ for (ent = HT_START(rsamap, &the_rsa_map); ent != NULL; ent = next) {
+ this = *ent;
+ next = HT_NEXT_RMV(rsamap, &the_rsa_map, ent);
+
+ keypin_ent_t *other_ent = HT_REMOVE(edmap, &the_ed_map, this);
+ bad_entries += (other_ent != this);
+
+ tor_free(this);
+ }
+ }
+ bad_entries += HT_SIZE(&the_ed_map);
+
+ HT_CLEAR(edmap,&the_ed_map);
+ HT_CLEAR(rsamap,&the_rsa_map);
+
+ if (bad_entries) {
+ log_warn(LD_BUG, "Found %d discrepencies in the the keypin database.",
+ bad_entries);
+ }
+}
+
diff --git a/src/or/keypin.h b/src/or/keypin.h
new file mode 100644
index 0000000..16a0775
--- /dev/null
+++ b/src/or/keypin.h
@@ -0,0 +1,44 @@
+/* Copyright (c) 2014, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#ifndef TOR_KEYPIN_H
+#define TOR_KEYPIN_H
+
+#include "testsupport.h"
+
+int keypin_check_and_add(const uint8_t *rsa_id_digest,
+ const uint8_t *ed25519_id_key);
+
+int keypin_open_journal(const char *fname);
+int keypin_close_journal(void);
+int keypin_load_journal(const char *fname);
+void keypin_clear(void);
+int keypin_check_lone_rsa(const uint8_t *rsa_id_digest);
+
+#define KEYPIN_FOUND 0
+#define KEYPIN_ADDED 1
+#define KEYPIN_MISMATCH -1
+#define KEYPIN_NOT_FOUND -2
+
+#ifdef KEYPIN_PRIVATE
+
+/**
+ * In-memory representation of a key-pinning table entry.
+ */
+typedef struct keypin_ent_st {
+ HT_ENTRY(keypin_ent_st) rsamap_node;
+ HT_ENTRY(keypin_ent_st) edmap_node;
+ /** SHA1 hash of the RSA key */
+ uint8_t rsa_id[DIGEST_LEN];
+ /** Ed2219 key. */
+ uint8_t ed25519_key[DIGEST256_LEN];
+} keypin_ent_t;
+
+STATIC keypin_ent_t * keypin_parse_journal_line(const char *cp);
+STATIC int keypin_load_journal_impl(const char *data, size_t size);
+
+MOCK_DECL(STATIC void, keypin_add_entry_to_map, (keypin_ent_t *ent));
+#endif
+
+#endif
+
diff --git a/src/test/include.am b/src/test/include.am
index 44f63a7..b433fc5 100644
--- a/src/test/include.am
+++ b/src/test/include.am
@@ -44,6 +44,7 @@ src_test_test_SOURCES = \
src/test/test_extorport.c \
src/test/test_hs.c \
src/test/test_introduce.c \
+ src/test/test_keypin.c \
src/test/test_logging.c \
src/test/test_microdesc.c \
src/test/test_nodelist.c \
diff --git a/src/test/test.c b/src/test/test.c
index 0524a69..cd8aa3f 100644
--- a/src/test/test.c
+++ b/src/test/test.c
@@ -1136,6 +1136,7 @@ extern struct testcase_t guardfraction_tests[];
extern struct testcase_t extorport_tests[];
extern struct testcase_t hs_tests[];
extern struct testcase_t introduce_tests[];
+extern struct testcase_t keypin_tests[];
extern struct testcase_t logging_tests[];
extern struct testcase_t microdesc_tests[];
extern struct testcase_t nodelist_tests[];
@@ -1181,6 +1182,7 @@ struct testgroup_t testgroups[] = {
{ "extorport/", extorport_tests },
{ "hs/", hs_tests },
{ "introduce/", introduce_tests },
+ { "keypin/", keypin_tests },
{ "nodelist/", nodelist_tests },
{ "oom/", oom_tests },
{ "options/", options_tests },
diff --git a/src/test/test_keypin.c b/src/test/test_keypin.c
new file mode 100644
index 0000000..afd4ca2
--- /dev/null
+++ b/src/test/test_keypin.c
@@ -0,0 +1,255 @@
+/* Copyright (c) 2014, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+#define KEYPIN_PRIVATE
+#include "or.h"
+#include "keypin.h"
+#include "util.h"
+
+#include "test.h"
+
+static void
+test_keypin_parse_line(void *arg)
+{
+ (void)arg;
+ keypin_ent_t *ent = NULL;
+
+ /* Good line */
+ ent = keypin_parse_journal_line(
+ "aGVyZSBpcyBhIGdvb2Qgc2hhMSE "
+ "VGhpcyBlZDI1NTE5IHNjb2ZmcyBhdCB0aGUgc2hhMS4");
+ tt_assert(ent);
+ tt_mem_op(ent->rsa_id, ==, "here is a good sha1!", 20);
+ tt_mem_op(ent->ed25519_key, ==, "This ed25519 scoffs at the sha1.", 32);
+ tor_free(ent); ent = NULL;
+
+ /* Good line with extra stuff we will ignore. */
+ ent = keypin_parse_journal_line(
+ "aGVyZSBpcyBhIGdvb2Qgc2hhMSE "
+ "VGhpcyBlZDI1NTE5IHNjb2ZmcyBhdCB0aGUgc2hhMS4helloworld");
+ tt_assert(ent);
+ tt_mem_op(ent->rsa_id, ==, "here is a good sha1!", 20);
+ tt_mem_op(ent->ed25519_key, ==, "This ed25519 scoffs at the sha1.", 32);
+ tor_free(ent); ent = NULL;
+
+ /* Bad line: no space in the middle. */
+ ent = keypin_parse_journal_line(
+ "aGVyZSBpcyBhIGdvb2Qgc2hhMSE?"
+ "VGhpcyBlZDI1NTE5IHNjb2ZmcyBhdCB0aGUgc2hhMS4");
+ tt_assert(! ent);
+
+ /* Bad line: bad base64 in RSA ID */
+ ent = keypin_parse_journal_line(
+ "aGVyZSBpcyBhIGdv!2Qgc2hhMSE "
+ "VGhpcyBlZDI1NTE5IHNjb2ZmcyBhdCB0aGUgc2hhMS4");
+ tt_assert(! ent);
+
+ /* Bad line: bad base64 in Ed25519 */
+ ent = keypin_parse_journal_line(
+ "aGVyZSBpcyBhIGdvb2Qgc2hhMSE "
+ "VGhpcyBlZDI1NTE5IHNjb2ZmcyB!dCB0aGUgc2hhMS4");
+ tt_assert(! ent);
+
+ done:
+ tor_free(ent);
+}
+
+static smartlist_t *mock_addent_got = NULL;
+static void
+mock_addent(keypin_ent_t *ent)
+{
+ smartlist_add(mock_addent_got, ent);
+ keypin_add_entry_to_map__real(ent);
+}
+
+static void
+test_keypin_parse_file(void *arg)
+{
+ (void)arg;
+
+ mock_addent_got = smartlist_new();
+ MOCK(keypin_add_entry_to_map, mock_addent);
+
+ /* Simple, minimal, correct example. */
+ const char data1[] =
+"PT09PT09PT09PT09PT09PT09PT0 PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0\n"
+"TG9yYXggaXBzdW0gZ3J1dnZ1bHU cyB0aG5lZWQgYW1ldCwgc25lcmdlbGx5IG9uY2UtbGU\n"
+"ciBsZXJraW0sIHNlZCBkbyBiYXI YmFsb290IHRlbXBvciBnbHVwcGl0dXMgdXQgbGFib3I\n"
+"ZSBldCB0cnVmZnVsYSBtYWduYSA YWxpcXVhLiBVdCBlbmltIGFkIGdyaWNrbGUtZ3Jhc3M\n"
+"dmVuaWFtLCBxdWlzIG1pZmYtbXU ZmZlcmVkIGdhLXp1bXBjbyBsYWJvcmlzIG5pc2kgdXQ\n"
+"Y3J1ZmZ1bHVzIGV4IGVhIHNjaGw b3BwaXR5IGNvbnNlcXVhdC4gRHVpcyBhdXRlIHNuYXI\n"
+"Z2dsZSBpbiBzd29tZWVzd2FucyA aW4gdm9sdXB0YXRlIGF4ZS1oYWNrZXIgZXNzZSByaXA\n"
+"cHVsdXMgY3J1bW1paSBldSBtb28 ZiBudWxsYSBzbnV2di5QTFVHSFBMT1ZFUlhZWlpZLi4\n";
+
+ tt_int_op(0, ==, keypin_load_journal_impl(data1, strlen(data1)));
+ tt_int_op(8, ==, smartlist_len(mock_addent_got));
+ keypin_ent_t *ent = smartlist_get(mock_addent_got, 2);
+ tt_mem_op(ent->rsa_id, ==, "r lerkim, sed do bar", 20);
+ tt_mem_op(ent->ed25519_key, ==, "baloot tempor gluppitus ut labor", 32);
+
+ /* More complex example: weird lines, bogus lines,
+ duplicate/conflicting lines */
+ const char data2[] =
+ "PT09PT09PT09PT09PT09PT09PT0 PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0\n"
+ "# This is a comment.\n"
+ " \n"
+ "QXQgdGhlIGVuZCBvZiB0aGUgeWU YXIgS3VycmVta2FybWVycnVrIHNhaWQgdG8gaGltLCA\n"
+ "IllvdSBoYXZlIG1hZGUgYSBnb28 ZCBiZWdpbm5pbmcuIiBCdXQgbm8gbW9yZS4gV2l6YXI\n"
+ "\n"
+ "ZHMgc3BlYWsgdHJ1dGgsIGFuZCA aXQgd2FzIHRydWUgdGhhdCBhbGwgdGhlIG1hc3Rlcgo\n"
+ "@reserved for a future extension \n"
+ "eSBvZiBOYW1lcyB0aGF0IEdlZCA aGFkIHRvaWxlZCbyB3aW4gdGhhdCB5ZWFyIHdhcyA\n"
+ "eSBvZiBOYW1lcyB0aGF0IEdlZCA aGFkIHRvaWxlZCbyB3aW4gdGhhdCB5ZWFyIHdhcy"
+ "A line too long\n"
+ "dGhlIG1lcmUgc3RhcnQgb2Ygd2g YXQgaGUgbXVzdCBnbyBvb!BsZWFybmluZy4uLi4uLi4\n"
+ "ZHMgc3BlYWsgdaJ1dGgsIGFuZCA aXQgd2FzIHRydWUgdGhhdCBhbGwgdGhlIG1hc3Rlcgo\n"
+ "ZHMgc3BlYWsgdHJ1dGgsIGFuZCA aXQgd2FzIHRydaUgdGhhdCBhbGwgdGhlIG1hc3Rlcgo\n"
+ ;
+
+ tt_int_op(0, ==, keypin_load_journal_impl(data2, strlen(data2)));
+ tt_int_op(11, ==, smartlist_len(mock_addent_got));
+ ent = smartlist_get(mock_addent_got, 9);
+ tt_mem_op(ent->rsa_id, ==, "\"You have made a goo", 20);
+ tt_mem_op(ent->ed25519_key, ==, "d beginning.\" But no more. Wizar", 32);
+
+ ent = smartlist_get(mock_addent_got, 10);
+ tt_mem_op(ent->rsa_id, ==, "ds speak truth, and ", 20);
+ tt_mem_op(ent->ed25519_key, ==, "it was true that all the master\n", 32);
+
+ /* File truncated before NL */
+ const char data3[] =
+ "Tm8gZHJhZ29uIGNhbiByZXNpc3Q IHRoZSBmYXNjaW5hdGlvbiBvZiByaWRkbGluZyB0YWw";
+ tt_int_op(0, ==, keypin_load_journal_impl(data3, strlen(data3)));
+ tt_int_op(12, ==, smartlist_len(mock_addent_got));
+ ent = smartlist_get(mock_addent_got, 11);
+ tt_mem_op(ent->rsa_id, ==, "No dragon can resist", 20);
+ tt_mem_op(ent->ed25519_key, ==, " the fascination of riddling tal", 32);
+
+ done:
+ keypin_clear();
+ smartlist_free(mock_addent_got);
+}
+
+#define ADD(a,b) keypin_check_and_add((const uint8_t*)(a),(const uint8_t*)(b))
+#define LONE_RSA(a) keypin_check_lone_rsa((const uint8_t*)(a))
+
+static void
+test_keypin_add_entry(void *arg)
+{
+ (void)arg;
+ keypin_clear();
+
+ tt_int_op(KEYPIN_ADDED, ==, ADD("ambassadors-at-large",
+ "bread-and-butter thing-in-itself"));
+ tt_int_op(KEYPIN_ADDED, ==, ADD("gentleman-adventurer",
+ "cloak-and-dagger what's-his-face"));
+
+ tt_int_op(KEYPIN_FOUND, ==, ADD("ambassadors-at-large",
+ "bread-and-butter thing-in-itself"));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("ambassadors-at-large",
+ "bread-and-butter thing-in-itself"));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("gentleman-adventurer",
+ "cloak-and-dagger what's-his-face"));
+
+ tt_int_op(KEYPIN_ADDED, ==, ADD("Johnnies-come-lately",
+ "run-of-the-mill root-mean-square"));
+
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("gentleman-adventurer",
+ "hypersentimental closefistedness"));
+
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("disestablismentarian",
+ "cloak-and-dagger what's-his-face"));
+
+ tt_int_op(KEYPIN_FOUND, ==, ADD("gentleman-adventurer",
+ "cloak-and-dagger what's-his-face"));
+
+ tt_int_op(KEYPIN_NOT_FOUND, ==, LONE_RSA("Llanfairpwllgwyngyll"));
+ tt_int_op(KEYPIN_MISMATCH, ==, LONE_RSA("Johnnies-come-lately"));
+
+ done:
+ keypin_clear();
+}
+
+static void
+test_keypin_journal(void *arg)
+{
+ (void)arg;
+ char *contents = NULL;
+ const char *fname = get_fname("keypin-journal");
+
+ tt_int_op(0, ==, keypin_load_journal(fname)); /* ENOENT is okay */
+ update_approx_time(1217709000);
+ tt_int_op(0, ==, keypin_open_journal(fname));
+
+ tt_int_op(KEYPIN_ADDED, ==, ADD("king-of-the-herrings",
+ "good-for-nothing attorney-at-law"));
+ tt_int_op(KEYPIN_ADDED, ==, ADD("yellowish-red-yellow",
+ "salt-and-pepper high-muck-a-muck"));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("yellowish-red-yellow",
+ "salt-and-pepper high-muck-a-muck"));
+ keypin_close_journal();
+ keypin_clear();
+
+ tt_int_op(0, ==, keypin_load_journal(fname));
+ update_approx_time(1231041600);
+ tt_int_op(0, ==, keypin_open_journal(fname));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("yellowish-red-yellow",
+ "salt-and-pepper high-muck-a-muck"));
+ tt_int_op(KEYPIN_ADDED, ==, ADD("theatre-in-the-round",
+ "holier-than-thou jack-in-the-box"));
+ tt_int_op(KEYPIN_ADDED, ==, ADD("no-deposit-no-return",
+ "across-the-board will-o-the-wisp"));
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("intellectualizations",
+ "salt-and-pepper high-muck-a-muck"));
+ keypin_close_journal();
+ keypin_clear();
+
+ tt_int_op(0, ==, keypin_load_journal(fname));
+ update_approx_time(1412278354);
+ tt_int_op(0, ==, keypin_open_journal(fname));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("yellowish-red-yellow",
+ "salt-and-pepper high-muck-a-muck"));
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("intellectualizations",
+ "salt-and-pepper high-muck-a-muck"));
+ tt_int_op(KEYPIN_FOUND, ==, ADD("theatre-in-the-round",
+ "holier-than-thou jack-in-the-box"));
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("counterrevolutionary",
+ "holier-than-thou jack-in-the-box"));
+ tt_int_op(KEYPIN_MISMATCH, ==, ADD("no-deposit-no-return",
+ "floccinaucinihilipilificationism"));
+ keypin_close_journal();
+
+ contents = read_file_to_str(fname, RFTS_BIN, NULL);
+ tt_assert(contents);
+ tt_str_op(contents,==,
+ "\n"
+ "@opened-at 2008-08-02 20:30:00\n"
+ "a2luZy1vZi10aGUtaGVycmluZ3M Z29vZC1mb3Itbm90aGluZyBhdHRvcm5leS1hdC1sYXc\n"
+ "eWVsbG93aXNoLXJlZC15ZWxsb3c c2FsdC1hbmQtcGVwcGVyIGhpZ2gtbXVjay1hLW11Y2s\n"
+ "\n"
+ "@opened-at 2009-01-04 04:00:00\n"
+ "dGhlYXRyZS1pbi10aGUtcm91bmQ aG9saWVyLXRoYW4tdGhvdSBqYWNrLWluLXRoZS1ib3g\n"
+ "bm8tZGVwb3NpdC1uby1yZXR1cm4 YWNyb3NzLXRoZS1ib2FyZCB3aWxsLW8tdGhlLXdpc3A\n"
+ "\n"
+ "@opened-at 2014-10-02 19:32:34\n");
+
+ done:
+ tor_free(contents);
+ keypin_clear();
+}
+
+#undef ADD
+#undef LONE_RSA
+
+#define TEST(name, flags) \
+ { #name , test_keypin_ ## name, (flags), NULL, NULL }
+
+struct testcase_t keypin_tests[] = {
+ TEST( parse_line, 0 ),
+ TEST( parse_file, TT_FORK ),
+ TEST( add_entry, TT_FORK ),
+ TEST( journal, TT_FORK ),
+ END_OF_TESTCASES
+};
+
1
0

[tor/master] Fix the position-check for ed25519 certs to work with annotations
by nickm@torproject.org 28 May '15
by nickm@torproject.org 28 May '15
28 May '15
commit 006b7ce5ff2a90a517e2842fcdd716ed60a90f14
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Wed Oct 8 09:13:09 2014 -0400
Fix the position-check for ed25519 certs to work with annotations
When there are annotations on a router descriptor, the
ed25519-identity element won't be at position 0 or 1; it will be at
router+1 or router-1.
This patch also adds a missing smartlist function to search a list for
an item with a particular pointer.
---
src/common/container.c | 13 +++++++++++++
src/common/container.h | 1 +
src/or/routerparse.c | 7 +++++--
src/test/test_containers.c | 38 ++++++++++++++++++++++++++++++++++++++
4 files changed, 57 insertions(+), 2 deletions(-)
diff --git a/src/common/container.c b/src/common/container.c
index 864fd8a..082afb5 100644
--- a/src/common/container.c
+++ b/src/common/container.c
@@ -208,6 +208,19 @@ smartlist_string_pos(const smartlist_t *sl, const char *element)
return -1;
}
+/** If <b>element</b> is the same pointer as an element of <b>sl</b>, return
+ * that element's index. Otherwise, return -1. */
+int
+smartlist_pos(const smartlist_t *sl, const void *element)
+{
+ int i;
+ if (!sl) return -1;
+ for (i=0; i < sl->num_used; i++)
+ if (element == sl->list[i])
+ return i;
+ return -1;
+}
+
/** Return true iff <b>sl</b> has some element E such that
* !strcasecmp(E,<b>element</b>)
*/
diff --git a/src/common/container.h b/src/common/container.h
index d07697f..64c9b78 100644
--- a/src/common/container.h
+++ b/src/common/container.h
@@ -38,6 +38,7 @@ void smartlist_reverse(smartlist_t *sl);
void smartlist_string_remove(smartlist_t *sl, const char *element);
int smartlist_contains(const smartlist_t *sl, const void *element);
int smartlist_contains_string(const smartlist_t *sl, const char *element);
+int smartlist_pos(const smartlist_t *sl, const void *element);
int smartlist_string_pos(const smartlist_t *, const char *elt);
int smartlist_contains_string_case(const smartlist_t *sl, const char *element);
int smartlist_contains_int_as_string(const smartlist_t *sl, int num);
diff --git a/src/or/routerparse.c b/src/or/routerparse.c
index b3bb565..98104f4 100644
--- a/src/or/routerparse.c
+++ b/src/or/routerparse.c
@@ -1195,6 +1195,7 @@ router_parse_entry_from_string(const char *s, const char *end,
}
tok = find_by_keyword(tokens, K_ROUTER);
+ const int router_token_pos = smartlist_pos(tokens, tok);
tor_assert(tok->n_args >= 5);
router = tor_malloc_zero(sizeof(routerinfo_t));
@@ -1345,8 +1346,10 @@ router_parse_entry_from_string(const char *s, const char *end,
}
if (ed_sig_tok) {
tor_assert(ed_cert_tok && cc_tap_tok && cc_ntor_tok);
- if (ed_cert_tok != smartlist_get(tokens, 0) &&
- ed_cert_tok != smartlist_get(tokens, 1)) {
+ const int ed_cert_token_pos = smartlist_pos(tokens, ed_cert_tok);
+ if (ed_cert_token_pos == -1 || router_token_pos == -1 ||
+ (ed_cert_token_pos != router_token_pos + 1 &&
+ ed_cert_token_pos != router_token_pos - 1)) {
log_warn(LD_DIR, "Ed25519 certificate in wrong position");
goto err;
}
diff --git a/src/test/test_containers.c b/src/test/test_containers.c
index 79085a7..3d150f5 100644
--- a/src/test/test_containers.c
+++ b/src/test/test_containers.c
@@ -496,6 +496,43 @@ test_container_smartlist_join(void *arg)
}
static void
+test_container_smartlist_pos(void *arg)
+{
+ (void) arg;
+ smartlist_t *sl = smartlist_new();
+
+ smartlist_add(sl, tor_strdup("This"));
+ smartlist_add(sl, tor_strdup("is"));
+ smartlist_add(sl, tor_strdup("a"));
+ smartlist_add(sl, tor_strdup("test"));
+ smartlist_add(sl, tor_strdup("for"));
+ smartlist_add(sl, tor_strdup("a"));
+ smartlist_add(sl, tor_strdup("function"));
+
+ /* Test string_pos */
+ tt_int_op(smartlist_string_pos(NULL, "Fred"), ==, -1);
+ tt_int_op(smartlist_string_pos(sl, "Fred"), ==, -1);
+ tt_int_op(smartlist_string_pos(sl, "This"), ==, 0);
+ tt_int_op(smartlist_string_pos(sl, "a"), ==, 2);
+ tt_int_op(smartlist_string_pos(sl, "function"), ==, 6);
+
+ /* Test pos */
+ tt_int_op(smartlist_pos(NULL, "Fred"), ==, -1);
+ tt_int_op(smartlist_pos(sl, "Fred"), ==, -1);
+ tt_int_op(smartlist_pos(sl, "This"), ==, -1);
+ tt_int_op(smartlist_pos(sl, "a"), ==, -1);
+ tt_int_op(smartlist_pos(sl, "function"), ==, -1);
+ tt_int_op(smartlist_pos(sl, smartlist_get(sl,0)), ==, 0);
+ tt_int_op(smartlist_pos(sl, smartlist_get(sl,2)), ==, 2);
+ tt_int_op(smartlist_pos(sl, smartlist_get(sl,5)), ==, 5);
+ tt_int_op(smartlist_pos(sl, smartlist_get(sl,6)), ==, 6);
+
+ done:
+ SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
+ smartlist_free(sl);
+}
+
+static void
test_container_smartlist_ints_eq(void *arg)
{
smartlist_t *sl1 = NULL, *sl2 = NULL;
@@ -1053,6 +1090,7 @@ struct testcase_t container_tests[] = {
CONTAINER_LEGACY(smartlist_overlap),
CONTAINER_LEGACY(smartlist_digests),
CONTAINER_LEGACY(smartlist_join),
+ CONTAINER_LEGACY(smartlist_pos),
CONTAINER(smartlist_ints_eq, 0),
CONTAINER_LEGACY(bitarray),
CONTAINER_LEGACY(digestset),
1
0