int mtls_read(mtlsctx_t* ctx, void* buf, int len) { int rv; TRACE("called\n"); if (ctx->usessl == 0) { rv = mbedtls_net_recv(&ctx->net, buf, len); } else { rv = mbedtls_ssl_read(&ctx->ssl, buf, len); } if (rv == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { // EOF TRACE("EOF\n"); return 0; } if (rv < 0) { ERROR("mtls_read failed: %s\n", mtls_errmsg(rv)); return rv; } TRACE("%d bytes\n", rv); return rv; }
int dslink_socket_read(Socket *sock, char *buf, size_t len) { int r; if (sock->secure) { r = mbedtls_ssl_read(((SslSocket *) sock)->ssl, (unsigned char *) buf, len); } else { r = mbedtls_net_recv(sock->socket_fd, (unsigned char *) buf, len); } if (r < 0) { errno = r; return DSLINK_SOCK_READ_ERR; } return r; }
static int write_and_get_response( mbedtls_net_context *sock_fd, unsigned char *buf, size_t len ) { int ret; unsigned char data[128]; char code[4]; size_t i, idx = 0; mbedtls_printf("\n%s", buf); if( len && ( ret = mbedtls_net_send( sock_fd, buf, len ) ) <= 0 ) { mbedtls_printf( " failed\n ! mbedtls_ssl_write returned %d\n\n", ret ); return -1; } do { len = sizeof( data ) - 1; memset( data, 0, sizeof( data ) ); ret = mbedtls_net_recv( sock_fd, data, len ); if( ret <= 0 ) { mbedtls_printf( "failed\n ! read returned %d\n\n", ret ); return -1; } data[len] = '\0'; mbedtls_printf("\n%s", data); len = ret; for( i = 0; i < len; i++ ) { if( data[i] != '\n' ) { if( idx < 4 ) code[ idx++ ] = data[i]; continue; } if( idx == 4 && code[0] >= '0' && code[0] <= '9' && code[3] == ' ' ) { code[3] = '\0'; return atoi( code ); } idx = 0; } } while( 1 ); }
/* * Read at most 'len' characters, blocking for at most 'timeout' ms */ int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len, uint32_t timeout ) { int ret; timeval tv; fd_set read_fds; int fd = ((mbedtls_net_context *) ctx)->fd; if( fd < 0 ) return( MBEDTLS_ERR_NET_INVALID_CONTEXT ); FD_ZERO( &read_fds ); FD_SET( fd, &read_fds ); tv.tv_sec = timeout / 1000; tv.tv_usec = ( timeout % 1000 ) * 1000; const timeval tv_const = tv; ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv_const ); /* Zero fds ready means we timed out */ if( ret == 0 ) return( MBEDTLS_ERR_SSL_TIMEOUT ); if( ret < 0 ) { #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \ !defined(EFI32) if( WSAGetLastError() == WSAEINTR ) return( MBEDTLS_ERR_SSL_WANT_READ ); #else if( errno == EINTR ) return( MBEDTLS_ERR_SSL_WANT_READ ); #endif return( MBEDTLS_ERR_NET_RECV_FAILED ); } /* This call will not block */ return( mbedtls_net_recv( ctx, buf, len ) ); }
/* * Read at most 'len' characters, blocking for at most 'timeout' ms */ int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len, uint32_t timeout ) { int ret; struct timeval tv; fd_set read_fds; int fd = ((mbedtls_net_context *) ctx)->fd; if ( fd < 0 ) { return ( MBEDTLS_ERR_NET_INVALID_CONTEXT ); } FD_ZERO( &read_fds ); FD_SET( fd, &read_fds ); tv.tv_sec = timeout / 1000; tv.tv_usec = ( timeout % 1000 ) * 1000; ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv ); /* Zero fds ready means we timed out */ if ( ret == 0 ) { return ( MBEDTLS_ERR_SSL_TIMEOUT ); } if ( ret < 0 ) { if ( errno == EINTR ) { return ( MBEDTLS_ERR_SSL_WANT_READ ); } return ( MBEDTLS_ERR_NET_RECV_FAILED ); } /* This call will not block */ return ( mbedtls_net_recv( ctx, buf, len ) ); }
int handle_message( const char *way, mbedtls_net_context *dst, mbedtls_net_context *src ) { int ret; packet cur; size_t id; /* receive packet */ if( ( ret = mbedtls_net_recv( src, cur.buf, sizeof( cur.buf ) ) ) <= 0 ) { mbedtls_printf( " ! mbedtls_net_recv returned %d\n", ret ); return( ret ); } cur.len = ret; cur.type = msg_type( cur.buf, cur.len ); cur.way = way; cur.dst = dst; print_packet( &cur, NULL ); id = cur.len % sizeof( dropped ); /* do we want to drop, delay, or forward it? */ if( ( opt.mtu != 0 && cur.len > (unsigned) opt.mtu ) || ( opt.drop != 0 && strcmp( cur.type, "ApplicationData" ) != 0 && ! ( opt.protect_hvr && strcmp( cur.type, "HelloVerifyRequest" ) == 0 ) && cur.len != (size_t) opt.protect_len && dropped[id] < DROP_MAX && rand() % opt.drop == 0 ) ) { update_dropped( &cur ); } else if( ( opt.delay_ccs == 1 && strcmp( cur.type, "ChangeCipherSpec" ) == 0 ) || ( opt.delay != 0 && strcmp( cur.type, "ApplicationData" ) != 0 && ! ( opt.protect_hvr && strcmp( cur.type, "HelloVerifyRequest" ) == 0 ) && prev.dst == NULL && cur.len != (size_t) opt.protect_len && dropped[id] < DROP_MAX && rand() % opt.delay == 0 ) ) { memcpy( &prev, &cur, sizeof( packet ) ); } else { /* forward and possibly duplicate */ if( ( ret = send_packet( &cur, "forwarded" ) ) != 0 ) return( ret ); /* send previously delayed message if any */ if( prev.dst != NULL ) { ret = send_packet( &prev, "delayed" ); memset( &prev, 0, sizeof( packet ) ); if( ret != 0 ) return( ret ); } } return( 0 ); }
int main( void ) { FILE *f; int ret; size_t n, buflen; mbedtls_net_context server_fd; unsigned char *p, *end; unsigned char buf[2048]; unsigned char hash[32]; const char *pers = "dh_client"; mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; mbedtls_rsa_context rsa; mbedtls_dhm_context dhm; mbedtls_aes_context aes; mbedtls_net_init( &server_fd ); mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256 ); mbedtls_dhm_init( &dhm ); mbedtls_aes_init( &aes ); mbedtls_ctr_drbg_init( &ctr_drbg ); /* * 1. Setup the RNG */ mbedtls_printf( "\n . Seeding the random number generator" ); fflush( stdout ); mbedtls_entropy_init( &entropy ); if( ( ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy, (const unsigned char *) pers, strlen( pers ) ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_ctr_drbg_seed returned %d\n", ret ); goto exit; } /* * 2. Read the server's public RSA key */ mbedtls_printf( "\n . Reading public key from rsa_pub.txt" ); fflush( stdout ); if( ( f = fopen( "rsa_pub.txt", "rb" ) ) == NULL ) { ret = 1; mbedtls_printf( " failed\n ! Could not open rsa_pub.txt\n" \ " ! Please run rsa_genkey first\n\n" ); goto exit; } mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 ); if( ( ret = mbedtls_mpi_read_file( &rsa.N, 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &rsa.E, 16, f ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_mpi_read_file returned %d\n\n", ret ); goto exit; } rsa.len = ( mbedtls_mpi_bitlen( &rsa.N ) + 7 ) >> 3; fclose( f ); /* * 3. Initiate the connection */ mbedtls_printf( "\n . Connecting to tcp/%s/%s", SERVER_NAME, SERVER_PORT ); fflush( stdout ); if( ( ret = mbedtls_net_connect( &server_fd, SERVER_NAME, SERVER_PORT, MBEDTLS_NET_PROTO_TCP ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_net_connect returned %d\n\n", ret ); goto exit; } /* * 4a. First get the buffer length */ mbedtls_printf( "\n . Receiving the server's DH parameters" ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); if( ( ret = mbedtls_net_recv( &server_fd, buf, 2 ) ) != 2 ) { mbedtls_printf( " failed\n ! mbedtls_net_recv returned %d\n\n", ret ); goto exit; } n = buflen = ( buf[0] << 8 ) | buf[1]; if( buflen < 1 || buflen > sizeof( buf ) ) { mbedtls_printf( " failed\n ! Got an invalid buffer length\n\n" ); goto exit; } /* * 4b. Get the DHM parameters: P, G and Ys = G^Xs mod P */ memset( buf, 0, sizeof( buf ) ); if( ( ret = mbedtls_net_recv( &server_fd, buf, n ) ) != (int) n ) { mbedtls_printf( " failed\n ! mbedtls_net_recv returned %d\n\n", ret ); goto exit; } p = buf, end = buf + buflen; if( ( ret = mbedtls_dhm_read_params( &dhm, &p, end ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_dhm_read_params returned %d\n\n", ret ); goto exit; } if( dhm.len < 64 || dhm.len > 512 ) { ret = 1; mbedtls_printf( " failed\n ! Invalid DHM modulus size\n\n" ); goto exit; } /* * 5. Check that the server's RSA signature matches * the SHA-256 hash of (P,G,Ys) */ mbedtls_printf( "\n . Verifying the server's RSA signature" ); fflush( stdout ); p += 2; if( ( n = (size_t) ( end - p ) ) != rsa.len ) { ret = 1; mbedtls_printf( " failed\n ! Invalid RSA signature size\n\n" ); goto exit; } mbedtls_sha1( buf, (int)( p - 2 - buf ), hash ); if( ( ret = mbedtls_rsa_pkcs1_verify( &rsa, NULL, NULL, MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA256, 0, hash, p ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_rsa_pkcs1_verify returned %d\n\n", ret ); goto exit; } /* * 6. Send our public value: Yc = G ^ Xc mod P */ mbedtls_printf( "\n . Sending own public value to server" ); fflush( stdout ); n = dhm.len; if( ( ret = mbedtls_dhm_make_public( &dhm, (int) dhm.len, buf, n, mbedtls_ctr_drbg_random, &ctr_drbg ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_dhm_make_public returned %d\n\n", ret ); goto exit; } if( ( ret = mbedtls_net_send( &server_fd, buf, n ) ) != (int) n ) { mbedtls_printf( " failed\n ! mbedtls_net_send returned %d\n\n", ret ); goto exit; } /* * 7. Derive the shared secret: K = Ys ^ Xc mod P */ mbedtls_printf( "\n . Shared secret: " ); fflush( stdout ); if( ( ret = mbedtls_dhm_calc_secret( &dhm, buf, sizeof( buf ), &n, mbedtls_ctr_drbg_random, &ctr_drbg ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_dhm_calc_secret returned %d\n\n", ret ); goto exit; } for( n = 0; n < 16; n++ ) mbedtls_printf( "%02x", buf[n] ); /* * 8. Setup the AES-256 decryption key * * This is an overly simplified example; best practice is * to hash the shared secret with a random value to derive * the keying material for the encryption/decryption keys, * IVs and MACs. */ mbedtls_printf( "...\n . Receiving and decrypting the ciphertext" ); fflush( stdout ); mbedtls_aes_setkey_dec( &aes, buf, 256 ); memset( buf, 0, sizeof( buf ) ); if( ( ret = mbedtls_net_recv( &server_fd, buf, 16 ) ) != 16 ) { mbedtls_printf( " failed\n ! mbedtls_net_recv returned %d\n\n", ret ); goto exit; } mbedtls_aes_crypt_ecb( &aes, MBEDTLS_AES_DECRYPT, buf, buf ); buf[16] = '\0'; mbedtls_printf( "\n . Plaintext is \"%s\"\n\n", (char *) buf ); exit: mbedtls_net_free( &server_fd ); mbedtls_aes_free( &aes ); mbedtls_rsa_free( &rsa ); mbedtls_dhm_free( &dhm ); mbedtls_ctr_drbg_free( &ctr_drbg ); mbedtls_entropy_free( &entropy ); #if defined(_WIN32) mbedtls_printf( " + Press Enter to exit this program.\n" ); fflush( stdout ); getchar(); #endif return( ret ); }
/* * Read at most 'len' characters, blocking for at most 'timeout' ms */ int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len, uint32_t timeout ) { int ret; struct timeval tv; fd_set read_fds; int fd = ((mbedtls_net_context *) ctx)->fd; if( fd < 0 ) return( MBEDTLS_ERR_NET_INVALID_CONTEXT ); FD_ZERO( &read_fds ); FD_SET( fd, &read_fds ); tv.tv_sec = timeout / 1000; tv.tv_usec = ( timeout % 1000 ) * 1000; #if defined(__CELLOS_LV2__) ret = socketselect(fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv); #elif defined(VITA) extern int retro_epoll_fd; SceNetEpollEvent ev = {0}; ev.events = SCE_NET_EPOLLIN | SCE_NET_EPOLLHUP; ev.data.fd = fd + 1; if((sceNetEpollControl(retro_epoll_fd, SCE_NET_EPOLL_CTL_ADD, fd + 1, &ev))) { int ret = sceNetEpollWait(retro_epoll_fd, &ev, 1, 0); sceNetEpollControl(retro_epoll_fd, SCE_NET_EPOLL_CTL_DEL, fd + 1, NULL); #else ret = select( fd + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv ); #endif /* Zero fds ready means we timed out */ if( ret == 0 ) return( MBEDTLS_ERR_SSL_TIMEOUT ); if( ret < 0 ) { #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \ !defined(EFI32) if( WSAGetLastError() == WSAEINTR ) return( MBEDTLS_ERR_SSL_WANT_READ ); #else if( errno == EINTR ) return( MBEDTLS_ERR_SSL_WANT_READ ); #endif return( MBEDTLS_ERR_NET_RECV_FAILED ); } /* This call will not block */ return( mbedtls_net_recv( ctx, buf, len ) ); } /* * Write at most 'len' characters */ int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len ) { int ret; int fd = ((mbedtls_net_context *) ctx)->fd; if( fd < 0 ) return( MBEDTLS_ERR_NET_INVALID_CONTEXT ); ret = (int) write( fd, buf, len ); if( ret < 0 ) { if( net_would_block( ctx ) != 0 ) return( MBEDTLS_ERR_SSL_WANT_WRITE ); #if ( defined(_WIN32) || defined(_WIN32_WCE) ) && !defined(EFIX64) && \ !defined(EFI32) if( WSAGetLastError() == WSAECONNRESET ) return( MBEDTLS_ERR_NET_CONN_RESET ); #else if( errno == EPIPE || errno == ECONNRESET ) return( MBEDTLS_ERR_NET_CONN_RESET ); if( errno == EINTR ) return( MBEDTLS_ERR_SSL_WANT_WRITE ); #endif return( MBEDTLS_ERR_NET_SEND_FAILED ); } return( ret ); }
static void session_receive_from_client(EV_P_ session_context *sc) { int ret; packet_data *pd; packet_data temp = { .length = sizeof(temp.payload) }; ret = mbedtls_net_recv(&sc->client_fd, temp.payload, temp.length); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_NET_RECV_FAILED) { session_mark_activity(EV_A_ sc); return; } if (ret < 0) { session_deferred_free_after_error(sc, ret, "session_receive_from_client"); return; } /* ret is the number of bytes read from the backend server */ log_debug("(%s:%d) %d bytes received from backend server", sc->client_ip_str, sc->client_port, ret); if (ret > PACKET_DATA_BUFFER_SIZE) { session_deferred_free_after_error(sc, 0, "session_receive_from_client - packet payload too big"); return; } pd = calloc(1, sizeof(packet_data)); memcpy(pd->payload, temp.payload, ret); pd->length = ret; pd->next = 0; LL_APPEND(sc->from_client, pd); session_mark_activity(EV_A_ sc); ev_io_start(EV_A_ &sc->backend_wr_watcher); } static void session_send_to_backend(EV_P_ session_context *sc) { int ret; packet_data* head = sc->from_client; if (!head) { ev_io_stop(EV_A_ &sc->backend_wr_watcher); return; } ret = mbedtls_ssl_write(&sc->ssl, head->payload, head->length); if (ret == MBEDTLS_ERR_SSL_WANT_WRITE || ret == MBEDTLS_ERR_SSL_WANT_READ) { session_mark_activity(EV_A_ sc); return; } if (ret < 0) { session_deferred_free_after_error(sc, ret, "session_send_to_backend - write error"); return; } /* ret is the written len */ log_debug("(%s:%d) %d bytes written to DTLS socket", sc->options->backend_host, sc->options->backend_port, ret); if ((size_t)ret != head->length) { log_error("Sent only %d bytes out of %d", ret, head->length); } session_mark_activity(EV_A_ sc); LL_DELETE(sc->from_client, head); free(head); if (!sc->from_client) { ev_io_stop(EV_A_ &sc->backend_wr_watcher); } }