diff options
Diffstat (limited to 'openssl/demos/tunala')
-rw-r--r-- | openssl/demos/tunala/breakage.c | 106 | ||||
-rw-r--r-- | openssl/demos/tunala/buffer.c | 409 | ||||
-rw-r--r-- | openssl/demos/tunala/cb.c | 239 | ||||
-rw-r--r-- | openssl/demos/tunala/ip.c | 221 | ||||
-rw-r--r-- | openssl/demos/tunala/sm.c | 255 | ||||
-rw-r--r-- | openssl/demos/tunala/tunala.c | 1928 | ||||
-rw-r--r-- | openssl/demos/tunala/tunala.h | 363 |
7 files changed, 1842 insertions, 1679 deletions
diff --git a/openssl/demos/tunala/breakage.c b/openssl/demos/tunala/breakage.c index dcdd64b0e..16a3b9e0c 100644 --- a/openssl/demos/tunala/breakage.c +++ b/openssl/demos/tunala/breakage.c @@ -3,64 +3,66 @@ int int_strtoul(const char *str, unsigned long *val) { #ifdef HAVE_STRTOUL - char *tmp; - unsigned long ret = strtoul(str, &tmp, 10); - if((str == tmp) || (*tmp != '\0')) - /* The value didn't parse cleanly */ - return 0; - if(ret == ULONG_MAX) - /* We hit a limit */ - return 0; - *val = ret; - return 1; + char *tmp; + unsigned long ret = strtoul(str, &tmp, 10); + if ((str == tmp) || (*tmp != '\0')) + /* The value didn't parse cleanly */ + return 0; + if (ret == ULONG_MAX) + /* We hit a limit */ + return 0; + *val = ret; + return 1; #else - char buf[2]; - unsigned long ret = 0; - buf[1] = '\0'; - if(str == '\0') - /* An empty string ... */ - return 0; - while(*str != '\0') { - /* We have to multiply 'ret' by 10 before absorbing the next - * digit. If this will overflow, catch it now. */ - if(ret && (((ULONG_MAX + 10) / ret) < 10)) - return 0; - ret *= 10; - if(!isdigit(*str)) - return 0; - buf[0] = *str; - ret += atoi(buf); - str++; - } - *val = ret; - return 1; + char buf[2]; + unsigned long ret = 0; + buf[1] = '\0'; + if (str == '\0') + /* An empty string ... */ + return 0; + while (*str != '\0') { + /* + * We have to multiply 'ret' by 10 before absorbing the next digit. + * If this will overflow, catch it now. + */ + if (ret && (((ULONG_MAX + 10) / ret) < 10)) + return 0; + ret *= 10; + if (!isdigit(*str)) + return 0; + buf[0] = *str; + ret += atoi(buf); + str++; + } + *val = ret; + return 1; #endif } #ifndef HAVE_STRSTR char *int_strstr(const char *haystack, const char *needle) { - const char *sub_haystack = haystack, *sub_needle = needle; - unsigned int offset = 0; - if(!needle) - return haystack; - if(!haystack) - return NULL; - while((*sub_haystack != '\0') && (*sub_needle != '\0')) { - if(sub_haystack[offset] == sub_needle) { - /* sub_haystack is still a candidate */ - offset++; - sub_needle++; - } else { - /* sub_haystack is no longer a possibility */ - sub_haystack++; - offset = 0; - sub_needle = needle; - } - } - if(*sub_haystack == '\0') - /* Found nothing */ - return NULL; - return sub_haystack; + const char *sub_haystack = haystack, *sub_needle = needle; + unsigned int offset = 0; + if (!needle) + return haystack; + if (!haystack) + return NULL; + while ((*sub_haystack != '\0') && (*sub_needle != '\0')) { + if (sub_haystack[offset] == sub_needle) { + /* sub_haystack is still a candidate */ + offset++; + sub_needle++; + } else { + /* sub_haystack is no longer a possibility */ + sub_haystack++; + offset = 0; + sub_needle = needle; + } + } + if (*sub_haystack == '\0') + /* Found nothing */ + return NULL; + return sub_haystack; } #endif diff --git a/openssl/demos/tunala/buffer.c b/openssl/demos/tunala/buffer.c index c5cd00420..8e2cc9d20 100644 --- a/openssl/demos/tunala/buffer.c +++ b/openssl/demos/tunala/buffer.c @@ -2,204 +2,235 @@ #ifndef NO_BUFFER -void buffer_init(buffer_t *buf) +void buffer_init(buffer_t * buf) { - buf->used = 0; - buf->total_in = buf->total_out = 0; + buf->used = 0; + buf->total_in = buf->total_out = 0; } -void buffer_close(buffer_t *buf) +void buffer_close(buffer_t * buf) { - /* Our data is static - nothing needs "release", just reset it */ - buf->used = 0; + /* Our data is static - nothing needs "release", just reset it */ + buf->used = 0; } /* Code these simple ones in compact form */ -unsigned int buffer_used(buffer_t *buf) { - return buf->used; } -unsigned int buffer_unused(buffer_t *buf) { - return (MAX_DATA_SIZE - buf->used); } -int buffer_full(buffer_t *buf) { - return (buf->used == MAX_DATA_SIZE ? 1 : 0); } -int buffer_notfull(buffer_t *buf) { - return (buf->used < MAX_DATA_SIZE ? 1 : 0); } -int buffer_empty(buffer_t *buf) { - return (buf->used == 0 ? 1 : 0); } -int buffer_notempty(buffer_t *buf) { - return (buf->used > 0 ? 1 : 0); } -unsigned long buffer_total_in(buffer_t *buf) { - return buf->total_in; } -unsigned long buffer_total_out(buffer_t *buf) { - return buf->total_out; } - -/* These 3 static (internal) functions don't adjust the "total" variables as +unsigned int buffer_used(buffer_t * buf) +{ + return buf->used; +} + +unsigned int buffer_unused(buffer_t * buf) +{ + return (MAX_DATA_SIZE - buf->used); +} + +int buffer_full(buffer_t * buf) +{ + return (buf->used == MAX_DATA_SIZE ? 1 : 0); +} + +int buffer_notfull(buffer_t * buf) +{ + return (buf->used < MAX_DATA_SIZE ? 1 : 0); +} + +int buffer_empty(buffer_t * buf) +{ + return (buf->used == 0 ? 1 : 0); +} + +int buffer_notempty(buffer_t * buf) +{ + return (buf->used > 0 ? 1 : 0); +} + +unsigned long buffer_total_in(buffer_t * buf) +{ + return buf->total_in; +} + +unsigned long buffer_total_out(buffer_t * buf) +{ + return buf->total_out; +} + +/* + * These 3 static (internal) functions don't adjust the "total" variables as * it's not sure when they're called how it should be interpreted. Only the * higher-level "buffer_[to|from]_[fd|SSL|BIO]" functions should alter these - * values. */ -#if 0 /* To avoid "unused" warnings */ -static unsigned int buffer_adddata(buffer_t *buf, const unsigned char *ptr, - unsigned int size) -{ - unsigned int added = MAX_DATA_SIZE - buf->used; - if(added > size) - added = size; - if(added == 0) - return 0; - memcpy(buf->data + buf->used, ptr, added); - buf->used += added; - buf->total_in += added; - return added; -} - -static unsigned int buffer_tobuffer(buffer_t *to, buffer_t *from, int cap) -{ - unsigned int moved, tomove = from->used; - if((int)tomove > cap) - tomove = cap; - if(tomove == 0) - return 0; - moved = buffer_adddata(to, from->data, tomove); - if(moved == 0) - return 0; - buffer_takedata(from, NULL, moved); - return moved; -} -#endif - -static unsigned int buffer_takedata(buffer_t *buf, unsigned char *ptr, - unsigned int size) -{ - unsigned int taken = buf->used; - if(taken > size) - taken = size; - if(taken == 0) - return 0; - if(ptr) - memcpy(ptr, buf->data, taken); - buf->used -= taken; - /* Do we have to scroll? */ - if(buf->used > 0) - memmove(buf->data, buf->data + taken, buf->used); - return taken; -} - -#ifndef NO_IP - -int buffer_from_fd(buffer_t *buf, int fd) -{ - int toread = buffer_unused(buf); - if(toread == 0) - /* Shouldn't be called in this case! */ - abort(); - toread = read(fd, buf->data + buf->used, toread); - if(toread > 0) { - buf->used += toread; - buf->total_in += toread; - } - return toread; -} - -int buffer_to_fd(buffer_t *buf, int fd) -{ - int towrite = buffer_used(buf); - if(towrite == 0) - /* Shouldn't be called in this case! */ - abort(); - towrite = write(fd, buf->data, towrite); - if(towrite > 0) { - buffer_takedata(buf, NULL, towrite); - buf->total_out += towrite; - } - return towrite; -} - -#endif /* !defined(NO_IP) */ - -#ifndef NO_OPENSSL + * values. + */ +# if 0 /* To avoid "unused" warnings */ +static unsigned int buffer_adddata(buffer_t * buf, const unsigned char *ptr, + unsigned int size) +{ + unsigned int added = MAX_DATA_SIZE - buf->used; + if (added > size) + added = size; + if (added == 0) + return 0; + memcpy(buf->data + buf->used, ptr, added); + buf->used += added; + buf->total_in += added; + return added; +} + +static unsigned int buffer_tobuffer(buffer_t * to, buffer_t * from, int cap) +{ + unsigned int moved, tomove = from->used; + if ((int)tomove > cap) + tomove = cap; + if (tomove == 0) + return 0; + moved = buffer_adddata(to, from->data, tomove); + if (moved == 0) + return 0; + buffer_takedata(from, NULL, moved); + return moved; +} +# endif + +static unsigned int buffer_takedata(buffer_t * buf, unsigned char *ptr, + unsigned int size) +{ + unsigned int taken = buf->used; + if (taken > size) + taken = size; + if (taken == 0) + return 0; + if (ptr) + memcpy(ptr, buf->data, taken); + buf->used -= taken; + /* Do we have to scroll? */ + if (buf->used > 0) + memmove(buf->data, buf->data + taken, buf->used); + return taken; +} + +# ifndef NO_IP + +int buffer_from_fd(buffer_t * buf, int fd) +{ + int toread = buffer_unused(buf); + if (toread == 0) + /* Shouldn't be called in this case! */ + abort(); + toread = read(fd, buf->data + buf->used, toread); + if (toread > 0) { + buf->used += toread; + buf->total_in += toread; + } + return toread; +} + +int buffer_to_fd(buffer_t * buf, int fd) +{ + int towrite = buffer_used(buf); + if (towrite == 0) + /* Shouldn't be called in this case! */ + abort(); + towrite = write(fd, buf->data, towrite); + if (towrite > 0) { + buffer_takedata(buf, NULL, towrite); + buf->total_out += towrite; + } + return towrite; +} + +# endif /* !defined(NO_IP) */ + +# ifndef NO_OPENSSL static void int_ssl_check(SSL *s, int ret) { - int e = SSL_get_error(s, ret); - switch(e) { - /* These seem to be harmless and already "dealt with" by our - * non-blocking environment. NB: "ZERO_RETURN" is the clean - * "error" indicating a successfully closed SSL tunnel. We let - * this happen because our IO loop should not appear to have - * broken on this condition - and outside the IO loop, the - * "shutdown" state is checked. */ - case SSL_ERROR_NONE: - case SSL_ERROR_WANT_READ: - case SSL_ERROR_WANT_WRITE: - case SSL_ERROR_WANT_X509_LOOKUP: - case SSL_ERROR_ZERO_RETURN: - return; - /* These seem to be indications of a genuine error that should - * result in the SSL tunnel being regarded as "dead". */ - case SSL_ERROR_SYSCALL: - case SSL_ERROR_SSL: - SSL_set_app_data(s, (char *)1); - return; - default: - break; - } - /* For any other errors that (a) exist, and (b) crop up - we need to - * interpret what to do with them - so "politely inform" the caller that - * the code needs updating here. */ - abort(); -} - -void buffer_from_SSL(buffer_t *buf, SSL *ssl) -{ - int ret; - if(!ssl || buffer_full(buf)) - return; - ret = SSL_read(ssl, buf->data + buf->used, buffer_unused(buf)); - if(ret > 0) { - buf->used += ret; - buf->total_in += ret; - } - if(ret < 0) - int_ssl_check(ssl, ret); -} - -void buffer_to_SSL(buffer_t *buf, SSL *ssl) -{ - int ret; - if(!ssl || buffer_empty(buf)) - return; - ret = SSL_write(ssl, buf->data, buf->used); - if(ret > 0) { - buffer_takedata(buf, NULL, ret); - buf->total_out += ret; - } - if(ret < 0) - int_ssl_check(ssl, ret); -} - -void buffer_from_BIO(buffer_t *buf, BIO *bio) -{ - int ret; - if(!bio || buffer_full(buf)) - return; - ret = BIO_read(bio, buf->data + buf->used, buffer_unused(buf)); - if(ret > 0) { - buf->used += ret; - buf->total_in += ret; - } -} - -void buffer_to_BIO(buffer_t *buf, BIO *bio) -{ - int ret; - if(!bio || buffer_empty(buf)) - return; - ret = BIO_write(bio, buf->data, buf->used); - if(ret > 0) { - buffer_takedata(buf, NULL, ret); - buf->total_out += ret; - } -} - -#endif /* !defined(NO_OPENSSL) */ - -#endif /* !defined(NO_BUFFER) */ + int e = SSL_get_error(s, ret); + switch (e) { + /* + * These seem to be harmless and already "dealt with" by our + * non-blocking environment. NB: "ZERO_RETURN" is the clean "error" + * indicating a successfully closed SSL tunnel. We let this happen + * because our IO loop should not appear to have broken on this + * condition - and outside the IO loop, the "shutdown" state is + * checked. + */ + case SSL_ERROR_NONE: + case SSL_ERROR_WANT_READ: + case SSL_ERROR_WANT_WRITE: + case SSL_ERROR_WANT_X509_LOOKUP: + case SSL_ERROR_ZERO_RETURN: + return; + /* + * These seem to be indications of a genuine error that should result + * in the SSL tunnel being regarded as "dead". + */ + case SSL_ERROR_SYSCALL: + case SSL_ERROR_SSL: + SSL_set_app_data(s, (char *)1); + return; + default: + break; + } + /* + * For any other errors that (a) exist, and (b) crop up - we need to + * interpret what to do with them - so "politely inform" the caller that + * the code needs updating here. + */ + abort(); +} + +void buffer_from_SSL(buffer_t * buf, SSL *ssl) +{ + int ret; + if (!ssl || buffer_full(buf)) + return; + ret = SSL_read(ssl, buf->data + buf->used, buffer_unused(buf)); + if (ret > 0) { + buf->used += ret; + buf->total_in += ret; + } + if (ret < 0) + int_ssl_check(ssl, ret); +} + +void buffer_to_SSL(buffer_t * buf, SSL *ssl) +{ + int ret; + if (!ssl || buffer_empty(buf)) + return; + ret = SSL_write(ssl, buf->data, buf->used); + if (ret > 0) { + buffer_takedata(buf, NULL, ret); + buf->total_out += ret; + } + if (ret < 0) + int_ssl_check(ssl, ret); +} + +void buffer_from_BIO(buffer_t * buf, BIO *bio) +{ + int ret; + if (!bio || buffer_full(buf)) + return; + ret = BIO_read(bio, buf->data + buf->used, buffer_unused(buf)); + if (ret > 0) { + buf->used += ret; + buf->total_in += ret; + } +} + +void buffer_to_BIO(buffer_t * buf, BIO *bio) +{ + int ret; + if (!bio || buffer_empty(buf)) + return; + ret = BIO_write(bio, buf->data, buf->used); + if (ret > 0) { + buffer_takedata(buf, NULL, ret); + buf->total_out += ret; + } +} + +# endif /* !defined(NO_OPENSSL) */ + +#endif /* !defined(NO_BUFFER) */ diff --git a/openssl/demos/tunala/cb.c b/openssl/demos/tunala/cb.c index f6e452ae9..684a07f08 100644 --- a/openssl/demos/tunala/cb.c +++ b/openssl/demos/tunala/cb.c @@ -5,7 +5,8 @@ /* For callbacks generating output, here are their file-descriptors. */ static FILE *fp_cb_ssl_info = NULL; static FILE *fp_cb_ssl_verify = NULL; -/* Output level: +/*- + * Output level: * 0 = nothing, * 1 = minimal, just errors, * 2 = minimal, all steps, @@ -15,148 +16,158 @@ static unsigned int cb_ssl_verify_level = 1; /* Other static rubbish (to mirror s_cb.c where required) */ static int int_verify_depth = 10; -/* This function is largely borrowed from the one used in OpenSSL's "s_client" - * and "s_server" utilities. */ +/* + * This function is largely borrowed from the one used in OpenSSL's + * "s_client" and "s_server" utilities. + */ void cb_ssl_info(const SSL *s, int where, int ret) { - const char *str1, *str2; - int w; - - if(!fp_cb_ssl_info) - return; - - w = where & ~SSL_ST_MASK; - str1 = (w & SSL_ST_CONNECT ? "SSL_connect" : (w & SSL_ST_ACCEPT ? - "SSL_accept" : "undefined")), - str2 = SSL_state_string_long(s); - - if (where & SSL_CB_LOOP) - fprintf(fp_cb_ssl_info, "(%s) %s\n", str1, str2); - else if (where & SSL_CB_EXIT) { - if (ret == 0) - fprintf(fp_cb_ssl_info, "(%s) failed in %s\n", str1, str2); -/* In a non-blocking model, we get a few of these "error"s simply because we're - * calling "reads" and "writes" on the state-machine that are virtual NOPs - * simply to avoid wasting the time seeing if we *should* call them. Removing - * this case makes the "-out_state" output a lot easier on the eye. */ -#if 0 - else if (ret < 0) - fprintf(fp_cb_ssl_info, "%s:error in %s\n", str1, str2); -#endif - } + const char *str1, *str2; + int w; + + if (!fp_cb_ssl_info) + return; + + w = where & ~SSL_ST_MASK; + str1 = (w & SSL_ST_CONNECT ? "SSL_connect" : (w & SSL_ST_ACCEPT ? + "SSL_accept" : + "undefined")), str2 = + SSL_state_string_long(s); + + if (where & SSL_CB_LOOP) + fprintf(fp_cb_ssl_info, "(%s) %s\n", str1, str2); + else if (where & SSL_CB_EXIT) { + if (ret == 0) + fprintf(fp_cb_ssl_info, "(%s) failed in %s\n", str1, str2); + /* + * In a non-blocking model, we get a few of these "error"s simply + * because we're calling "reads" and "writes" on the state-machine + * that are virtual NOPs simply to avoid wasting the time seeing if + * we *should* call them. Removing this case makes the "-out_state" + * output a lot easier on the eye. + */ +# if 0 + else if (ret < 0) + fprintf(fp_cb_ssl_info, "%s:error in %s\n", str1, str2); +# endif + } } void cb_ssl_info_set_output(FILE *fp) { - fp_cb_ssl_info = fp; + fp_cb_ssl_info = fp; } -static const char *int_reason_no_issuer = "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT"; +static const char *int_reason_no_issuer = + "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT"; static const char *int_reason_not_yet = "X509_V_ERR_CERT_NOT_YET_VALID"; -static const char *int_reason_before = "X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD"; +static const char *int_reason_before = + "X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD"; static const char *int_reason_expired = "X509_V_ERR_CERT_HAS_EXPIRED"; -static const char *int_reason_after = "X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD"; +static const char *int_reason_after = + "X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD"; /* Stolen wholesale from apps/s_cb.c :-) And since then, mutilated ... */ int cb_ssl_verify(int ok, X509_STORE_CTX *ctx) { - char buf1[256]; /* Used for the subject name */ - char buf2[256]; /* Used for the issuer name */ - const char *reason = NULL; /* Error reason (if any) */ - X509 *err_cert; - int err, depth; - - if(!fp_cb_ssl_verify || (cb_ssl_verify_level == 0)) - return ok; - err_cert = X509_STORE_CTX_get_current_cert(ctx); - err = X509_STORE_CTX_get_error(ctx); - depth = X509_STORE_CTX_get_error_depth(ctx); - - buf1[0] = buf2[0] = '\0'; - /* Fill buf1 */ - X509_NAME_oneline(X509_get_subject_name(err_cert), buf1, 256); - /* Fill buf2 */ - X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf2, 256); - switch (ctx->error) { - case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: - reason = int_reason_no_issuer; - break; - case X509_V_ERR_CERT_NOT_YET_VALID: - reason = int_reason_not_yet; - break; - case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: - reason = int_reason_before; - break; - case X509_V_ERR_CERT_HAS_EXPIRED: - reason = int_reason_expired; - break; - case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: - reason = int_reason_after; - break; - } - - if((cb_ssl_verify_level == 1) && ok) - return ok; - fprintf(fp_cb_ssl_verify, "chain-depth=%d, ", depth); - if(reason) - fprintf(fp_cb_ssl_verify, "error=%s\n", reason); - else - fprintf(fp_cb_ssl_verify, "error=%d\n", err); - if(cb_ssl_verify_level < 3) - return ok; - fprintf(fp_cb_ssl_verify, "--> subject = %s\n", buf1); - fprintf(fp_cb_ssl_verify, "--> issuer = %s\n", buf2); - if(!ok) - fprintf(fp_cb_ssl_verify,"--> verify error:num=%d:%s\n",err, - X509_verify_cert_error_string(err)); - fprintf(fp_cb_ssl_verify, "--> verify return:%d\n",ok); - return ok; + char buf1[256]; /* Used for the subject name */ + char buf2[256]; /* Used for the issuer name */ + const char *reason = NULL; /* Error reason (if any) */ + X509 *err_cert; + int err, depth; + + if (!fp_cb_ssl_verify || (cb_ssl_verify_level == 0)) + return ok; + err_cert = X509_STORE_CTX_get_current_cert(ctx); + err = X509_STORE_CTX_get_error(ctx); + depth = X509_STORE_CTX_get_error_depth(ctx); + + buf1[0] = buf2[0] = '\0'; + /* Fill buf1 */ + X509_NAME_oneline(X509_get_subject_name(err_cert), buf1, 256); + /* Fill buf2 */ + X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf2, 256); + switch (ctx->error) { + case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: + reason = int_reason_no_issuer; + break; + case X509_V_ERR_CERT_NOT_YET_VALID: + reason = int_reason_not_yet; + break; + case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: + reason = int_reason_before; + break; + case X509_V_ERR_CERT_HAS_EXPIRED: + reason = int_reason_expired; + break; + case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: + reason = int_reason_after; + break; + } + + if ((cb_ssl_verify_level == 1) && ok) + return ok; + fprintf(fp_cb_ssl_verify, "chain-depth=%d, ", depth); + if (reason) + fprintf(fp_cb_ssl_verify, "error=%s\n", reason); + else + fprintf(fp_cb_ssl_verify, "error=%d\n", err); + if (cb_ssl_verify_level < 3) + return ok; + fprintf(fp_cb_ssl_verify, "--> subject = %s\n", buf1); + fprintf(fp_cb_ssl_verify, "--> issuer = %s\n", buf2); + if (!ok) + fprintf(fp_cb_ssl_verify, "--> verify error:num=%d:%s\n", err, + X509_verify_cert_error_string(err)); + fprintf(fp_cb_ssl_verify, "--> verify return:%d\n", ok); + return ok; } void cb_ssl_verify_set_output(FILE *fp) { - fp_cb_ssl_verify = fp; + fp_cb_ssl_verify = fp; } void cb_ssl_verify_set_depth(unsigned int verify_depth) { - int_verify_depth = verify_depth; + int_verify_depth = verify_depth; } void cb_ssl_verify_set_level(unsigned int level) { - if(level < 4) - cb_ssl_verify_level = level; + if (level < 4) + cb_ssl_verify_level = level; } RSA *cb_generate_tmp_rsa(SSL *s, int is_export, int keylength) { - /* TODO: Perhaps make it so our global key can be generated on-the-fly - * after certain intervals? */ - static RSA *rsa_tmp = NULL; - BIGNUM *bn = NULL; - int ok = 1; - if(!rsa_tmp) { - ok = 0; - if(!(bn = BN_new())) - goto end; - if(!BN_set_word(bn, RSA_F4)) - goto end; - if(!(rsa_tmp = RSA_new())) - goto end; - if(!RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) - goto end; - ok = 1; - } -end: - if(bn) - BN_free(bn); - if(!ok) { - RSA_free(rsa_tmp); - rsa_tmp = NULL; - } - return rsa_tmp; + /* + * TODO: Perhaps make it so our global key can be generated on-the-fly + * after certain intervals? + */ + static RSA *rsa_tmp = NULL; + BIGNUM *bn = NULL; + int ok = 1; + if (!rsa_tmp) { + ok = 0; + if (!(bn = BN_new())) + goto end; + if (!BN_set_word(bn, RSA_F4)) + goto end; + if (!(rsa_tmp = RSA_new())) + goto end; + if (!RSA_generate_key_ex(rsa_tmp, keylength, bn, NULL)) + goto end; + ok = 1; + } + end: + if (bn) + BN_free(bn); + if (!ok) { + RSA_free(rsa_tmp); + rsa_tmp = NULL; + } + return rsa_tmp; } -#endif /* !defined(NO_OPENSSL) */ - +#endif /* !defined(NO_OPENSSL) */ diff --git a/openssl/demos/tunala/ip.c b/openssl/demos/tunala/ip.c index 96ef4e653..b172d2e4e 100644 --- a/openssl/demos/tunala/ip.c +++ b/openssl/demos/tunala/ip.c @@ -2,145 +2,148 @@ #ifndef NO_IP -#define IP_LISTENER_BACKLOG 511 /* So if it gets masked by 256 or some other - such value it'll still be respectable */ +# define IP_LISTENER_BACKLOG 511/* So if it gets masked by 256 or some other + * such value it'll still be respectable */ /* Any IP-related initialisations. For now, this means blocking SIGPIPE */ int ip_initialise(void) { - struct sigaction sa; - - sa.sa_handler = SIG_IGN; - sa.sa_flags = 0; - sigemptyset(&sa.sa_mask); - if(sigaction(SIGPIPE, &sa, NULL) != 0) - return 0; - return 1; + struct sigaction sa; + + sa.sa_handler = SIG_IGN; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + if (sigaction(SIGPIPE, &sa, NULL) != 0) + return 0; + return 1; } int ip_create_listener_split(const char *ip, unsigned short port) { - struct sockaddr_in in_addr; - int fd = -1; - int reuseVal = 1; - - /* Create the socket */ - if((fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) - goto err; - /* Set the SO_REUSEADDR flag - servers act weird without it */ - if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)(&reuseVal), - sizeof(reuseVal)) != 0) - goto err; - /* Prepare the listen address stuff */ - in_addr.sin_family = AF_INET; - memcpy(&in_addr.sin_addr.s_addr, ip, 4); - in_addr.sin_port = htons(port); - /* Bind to the required port/address/interface */ - if(bind(fd, (struct sockaddr *)&in_addr, sizeof(struct sockaddr_in)) != 0) - goto err; - /* Start "listening" */ - if(listen(fd, IP_LISTENER_BACKLOG) != 0) - goto err; - return fd; -err: - if(fd != -1) - close(fd); - return -1; + struct sockaddr_in in_addr; + int fd = -1; + int reuseVal = 1; + + /* Create the socket */ + if ((fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) + goto err; + /* Set the SO_REUSEADDR flag - servers act weird without it */ + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)(&reuseVal), + sizeof(reuseVal)) != 0) + goto err; + /* Prepare the listen address stuff */ + in_addr.sin_family = AF_INET; + memcpy(&in_addr.sin_addr.s_addr, ip, 4); + in_addr.sin_port = htons(port); + /* Bind to the required port/address/interface */ + if (bind(fd, (struct sockaddr *)&in_addr, sizeof(struct sockaddr_in)) != + 0) + goto err; + /* Start "listening" */ + if (listen(fd, IP_LISTENER_BACKLOG) != 0) + goto err; + return fd; + err: + if (fd != -1) + close(fd); + return -1; } int ip_create_connection_split(const char *ip, unsigned short port) { - struct sockaddr_in in_addr; - int flags, fd = -1; - - /* Create the socket */ - if((fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) - goto err; - /* Make it non-blocking */ - if(((flags = fcntl(fd, F_GETFL, 0)) < 0) || - (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)) - goto err; - /* Prepare the connection address stuff */ - in_addr.sin_family = AF_INET; - memcpy(&in_addr.sin_addr.s_addr, ip, 4); - in_addr.sin_port = htons(port); - /* Start a connect (non-blocking, in all likelihood) */ - if((connect(fd, (struct sockaddr *)&in_addr, - sizeof(struct sockaddr_in)) != 0) && - (errno != EINPROGRESS)) - goto err; - return fd; -err: - if(fd != -1) - close(fd); - return -1; + struct sockaddr_in in_addr; + int flags, fd = -1; + + /* Create the socket */ + if ((fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) + goto err; + /* Make it non-blocking */ + if (((flags = fcntl(fd, F_GETFL, 0)) < 0) || + (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)) + goto err; + /* Prepare the connection address stuff */ + in_addr.sin_family = AF_INET; + memcpy(&in_addr.sin_addr.s_addr, ip, 4); + in_addr.sin_port = htons(port); + /* Start a connect (non-blocking, in all likelihood) */ + if ((connect(fd, (struct sockaddr *)&in_addr, + sizeof(struct sockaddr_in)) != 0) && (errno != EINPROGRESS)) + goto err; + return fd; + err: + if (fd != -1) + close(fd); + return -1; } -static char all_local_ip[] = {0x00,0x00,0x00,0x00}; +static char all_local_ip[] = { 0x00, 0x00, 0x00, 0x00 }; int ip_parse_address(const char *address, const char **parsed_ip, - unsigned short *parsed_port, int accept_all_ip) + unsigned short *parsed_port, int accept_all_ip) { - char buf[256]; - struct hostent *lookup; - unsigned long port; - const char *ptr = strstr(address, ":"); - const char *ip = all_local_ip; - - if(!ptr) { - /* We assume we're listening on all local interfaces and have - * only specified a port. */ - if(!accept_all_ip) - return 0; - ptr = address; - goto determine_port; - } - if((ptr - address) > 255) - return 0; - memset(buf, 0, 256); - memcpy(buf, address, ptr - address); - ptr++; - if((lookup = gethostbyname(buf)) == NULL) { - /* Spit a message to differentiate between lookup failures and - * bad strings. */ - fprintf(stderr, "hostname lookup for '%s' failed\n", buf); - return 0; - } - ip = lookup->h_addr_list[0]; -determine_port: - if(strlen(ptr) < 1) - return 0; - if(!int_strtoul(ptr, &port) || (port > 65535)) - return 0; - *parsed_ip = ip; - *parsed_port = (unsigned short)port; - return 1; + char buf[256]; + struct hostent *lookup; + unsigned long port; + const char *ptr = strstr(address, ":"); + const char *ip = all_local_ip; + + if (!ptr) { + /* + * We assume we're listening on all local interfaces and have only + * specified a port. + */ + if (!accept_all_ip) + return 0; + ptr = address; + goto determine_port; + } + if ((ptr - address) > 255) + return 0; + memset(buf, 0, 256); + memcpy(buf, address, ptr - address); + ptr++; + if ((lookup = gethostbyname(buf)) == NULL) { + /* + * Spit a message to differentiate between lookup failures and bad + * strings. + */ + fprintf(stderr, "hostname lookup for '%s' failed\n", buf); + return 0; + } + ip = lookup->h_addr_list[0]; + determine_port: + if (strlen(ptr) < 1) + return 0; + if (!int_strtoul(ptr, &port) || (port > 65535)) + return 0; + *parsed_ip = ip; + *parsed_port = (unsigned short)port; + return 1; } int ip_create_listener(const char *address) { - const char *ip; - unsigned short port; + const char *ip; + unsigned short port; - if(!ip_parse_address(address, &ip, &port, 1)) - return -1; - return ip_create_listener_split(ip, port); + if (!ip_parse_address(address, &ip, &port, 1)) + return -1; + return ip_create_listener_split(ip, port); } int ip_create_connection(const char *address) { - const char *ip; - unsigned short port; + const char *ip; + unsigned short port; - if(!ip_parse_address(address, &ip, &port, 0)) - return -1; - return ip_create_connection_split(ip, port); + if (!ip_parse_address(address, &ip, &port, 0)) + return -1; + return ip_create_connection_split(ip, port); } int ip_accept_connection(int listen_fd) { - return accept(listen_fd, NULL, NULL); + return accept(listen_fd, NULL, NULL); } -#endif /* !defined(NO_IP) */ - +#endif /* !defined(NO_IP) */ diff --git a/openssl/demos/tunala/sm.c b/openssl/demos/tunala/sm.c index 25359e67e..5658dfff2 100644 --- a/openssl/demos/tunala/sm.c +++ b/openssl/demos/tunala/sm.c @@ -2,150 +2,163 @@ #ifndef NO_TUNALA -void state_machine_init(state_machine_t *machine) +void state_machine_init(state_machine_t * machine) { - machine->ssl = NULL; - machine->bio_intossl = machine->bio_fromssl = NULL; - buffer_init(&machine->clean_in); - buffer_init(&machine->clean_out); - buffer_init(&machine->dirty_in); - buffer_init(&machine->dirty_out); + machine->ssl = NULL; + machine->bio_intossl = machine->bio_fromssl = NULL; + buffer_init(&machine->clean_in); + buffer_init(&machine->clean_out); + buffer_init(&machine->dirty_in); + buffer_init(&machine->dirty_out); } -void state_machine_close(state_machine_t *machine) +void state_machine_close(state_machine_t * machine) { - if(machine->ssl) - SSL_free(machine->ssl); -/* SSL_free seems to decrement the reference counts already so doing this goes - * kaboom. */ -#if 0 - if(machine->bio_intossl) - BIO_free(machine->bio_intossl); - if(machine->bio_fromssl) - BIO_free(machine->bio_fromssl); -#endif - buffer_close(&machine->clean_in); - buffer_close(&machine->clean_out); - buffer_close(&machine->dirty_in); - buffer_close(&machine->dirty_out); - state_machine_init(machine); + if (machine->ssl) + SSL_free(machine->ssl); + /* + * SSL_free seems to decrement the reference counts already so doing this + * goes kaboom. + */ +# if 0 + if (machine->bio_intossl) + BIO_free(machine->bio_intossl); + if (machine->bio_fromssl) + BIO_free(machine->bio_fromssl); +# endif + buffer_close(&machine->clean_in); + buffer_close(&machine->clean_out); + buffer_close(&machine->dirty_in); + buffer_close(&machine->dirty_out); + state_machine_init(machine); } -buffer_t *state_machine_get_buffer(state_machine_t *machine, sm_buffer_t type) +buffer_t *state_machine_get_buffer(state_machine_t * machine, + sm_buffer_t type) { - switch(type) { - case SM_CLEAN_IN: - return &machine->clean_in; - case SM_CLEAN_OUT: - return &machine->clean_out; - case SM_DIRTY_IN: - return &machine->dirty_in; - case SM_DIRTY_OUT: - return &machine->dirty_out; - default: - break; - } - /* Should never get here */ - abort(); - return NULL; + switch (type) { + case SM_CLEAN_IN: + return &machine->clean_in; + case SM_CLEAN_OUT: + return &machine->clean_out; + case SM_DIRTY_IN: + return &machine->dirty_in; + case SM_DIRTY_OUT: + return &machine->dirty_out; + default: + break; + } + /* Should never get here */ + abort(); + return NULL; } -SSL *state_machine_get_SSL(state_machine_t *machine) +SSL *state_machine_get_SSL(state_machine_t * machine) { - return machine->ssl; + return machine->ssl; } -int state_machine_set_SSL(state_machine_t *machine, SSL *ssl, int is_server) +int state_machine_set_SSL(state_machine_t * machine, SSL *ssl, int is_server) { - if(machine->ssl) - /* Shouldn't ever be set twice */ - abort(); - machine->ssl = ssl; - /* Create the BIOs to handle the dirty side of the SSL */ - if((machine->bio_intossl = BIO_new(BIO_s_mem())) == NULL) - abort(); - if((machine->bio_fromssl = BIO_new(BIO_s_mem())) == NULL) - abort(); - /* Hook up the BIOs on the dirty side of the SSL */ - SSL_set_bio(machine->ssl, machine->bio_intossl, machine->bio_fromssl); - if(is_server) - SSL_set_accept_state(machine->ssl); - else - SSL_set_connect_state(machine->ssl); - /* If we're the first one to generate traffic - do it now otherwise we - * go into the next select empty-handed and our peer will not send data - * but will similarly wait for us. */ - return state_machine_churn(machine); + if (machine->ssl) + /* Shouldn't ever be set twice */ + abort(); + machine->ssl = ssl; + /* Create the BIOs to handle the dirty side of the SSL */ + if ((machine->bio_intossl = BIO_new(BIO_s_mem())) == NULL) + abort(); + if ((machine->bio_fromssl = BIO_new(BIO_s_mem())) == NULL) + abort(); + /* Hook up the BIOs on the dirty side of the SSL */ + SSL_set_bio(machine->ssl, machine->bio_intossl, machine->bio_fromssl); + if (is_server) + SSL_set_accept_state(machine->ssl); + else + SSL_set_connect_state(machine->ssl); + /* + * If we're the first one to generate traffic - do it now otherwise we go + * into the next select empty-handed and our peer will not send data but + * will similarly wait for us. + */ + return state_machine_churn(machine); } /* Performs the data-IO loop and returns zero if the machine should close */ -int state_machine_churn(state_machine_t *machine) +int state_machine_churn(state_machine_t * machine) { - unsigned int loop; - if(machine->ssl == NULL) { - if(buffer_empty(&machine->clean_out)) - /* Time to close this state-machine altogether */ - return 0; - else - /* Still buffered data on the clean side to go out */ - return 1; - } - /* Do this loop twice to cover any dependencies about which precise - * order of reads and writes is required. */ - for(loop = 0; loop < 2; loop++) { - buffer_to_SSL(&machine->clean_in, machine->ssl); - buffer_to_BIO(&machine->dirty_in, machine->bio_intossl); - buffer_from_SSL(&machine->clean_out, machine->ssl); - buffer_from_BIO(&machine->dirty_out, machine->bio_fromssl); - } - /* We close on the SSL side if the info callback noticed some problems - * or an SSL shutdown was underway and shutdown traffic had all been - * sent. */ - if(SSL_get_app_data(machine->ssl) || (SSL_get_shutdown(machine->ssl) && - buffer_empty(&machine->dirty_out))) { - /* Great, we can seal off the dirty side completely */ - if(!state_machine_close_dirty(machine)) - return 0; - } - /* Either the SSL is alive and well, or the closing process still has - * outgoing data waiting to be sent */ - return 1; + unsigned int loop; + if (machine->ssl == NULL) { + if (buffer_empty(&machine->clean_out)) + /* Time to close this state-machine altogether */ + return 0; + else + /* Still buffered data on the clean side to go out */ + return 1; + } + /* + * Do this loop twice to cover any dependencies about which precise order + * of reads and writes is required. + */ + for (loop = 0; loop < 2; loop++) { + buffer_to_SSL(&machine->clean_in, machine->ssl); + buffer_to_BIO(&machine->dirty_in, machine->bio_intossl); + buffer_from_SSL(&machine->clean_out, machine->ssl); + buffer_from_BIO(&machine->dirty_out, machine->bio_fromssl); + } + /* + * We close on the SSL side if the info callback noticed some problems or + * an SSL shutdown was underway and shutdown traffic had all been sent. + */ + if (SSL_get_app_data(machine->ssl) || (SSL_get_shutdown(machine->ssl) && + buffer_empty(&machine->dirty_out))) + { + /* Great, we can seal off the dirty side completely */ + if (!state_machine_close_dirty(machine)) + return 0; + } + /* + * Either the SSL is alive and well, or the closing process still has + * outgoing data waiting to be sent + */ + return 1; } /* Called when the clean side of the SSL has lost its connection */ -int state_machine_close_clean(state_machine_t *machine) +int state_machine_close_clean(state_machine_t * machine) { - /* Well, first thing to do is null out the clean-side buffers - they're - * no use any more. */ - buffer_close(&machine->clean_in); - buffer_close(&machine->clean_out); - /* And start an SSL shutdown */ - if(machine->ssl) - SSL_shutdown(machine->ssl); - /* This is an "event", so flush the SSL of any generated traffic */ - state_machine_churn(machine); - if(buffer_empty(&machine->dirty_in) && - buffer_empty(&machine->dirty_out)) - return 0; - return 1; + /* + * Well, first thing to do is null out the clean-side buffers - they're + * no use any more. + */ + buffer_close(&machine->clean_in); + buffer_close(&machine->clean_out); + /* And start an SSL shutdown */ + if (machine->ssl) + SSL_shutdown(machine->ssl); + /* This is an "event", so flush the SSL of any generated traffic */ + state_machine_churn(machine); + if (buffer_empty(&machine->dirty_in) && buffer_empty(&machine->dirty_out)) + return 0; + return 1; } -/* Called when the dirty side of the SSL has lost its connection. This is pretty - * terminal as all that can be left to do is send any buffered output on the - * clean side - after that, we're done. */ -int state_machine_close_dirty(state_machine_t *machine) +/* + * Called when the dirty side of the SSL has lost its connection. This is + * pretty terminal as all that can be left to do is send any buffered output + * on the clean side - after that, we're done. + */ +int state_machine_close_dirty(state_machine_t * machine) { - buffer_close(&machine->dirty_in); - buffer_close(&machine->dirty_out); - buffer_close(&machine->clean_in); - if(machine->ssl) - SSL_free(machine->ssl); - machine->ssl = NULL; - machine->bio_intossl = machine->bio_fromssl = NULL; - if(buffer_empty(&machine->clean_out)) - return 0; - return 1; + buffer_close(&machine->dirty_in); + buffer_close(&machine->dirty_out); + buffer_close(&machine->clean_in); + if (machine->ssl) + SSL_free(machine->ssl); + machine->ssl = NULL; + machine->bio_intossl = machine->bio_fromssl = NULL; + if (buffer_empty(&machine->clean_out)) + return 0; + return 1; } -#endif /* !defined(NO_TUNALA) */ - +#endif /* !defined(NO_TUNALA) */ diff --git a/openssl/demos/tunala/tunala.c b/openssl/demos/tunala/tunala.c index ec49d3e94..11a7c5bb1 100644 --- a/openssl/demos/tunala/tunala.c +++ b/openssl/demos/tunala/tunala.c @@ -1,65 +1,81 @@ #if defined(NO_BUFFER) || defined(NO_IP) || defined(NO_OPENSSL) -#error "Badness, NO_BUFFER, NO_IP or NO_OPENSSL is defined, turn them *off*" +# error "Badness, NO_BUFFER, NO_IP or NO_OPENSSL is defined, turn them *off*" #endif /* Include our bits'n'pieces */ #include "tunala.h" - /********************************************/ /* Our local types that specify our "world" */ /********************************************/ -/* These represent running "tunnels". Eg. if you wanted to do SSL in a - * "message-passing" scanario, the "int" file-descriptors might be replaced by - * thread or process IDs, and the "select" code might be replaced by message - * handling code. Whatever. */ +/* + * These represent running "tunnels". Eg. if you wanted to do SSL in a + * "message-passing" scanario, the "int" file-descriptors might be replaced + * by thread or process IDs, and the "select" code might be replaced by + * message handling code. Whatever. + */ typedef struct _tunala_item_t { - /* The underlying SSL state machine. This is a data-only processing unit - * and we communicate with it by talking to its four "buffers". */ - state_machine_t sm; - /* The file-descriptors for the "dirty" (encrypted) side of the SSL - * setup. In actuality, this is typically a socket and both values are - * identical. */ - int dirty_read, dirty_send; - /* The file-descriptors for the "clean" (unencrypted) side of the SSL - * setup. These could be stdin/stdout, a socket (both values the same), - * or whatever you like. */ - int clean_read, clean_send; + /* + * The underlying SSL state machine. This is a data-only processing unit + * and we communicate with it by talking to its four "buffers". + */ + state_machine_t sm; + /* + * The file-descriptors for the "dirty" (encrypted) side of the SSL + * setup. In actuality, this is typically a socket and both values are + * identical. + */ + int dirty_read, dirty_send; + /* + * The file-descriptors for the "clean" (unencrypted) side of the SSL + * setup. These could be stdin/stdout, a socket (both values the same), + * or whatever you like. + */ + int clean_read, clean_send; } tunala_item_t; -/* This structure is used as the data for running the main loop. Namely, in a +/* + * This structure is used as the data for running the main loop. Namely, in a * network format such as this, it is stuff for select() - but as pointed out, * when moving the real-world to somewhere else, this might be replaced by * something entirely different. It's basically the stuff that controls when - * it's time to do some "work". */ + * it's time to do some "work". + */ typedef struct _select_sets_t { - int max; /* As required as the first argument to select() */ - fd_set reads, sends, excepts; /* As passed to select() */ + int max; /* As required as the first argument to + * select() */ + fd_set reads, sends, excepts; /* As passed to select() */ } select_sets_t; typedef struct _tunala_selector_t { - select_sets_t last_selected; /* Results of the last select() */ - select_sets_t next_select; /* What we'll next select on */ + select_sets_t last_selected; /* Results of the last select() */ + select_sets_t next_select; /* What we'll next select on */ } tunala_selector_t; -/* This structure is *everything*. We do it to avoid the use of globals so that, - * for example, it would be easier to shift things around between async-IO, - * thread-based, or multi-fork()ed (or combinations thereof). */ +/* + * This structure is *everything*. We do it to avoid the use of globals so + * that, for example, it would be easier to shift things around between + * async-IO, thread-based, or multi-fork()ed (or combinations thereof). + */ typedef struct _tunala_world_t { - /* The file-descriptor we "listen" on for new connections */ - int listen_fd; - /* The array of tunnels */ - tunala_item_t *tunnels; - /* the number of tunnels in use and allocated, respectively */ - unsigned int tunnels_used, tunnels_size; - /* Our outside "loop" context stuff */ - tunala_selector_t selector; - /* Our SSL_CTX, which is configured as the SSL client or server and has - * the various cert-settings and callbacks configured. */ - SSL_CTX *ssl_ctx; - /* Simple flag with complex logic :-) Indicates whether we're an SSL - * server or an SSL client. */ - int server_mode; + /* The file-descriptor we "listen" on for new connections */ + int listen_fd; + /* The array of tunnels */ + tunala_item_t *tunnels; + /* the number of tunnels in use and allocated, respectively */ + unsigned int tunnels_used, tunnels_size; + /* Our outside "loop" context stuff */ + tunala_selector_t selector; + /* + * Our SSL_CTX, which is configured as the SSL client or server and has + * the various cert-settings and callbacks configured. + */ + SSL_CTX *ssl_ctx; + /* + * Simple flag with complex logic :-) Indicates whether we're an SSL + * server or an SSL client. + */ + int server_mode; } tunala_world_t; /*****************************/ @@ -67,22 +83,30 @@ typedef struct _tunala_world_t { /*****************************/ static SSL_CTX *initialise_ssl_ctx(int server_mode, const char *engine_id, - const char *CAfile, const char *cert, const char *key, - const char *dcert, const char *dkey, const char *cipher_list, - const char *dh_file, const char *dh_special, int tmp_rsa, - int ctx_options, int out_state, int out_verify, int verify_mode, - unsigned int verify_depth); -static void selector_init(tunala_selector_t *selector); -static void selector_add_listener(tunala_selector_t *selector, int fd); -static void selector_add_tunala(tunala_selector_t *selector, tunala_item_t *t); -static int selector_select(tunala_selector_t *selector); -/* This returns -1 for error, 0 for no new connections, or 1 for success, in - * which case *newfd is populated. */ -static int selector_get_listener(tunala_selector_t *selector, int fd, int *newfd); -static int tunala_world_new_item(tunala_world_t *world, int fd, - const char *ip, unsigned short port, int flipped); -static void tunala_world_del_item(tunala_world_t *world, unsigned int idx); -static int tunala_item_io(tunala_selector_t *selector, tunala_item_t *item); + const char *CAfile, const char *cert, + const char *key, const char *dcert, + const char *dkey, const char *cipher_list, + const char *dh_file, + const char *dh_special, int tmp_rsa, + int ctx_options, int out_state, + int out_verify, int verify_mode, + unsigned int verify_depth); +static void selector_init(tunala_selector_t * selector); +static void selector_add_listener(tunala_selector_t * selector, int fd); +static void selector_add_tunala(tunala_selector_t * selector, + tunala_item_t * t); +static int selector_select(tunala_selector_t * selector); +/* + * This returns -1 for error, 0 for no new connections, or 1 for success, in + * which case *newfd is populated. + */ +static int selector_get_listener(tunala_selector_t * selector, int fd, + int *newfd); +static int tunala_world_new_item(tunala_world_t * world, int fd, + const char *ip, unsigned short port, + int flipped); +static void tunala_world_del_item(tunala_world_t * world, unsigned int idx); +static int tunala_item_io(tunala_selector_t * selector, tunala_item_t * item); /*********************************************/ /* MAIN FUNCTION (and its utility functions) */ @@ -112,492 +136,518 @@ static int def_out_totals = 0; static int def_out_conns = 0; static const char *helpstring = -"\n'Tunala' (A tunneler with a New Zealand accent)\n" -"Usage: tunala [options], where options are from;\n" -" -listen [host:]<port> (default = 127.0.0.1:8080)\n" -" -proxy <host>:<port> (default = 127.0.0.1:443)\n" -" -maxtunnels <num> (default = 50)\n" -" -cacert <path|NULL> (default = NULL)\n" -" -cert <path|NULL> (default = NULL)\n" -" -key <path|NULL> (default = whatever '-cert' is)\n" -" -dcert <path|NULL> (usually for DSA, default = NULL)\n" -" -dkey <path|NULL> (usually for DSA, default = whatever '-dcert' is)\n" -" -engine <id|NULL> (default = NULL)\n" -" -server <0|1> (default = 0, ie. an SSL client)\n" -" -flipped <0|1> (makes SSL servers be network clients, and vice versa)\n" -" -cipher <list> (specifies cipher list to use)\n" -" -dh_file <path> (a PEM file containing DH parameters to use)\n" -" -dh_special <NULL|generate|standard> (see below: def=NULL)\n" -" -no_tmp_rsa (don't generate temporary RSA keys)\n" -" -no_ssl2 (disable SSLv2)\n" -" -no_ssl3 (disable SSLv3)\n" -" -no_tls1 (disable TLSv1)\n" -" -v_peer (verify the peer certificate)\n" -" -v_strict (do not continue if peer doesn't authenticate)\n" -" -v_once (no verification in renegotiates)\n" -" -v_depth <num> (limit certificate chain depth, default = 10)\n" -" -out_conns (prints client connections and disconnections)\n" -" -out_state (prints SSL handshake states)\n" -" -out_verify <0|1|2|3> (prints certificate verification states: def=1)\n" -" -out_totals (prints out byte-totals when a tunnel closes)\n" -" -<h|help|?> (displays this help screen)\n" -"Notes:\n" -"(1) It is recommended to specify a cert+key when operating as an SSL server.\n" -" If you only specify '-cert', the same file must contain a matching\n" -" private key.\n" -"(2) Either dh_file or dh_special can be used to specify where DH parameters\n" -" will be obtained from (or '-dh_special NULL' for the default choice) but\n" -" you cannot specify both. For dh_special, 'generate' will create new DH\n" -" parameters on startup, and 'standard' will use embedded parameters\n" -" instead.\n" -"(3) Normally an ssl client connects to an ssl server - so that an 'ssl client\n" -" tunala' listens for 'clean' client connections and proxies ssl, and an\n" -" 'ssl server tunala' listens for ssl connections and proxies 'clean'. With\n" -" '-flipped 1', this behaviour is reversed so that an 'ssl server tunala'\n" -" listens for clean client connections and proxies ssl (but participating\n" -" as an ssl *server* in the SSL/TLS protocol), and an 'ssl client tunala'\n" -" listens for ssl connections (participating as an ssl *client* in the\n" -" SSL/TLS protocol) and proxies 'clean' to the end destination. This can\n" -" be useful for allowing network access to 'servers' where only the server\n" -" needs to authenticate the client (ie. the other way is not required).\n" -" Even with client and server authentication, this 'technique' mitigates\n" -" some DoS (denial-of-service) potential as it will be the network client\n" -" having to perform the first private key operation rather than the other\n" -" way round.\n" -"(4) The 'technique' used by setting '-flipped 1' is probably compatible with\n" -" absolutely nothing except another complimentary instance of 'tunala'\n" -" running with '-flipped 1'. :-)\n"; + "\n'Tunala' (A tunneler with a New Zealand accent)\n" + "Usage: tunala [options], where options are from;\n" + " -listen [host:]<port> (default = 127.0.0.1:8080)\n" + " -proxy <host>:<port> (default = 127.0.0.1:443)\n" + " -maxtunnels <num> (default = 50)\n" + " -cacert <path|NULL> (default = NULL)\n" + " -cert <path|NULL> (default = NULL)\n" + " -key <path|NULL> (default = whatever '-cert' is)\n" + " -dcert <path|NULL> (usually for DSA, default = NULL)\n" + " -dkey <path|NULL> (usually for DSA, default = whatever '-dcert' is)\n" + " -engine <id|NULL> (default = NULL)\n" + " -server <0|1> (default = 0, ie. an SSL client)\n" + " -flipped <0|1> (makes SSL servers be network clients, and vice versa)\n" + " -cipher <list> (specifies cipher list to use)\n" + " -dh_file <path> (a PEM file containing DH parameters to use)\n" + " -dh_special <NULL|generate|standard> (see below: def=NULL)\n" + " -no_tmp_rsa (don't generate temporary RSA keys)\n" + " -no_ssl2 (disable SSLv2)\n" + " -no_ssl3 (disable SSLv3)\n" + " -no_tls1 (disable TLSv1)\n" + " -v_peer (verify the peer certificate)\n" + " -v_strict (do not continue if peer doesn't authenticate)\n" + " -v_once (no verification in renegotiates)\n" + " -v_depth <num> (limit certificate chain depth, default = 10)\n" + " -out_conns (prints client connections and disconnections)\n" + " -out_state (prints SSL handshake states)\n" + " -out_verify <0|1|2|3> (prints certificate verification states: def=1)\n" + " -out_totals (prints out byte-totals when a tunnel closes)\n" + " -<h|help|?> (displays this help screen)\n" + "Notes:\n" + "(1) It is recommended to specify a cert+key when operating as an SSL server.\n" + " If you only specify '-cert', the same file must contain a matching\n" + " private key.\n" + "(2) Either dh_file or dh_special can be used to specify where DH parameters\n" + " will be obtained from (or '-dh_special NULL' for the default choice) but\n" + " you cannot specify both. For dh_special, 'generate' will create new DH\n" + " parameters on startup, and 'standard' will use embedded parameters\n" + " instead.\n" + "(3) Normally an ssl client connects to an ssl server - so that an 'ssl client\n" + " tunala' listens for 'clean' client connections and proxies ssl, and an\n" + " 'ssl server tunala' listens for ssl connections and proxies 'clean'. With\n" + " '-flipped 1', this behaviour is reversed so that an 'ssl server tunala'\n" + " listens for clean client connections and proxies ssl (but participating\n" + " as an ssl *server* in the SSL/TLS protocol), and an 'ssl client tunala'\n" + " listens for ssl connections (participating as an ssl *client* in the\n" + " SSL/TLS protocol) and proxies 'clean' to the end destination. This can\n" + " be useful for allowing network access to 'servers' where only the server\n" + " needs to authenticate the client (ie. the other way is not required).\n" + " Even with client and server authentication, this 'technique' mitigates\n" + " some DoS (denial-of-service) potential as it will be the network client\n" + " having to perform the first private key operation rather than the other\n" + " way round.\n" + "(4) The 'technique' used by setting '-flipped 1' is probably compatible with\n" + " absolutely nothing except another complimentary instance of 'tunala'\n" + " running with '-flipped 1'. :-)\n"; + +/* + * Default DH parameters for use with "-dh_special standard" ... stolen + * striaght from s_server. + */ +static unsigned char dh512_p[] = { + 0xDA, 0x58, 0x3C, 0x16, 0xD9, 0x85, 0x22, 0x89, 0xD0, 0xE4, 0xAF, 0x75, + 0x6F, 0x4C, 0xCA, 0x92, 0xDD, 0x4B, 0xE5, 0x33, 0xB8, 0x04, 0xFB, 0x0F, + 0xED, 0x94, 0xEF, 0x9C, 0x8A, 0x44, 0x03, 0xED, 0x57, 0x46, 0x50, 0xD3, + 0x69, 0x99, 0xDB, 0x29, 0xD7, 0x76, 0x27, 0x6B, 0xA2, 0xD3, 0xD4, 0x12, + 0xE2, 0x18, 0xF4, 0xDD, 0x1E, 0x08, 0x4C, 0xF6, 0xD8, 0x00, 0x3E, 0x7C, + 0x47, 0x74, 0xE8, 0x33, +}; -/* Default DH parameters for use with "-dh_special standard" ... stolen striaght - * from s_server. */ -static unsigned char dh512_p[]={ - 0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75, - 0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F, - 0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3, - 0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12, - 0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C, - 0x47,0x74,0xE8,0x33, - }; -static unsigned char dh512_g[]={ - 0x02, - }; +static unsigned char dh512_g[] = { + 0x02, +}; -/* And the function that parses the above "standard" parameters, again, straight - * out of s_server. */ +/* + * And the function that parses the above "standard" parameters, again, + * straight out of s_server. + */ static DH *get_dh512(void) - { - DH *dh=NULL; +{ + DH *dh = NULL; - if ((dh=DH_new()) == NULL) return(NULL); - dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL); - dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL); - if ((dh->p == NULL) || (dh->g == NULL)) - return(NULL); - return(dh); - } + if ((dh = DH_new()) == NULL) + return (NULL); + dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL); + dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL); + if ((dh->p == NULL) || (dh->g == NULL)) + return (NULL); + return (dh); +} /* Various help/error messages used by main() */ static int usage(const char *errstr, int isunknownarg) { - if(isunknownarg) - fprintf(stderr, "Error: unknown argument '%s'\n", errstr); - else - fprintf(stderr, "Error: %s\n", errstr); - fprintf(stderr, "%s\n", helpstring); - return 1; + if (isunknownarg) + fprintf(stderr, "Error: unknown argument '%s'\n", errstr); + else + fprintf(stderr, "Error: %s\n", errstr); + fprintf(stderr, "%s\n", helpstring); + return 1; } static int err_str0(const char *str0) { - fprintf(stderr, "%s\n", str0); - return 1; + fprintf(stderr, "%s\n", str0); + return 1; } static int err_str1(const char *fmt, const char *str1) { - fprintf(stderr, fmt, str1); - fprintf(stderr, "\n"); - return 1; + fprintf(stderr, fmt, str1); + fprintf(stderr, "\n"); + return 1; } static int parse_max_tunnels(const char *s, unsigned int *maxtunnels) { - unsigned long l; - if(!int_strtoul(s, &l) || (l < 1) || (l > 1024)) { - fprintf(stderr, "Error, '%s' is an invalid value for " - "maxtunnels\n", s); - return 0; - } - *maxtunnels = (unsigned int)l; - return 1; + unsigned long l; + if (!int_strtoul(s, &l) || (l < 1) || (l > 1024)) { + fprintf(stderr, "Error, '%s' is an invalid value for " + "maxtunnels\n", s); + return 0; + } + *maxtunnels = (unsigned int)l; + return 1; } static int parse_server_mode(const char *s, int *servermode) { - unsigned long l; - if(!int_strtoul(s, &l) || (l > 1)) { - fprintf(stderr, "Error, '%s' is an invalid value for the " - "server mode\n", s); - return 0; - } - *servermode = (int)l; - return 1; + unsigned long l; + if (!int_strtoul(s, &l) || (l > 1)) { + fprintf(stderr, "Error, '%s' is an invalid value for the " + "server mode\n", s); + return 0; + } + *servermode = (int)l; + return 1; } static int parse_dh_special(const char *s, const char **dh_special) { - if((strcmp(s, "NULL") == 0) || (strcmp(s, "generate") == 0) || - (strcmp(s, "standard") == 0)) { - *dh_special = s; - return 1; - } - fprintf(stderr, "Error, '%s' is an invalid value for 'dh_special'\n", s); - return 0; + if ((strcmp(s, "NULL") == 0) || (strcmp(s, "generate") == 0) || + (strcmp(s, "standard") == 0)) { + *dh_special = s; + return 1; + } + fprintf(stderr, "Error, '%s' is an invalid value for 'dh_special'\n", s); + return 0; } static int parse_verify_level(const char *s, unsigned int *verify_level) { - unsigned long l; - if(!int_strtoul(s, &l) || (l > 3)) { - fprintf(stderr, "Error, '%s' is an invalid value for " - "out_verify\n", s); - return 0; - } - *verify_level = (unsigned int)l; - return 1; + unsigned long l; + if (!int_strtoul(s, &l) || (l > 3)) { + fprintf(stderr, "Error, '%s' is an invalid value for " + "out_verify\n", s); + return 0; + } + *verify_level = (unsigned int)l; + return 1; } static int parse_verify_depth(const char *s, unsigned int *verify_depth) { - unsigned long l; - if(!int_strtoul(s, &l) || (l < 1) || (l > 50)) { - fprintf(stderr, "Error, '%s' is an invalid value for " - "verify_depth\n", s); - return 0; - } - *verify_depth = (unsigned int)l; - return 1; + unsigned long l; + if (!int_strtoul(s, &l) || (l < 1) || (l > 50)) { + fprintf(stderr, "Error, '%s' is an invalid value for " + "verify_depth\n", s); + return 0; + } + *verify_depth = (unsigned int)l; + return 1; } /* Some fprintf format strings used when tunnels close */ static const char *io_stats_dirty = -" SSL traffic; %8lu bytes in, %8lu bytes out\n"; + " SSL traffic; %8lu bytes in, %8lu bytes out\n"; static const char *io_stats_clean = -" clear traffic; %8lu bytes in, %8lu bytes out\n"; + " clear traffic; %8lu bytes in, %8lu bytes out\n"; int main(int argc, char *argv[]) { - unsigned int loop; - int newfd; - tunala_world_t world; - tunala_item_t *t_item; - const char *proxy_ip; - unsigned short proxy_port; - /* Overridables */ - const char *proxyhost = def_proxyhost; - const char *listenhost = def_listenhost; - unsigned int max_tunnels = def_max_tunnels; - const char *cacert = def_cacert; - const char *cert = def_cert; - const char *key = def_key; - const char *dcert = def_dcert; - const char *dkey = def_dkey; - const char *engine_id = def_engine_id; - int server_mode = def_server_mode; - int flipped = def_flipped; - const char *cipher_list = def_cipher_list; - const char *dh_file = def_dh_file; - const char *dh_special = def_dh_special; - int tmp_rsa = def_tmp_rsa; - int ctx_options = def_ctx_options; - int verify_mode = def_verify_mode; - unsigned int verify_depth = def_verify_depth; - int out_state = def_out_state; - unsigned int out_verify = def_out_verify; - int out_totals = def_out_totals; - int out_conns = def_out_conns; + unsigned int loop; + int newfd; + tunala_world_t world; + tunala_item_t *t_item; + const char *proxy_ip; + unsigned short proxy_port; + /* Overridables */ + const char *proxyhost = def_proxyhost; + const char *listenhost = def_listenhost; + unsigned int max_tunnels = def_max_tunnels; + const char *cacert = def_cacert; + const char *cert = def_cert; + const char *key = def_key; + const char *dcert = def_dcert; + const char *dkey = def_dkey; + const char *engine_id = def_engine_id; + int server_mode = def_server_mode; + int flipped = def_flipped; + const char *cipher_list = def_cipher_list; + const char *dh_file = def_dh_file; + const char *dh_special = def_dh_special; + int tmp_rsa = def_tmp_rsa; + int ctx_options = def_ctx_options; + int verify_mode = def_verify_mode; + unsigned int verify_depth = def_verify_depth; + int out_state = def_out_state; + unsigned int out_verify = def_out_verify; + int out_totals = def_out_totals; + int out_conns = def_out_conns; /* Parse command-line arguments */ -next_arg: - argc--; argv++; - if(argc > 0) { - if(strcmp(*argv, "-listen") == 0) { - if(argc < 2) - return usage("-listen requires an argument", 0); - argc--; argv++; - listenhost = *argv; - goto next_arg; - } else if(strcmp(*argv, "-proxy") == 0) { - if(argc < 2) - return usage("-proxy requires an argument", 0); - argc--; argv++; - proxyhost = *argv; - goto next_arg; - } else if(strcmp(*argv, "-maxtunnels") == 0) { - if(argc < 2) - return usage("-maxtunnels requires an argument", 0); - argc--; argv++; - if(!parse_max_tunnels(*argv, &max_tunnels)) - return 1; - goto next_arg; - } else if(strcmp(*argv, "-cacert") == 0) { - if(argc < 2) - return usage("-cacert requires an argument", 0); - argc--; argv++; - if(strcmp(*argv, "NULL") == 0) - cacert = NULL; - else - cacert = *argv; - goto next_arg; - } else if(strcmp(*argv, "-cert") == 0) { - if(argc < 2) - return usage("-cert requires an argument", 0); - argc--; argv++; - if(strcmp(*argv, "NULL") == 0) - cert = NULL; - else - cert = *argv; - goto next_arg; - } else if(strcmp(*argv, "-key") == 0) { - if(argc < 2) - return usage("-key requires an argument", 0); - argc--; argv++; - if(strcmp(*argv, "NULL") == 0) - key = NULL; - else - key = *argv; - goto next_arg; - } else if(strcmp(*argv, "-dcert") == 0) { - if(argc < 2) - return usage("-dcert requires an argument", 0); - argc--; argv++; - if(strcmp(*argv, "NULL") == 0) - dcert = NULL; - else - dcert = *argv; - goto next_arg; - } else if(strcmp(*argv, "-dkey") == 0) { - if(argc < 2) - return usage("-dkey requires an argument", 0); - argc--; argv++; - if(strcmp(*argv, "NULL") == 0) - dkey = NULL; - else - dkey = *argv; - goto next_arg; - } else if(strcmp(*argv, "-engine") == 0) { - if(argc < 2) - return usage("-engine requires an argument", 0); - argc--; argv++; - engine_id = *argv; - goto next_arg; - } else if(strcmp(*argv, "-server") == 0) { - if(argc < 2) - return usage("-server requires an argument", 0); - argc--; argv++; - if(!parse_server_mode(*argv, &server_mode)) - return 1; - goto next_arg; - } else if(strcmp(*argv, "-flipped") == 0) { - if(argc < 2) - return usage("-flipped requires an argument", 0); - argc--; argv++; - if(!parse_server_mode(*argv, &flipped)) - return 1; - goto next_arg; - } else if(strcmp(*argv, "-cipher") == 0) { - if(argc < 2) - return usage("-cipher requires an argument", 0); - argc--; argv++; - cipher_list = *argv; - goto next_arg; - } else if(strcmp(*argv, "-dh_file") == 0) { - if(argc < 2) - return usage("-dh_file requires an argument", 0); - if(dh_special) - return usage("cannot mix -dh_file with " - "-dh_special", 0); - argc--; argv++; - dh_file = *argv; - goto next_arg; - } else if(strcmp(*argv, "-dh_special") == 0) { - if(argc < 2) - return usage("-dh_special requires an argument", 0); - if(dh_file) - return usage("cannot mix -dh_file with " - "-dh_special", 0); - argc--; argv++; - if(!parse_dh_special(*argv, &dh_special)) - return 1; - goto next_arg; - } else if(strcmp(*argv, "-no_tmp_rsa") == 0) { - tmp_rsa = 0; - goto next_arg; - } else if(strcmp(*argv, "-no_ssl2") == 0) { - ctx_options |= SSL_OP_NO_SSLv2; - goto next_arg; - } else if(strcmp(*argv, "-no_ssl3") == 0) { - ctx_options |= SSL_OP_NO_SSLv3; - goto next_arg; - } else if(strcmp(*argv, "-no_tls1") == 0) { - ctx_options |= SSL_OP_NO_TLSv1; - goto next_arg; - } else if(strcmp(*argv, "-v_peer") == 0) { - verify_mode |= SSL_VERIFY_PEER; - goto next_arg; - } else if(strcmp(*argv, "-v_strict") == 0) { - verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; - goto next_arg; - } else if(strcmp(*argv, "-v_once") == 0) { - verify_mode |= SSL_VERIFY_CLIENT_ONCE; - goto next_arg; - } else if(strcmp(*argv, "-v_depth") == 0) { - if(argc < 2) - return usage("-v_depth requires an argument", 0); - argc--; argv++; - if(!parse_verify_depth(*argv, &verify_depth)) - return 1; - goto next_arg; - } else if(strcmp(*argv, "-out_state") == 0) { - out_state = 1; - goto next_arg; - } else if(strcmp(*argv, "-out_verify") == 0) { - if(argc < 2) - return usage("-out_verify requires an argument", 0); - argc--; argv++; - if(!parse_verify_level(*argv, &out_verify)) - return 1; - goto next_arg; - } else if(strcmp(*argv, "-out_totals") == 0) { - out_totals = 1; - goto next_arg; - } else if(strcmp(*argv, "-out_conns") == 0) { - out_conns = 1; - goto next_arg; - } else if((strcmp(*argv, "-h") == 0) || - (strcmp(*argv, "-help") == 0) || - (strcmp(*argv, "-?") == 0)) { - fprintf(stderr, "%s\n", helpstring); - return 0; - } else - return usage(*argv, 1); - } - /* Run any sanity checks we want here */ - if(!cert && !dcert && server_mode) - fprintf(stderr, "WARNING: you are running an SSL server without " - "a certificate - this may not work!\n"); + next_arg: + argc--; + argv++; + if (argc > 0) { + if (strcmp(*argv, "-listen") == 0) { + if (argc < 2) + return usage("-listen requires an argument", 0); + argc--; + argv++; + listenhost = *argv; + goto next_arg; + } else if (strcmp(*argv, "-proxy") == 0) { + if (argc < 2) + return usage("-proxy requires an argument", 0); + argc--; + argv++; + proxyhost = *argv; + goto next_arg; + } else if (strcmp(*argv, "-maxtunnels") == 0) { + if (argc < 2) + return usage("-maxtunnels requires an argument", 0); + argc--; + argv++; + if (!parse_max_tunnels(*argv, &max_tunnels)) + return 1; + goto next_arg; + } else if (strcmp(*argv, "-cacert") == 0) { + if (argc < 2) + return usage("-cacert requires an argument", 0); + argc--; + argv++; + if (strcmp(*argv, "NULL") == 0) + cacert = NULL; + else + cacert = *argv; + goto next_arg; + } else if (strcmp(*argv, "-cert") == 0) { + if (argc < 2) + return usage("-cert requires an argument", 0); + argc--; + argv++; + if (strcmp(*argv, "NULL") == 0) + cert = NULL; + else + cert = *argv; + goto next_arg; + } else if (strcmp(*argv, "-key") == 0) { + if (argc < 2) + return usage("-key requires an argument", 0); + argc--; + argv++; + if (strcmp(*argv, "NULL") == 0) + key = NULL; + else + key = *argv; + goto next_arg; + } else if (strcmp(*argv, "-dcert") == 0) { + if (argc < 2) + return usage("-dcert requires an argument", 0); + argc--; + argv++; + if (strcmp(*argv, "NULL") == 0) + dcert = NULL; + else + dcert = *argv; + goto next_arg; + } else if (strcmp(*argv, "-dkey") == 0) { + if (argc < 2) + return usage("-dkey requires an argument", 0); + argc--; + argv++; + if (strcmp(*argv, "NULL") == 0) + dkey = NULL; + else + dkey = *argv; + goto next_arg; + } else if (strcmp(*argv, "-engine") == 0) { + if (argc < 2) + return usage("-engine requires an argument", 0); + argc--; + argv++; + engine_id = *argv; + goto next_arg; + } else if (strcmp(*argv, "-server") == 0) { + if (argc < 2) + return usage("-server requires an argument", 0); + argc--; + argv++; + if (!parse_server_mode(*argv, &server_mode)) + return 1; + goto next_arg; + } else if (strcmp(*argv, "-flipped") == 0) { + if (argc < 2) + return usage("-flipped requires an argument", 0); + argc--; + argv++; + if (!parse_server_mode(*argv, &flipped)) + return 1; + goto next_arg; + } else if (strcmp(*argv, "-cipher") == 0) { + if (argc < 2) + return usage("-cipher requires an argument", 0); + argc--; + argv++; + cipher_list = *argv; + goto next_arg; + } else if (strcmp(*argv, "-dh_file") == 0) { + if (argc < 2) + return usage("-dh_file requires an argument", 0); + if (dh_special) + return usage("cannot mix -dh_file with " "-dh_special", 0); + argc--; + argv++; + dh_file = *argv; + goto next_arg; + } else if (strcmp(*argv, "-dh_special") == 0) { + if (argc < 2) + return usage("-dh_special requires an argument", 0); + if (dh_file) + return usage("cannot mix -dh_file with " "-dh_special", 0); + argc--; + argv++; + if (!parse_dh_special(*argv, &dh_special)) + return 1; + goto next_arg; + } else if (strcmp(*argv, "-no_tmp_rsa") == 0) { + tmp_rsa = 0; + goto next_arg; + } else if (strcmp(*argv, "-no_ssl2") == 0) { + ctx_options |= SSL_OP_NO_SSLv2; + goto next_arg; + } else if (strcmp(*argv, "-no_ssl3") == 0) { + ctx_options |= SSL_OP_NO_SSLv3; + goto next_arg; + } else if (strcmp(*argv, "-no_tls1") == 0) { + ctx_options |= SSL_OP_NO_TLSv1; + goto next_arg; + } else if (strcmp(*argv, "-v_peer") == 0) { + verify_mode |= SSL_VERIFY_PEER; + goto next_arg; + } else if (strcmp(*argv, "-v_strict") == 0) { + verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + goto next_arg; + } else if (strcmp(*argv, "-v_once") == 0) { + verify_mode |= SSL_VERIFY_CLIENT_ONCE; + goto next_arg; + } else if (strcmp(*argv, "-v_depth") == 0) { + if (argc < 2) + return usage("-v_depth requires an argument", 0); + argc--; + argv++; + if (!parse_verify_depth(*argv, &verify_depth)) + return 1; + goto next_arg; + } else if (strcmp(*argv, "-out_state") == 0) { + out_state = 1; + goto next_arg; + } else if (strcmp(*argv, "-out_verify") == 0) { + if (argc < 2) + return usage("-out_verify requires an argument", 0); + argc--; + argv++; + if (!parse_verify_level(*argv, &out_verify)) + return 1; + goto next_arg; + } else if (strcmp(*argv, "-out_totals") == 0) { + out_totals = 1; + goto next_arg; + } else if (strcmp(*argv, "-out_conns") == 0) { + out_conns = 1; + goto next_arg; + } else if ((strcmp(*argv, "-h") == 0) || + (strcmp(*argv, "-help") == 0) || + (strcmp(*argv, "-?") == 0)) { + fprintf(stderr, "%s\n", helpstring); + return 0; + } else + return usage(*argv, 1); + } + /* Run any sanity checks we want here */ + if (!cert && !dcert && server_mode) + fprintf(stderr, "WARNING: you are running an SSL server without " + "a certificate - this may not work!\n"); - /* Initialise network stuff */ - if(!ip_initialise()) - return err_str0("ip_initialise failed"); - /* Create the SSL_CTX */ - if((world.ssl_ctx = initialise_ssl_ctx(server_mode, engine_id, - cacert, cert, key, dcert, dkey, cipher_list, dh_file, - dh_special, tmp_rsa, ctx_options, out_state, out_verify, - verify_mode, verify_depth)) == NULL) - return err_str1("initialise_ssl_ctx(engine_id=%s) failed", - (engine_id == NULL) ? "NULL" : engine_id); - if(engine_id) - fprintf(stderr, "Info, engine '%s' initialised\n", engine_id); - /* Create the listener */ - if((world.listen_fd = ip_create_listener(listenhost)) == -1) - return err_str1("ip_create_listener(%s) failed", listenhost); - fprintf(stderr, "Info, listening on '%s'\n", listenhost); - if(!ip_parse_address(proxyhost, &proxy_ip, &proxy_port, 0)) - return err_str1("ip_parse_address(%s) failed", proxyhost); - fprintf(stderr, "Info, proxying to '%s' (%d.%d.%d.%d:%d)\n", proxyhost, - (int)proxy_ip[0], (int)proxy_ip[1], - (int)proxy_ip[2], (int)proxy_ip[3], (int)proxy_port); - fprintf(stderr, "Info, set maxtunnels to %d\n", (int)max_tunnels); - fprintf(stderr, "Info, set to operate as an SSL %s\n", - (server_mode ? "server" : "client")); - /* Initialise the rest of the stuff */ - world.tunnels_used = world.tunnels_size = 0; - world.tunnels = NULL; - world.server_mode = server_mode; - selector_init(&world.selector); + /* Initialise network stuff */ + if (!ip_initialise()) + return err_str0("ip_initialise failed"); + /* Create the SSL_CTX */ + if ((world.ssl_ctx = initialise_ssl_ctx(server_mode, engine_id, + cacert, cert, key, dcert, dkey, + cipher_list, dh_file, dh_special, + tmp_rsa, ctx_options, out_state, + out_verify, verify_mode, + verify_depth)) == NULL) + return err_str1("initialise_ssl_ctx(engine_id=%s) failed", + (engine_id == NULL) ? "NULL" : engine_id); + if (engine_id) + fprintf(stderr, "Info, engine '%s' initialised\n", engine_id); + /* Create the listener */ + if ((world.listen_fd = ip_create_listener(listenhost)) == -1) + return err_str1("ip_create_listener(%s) failed", listenhost); + fprintf(stderr, "Info, listening on '%s'\n", listenhost); + if (!ip_parse_address(proxyhost, &proxy_ip, &proxy_port, 0)) + return err_str1("ip_parse_address(%s) failed", proxyhost); + fprintf(stderr, "Info, proxying to '%s' (%d.%d.%d.%d:%d)\n", proxyhost, + (int)proxy_ip[0], (int)proxy_ip[1], + (int)proxy_ip[2], (int)proxy_ip[3], (int)proxy_port); + fprintf(stderr, "Info, set maxtunnels to %d\n", (int)max_tunnels); + fprintf(stderr, "Info, set to operate as an SSL %s\n", + (server_mode ? "server" : "client")); + /* Initialise the rest of the stuff */ + world.tunnels_used = world.tunnels_size = 0; + world.tunnels = NULL; + world.server_mode = server_mode; + selector_init(&world.selector); /* We're ready to loop */ -main_loop: - /* Should we listen for *new* tunnels? */ - if(world.tunnels_used < max_tunnels) - selector_add_listener(&world.selector, world.listen_fd); - /* We should add in our existing tunnels */ - for(loop = 0; loop < world.tunnels_used; loop++) - selector_add_tunala(&world.selector, world.tunnels + loop); - /* Now do the select */ - switch(selector_select(&world.selector)) { - case -1: - if(errno != EINTR) { - fprintf(stderr, "selector_select returned a " - "badness error.\n"); - goto shouldnt_happen; - } - fprintf(stderr, "Warn, selector interrupted by a signal\n"); - goto main_loop; - case 0: - fprintf(stderr, "Warn, selector_select returned 0 - signal?""?\n"); - goto main_loop; - default: - break; - } - /* Accept new connection if we should and can */ - if((world.tunnels_used < max_tunnels) && (selector_get_listener( - &world.selector, world.listen_fd, - &newfd) == 1)) { - /* We have a new connection */ - if(!tunala_world_new_item(&world, newfd, proxy_ip, - proxy_port, flipped)) - fprintf(stderr, "tunala_world_new_item failed\n"); - else if(out_conns) - fprintf(stderr, "Info, new tunnel opened, now up to " - "%d\n", world.tunnels_used); - } - /* Give each tunnel its moment, note the while loop is because it makes - * the logic easier than with "for" to deal with an array that may shift - * because of deletes. */ - loop = 0; - t_item = world.tunnels; - while(loop < world.tunnels_used) { - if(!tunala_item_io(&world.selector, t_item)) { - /* We're closing whether for reasons of an error or a - * natural close. Don't increment loop or t_item because - * the next item is moving to us! */ - if(!out_totals) - goto skip_totals; - fprintf(stderr, "Tunnel closing, traffic stats follow\n"); - /* Display the encrypted (over the network) stats */ - fprintf(stderr, io_stats_dirty, - buffer_total_in(state_machine_get_buffer( - &t_item->sm,SM_DIRTY_IN)), - buffer_total_out(state_machine_get_buffer( - &t_item->sm,SM_DIRTY_OUT))); - /* Display the local (tunnelled) stats. NB: Data we - * *receive* is data sent *out* of the state_machine on - * its 'clean' side. Hence the apparent back-to-front - * OUT/IN mixup here :-) */ - fprintf(stderr, io_stats_clean, - buffer_total_out(state_machine_get_buffer( - &t_item->sm,SM_CLEAN_OUT)), - buffer_total_in(state_machine_get_buffer( - &t_item->sm,SM_CLEAN_IN))); -skip_totals: - tunala_world_del_item(&world, loop); - if(out_conns) - fprintf(stderr, "Info, tunnel closed, down to %d\n", - world.tunnels_used); - } - else { - /* Move to the next item */ - loop++; - t_item++; - } - } - goto main_loop; - /* Should never get here */ -shouldnt_happen: - abort(); - return 1; + main_loop: + /* Should we listen for *new* tunnels? */ + if (world.tunnels_used < max_tunnels) + selector_add_listener(&world.selector, world.listen_fd); + /* We should add in our existing tunnels */ + for (loop = 0; loop < world.tunnels_used; loop++) + selector_add_tunala(&world.selector, world.tunnels + loop); + /* Now do the select */ + switch (selector_select(&world.selector)) { + case -1: + if (errno != EINTR) { + fprintf(stderr, "selector_select returned a " "badness error.\n"); + goto shouldnt_happen; + } + fprintf(stderr, "Warn, selector interrupted by a signal\n"); + goto main_loop; + case 0: + fprintf(stderr, "Warn, selector_select returned 0 - signal?" "?\n"); + goto main_loop; + default: + break; + } + /* Accept new connection if we should and can */ + if ((world.tunnels_used < max_tunnels) + && (selector_get_listener(&world.selector, world.listen_fd, &newfd) == + 1)) { + /* We have a new connection */ + if (!tunala_world_new_item(&world, newfd, proxy_ip, + proxy_port, flipped)) + fprintf(stderr, "tunala_world_new_item failed\n"); + else if (out_conns) + fprintf(stderr, "Info, new tunnel opened, now up to " + "%d\n", world.tunnels_used); + } + /* + * Give each tunnel its moment, note the while loop is because it makes + * the logic easier than with "for" to deal with an array that may shift + * because of deletes. + */ + loop = 0; + t_item = world.tunnels; + while (loop < world.tunnels_used) { + if (!tunala_item_io(&world.selector, t_item)) { + /* + * We're closing whether for reasons of an error or a natural + * close. Don't increment loop or t_item because the next item is + * moving to us! + */ + if (!out_totals) + goto skip_totals; + fprintf(stderr, "Tunnel closing, traffic stats follow\n"); + /* Display the encrypted (over the network) stats */ + fprintf(stderr, io_stats_dirty, + buffer_total_in(state_machine_get_buffer + (&t_item->sm, SM_DIRTY_IN)), + buffer_total_out(state_machine_get_buffer + (&t_item->sm, SM_DIRTY_OUT))); + /* + * Display the local (tunnelled) stats. NB: Data we *receive* is + * data sent *out* of the state_machine on its 'clean' side. + * Hence the apparent back-to-front OUT/IN mixup here :-) + */ + fprintf(stderr, io_stats_clean, + buffer_total_out(state_machine_get_buffer + (&t_item->sm, SM_CLEAN_OUT)), + buffer_total_in(state_machine_get_buffer + (&t_item->sm, SM_CLEAN_IN))); + skip_totals: + tunala_world_del_item(&world, loop); + if (out_conns) + fprintf(stderr, "Info, tunnel closed, down to %d\n", + world.tunnels_used); + } else { + /* Move to the next item */ + loop++; + t_item++; + } + } + goto main_loop; + /* Should never get here */ + shouldnt_happen: + abort(); + return 1; } /****************/ @@ -606,504 +656,528 @@ shouldnt_happen: static int ctx_set_cert(SSL_CTX *ctx, const char *cert, const char *key) { - FILE *fp = NULL; - X509 *x509 = NULL; - EVP_PKEY *pkey = NULL; - int toret = 0; /* Assume an error */ + FILE *fp = NULL; + X509 *x509 = NULL; + EVP_PKEY *pkey = NULL; + int toret = 0; /* Assume an error */ - /* cert */ - if(cert) { - if((fp = fopen(cert, "r")) == NULL) { - fprintf(stderr, "Error opening cert file '%s'\n", cert); - goto err; - } - if(!PEM_read_X509(fp, &x509, NULL, NULL)) { - fprintf(stderr, "Error reading PEM cert from '%s'\n", - cert); - goto err; - } - if(!SSL_CTX_use_certificate(ctx, x509)) { - fprintf(stderr, "Error, cert in '%s' can not be used\n", - cert); - goto err; - } - /* Clear the FILE* for reuse in the "key" code */ - fclose(fp); - fp = NULL; - fprintf(stderr, "Info, operating with cert in '%s'\n", cert); - /* If a cert was given without matching key, we assume the same - * file contains the required key. */ - if(!key) - key = cert; - } else { - if(key) - fprintf(stderr, "Error, can't specify a key without a " - "corresponding certificate\n"); - else - fprintf(stderr, "Error, ctx_set_cert called with " - "NULLs!\n"); - goto err; - } - /* key */ - if(key) { - if((fp = fopen(key, "r")) == NULL) { - fprintf(stderr, "Error opening key file '%s'\n", key); - goto err; - } - if(!PEM_read_PrivateKey(fp, &pkey, NULL, NULL)) { - fprintf(stderr, "Error reading PEM key from '%s'\n", - key); - goto err; - } - if(!SSL_CTX_use_PrivateKey(ctx, pkey)) { - fprintf(stderr, "Error, key in '%s' can not be used\n", - key); - goto err; - } - fprintf(stderr, "Info, operating with key in '%s'\n", key); - } else - fprintf(stderr, "Info, operating without a cert or key\n"); - /* Success */ - toret = 1; err: - if(x509) - X509_free(x509); - if(pkey) - EVP_PKEY_free(pkey); - if(fp) - fclose(fp); - return toret; + /* cert */ + if (cert) { + if ((fp = fopen(cert, "r")) == NULL) { + fprintf(stderr, "Error opening cert file '%s'\n", cert); + goto err; + } + if (!PEM_read_X509(fp, &x509, NULL, NULL)) { + fprintf(stderr, "Error reading PEM cert from '%s'\n", cert); + goto err; + } + if (!SSL_CTX_use_certificate(ctx, x509)) { + fprintf(stderr, "Error, cert in '%s' can not be used\n", cert); + goto err; + } + /* Clear the FILE* for reuse in the "key" code */ + fclose(fp); + fp = NULL; + fprintf(stderr, "Info, operating with cert in '%s'\n", cert); + /* + * If a cert was given without matching key, we assume the same file + * contains the required key. + */ + if (!key) + key = cert; + } else { + if (key) + fprintf(stderr, "Error, can't specify a key without a " + "corresponding certificate\n"); + else + fprintf(stderr, "Error, ctx_set_cert called with " "NULLs!\n"); + goto err; + } + /* key */ + if (key) { + if ((fp = fopen(key, "r")) == NULL) { + fprintf(stderr, "Error opening key file '%s'\n", key); + goto err; + } + if (!PEM_read_PrivateKey(fp, &pkey, NULL, NULL)) { + fprintf(stderr, "Error reading PEM key from '%s'\n", key); + goto err; + } + if (!SSL_CTX_use_PrivateKey(ctx, pkey)) { + fprintf(stderr, "Error, key in '%s' can not be used\n", key); + goto err; + } + fprintf(stderr, "Info, operating with key in '%s'\n", key); + } else + fprintf(stderr, "Info, operating without a cert or key\n"); + /* Success */ + toret = 1; + err: + if (x509) + X509_free(x509); + if (pkey) + EVP_PKEY_free(pkey); + if (fp) + fclose(fp); + return toret; } -static int ctx_set_dh(SSL_CTX *ctx, const char *dh_file, const char *dh_special) +static int ctx_set_dh(SSL_CTX *ctx, const char *dh_file, + const char *dh_special) { - DH *dh = NULL; - FILE *fp = NULL; + DH *dh = NULL; + FILE *fp = NULL; - if(dh_special) { - if(strcmp(dh_special, "NULL") == 0) - return 1; - if(strcmp(dh_special, "standard") == 0) { - if((dh = get_dh512()) == NULL) { - fprintf(stderr, "Error, can't parse 'standard'" - " DH parameters\n"); - return 0; - } - fprintf(stderr, "Info, using 'standard' DH parameters\n"); - goto do_it; - } - if(strcmp(dh_special, "generate") != 0) - /* This shouldn't happen - screening values is handled - * in main(). */ - abort(); - fprintf(stderr, "Info, generating DH parameters ... "); - fflush(stderr); - if(!(dh = DH_new()) || !DH_generate_parameters_ex(dh, 512, - DH_GENERATOR_5, NULL)) { - fprintf(stderr, "error!\n"); - if(dh) - DH_free(dh); - return 0; - } - fprintf(stderr, "complete\n"); - goto do_it; - } - /* So, we're loading dh_file */ - if((fp = fopen(dh_file, "r")) == NULL) { - fprintf(stderr, "Error, couldn't open '%s' for DH parameters\n", - dh_file); - return 0; - } - dh = PEM_read_DHparams(fp, NULL, NULL, NULL); - fclose(fp); - if(dh == NULL) { - fprintf(stderr, "Error, could not parse DH parameters from '%s'\n", - dh_file); - return 0; - } - fprintf(stderr, "Info, using DH parameters from file '%s'\n", dh_file); -do_it: - SSL_CTX_set_tmp_dh(ctx, dh); - DH_free(dh); - return 1; + if (dh_special) { + if (strcmp(dh_special, "NULL") == 0) + return 1; + if (strcmp(dh_special, "standard") == 0) { + if ((dh = get_dh512()) == NULL) { + fprintf(stderr, "Error, can't parse 'standard'" + " DH parameters\n"); + return 0; + } + fprintf(stderr, "Info, using 'standard' DH parameters\n"); + goto do_it; + } + if (strcmp(dh_special, "generate") != 0) + /* + * This shouldn't happen - screening values is handled in main(). + */ + abort(); + fprintf(stderr, "Info, generating DH parameters ... "); + fflush(stderr); + if (!(dh = DH_new()) || !DH_generate_parameters_ex(dh, 512, + DH_GENERATOR_5, + NULL)) { + fprintf(stderr, "error!\n"); + if (dh) + DH_free(dh); + return 0; + } + fprintf(stderr, "complete\n"); + goto do_it; + } + /* So, we're loading dh_file */ + if ((fp = fopen(dh_file, "r")) == NULL) { + fprintf(stderr, "Error, couldn't open '%s' for DH parameters\n", + dh_file); + return 0; + } + dh = PEM_read_DHparams(fp, NULL, NULL, NULL); + fclose(fp); + if (dh == NULL) { + fprintf(stderr, "Error, could not parse DH parameters from '%s'\n", + dh_file); + return 0; + } + fprintf(stderr, "Info, using DH parameters from file '%s'\n", dh_file); + do_it: + SSL_CTX_set_tmp_dh(ctx, dh); + DH_free(dh); + return 1; } static SSL_CTX *initialise_ssl_ctx(int server_mode, const char *engine_id, - const char *CAfile, const char *cert, const char *key, - const char *dcert, const char *dkey, const char *cipher_list, - const char *dh_file, const char *dh_special, int tmp_rsa, - int ctx_options, int out_state, int out_verify, int verify_mode, - unsigned int verify_depth) + const char *CAfile, const char *cert, + const char *key, const char *dcert, + const char *dkey, const char *cipher_list, + const char *dh_file, + const char *dh_special, int tmp_rsa, + int ctx_options, int out_state, + int out_verify, int verify_mode, + unsigned int verify_depth) { - SSL_CTX *ctx = NULL, *ret = NULL; - const SSL_METHOD *meth; - ENGINE *e = NULL; + SSL_CTX *ctx = NULL, *ret = NULL; + const SSL_METHOD *meth; + ENGINE *e = NULL; - OpenSSL_add_ssl_algorithms(); - SSL_load_error_strings(); + OpenSSL_add_ssl_algorithms(); + SSL_load_error_strings(); - meth = (server_mode ? SSLv23_server_method() : SSLv23_client_method()); - if(meth == NULL) - goto err; - if(engine_id) { - ENGINE_load_builtin_engines(); - if((e = ENGINE_by_id(engine_id)) == NULL) { - fprintf(stderr, "Error obtaining '%s' engine, openssl " - "errors follow\n", engine_id); - goto err; - } - if(!ENGINE_set_default(e, ENGINE_METHOD_ALL)) { - fprintf(stderr, "Error assigning '%s' engine, openssl " - "errors follow\n", engine_id); - goto err; - } - ENGINE_free(e); - } - if((ctx = SSL_CTX_new(meth)) == NULL) - goto err; - /* cacert */ - if(CAfile) { - if(!X509_STORE_load_locations(SSL_CTX_get_cert_store(ctx), - CAfile, NULL)) { - fprintf(stderr, "Error loading CA cert(s) in '%s'\n", - CAfile); - goto err; - } - fprintf(stderr, "Info, operating with CA cert(s) in '%s'\n", - CAfile); - } else - fprintf(stderr, "Info, operating without a CA cert(-list)\n"); - if(!SSL_CTX_set_default_verify_paths(ctx)) { - fprintf(stderr, "Error setting default verify paths\n"); - goto err; - } + meth = (server_mode ? SSLv23_server_method() : SSLv23_client_method()); + if (meth == NULL) + goto err; + if (engine_id) { + ENGINE_load_builtin_engines(); + if ((e = ENGINE_by_id(engine_id)) == NULL) { + fprintf(stderr, "Error obtaining '%s' engine, openssl " + "errors follow\n", engine_id); + goto err; + } + if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) { + fprintf(stderr, "Error assigning '%s' engine, openssl " + "errors follow\n", engine_id); + goto err; + } + ENGINE_free(e); + } + if ((ctx = SSL_CTX_new(meth)) == NULL) + goto err; + /* cacert */ + if (CAfile) { + if (!X509_STORE_load_locations(SSL_CTX_get_cert_store(ctx), + CAfile, NULL)) { + fprintf(stderr, "Error loading CA cert(s) in '%s'\n", CAfile); + goto err; + } + fprintf(stderr, "Info, operating with CA cert(s) in '%s'\n", CAfile); + } else + fprintf(stderr, "Info, operating without a CA cert(-list)\n"); + if (!SSL_CTX_set_default_verify_paths(ctx)) { + fprintf(stderr, "Error setting default verify paths\n"); + goto err; + } - /* cert and key */ - if((cert || key) && !ctx_set_cert(ctx, cert, key)) - goto err; - /* dcert and dkey */ - if((dcert || dkey) && !ctx_set_cert(ctx, dcert, dkey)) - goto err; - /* temporary RSA key generation */ - if(tmp_rsa) - SSL_CTX_set_tmp_rsa_callback(ctx, cb_generate_tmp_rsa); + /* cert and key */ + if ((cert || key) && !ctx_set_cert(ctx, cert, key)) + goto err; + /* dcert and dkey */ + if ((dcert || dkey) && !ctx_set_cert(ctx, dcert, dkey)) + goto err; + /* temporary RSA key generation */ + if (tmp_rsa) + SSL_CTX_set_tmp_rsa_callback(ctx, cb_generate_tmp_rsa); - /* cipher_list */ - if(cipher_list) { - if(!SSL_CTX_set_cipher_list(ctx, cipher_list)) { - fprintf(stderr, "Error setting cipher list '%s'\n", - cipher_list); - goto err; - } - fprintf(stderr, "Info, set cipher list '%s'\n", cipher_list); - } else - fprintf(stderr, "Info, operating with default cipher list\n"); + /* cipher_list */ + if (cipher_list) { + if (!SSL_CTX_set_cipher_list(ctx, cipher_list)) { + fprintf(stderr, "Error setting cipher list '%s'\n", cipher_list); + goto err; + } + fprintf(stderr, "Info, set cipher list '%s'\n", cipher_list); + } else + fprintf(stderr, "Info, operating with default cipher list\n"); - /* dh_file & dh_special */ - if((dh_file || dh_special) && !ctx_set_dh(ctx, dh_file, dh_special)) - goto err; + /* dh_file & dh_special */ + if ((dh_file || dh_special) && !ctx_set_dh(ctx, dh_file, dh_special)) + goto err; - /* ctx_options */ - SSL_CTX_set_options(ctx, ctx_options); + /* ctx_options */ + SSL_CTX_set_options(ctx, ctx_options); - /* out_state (output of SSL handshake states to screen). */ - if(out_state) - cb_ssl_info_set_output(stderr); + /* out_state (output of SSL handshake states to screen). */ + if (out_state) + cb_ssl_info_set_output(stderr); - /* out_verify */ - if(out_verify > 0) { - cb_ssl_verify_set_output(stderr); - cb_ssl_verify_set_level(out_verify); - } + /* out_verify */ + if (out_verify > 0) { + cb_ssl_verify_set_output(stderr); + cb_ssl_verify_set_level(out_verify); + } - /* verify_depth */ - cb_ssl_verify_set_depth(verify_depth); + /* verify_depth */ + cb_ssl_verify_set_depth(verify_depth); - /* Success! (includes setting verify_mode) */ - SSL_CTX_set_info_callback(ctx, cb_ssl_info); - SSL_CTX_set_verify(ctx, verify_mode, cb_ssl_verify); - ret = ctx; -err: - if(!ret) { - ERR_print_errors_fp(stderr); - if(ctx) - SSL_CTX_free(ctx); - } - return ret; + /* Success! (includes setting verify_mode) */ + SSL_CTX_set_info_callback(ctx, cb_ssl_info); + SSL_CTX_set_verify(ctx, verify_mode, cb_ssl_verify); + ret = ctx; + err: + if (!ret) { + ERR_print_errors_fp(stderr); + if (ctx) + SSL_CTX_free(ctx); + } + return ret; } /*****************/ /* Selector bits */ /*****************/ -static void selector_sets_init(select_sets_t *s) +static void selector_sets_init(select_sets_t * s) { - s->max = 0; - FD_ZERO(&s->reads); - FD_ZERO(&s->sends); - FD_ZERO(&s->excepts); + s->max = 0; + FD_ZERO(&s->reads); + FD_ZERO(&s->sends); + FD_ZERO(&s->excepts); } -static void selector_init(tunala_selector_t *selector) + +static void selector_init(tunala_selector_t * selector) { - selector_sets_init(&selector->last_selected); - selector_sets_init(&selector->next_select); + selector_sets_init(&selector->last_selected); + selector_sets_init(&selector->next_select); } #define SEL_EXCEPTS 0x00 #define SEL_READS 0x01 #define SEL_SENDS 0x02 -static void selector_add_raw_fd(tunala_selector_t *s, int fd, int flags) +static void selector_add_raw_fd(tunala_selector_t * s, int fd, int flags) { - FD_SET(fd, &s->next_select.excepts); - if(flags & SEL_READS) - FD_SET(fd, &s->next_select.reads); - if(flags & SEL_SENDS) - FD_SET(fd, &s->next_select.sends); - /* Adjust "max" */ - if(s->next_select.max < (fd + 1)) - s->next_select.max = fd + 1; + FD_SET(fd, &s->next_select.excepts); + if (flags & SEL_READS) + FD_SET(fd, &s->next_select.reads); + if (flags & SEL_SENDS) + FD_SET(fd, &s->next_select.sends); + /* Adjust "max" */ + if (s->next_select.max < (fd + 1)) + s->next_select.max = fd + 1; } -static void selector_add_listener(tunala_selector_t *selector, int fd) +static void selector_add_listener(tunala_selector_t * selector, int fd) { - selector_add_raw_fd(selector, fd, SEL_READS); + selector_add_raw_fd(selector, fd, SEL_READS); } -static void selector_add_tunala(tunala_selector_t *s, tunala_item_t *t) +static void selector_add_tunala(tunala_selector_t * s, tunala_item_t * t) { - /* Set clean read if sm.clean_in is not full */ - if(t->clean_read != -1) { - selector_add_raw_fd(s, t->clean_read, - (buffer_full(state_machine_get_buffer(&t->sm, - SM_CLEAN_IN)) ? SEL_EXCEPTS : SEL_READS)); - } - /* Set clean send if sm.clean_out is not empty */ - if(t->clean_send != -1) { - selector_add_raw_fd(s, t->clean_send, - (buffer_empty(state_machine_get_buffer(&t->sm, - SM_CLEAN_OUT)) ? SEL_EXCEPTS : SEL_SENDS)); - } - /* Set dirty read if sm.dirty_in is not full */ - if(t->dirty_read != -1) { - selector_add_raw_fd(s, t->dirty_read, - (buffer_full(state_machine_get_buffer(&t->sm, - SM_DIRTY_IN)) ? SEL_EXCEPTS : SEL_READS)); - } - /* Set dirty send if sm.dirty_out is not empty */ - if(t->dirty_send != -1) { - selector_add_raw_fd(s, t->dirty_send, - (buffer_empty(state_machine_get_buffer(&t->sm, - SM_DIRTY_OUT)) ? SEL_EXCEPTS : SEL_SENDS)); - } + /* Set clean read if sm.clean_in is not full */ + if (t->clean_read != -1) { + selector_add_raw_fd(s, t->clean_read, + (buffer_full(state_machine_get_buffer(&t->sm, + SM_CLEAN_IN)) + ? SEL_EXCEPTS : SEL_READS)); + } + /* Set clean send if sm.clean_out is not empty */ + if (t->clean_send != -1) { + selector_add_raw_fd(s, t->clean_send, + (buffer_empty(state_machine_get_buffer(&t->sm, + SM_CLEAN_OUT)) + ? SEL_EXCEPTS : SEL_SENDS)); + } + /* Set dirty read if sm.dirty_in is not full */ + if (t->dirty_read != -1) { + selector_add_raw_fd(s, t->dirty_read, + (buffer_full(state_machine_get_buffer(&t->sm, + SM_DIRTY_IN)) + ? SEL_EXCEPTS : SEL_READS)); + } + /* Set dirty send if sm.dirty_out is not empty */ + if (t->dirty_send != -1) { + selector_add_raw_fd(s, t->dirty_send, + (buffer_empty(state_machine_get_buffer(&t->sm, + SM_DIRTY_OUT)) + ? SEL_EXCEPTS : SEL_SENDS)); + } } -static int selector_select(tunala_selector_t *selector) +static int selector_select(tunala_selector_t * selector) { - memcpy(&selector->last_selected, &selector->next_select, - sizeof(select_sets_t)); - selector_sets_init(&selector->next_select); - return select(selector->last_selected.max, - &selector->last_selected.reads, - &selector->last_selected.sends, - &selector->last_selected.excepts, NULL); + memcpy(&selector->last_selected, &selector->next_select, + sizeof(select_sets_t)); + selector_sets_init(&selector->next_select); + return select(selector->last_selected.max, + &selector->last_selected.reads, + &selector->last_selected.sends, + &selector->last_selected.excepts, NULL); } -/* This returns -1 for error, 0 for no new connections, or 1 for success, in - * which case *newfd is populated. */ -static int selector_get_listener(tunala_selector_t *selector, int fd, int *newfd) +/* + * This returns -1 for error, 0 for no new connections, or 1 for success, in + * which case *newfd is populated. + */ +static int selector_get_listener(tunala_selector_t * selector, int fd, + int *newfd) { - if(FD_ISSET(fd, &selector->last_selected.excepts)) - return -1; - if(!FD_ISSET(fd, &selector->last_selected.reads)) - return 0; - if((*newfd = ip_accept_connection(fd)) == -1) - return -1; - return 1; + if (FD_ISSET(fd, &selector->last_selected.excepts)) + return -1; + if (!FD_ISSET(fd, &selector->last_selected.reads)) + return 0; + if ((*newfd = ip_accept_connection(fd)) == -1) + return -1; + return 1; } /************************/ /* "Tunala" world stuff */ /************************/ -static int tunala_world_make_room(tunala_world_t *world) +static int tunala_world_make_room(tunala_world_t * world) { - unsigned int newsize; - tunala_item_t *newarray; + unsigned int newsize; + tunala_item_t *newarray; - if(world->tunnels_used < world->tunnels_size) - return 1; - newsize = (world->tunnels_size == 0 ? 16 : - ((world->tunnels_size * 3) / 2)); - if((newarray = malloc(newsize * sizeof(tunala_item_t))) == NULL) - return 0; - memset(newarray, 0, newsize * sizeof(tunala_item_t)); - if(world->tunnels_used > 0) - memcpy(newarray, world->tunnels, - world->tunnels_used * sizeof(tunala_item_t)); - if(world->tunnels_size > 0) - free(world->tunnels); - /* migrate */ - world->tunnels = newarray; - world->tunnels_size = newsize; - return 1; + if (world->tunnels_used < world->tunnels_size) + return 1; + newsize = (world->tunnels_size == 0 ? 16 : + ((world->tunnels_size * 3) / 2)); + if ((newarray = malloc(newsize * sizeof(tunala_item_t))) == NULL) + return 0; + memset(newarray, 0, newsize * sizeof(tunala_item_t)); + if (world->tunnels_used > 0) + memcpy(newarray, world->tunnels, + world->tunnels_used * sizeof(tunala_item_t)); + if (world->tunnels_size > 0) + free(world->tunnels); + /* migrate */ + world->tunnels = newarray; + world->tunnels_size = newsize; + return 1; } -static int tunala_world_new_item(tunala_world_t *world, int fd, - const char *ip, unsigned short port, int flipped) +static int tunala_world_new_item(tunala_world_t * world, int fd, + const char *ip, unsigned short port, + int flipped) { - tunala_item_t *item; - int newfd; - SSL *new_ssl = NULL; + tunala_item_t *item; + int newfd; + SSL *new_ssl = NULL; - if(!tunala_world_make_room(world)) - return 0; - if((new_ssl = SSL_new(world->ssl_ctx)) == NULL) { - fprintf(stderr, "Error creating new SSL\n"); - ERR_print_errors_fp(stderr); - return 0; - } - item = world->tunnels + (world->tunnels_used++); - state_machine_init(&item->sm); - item->clean_read = item->clean_send = - item->dirty_read = item->dirty_send = -1; - if((newfd = ip_create_connection_split(ip, port)) == -1) - goto err; - /* Which way round? If we're a server, "fd" is the dirty side and the - * connection we open is the clean one. For a client, it's the other way - * around. Unless, of course, we're "flipped" in which case everything - * gets reversed. :-) */ - if((world->server_mode && !flipped) || - (!world->server_mode && flipped)) { - item->dirty_read = item->dirty_send = fd; - item->clean_read = item->clean_send = newfd; - } else { - item->clean_read = item->clean_send = fd; - item->dirty_read = item->dirty_send = newfd; - } - /* We use the SSL's "app_data" to indicate a call-back induced "kill" */ - SSL_set_app_data(new_ssl, NULL); - if(!state_machine_set_SSL(&item->sm, new_ssl, world->server_mode)) - goto err; - return 1; -err: - tunala_world_del_item(world, world->tunnels_used - 1); - return 0; + if (!tunala_world_make_room(world)) + return 0; + if ((new_ssl = SSL_new(world->ssl_ctx)) == NULL) { + fprintf(stderr, "Error creating new SSL\n"); + ERR_print_errors_fp(stderr); + return 0; + } + item = world->tunnels + (world->tunnels_used++); + state_machine_init(&item->sm); + item->clean_read = item->clean_send = + item->dirty_read = item->dirty_send = -1; + if ((newfd = ip_create_connection_split(ip, port)) == -1) + goto err; + /* + * Which way round? If we're a server, "fd" is the dirty side and the + * connection we open is the clean one. For a client, it's the other way + * around. Unless, of course, we're "flipped" in which case everything + * gets reversed. :-) + */ + if ((world->server_mode && !flipped) || (!world->server_mode && flipped)) { + item->dirty_read = item->dirty_send = fd; + item->clean_read = item->clean_send = newfd; + } else { + item->clean_read = item->clean_send = fd; + item->dirty_read = item->dirty_send = newfd; + } + /* + * We use the SSL's "app_data" to indicate a call-back induced "kill" + */ + SSL_set_app_data(new_ssl, NULL); + if (!state_machine_set_SSL(&item->sm, new_ssl, world->server_mode)) + goto err; + return 1; + err: + tunala_world_del_item(world, world->tunnels_used - 1); + return 0; } -static void tunala_world_del_item(tunala_world_t *world, unsigned int idx) +static void tunala_world_del_item(tunala_world_t * world, unsigned int idx) { - tunala_item_t *item = world->tunnels + idx; - if(item->clean_read != -1) - close(item->clean_read); - if(item->clean_send != item->clean_read) - close(item->clean_send); - item->clean_read = item->clean_send = -1; - if(item->dirty_read != -1) - close(item->dirty_read); - if(item->dirty_send != item->dirty_read) - close(item->dirty_send); - item->dirty_read = item->dirty_send = -1; - state_machine_close(&item->sm); - /* OK, now we fix the item array */ - if(idx + 1 < world->tunnels_used) - /* We need to scroll entries to the left */ - memmove(world->tunnels + idx, - world->tunnels + (idx + 1), - (world->tunnels_used - (idx + 1)) * - sizeof(tunala_item_t)); - world->tunnels_used--; + tunala_item_t *item = world->tunnels + idx; + if (item->clean_read != -1) + close(item->clean_read); + if (item->clean_send != item->clean_read) + close(item->clean_send); + item->clean_read = item->clean_send = -1; + if (item->dirty_read != -1) + close(item->dirty_read); + if (item->dirty_send != item->dirty_read) + close(item->dirty_send); + item->dirty_read = item->dirty_send = -1; + state_machine_close(&item->sm); + /* OK, now we fix the item array */ + if (idx + 1 < world->tunnels_used) + /* We need to scroll entries to the left */ + memmove(world->tunnels + idx, + world->tunnels + (idx + 1), + (world->tunnels_used - (idx + 1)) * sizeof(tunala_item_t)); + world->tunnels_used--; } -static int tunala_item_io(tunala_selector_t *selector, tunala_item_t *item) +static int tunala_item_io(tunala_selector_t * selector, tunala_item_t * item) { - int c_r, c_s, d_r, d_s; /* Four boolean flags */ + int c_r, c_s, d_r, d_s; /* Four boolean flags */ - /* Take ourselves out of the gene-pool if there was an except */ - if((item->clean_read != -1) && FD_ISSET(item->clean_read, - &selector->last_selected.excepts)) - return 0; - if((item->clean_send != -1) && FD_ISSET(item->clean_send, - &selector->last_selected.excepts)) - return 0; - if((item->dirty_read != -1) && FD_ISSET(item->dirty_read, - &selector->last_selected.excepts)) - return 0; - if((item->dirty_send != -1) && FD_ISSET(item->dirty_send, - &selector->last_selected.excepts)) - return 0; - /* Grab our 4 IO flags */ - c_r = c_s = d_r = d_s = 0; - if(item->clean_read != -1) - c_r = FD_ISSET(item->clean_read, &selector->last_selected.reads); - if(item->clean_send != -1) - c_s = FD_ISSET(item->clean_send, &selector->last_selected.sends); - if(item->dirty_read != -1) - d_r = FD_ISSET(item->dirty_read, &selector->last_selected.reads); - if(item->dirty_send != -1) - d_s = FD_ISSET(item->dirty_send, &selector->last_selected.sends); - /* If no IO has happened for us, skip needless data looping */ - if(!c_r && !c_s && !d_r && !d_s) - return 1; - if(c_r) - c_r = (buffer_from_fd(state_machine_get_buffer(&item->sm, - SM_CLEAN_IN), item->clean_read) <= 0); - if(c_s) - c_s = (buffer_to_fd(state_machine_get_buffer(&item->sm, - SM_CLEAN_OUT), item->clean_send) <= 0); - if(d_r) - d_r = (buffer_from_fd(state_machine_get_buffer(&item->sm, - SM_DIRTY_IN), item->dirty_read) <= 0); - if(d_s) - d_s = (buffer_to_fd(state_machine_get_buffer(&item->sm, - SM_DIRTY_OUT), item->dirty_send) <= 0); - /* If any of the flags is non-zero, that means they need closing */ - if(c_r) { - close(item->clean_read); - if(item->clean_send == item->clean_read) - item->clean_send = -1; - item->clean_read = -1; - } - if(c_s && (item->clean_send != -1)) { - close(item->clean_send); - if(item->clean_send == item->clean_read) - item->clean_read = -1; - item->clean_send = -1; - } - if(d_r) { - close(item->dirty_read); - if(item->dirty_send == item->dirty_read) - item->dirty_send = -1; - item->dirty_read = -1; - } - if(d_s && (item->dirty_send != -1)) { - close(item->dirty_send); - if(item->dirty_send == item->dirty_read) - item->dirty_read = -1; - item->dirty_send = -1; - } - /* This function name is attributed to the term donated by David - * Schwartz on openssl-dev, message-ID: - * <NCBBLIEPOCNJOAEKBEAKEEDGLIAA.davids@webmaster.com>. :-) */ - if(!state_machine_churn(&item->sm)) - /* If the SSL closes, it will also zero-out the _in buffers - * and will in future process just outgoing data. As and - * when the outgoing data has gone, it will return zero - * here to tell us to bail out. */ - return 0; - /* Otherwise, we return zero if both sides are dead. */ - if(((item->clean_read == -1) || (item->clean_send == -1)) && - ((item->dirty_read == -1) || (item->dirty_send == -1))) - return 0; - /* If only one side closed, notify the SSL of this so it can take - * appropriate action. */ - if((item->clean_read == -1) || (item->clean_send == -1)) { - if(!state_machine_close_clean(&item->sm)) - return 0; - } - if((item->dirty_read == -1) || (item->dirty_send == -1)) { - if(!state_machine_close_dirty(&item->sm)) - return 0; - } - return 1; + /* Take ourselves out of the gene-pool if there was an except */ + if ((item->clean_read != -1) && FD_ISSET(item->clean_read, + &selector-> + last_selected.excepts)) + return 0; + if ((item->clean_send != -1) && FD_ISSET(item->clean_send, + &selector-> + last_selected.excepts)) + return 0; + if ((item->dirty_read != -1) && FD_ISSET(item->dirty_read, + &selector-> + last_selected.excepts)) + return 0; + if ((item->dirty_send != -1) && FD_ISSET(item->dirty_send, + &selector-> + last_selected.excepts)) + return 0; + /* Grab our 4 IO flags */ + c_r = c_s = d_r = d_s = 0; + if (item->clean_read != -1) + c_r = FD_ISSET(item->clean_read, &selector->last_selected.reads); + if (item->clean_send != -1) + c_s = FD_ISSET(item->clean_send, &selector->last_selected.sends); + if (item->dirty_read != -1) + d_r = FD_ISSET(item->dirty_read, &selector->last_selected.reads); + if (item->dirty_send != -1) + d_s = FD_ISSET(item->dirty_send, &selector->last_selected.sends); + /* If no IO has happened for us, skip needless data looping */ + if (!c_r && !c_s && !d_r && !d_s) + return 1; + if (c_r) + c_r = (buffer_from_fd(state_machine_get_buffer(&item->sm, + SM_CLEAN_IN), + item->clean_read) <= 0); + if (c_s) + c_s = (buffer_to_fd(state_machine_get_buffer(&item->sm, + SM_CLEAN_OUT), + item->clean_send) <= 0); + if (d_r) + d_r = (buffer_from_fd(state_machine_get_buffer(&item->sm, + SM_DIRTY_IN), + item->dirty_read) <= 0); + if (d_s) + d_s = (buffer_to_fd(state_machine_get_buffer(&item->sm, + SM_DIRTY_OUT), + item->dirty_send) <= 0); + /* If any of the flags is non-zero, that means they need closing */ + if (c_r) { + close(item->clean_read); + if (item->clean_send == item->clean_read) + item->clean_send = -1; + item->clean_read = -1; + } + if (c_s && (item->clean_send != -1)) { + close(item->clean_send); + if (item->clean_send == item->clean_read) + item->clean_read = -1; + item->clean_send = -1; + } + if (d_r) { + close(item->dirty_read); + if (item->dirty_send == item->dirty_read) + item->dirty_send = -1; + item->dirty_read = -1; + } + if (d_s && (item->dirty_send != -1)) { + close(item->dirty_send); + if (item->dirty_send == item->dirty_read) + item->dirty_read = -1; + item->dirty_send = -1; + } + /* + * This function name is attributed to the term donated by David Schwartz + * on openssl-dev, message-ID: + * <NCBBLIEPOCbmasEKBEAKEEDGLIAA.davids@webmaster.com>. :-) + */ + if (!state_machine_churn(&item->sm)) + /* + * If the SSL closes, it will also zero-out the _in buffers and will + * in future process just outgoing data. As and when the outgoing + * data has gone, it will return zero here to tell us to bail out. + */ + return 0; + /* Otherwise, we return zero if both sides are dead. */ + if (((item->clean_read == -1) || (item->clean_send == -1)) && + ((item->dirty_read == -1) || (item->dirty_send == -1))) + return 0; + /* + * If only one side closed, notify the SSL of this so it can take + * appropriate action. + */ + if ((item->clean_read == -1) || (item->clean_send == -1)) { + if (!state_machine_close_clean(&item->sm)) + return 0; + } + if ((item->dirty_read == -1) || (item->dirty_send == -1)) { + if (!state_machine_close_dirty(&item->sm)) + return 0; + } + return 1; } - diff --git a/openssl/demos/tunala/tunala.h b/openssl/demos/tunala/tunala.h index 3a752f259..28860d781 100644 --- a/openssl/demos/tunala/tunala.h +++ b/openssl/demos/tunala/tunala.h @@ -1,215 +1,244 @@ -/* Tunala ("Tunneler with a New Zealand accent") - * - * Written by Geoff Thorpe, but endorsed/supported by noone. Please use this is - * if it's useful or informative to you, but it's only here as a scratchpad for - * ideas about how you might (or might not) program with OpenSSL. If you deploy - * this is in a mission-critical environment, and have not read, understood, - * audited, and modified this code to your satisfaction, and the result is that - * all hell breaks loose and you are looking for a new employer, then it proves - * nothing except perhaps that Darwinism is alive and well. Let's just say, *I* - * don't use this in a mission-critical environment, so it would be stupid for - * anyone to assume that it is solid and/or tested enough when even its author - * doesn't place that much trust in it. You have been warned. - * +/* + * Tunala ("Tunneler with a New Zealand accent") Written by Geoff Thorpe, + * but endorsed/supported by noone. Please use this is if it's useful or + * informative to you, but it's only here as a scratchpad for ideas about how + * you might (or might not) program with OpenSSL. If you deploy this is in a + * mission-critical environment, and have not read, understood, audited, and + * modified this code to your satisfaction, and the result is that all hell + * breaks loose and you are looking for a new employer, then it proves + * nothing except perhaps that Darwinism is alive and well. Let's just say, + * *I* don't use this in a mission-critical environment, so it would be + * stupid for anyone to assume that it is solid and/or tested enough when + * even its author doesn't place that much trust in it. You have been warned. * With thanks to Cryptographic Appliances, Inc. */ #ifndef _TUNALA_H -#define _TUNALA_H +# define _TUNALA_H /* pull in autoconf fluff */ -#ifndef NO_CONFIG_H -#include "config.h" -#else -/* We don't have autoconf, we have to set all of these unless a tweaked Makefile - * tells us not to ... */ +# ifndef NO_CONFIG_H +# include "config.h" +# else +/* + * We don't have autoconf, we have to set all of these unless a tweaked + * Makefile tells us not to ... + */ /* headers */ -#ifndef NO_HAVE_SELECT -#define HAVE_SELECT -#endif -#ifndef NO_HAVE_SOCKET -#define HAVE_SOCKET -#endif -#ifndef NO_HAVE_UNISTD_H -#define HAVE_UNISTD_H -#endif -#ifndef NO_HAVE_FCNTL_H -#define HAVE_FCNTL_H -#endif -#ifndef NO_HAVE_LIMITS_H -#define HAVE_LIMITS_H -#endif +# ifndef NO_HAVE_SELECT +# define HAVE_SELECT +# endif +# ifndef NO_HAVE_SOCKET +# define HAVE_SOCKET +# endif +# ifndef NO_HAVE_UNISTD_H +# define HAVE_UNISTD_H +# endif +# ifndef NO_HAVE_FCNTL_H +# define HAVE_FCNTL_H +# endif +# ifndef NO_HAVE_LIMITS_H +# define HAVE_LIMITS_H +# endif /* features */ -#ifndef NO_HAVE_STRSTR -#define HAVE_STRSTR -#endif -#ifndef NO_HAVE_STRTOUL -#define HAVE_STRTOUL -#endif -#endif - -#if !defined(HAVE_SELECT) || !defined(HAVE_SOCKET) -#error "can't build without some network basics like select() and socket()" -#endif - -#include <stdlib.h> -#ifndef NO_SYSTEM_H -#include <string.h> -#ifdef HAVE_UNISTD_H -#include <unistd.h> -#endif -#ifdef HAVE_FCNTL_H -#include <fcntl.h> -#endif -#ifdef HAVE_LIMITS_H -#include <limits.h> -#endif -#include <netdb.h> -#include <signal.h> -#include <sys/socket.h> -#include <sys/types.h> -#include <netinet/in.h> -#endif /* !defined(NO_SYSTEM_H) */ - -#ifndef NO_OPENSSL -#include <openssl/err.h> -#include <openssl/engine.h> -#include <openssl/ssl.h> -#endif /* !defined(NO_OPENSSL) */ - -#ifndef OPENSSL_NO_BUFFER -/* This is the generic "buffer" type that is used when feeding the +# ifndef NO_HAVE_STRSTR +# define HAVE_STRSTR +# endif +# ifndef NO_HAVE_STRTOUL +# define HAVE_STRTOUL +# endif +# endif + +# if !defined(HAVE_SELECT) || !defined(HAVE_SOCKET) +# error "can't build without some network basics like select() and socket()" +# endif + +# include <stdlib.h> +# ifndef NO_SYSTEM_H +# include <string.h> +# ifdef HAVE_UNISTD_H +# include <unistd.h> +# endif +# ifdef HAVE_FCNTL_H +# include <fcntl.h> +# endif +# ifdef HAVE_LIMITS_H +# include <limits.h> +# endif +# include <netdb.h> +# include <signal.h> +# include <sys/socket.h> +# include <sys/types.h> +# include <netinet/in.h> +# endif /* !defined(NO_SYSTEM_H) */ + +# ifndef NO_OPENSSL +# include <openssl/err.h> +# include <openssl/engine.h> +# include <openssl/ssl.h> +# endif /* !defined(NO_OPENSSL) */ + +# ifndef OPENSSL_NO_BUFFER +/* + * This is the generic "buffer" type that is used when feeding the * state-machine. It's basically a FIFO with respect to the "adddata" & - * "takedata" type functions that operate on it. */ -#define MAX_DATA_SIZE 16384 + * "takedata" type functions that operate on it. + */ +# define MAX_DATA_SIZE 16384 typedef struct _buffer_t { - unsigned char data[MAX_DATA_SIZE]; - unsigned int used; - /* Statistical values - counts the total number of bytes read in and - * read out (respectively) since "buffer_init()" */ - unsigned long total_in, total_out; + unsigned char data[MAX_DATA_SIZE]; + unsigned int used; + /* + * Statistical values - counts the total number of bytes read in and read + * out (respectively) since "buffer_init()" + */ + unsigned long total_in, total_out; } buffer_t; /* Initialise a buffer structure before use */ -void buffer_init(buffer_t *buf); -/* Cleanup a buffer structure - presently not needed, but if buffer_t is - * converted to using dynamic allocation, this would be required - so should be - * called to protect against an explosion of memory leaks later if the change is - * made. */ -void buffer_close(buffer_t *buf); +void buffer_init(buffer_t * buf); +/* + * Cleanup a buffer structure - presently not needed, but if buffer_t is + * converted to using dynamic allocation, this would be required - so should + * be called to protect against an explosion of memory leaks later if the + * change is made. + */ +void buffer_close(buffer_t * buf); /* Basic functions to manipulate buffers */ -unsigned int buffer_used(buffer_t *buf); /* How much data in the buffer */ -unsigned int buffer_unused(buffer_t *buf); /* How much space in the buffer */ -int buffer_full(buffer_t *buf); /* Boolean, is it full? */ -int buffer_notfull(buffer_t *buf); /* Boolean, is it not full? */ -int buffer_empty(buffer_t *buf); /* Boolean, is it empty? */ -int buffer_notempty(buffer_t *buf); /* Boolean, is it not empty? */ -unsigned long buffer_total_in(buffer_t *buf); /* Total bytes written to buffer */ -unsigned long buffer_total_out(buffer_t *buf); /* Total bytes read from buffer */ - -#if 0 /* Currently used only within buffer.c - better to expose only - * higher-level functions anyway */ -/* Add data to the tail of the buffer, returns the amount that was actually - * added (so, you need to check if return value is less than size) */ -unsigned int buffer_adddata(buffer_t *buf, const unsigned char *ptr, - unsigned int size); - -/* Take data from the front of the buffer (and scroll the rest forward). If +unsigned int buffer_used(buffer_t * buf); /* How much data in the buffer */ +unsigned int buffer_unused(buffer_t * buf); /* How much space in the buffer */ +int buffer_full(buffer_t * buf); /* Boolean, is it full? */ +int buffer_notfull(buffer_t * buf); /* Boolean, is it not full? */ +int buffer_empty(buffer_t * buf); /* Boolean, is it empty? */ +int buffer_notempty(buffer_t * buf); /* Boolean, is it not empty? */ +unsigned long buffer_total_in(buffer_t * buf); /* Total bytes written to + * buffer */ +unsigned long buffer_total_out(buffer_t * buf); /* Total bytes read from + * buffer */ + +# if 0 /* Currently used only within buffer.c - + * better to expose only higher-level + * functions anyway */ +/* + * Add data to the tail of the buffer, returns the amount that was actually + * added (so, you need to check if return value is less than size) + */ +unsigned int buffer_adddata(buffer_t * buf, const unsigned char *ptr, + unsigned int size); + +/* + * Take data from the front of the buffer (and scroll the rest forward). If * "ptr" is NULL, this just removes data off the front of the buffer. Return - * value is the amount actually removed (can be less than size if the buffer has - * too little data). */ -unsigned int buffer_takedata(buffer_t *buf, unsigned char *ptr, - unsigned int size); - -/* Flushes as much data as possible out of the "from" buffer into the "to" - * buffer. Return value is the amount moved. The amount moved can be restricted - * to a maximum by specifying "cap" - setting it to -1 means no limit. */ -unsigned int buffer_tobuffer(buffer_t *to, buffer_t *from, int cap); -#endif - -#ifndef NO_IP + * value is the amount actually removed (can be less than size if the buffer + * has too little data). + */ +unsigned int buffer_takedata(buffer_t * buf, unsigned char *ptr, + unsigned int size); + +/* + * Flushes as much data as possible out of the "from" buffer into the "to" + * buffer. Return value is the amount moved. The amount moved can be + * restricted to a maximum by specifying "cap" - setting it to -1 means no + * limit. + */ +unsigned int buffer_tobuffer(buffer_t * to, buffer_t * from, int cap); +# endif + +# ifndef NO_IP /* Read or write between a file-descriptor and a buffer */ -int buffer_from_fd(buffer_t *buf, int fd); -int buffer_to_fd(buffer_t *buf, int fd); -#endif /* !defined(NO_IP) */ +int buffer_from_fd(buffer_t * buf, int fd); +int buffer_to_fd(buffer_t * buf, int fd); +# endif /* !defined(NO_IP) */ -#ifndef NO_OPENSSL +# ifndef NO_OPENSSL /* Read or write between an SSL or BIO and a buffer */ -void buffer_from_SSL(buffer_t *buf, SSL *ssl); -void buffer_to_SSL(buffer_t *buf, SSL *ssl); -void buffer_from_BIO(buffer_t *buf, BIO *bio); -void buffer_to_BIO(buffer_t *buf, BIO *bio); +void buffer_from_SSL(buffer_t * buf, SSL *ssl); +void buffer_to_SSL(buffer_t * buf, SSL *ssl); +void buffer_from_BIO(buffer_t * buf, BIO *bio); +void buffer_to_BIO(buffer_t * buf, BIO *bio); /* Callbacks */ void cb_ssl_info(const SSL *s, int where, int ret); -void cb_ssl_info_set_output(FILE *fp); /* Called if output should be sent too */ +/* Called if output should be sent too */ +void cb_ssl_info_set_output(FILE *fp); int cb_ssl_verify(int ok, X509_STORE_CTX *ctx); void cb_ssl_verify_set_output(FILE *fp); void cb_ssl_verify_set_depth(unsigned int verify_depth); void cb_ssl_verify_set_level(unsigned int level); RSA *cb_generate_tmp_rsa(SSL *s, int is_export, int keylength); -#endif /* !defined(NO_OPENSSL) */ -#endif /* !defined(OPENSSL_NO_BUFFER) */ +# endif /* !defined(NO_OPENSSL) */ +# endif /* !defined(OPENSSL_NO_BUFFER) */ -#ifndef NO_TUNALA -#ifdef OPENSSL_NO_BUFFER -#error "TUNALA section of tunala.h requires BUFFER support" -#endif +# ifndef NO_TUNALA +# ifdef OPENSSL_NO_BUFFER +# error "TUNALA section of tunala.h requires BUFFER support" +# endif typedef struct _state_machine_t { - SSL *ssl; - BIO *bio_intossl; - BIO *bio_fromssl; - buffer_t clean_in, clean_out; - buffer_t dirty_in, dirty_out; + SSL *ssl; + BIO *bio_intossl; + BIO *bio_fromssl; + buffer_t clean_in, clean_out; + buffer_t dirty_in, dirty_out; } state_machine_t; typedef enum { - SM_CLEAN_IN, SM_CLEAN_OUT, - SM_DIRTY_IN, SM_DIRTY_OUT + SM_CLEAN_IN, SM_CLEAN_OUT, + SM_DIRTY_IN, SM_DIRTY_OUT } sm_buffer_t; -void state_machine_init(state_machine_t *machine); -void state_machine_close(state_machine_t *machine); -buffer_t *state_machine_get_buffer(state_machine_t *machine, sm_buffer_t type); -SSL *state_machine_get_SSL(state_machine_t *machine); -int state_machine_set_SSL(state_machine_t *machine, SSL *ssl, int is_server); +void state_machine_init(state_machine_t * machine); +void state_machine_close(state_machine_t * machine); +buffer_t *state_machine_get_buffer(state_machine_t * machine, + sm_buffer_t type); +SSL *state_machine_get_SSL(state_machine_t * machine); +int state_machine_set_SSL(state_machine_t * machine, SSL *ssl, int is_server); /* Performs the data-IO loop and returns zero if the machine should close */ -int state_machine_churn(state_machine_t *machine); -/* Is used to handle closing conditions - namely when one side of the tunnel has - * closed but the other should finish flushing. */ -int state_machine_close_clean(state_machine_t *machine); -int state_machine_close_dirty(state_machine_t *machine); -#endif /* !defined(NO_TUNALA) */ - -#ifndef NO_IP -/* Initialise anything related to the networking. This includes blocking pesky - * SIGPIPE signals. */ +int state_machine_churn(state_machine_t * machine); +/* + * Is used to handle closing conditions - namely when one side of the tunnel + * has closed but the other should finish flushing. + */ +int state_machine_close_clean(state_machine_t * machine); +int state_machine_close_dirty(state_machine_t * machine); +# endif /* !defined(NO_TUNALA) */ + +# ifndef NO_IP +/* + * Initialise anything related to the networking. This includes blocking + * pesky SIGPIPE signals. + */ int ip_initialise(void); -/* ip is the 4-byte ip address (eg. 127.0.0.1 is {0x7F,0x00,0x00,0x01}), port is - * the port to listen on (host byte order), and the return value is the - * file-descriptor or -1 on error. */ +/* + * ip is the 4-byte ip address (eg. 127.0.0.1 is {0x7F,0x00,0x00,0x01}), port + * is the port to listen on (host byte order), and the return value is the + * file-descriptor or -1 on error. + */ int ip_create_listener_split(const char *ip, unsigned short port); /* Same semantics as above. */ int ip_create_connection_split(const char *ip, unsigned short port); /* Converts a string into the ip/port before calling the above */ int ip_create_listener(const char *address); int ip_create_connection(const char *address); -/* Just does a string conversion on its own. NB: If accept_all_ip is non-zero, - * then the address string could be just a port. Ie. it's suitable for a - * listening address but not a connecting address. */ +/* + * Just does a string conversion on its own. NB: If accept_all_ip is + * non-zero, then the address string could be just a port. Ie. it's suitable + * for a listening address but not a connecting address. + */ int ip_parse_address(const char *address, const char **parsed_ip, - unsigned short *port, int accept_all_ip); -/* Accepts an incoming connection through the listener. Assumes selects and - * what-not have deemed it an appropriate thing to do. */ + unsigned short *port, int accept_all_ip); +/* + * Accepts an incoming connection through the listener. Assumes selects and + * what-not have deemed it an appropriate thing to do. + */ int ip_accept_connection(int listen_fd); -#endif /* !defined(NO_IP) */ +# endif /* !defined(NO_IP) */ /* These functions wrap up things that can be portability hassles. */ int int_strtoul(const char *str, unsigned long *val); -#ifdef HAVE_STRSTR -#define int_strstr strstr -#else +# ifdef HAVE_STRSTR +# define int_strstr strstr +# else char *int_strstr(const char *haystack, const char *needle); -#endif +# endif -#endif /* !defined(_TUNALA_H) */ +#endif /* !defined(_TUNALA_H) */ |