Commit 908ccb9d authored by Nick Mathewson's avatar Nick Mathewson 🏃
Browse files

Handle windows socket errors correctly; comment most of common.


svn:r1756
parent ac4cb9bd
......@@ -54,8 +54,7 @@
#define OPENSSL_095
#endif
/*
* Certain functions that return a success code in OpenSSL 0.9.6 return void
/* Certain functions that return a success code in OpenSSL 0.9.6 return void
* (and don't indicate errors) in OpenSSL version 0.9.5.
*
* [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
......@@ -66,12 +65,14 @@
#define RETURN_SSL_OUTCOME(exp) return !(exp)
#endif
/* Macro: is k a valid RSA public or private key? */
#define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
/* Macro: is k a valid RSA private key? */
#define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
struct crypto_pk_env_t
{
int refs; /* reference counting; so we don't have to copy keys */
int refs; /* reference counting so we don't have to copy keys */
RSA *key;
};
......@@ -85,6 +86,8 @@ struct crypto_dh_env_t {
DH *dh;
};
/* Return the number of bytes added by padding method 'padding'
*/
static INLINE int
crypto_get_rsa_padding_overhead(int padding) {
switch(padding)
......@@ -96,6 +99,8 @@ crypto_get_rsa_padding_overhead(int padding) {
}
}
/* Given a padding method 'padding', return the correct OpenSSL constant.
*/
static INLINE int
crypto_get_rsa_padding(int padding) {
switch(padding)
......@@ -107,10 +112,12 @@ crypto_get_rsa_padding(int padding) {
}
}
/* Boolen: has OpenSSL's crypto been initialized? */
static int _crypto_global_initialized = 0;
/* errors */
/* Log all pending crypto errors at level 'severity'. Use 'doing' to describe
* our current activities.
*/
static void
crypto_log_errors(int severity, const char *doing)
{
......@@ -128,6 +135,8 @@ crypto_log_errors(int severity, const char *doing)
}
}
}
/* Initialize the crypto library.
*/
int crypto_global_init()
{
if (!_crypto_global_initialized) {
......@@ -137,13 +146,15 @@ int crypto_global_init()
return 0;
}
/* Uninitialize the crypto library.
*/
int crypto_global_cleanup()
{
ERR_free_strings();
return 0;
}
/* used by tortls.c */
/* used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa)
{
crypto_pk_env_t *env;
......@@ -154,13 +165,14 @@ crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa)
return env;
}
/* used by tortls.c */
/* used by tortls.c: return the RSA* from a crypto_pk_env_t */
RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env)
{
return env->key;
}
/* used by tortls.c */
/* used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
* private is set, include the private-key portion of the key. */
EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
{
RSA *key = NULL;
......@@ -186,11 +198,16 @@ EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
return NULL;
}
/* Used by tortls.c: Get the DH* from a crypto_dh_env_t.
*/
DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh)
{
return dh->dh;
}
/* Allocate and return storage for a public key. The key itself will not yet
* be set.
*/
crypto_pk_env_t *crypto_new_pk_env(void)
{
RSA *rsa;
......@@ -200,6 +217,8 @@ crypto_pk_env_t *crypto_new_pk_env(void)
return _crypto_new_pk_env_rsa(rsa);
}
/*
*/
void crypto_free_pk_env(crypto_pk_env_t *env)
{
tor_assert(env);
......@@ -273,7 +292,7 @@ int crypto_pk_generate_key(crypto_pk_env_t *env)
if (env->key)
RSA_free(env->key);
env->key = RSA_generate_key(PK_BITS,65537, NULL, NULL);
env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
if (!env->key) {
crypto_log_errors(LOG_WARN, "generating RSA key");
return -1;
......
......@@ -7,21 +7,29 @@
#include <stdio.h>
/* Length of the output of our message digest. */
#define DIGEST_LEN 20
/* Length of our symmetric cipher's keys. */
#define CIPHER_KEY_LEN 16
#define PK_BITS 1024
#define PK_BYTES (PK_BITS/8)
#define DH_BITS 1024
#define DH_BYTES (DH_BITS/8)
#define CRYPTO_DH_SIZE DH_BYTES
/* Length of our public keys. */
#define PK_BYTES (1024/8)
/* Length of our DH keys. */
#define DH_BYTES (1024/8)
/* Constants used to indicate disired public-key padding functions. */
#define PK_NO_PADDING 60000
#define PK_PKCS1_PADDING 60001
#define PK_PKCS1_OAEP_PADDING 60002
/* Bytes added for PKCS1 padding. */
#define PKCS1_PADDING_OVERHEAD 11
/* Bytes added for PKCS1-OAEP padding. */
#define PKCS1_OAEP_PADDING_OVERHEAD 42
/* Length of encoded public key fingerprints, including space and NUL. */
#define FINGERPRINT_LEN 49
typedef struct crypto_pk_env_t crypto_pk_env_t;
typedef struct crypto_cipher_env_t crypto_cipher_env_t;
typedef struct crypto_digest_env_t crypto_digest_env_t;
......@@ -64,7 +72,6 @@ int crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
const unsigned char *from, int fromlen,
unsigned char *to,int padding);
#define FINGERPRINT_LEN 49
int crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len);
crypto_pk_env_t *crypto_pk_asn1_decode(const char *str, int len);
int crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out);
......
......@@ -2,7 +2,9 @@
/* See LICENSE for licensing information */
/* $Id$ */
/* On systems where 'poll' doesn't exist, fake it with 'select'. */
/*****
* fakepoll.c: On systems where 'poll' doesn't exist, fake it with 'select'.
*****/
#include "orconfig.h"
#include "fakepoll.h"
......
......@@ -16,7 +16,7 @@
#endif
/* If _POLL_EMUL_H_ is defined, then poll is just a just a thin wrapper around
* select. On Mac OS 10.3, this wrapper is kinda flakey, and we should
* select. On Mac OS 10.3, this wrapper is kinda flaky, and we should
* use our own.
*/
#if (defined(HAVE_POLL_H)||defined(HAVE_SYS_POLL_H)) && !defined(_POLL_EMUL_H_)
......
......@@ -2,11 +2,16 @@
/* See LICENSE for licensing information */
/* $Id$ */
/*****
* torint.h: Header file to define uint32_t and friends.
*****/
#ifndef __TORINT_H
#define __TORINT_H
#include "orconfig.h"
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
......
......@@ -2,10 +2,11 @@
/* See LICENSE for licensing information */
/* $Id$ */
/* TLS wrappers for The Onion Router. (Unlike other tor functions, these
/*****
* tortls.c: TLS wrappers for Tor. (Unlike other tor functions, these
* are prefixed with tor_ in order to avoid conflicting with OpenSSL
* functions and variables.)
*/
*****/
#include "./crypto.h"
#include "./tortls.h"
......@@ -28,17 +29,20 @@
/* How much clock skew do we tolerate when checking certificates? (sec) */
#define CERT_ALLOW_SKEW (90*60)
struct tor_tls_context_st {
typedef struct tor_tls_context_st {
SSL_CTX *ctx;
};
} tor_tls_context;
/* Holds a SSL object and it associated data.
*/
struct tor_tls_st {
SSL *ssl;
int socket;
int socket; /* The underlying fd. */
enum {
TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
} state;
} state; /* The current SSL state, depending on which operatios have
* completed successfully. */
int isServer;
int wantwrite_n; /* 0 normally, >0 if we returned wantwrite last time */
};
......@@ -49,10 +53,12 @@ static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
const char *cname_sign,
unsigned int lifetime);
/* global tls context, keep it here because nobody else needs to touch it */
/* Global tls context. We keep it here because nobody else needs to touch it */
static tor_tls_context *global_tls_context = NULL;
/* True iff tor_tls_init() has been called. */
static int tls_library_is_initialized = 0;
/* Module-internal error codes. */
#define _TOR_TLS_SYSCALL -6
#define _TOR_TLS_ZERORETURN -5
......@@ -61,6 +67,9 @@ EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
/* Log all pending tls errors at level 'severity'. Use 'doing' to describe
* our current activities.
*/
static void
tls_log_errors(int severity, const char *doing)
{
......@@ -82,6 +91,16 @@ tls_log_errors(int severity, const char *doing)
#define CATCH_SYSCALL 1
#define CATCH_ZERO 2
/* Given a TLS object and the result of an SSL_* call, use
* SSL_get_error to determine whether an error has occurred, and if so
* which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
* If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
* reporting syscall errors. If extra&CATCH_ZERO is true, return
* _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
*
* If an error has occurred, log it at level 'severity' and describe the
* current action as 'doing.'
*/
static int
tor_tls_get_error(tor_tls *tls, int r, int extra,
const char *doing, int severity)
......@@ -97,8 +116,13 @@ tor_tls_get_error(tor_tls *tls, int r, int extra,
case SSL_ERROR_SYSCALL:
if (extra&CATCH_SYSCALL)
return _TOR_TLS_SYSCALL;
log(severity, "TLS error: <syscall error> (errno=%d: %s)",errno,
strerror(errno));
if (r == 0)
log(severity, "TLS error: unexpected close while %s", doing);
else {
int e = tor_socket_errno(tls->socket);
log(severity, "TLS error: <syscall error while %s> (errno=%d: %s)",
doing, e, strerror(e));
}
tls_log_errors(severity, doing);
return TOR_TLS_ERROR;
case SSL_ERROR_ZERO_RETURN:
......@@ -113,6 +137,8 @@ tor_tls_get_error(tor_tls *tls, int r, int extra,
}
}
/* Initialize OpenSSL, unless it has already been initialized.
*/
static void
tor_tls_init() {
if (!tls_library_is_initialized) {
......@@ -124,20 +150,24 @@ tor_tls_init() {
}
}
/* We need to give OpenSSL a callback to verify certificates. This is
* it: We always accept peer certs and complete the handshake. We
* don't validate them until later.
*/
static int always_accept_verify_cb(int preverify_ok,
X509_STORE_CTX *x509_ctx)
{
/* We always accept peer certs and complete the handshake. We don't validate
* them until later. */
return 1;
}
/* Generate a self-signed certificate with the private key 'rsa' and
* identity key 'identity and commonName 'nickname'. Return a certificate
* on success, NULL on failure.
* DOCDOC
/* Generate and sign an X509 certificate with the public key 'rsa',
* signed by the private key 'rsa_sign'. The commonName of the
* certificate will be 'cname'; the commonName of the issuer will be
* cname_sign. The cert will be valid for cert_lifetime seconds
* starting from now. Return a certificate on success, NULL on
* failure.
*/
X509 *
static X509 *
tor_tls_create_certificate(crypto_pk_env_t *rsa,
crypto_pk_env_t *rsa_sign,
const char *cname,
......@@ -236,7 +266,13 @@ tor_tls_create_certificate(crypto_pk_env_t *rsa,
/* Create a new TLS context. If we are going to be using it as a
* server, it must have isServer set to true, 'identity' set to the
* identity key used to sign that certificate, and 'nickname' set to
* the server's nickname. Return -1 if failure, else 0.
* the server's nickname. If we're only going to be a client,
* isServer should be false, identity should be NULL, and nickname
* should be NULL. Return -1 if failure, else 0.
*
* You can call this function multiple times. Each time you call it,
* it generates new certificates; all new connections will be begin
* with the new SSL context.
*/
int
tor_tls_context_new(crypto_pk_env_t *identity,
......@@ -254,12 +290,15 @@ tor_tls_context_new(crypto_pk_env_t *identity,
tor_tls_init();
if (isServer) {
/* Generate short-term RSA key. */
if (!(rsa = crypto_new_pk_env()))
goto error;
if (crypto_pk_generate_key(rsa)<0)
goto error;
/* Create certificate signed by identity key. */
cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
key_lifetime);
/* Create self-signed certificate for identity key. */
idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
IDENTITY_CERT_LIFETIME);
if (!cert || !idcert) {
......@@ -334,7 +373,7 @@ tor_tls_context_new(crypto_pk_env_t *identity,
return -1;
}
/* Create a new TLS object from a TLS context, a filedescriptor, and
/* Create a new TLS object from a TLS context, a file descriptor, and
* a flag to determine whether it is functioning as a server.
*/
tor_tls *
......@@ -515,6 +554,9 @@ tor_tls_peer_has_cert(tor_tls *tls)
return 1;
}
/* Return the nickname (if any) that the peer connected on 'tls'
* claims to have.
*/
int
tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, int buflen)
{
......@@ -593,7 +635,7 @@ tor_tls_verify(tor_tls *tls, crypto_pk_env_t *identity_key)
if (id_pkey)
EVP_PKEY_free(id_pkey);
/* XXXX */
/* XXXX This should never get invoked, but let's make sure for now. */
tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
return r;
......@@ -619,12 +661,15 @@ unsigned long tor_tls_get_n_bytes_read(tor_tls *tls)
tor_assert(tls);
return BIO_number_read(SSL_get_rbio(tls->ssl));
}
/* Return the number of bytes written across the underlying socket. */
unsigned long tor_tls_get_n_bytes_written(tor_tls *tls)
{
tor_assert(tls);
return BIO_number_written(SSL_get_wbio(tls->ssl));
}
/* Implement assert_no_tls_errors: If there are any pending OpenSSL
* errors, log an error message and assert(0). */
void _assert_no_tls_errors(const char *fname, int line)
{
if (ERR_peek_error() == 0)
......@@ -636,7 +681,6 @@ void _assert_no_tls_errors(const char *fname, int line)
tor_assert(0);
}
/*
Local Variables:
mode:c
......
......@@ -7,16 +7,16 @@
#include "../common/crypto.h"
typedef struct tor_tls_context_st tor_tls_context;
/* Opaque structure to hold a TLS connection. */
typedef struct tor_tls_st tor_tls;
/* Possible return values for most tor_tls_* functions. */
#define TOR_TLS_ERROR -4
#define TOR_TLS_CLOSE -3
#define TOR_TLS_WANTREAD -2
#define TOR_TLS_WANTWRITE -1
#define TOR_TLS_DONE 0
/* X509* tor_tls_write_certificate(char *certfile, crypto_pk_env_t *rsa, char *nickname); */
int tor_tls_context_new(crypto_pk_env_t *rsa, int isServer,
const char *nickname, unsigned int key_lifetime);
tor_tls *tor_tls_new(int sock, int isServer);
......@@ -33,6 +33,8 @@ int tor_tls_get_pending_bytes(tor_tls *tls);
unsigned long tor_tls_get_n_bytes_read(tor_tls *tls);
unsigned long tor_tls_get_n_bytes_written(tor_tls *tls);
/* Log and abort if there are unhandled TLS errors in OpenSSL's error stack.
*/
#define assert_no_tls_errors() _assert_no_tls_errors(__FILE__,__LINE__)
void _assert_no_tls_errors(const char *fname, int line);
......
......@@ -2,6 +2,11 @@
/* See LICENSE for licensing information */
/* $Id$ */
/*****
* util.c: Common functions for strings, IO, network, data structures,
* process control, and cross-platform portability.
*****/
#include "orconfig.h"
#ifdef MS_WINDOWS
......@@ -86,7 +91,7 @@
#define INADDR_NONE ((unsigned long) -1)
#endif
/* in-line the strl functions */
/* Inline the strl functions if the plaform doesn't have them. */
#ifndef HAVE_STRLCPY
#include "strlcpy.c"
#endif
......@@ -94,10 +99,14 @@
#include "strlcat.c"
#endif
/*
/*****
* Memory wrappers
*/
*****/
/* Allocate a chunk of 'size' bytes of memory, and return a pointer to
* result. On error, log and terminate the process. (Same as malloc(size),
* but never returns NULL.)
*/
void *tor_malloc(size_t size) {
void *result;
......@@ -115,12 +124,20 @@ void *tor_malloc(size_t size) {
return result;
}
/* Allocate a chunk of 'size' bytes of memory, fill the memory with
* zero bytes, and return a pointer to the result. Log and terminate
* the process on error. (Same as calloc(size,1), but never returns NULL.)
*/
void *tor_malloc_zero(size_t size) {
void *result = tor_malloc(size);
memset(result, 0, size);
return result;
}
/* Change the size of the memory block pointed to by 'ptr' to 'size'
* bytes long; return the new memory block. On error, log and
* terminate. (Like realloc(ptr,size), but never returns NULL.)
*/
void *tor_realloc(void *ptr, size_t size) {
void *result;
......@@ -132,6 +149,10 @@ void *tor_realloc(void *ptr, size_t size) {
return result;
}
/* Return a newly allocated copy of the NUL-terminated string s. On
* error, log and terminate. (Like strdup(s), but never returns
* NULL.)
*/
char *tor_strdup(const char *s) {
char *dup;
tor_assert(s);
......@@ -144,6 +165,11 @@ char *tor_strdup(const char *s) {
return dup;
}
/* Allocate and return a new string containing the first 'n'
* characters of 's'. If 's' is longer than 'n' characters, only the
* first 'n' are copied. The result is always NUL-terminated. (Like
* strndup(s,n), but never returns NULL.)
*/
char *tor_strndup(const char *s, size_t n) {
char *dup;
tor_assert(s);
......@@ -153,7 +179,8 @@ char *tor_strndup(const char *s, size_t n) {
return dup;
}
/* Convert s to lowercase. */
/* Convert all alphabetic characters in the nul-terminated string 's' to
* lowercase. */
void tor_strlower(char *s)
{
while (*s) {
......@@ -185,6 +212,10 @@ void set_uint32(char *cp, uint32_t v)
}
#endif
/* Encode the first 'fromlen' bytes stored at 'from' in hexidecimal;
* write the result as a NUL-terminated string to 'to'. 'to' must
* have at least (2*fromlen)+1 bytes of free space.
*/
void hex_encode(const char *from, int fromlen, char *to)
{
const unsigned char *fp = from;
......@@ -198,6 +229,11 @@ void hex_encode(const char *from, int fromlen, char *to)
*to = '\0';
}
/* Return a pointer to a NUL-terminated hexidecimal string encoding
* the first 'fromlen' bytes of 'from'. (fromlen must be <= 32.) The
* result does not need to be deallocated, but repeated calls to
* hex_str will trash old results.
*/
const char *hex_str(const char *from, int fromlen)
{
static char buf[65];
......@@ -207,21 +243,27 @@ const char *hex_str(const char *from, int fromlen)
return buf;
}
/*
* A simple smartlist interface to make an unordered list of acceptable
* nodes and then choose a random one.
* smartlist_create() mallocs the list, _free() frees the list,
* _add() adds an element, _remove() removes an element if it's there,
* _choose() returns a random element.
/*****
* smartlist_t: a simple resizeable array abstraction.
*****/
/* All newly allocated smartlists have this capacity.
*/
#define SMARTLIST_DEFAULT_CAPACITY 32
struct smartlist_t {
/* 'list' has enough capacity to store exactly 'capacity' elements
* before it needs to be resized. Only the first 'num_used' (<=
* capacity) elements point to valid data.
*/
void **list;
int num_used;
int capacity;
};
/* Allocate and return an empty smartlist.
*/
smartlist_t *smartlist_create() {
smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
sl->num_used = 0;
......@@ -230,32 +272,46 @@ smartlist_t *smartlist_create() {
return sl;
}
/* Deallocate a smartlist. Does not release storage associated with the
* list's elements.
*/
void smartlist_free(smartlist_t *sl) {
free(sl->list);
free(sl);
}
/* Change the capacity of the smartlist to 'n', so that we can grow
* the list upt to'n' elements with no further reallocation or wasted
* space. If 'n' is less than or equal to the number of elements
* currently in the list, reduces the list's capacity as much as
* possible without losing elements.
*/
void smartlist_set_capacity(smartlist_t *sl, int n) {
if (n<0)
if (n < sl->num_used)
n = sl->num_used;
if (sl->capacity != n && sl->num_used < n) {
if (sl->capacity != n) {
sl->capacity = n;
sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
}
}
/* Remove all elements from the list. */
/* Remove all elements from the list.
*/
void smartlist_clear(smartlist_t *sl) {
sl->num_used = 0;
}
/* Set the list's new length to 'len' (which must be <= the list's
* current size). Remove the last smartlist_len(sl)-len elements from the
* list.
*/
void smartlist_truncate(smartlist_t *sl, int len)
{
tor_assert(len <= sl->num_used);
sl->num_used = len;
}
/* add element to the list */
/* Append element to the end of the list. */
void smartlist_add(smartlist_t *sl, void *element) {
if (sl->num_used >= sl->capacity) {
sl->capacity *= 2;
......@@ -264,12 +320,15 @@ void smartlist_add(smartlist_t *sl, void *element) {
sl->list[sl->num_used++] = element;
}
/* Add all elements from S2 to S1. */