From 3235a2d4755b1bf83a42726488154952b1db10e1 Mon Sep 17 00:00:00 2001 From: Juliusz Sosinowicz Date: Wed, 22 Jun 2022 20:13:10 +0200 Subject: [PATCH] Init DTLS 1.3 examples --- dtls/Makefile | 8 +- dtls/client-dtls13.c | 182 +++++++++++++ dtls/dtls-common.h | 74 ++++++ dtls/server-dtls13-event.c | 511 +++++++++++++++++++++++++++++++++++++ dtls/server-dtls13.c | 230 +++++++++++++++++ 5 files changed, 1002 insertions(+), 3 deletions(-) create mode 100644 dtls/client-dtls13.c create mode 100644 dtls/dtls-common.h create mode 100644 dtls/server-dtls13-event.c create mode 100644 dtls/server-dtls13.c diff --git a/dtls/Makefile b/dtls/Makefile index 7eaef58b..39475f8d 100644 --- a/dtls/Makefile +++ b/dtls/Makefile @@ -7,13 +7,13 @@ LIBS = -L$(LIB_PATH)/lib -lm # option variables DYN_LIB = -lwolfssl STATIC_LIB = $(LIB_PATH)/lib/libwolfssl.a -DEBUG_FLAGS = -g -DDEBUG +DEBUG_FLAGS = -g3 -DDEBUG -O0 DEBUG_INC_PATHS = -MD OPTIMIZE = -Os # Options -#CFLAGS+=$(DEBUG_FLAGS) -CFLAGS+=$(OPTIMIZE) +CFLAGS+=$(DEBUG_FLAGS) +#CFLAGS+=$(OPTIMIZE) #LIBS+=$(STATIC_LIB) LIBS+=$(DYN_LIB) @@ -34,6 +34,8 @@ debug: all %-shared: CFLAGS+=-pthread %-shared: LIBS+=-lpthread +server-dtls13-event: LIBS+=-levent + # build template %: %.c $(CC) -o $@ $< $(CFLAGS) $(LIBS) diff --git a/dtls/client-dtls13.c b/dtls/client-dtls13.c new file mode 100644 index 00000000..b58d70bb --- /dev/null +++ b/dtls/client-dtls13.c @@ -0,0 +1,182 @@ +/* + * client-dtls13.c + * + * Copyright (C) 2006-2022 wolfSSL Inc. + * + * This file is part of wolfSSL. (formerly known as CyaSSL) + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + * + *============================================================================= + * + * Bare-bones example of a DTLS 1.3 client for instructional/learning purposes. + * This example uses blocking sockets for simplicity. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dtls-common.h" + +#define MAXLINE 4096 +#define SERV_PORT 11111 +#define LOOP_LIMIT 5 +#define SFD_TIMEOUT 1 + +int main (int argc, char** argv) +{ + /* standard variables used in a dtls client*/ + int n = 0; + int sockfd = INVALID_SOCKET; + int err; + int ret; + int exitVal = 1; + struct sockaddr_in servAddr; + WOLFSSL* ssl = NULL; + WOLFSSL_CTX* ctx = NULL; + char* certs = "../certs/ca-cert.pem"; + char sendLine[MAXLINE]; + char recvLine[MAXLINE - 1]; + + /* Program argument checking */ + if (argc != 2) { + fprintf(stderr, "usage: %s \n", argv[0]); + return exitVal; + } + + /* Initialize wolfSSL before assigning ctx */ + if (wolfSSL_Init() != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_CTX_new error.\n"); + return exitVal; + } + + /* No-op when debugging is not compiled in */ + wolfSSL_Debugging_ON(); + + if ( (ctx = wolfSSL_CTX_new(wolfDTLSv1_3_client_method())) == NULL) { + fprintf(stderr, "wolfSSL_CTX_new error.\n"); + goto cleanup; + } + + /* Load certificates into ctx variable */ + if (wolfSSL_CTX_load_verify_locations(ctx, certs, 0) + != SSL_SUCCESS) { + fprintf(stderr, "Error loading %s, please check the file.\n", certs); + goto cleanup; + } + + /* Assign ssl variable */ + ssl = wolfSSL_new(ctx); + if (ssl == NULL) { + fprintf(stderr, "unable to get ssl object\n"); + goto cleanup; + } + + /* servAddr setup */ + memset(&servAddr, 0, sizeof(servAddr)); + servAddr.sin_family = AF_INET; + servAddr.sin_port = htons(SERV_PORT); + if (inet_pton(AF_INET, argv[1], &servAddr.sin_addr) < 1) { + perror("inet_pton()"); + goto cleanup; + } + + if (wolfSSL_dtls_set_peer(ssl, &servAddr, sizeof(servAddr)) + != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_dtls_set_peer failed\n"); + goto cleanup; + } + + if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { + perror("socket()"); + goto cleanup; + } + + /* Set the file descriptor for ssl */ + if (wolfSSL_set_fd(ssl, sockfd) != WOLFSSL_SUCCESS) { + fprintf(stderr, "cannot set socket file descriptor\n"); + goto cleanup; + } + + /* Perform SSL connection */ + if (wolfSSL_connect(ssl) != SSL_SUCCESS) { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "err = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "wolfSSL_connect failed\n"); + goto cleanup; + } + +/*****************************************************************************/ +/* Code for sending datagram to server */ + if (fgets(sendLine, MAXLINE, stdin) != NULL) { + + /* Send sendLine to the server */ + if (wolfSSL_write(ssl, sendLine, strlen(sendLine)) != strlen(sendLine)) { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "err = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "wolfSSL_write failed\n"); + goto cleanup; + } + + /* n is the # of bytes received */ + n = wolfSSL_read(ssl, recvLine, sizeof(recvLine)-1); + + if (n > 0) { + /* Add a terminating character to the generic server message */ + recvLine[n] = '\0'; + printf("%s\n", recvLine); + } + else { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "err = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "wolfSSL_read failed\n"); + goto cleanup; + } + } +/* End code for sending datagram to server */ +/*****************************************************************************/ + + exitVal = 0; +cleanup: + if (ssl != NULL) { + /* Attempt a full shutdown */ + ret = wolfSSL_shutdown(ssl); + if (ret == WOLFSSL_SHUTDOWN_NOT_DONE) + ret = wolfSSL_shutdown(ssl); + if (ret != WOLFSSL_SUCCESS) { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "err = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "wolfSSL_shutdown failed\n"); + } + wolfSSL_free(ssl); + } + if (sockfd != INVALID_SOCKET) + close(sockfd); + if (ctx != NULL) + wolfSSL_CTX_free(ctx); + wolfSSL_Cleanup(); + + return exitVal; +} + diff --git a/dtls/dtls-common.h b/dtls/dtls-common.h new file mode 100644 index 00000000..c409b4ef --- /dev/null +++ b/dtls/dtls-common.h @@ -0,0 +1,74 @@ +/* + * dtls-common.h + * + * Copyright (C) 2006-2022 wolfSSL Inc. + * + * This file is part of wolfSSL. (formerly known as CyaSSL) + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + * + *============================================================================= + * + * Bare-bones example of a DTLS 1.3 client for instructional/learning purposes. + */ + +#ifndef DTLS_COMMON_H_ +#define DTLS_COMMON_H_ + +#define INVALID_SOCKET (-1) + +#define SFD_TIMEOUT_E (-1) +#define SFD_SOCKET_E (-2) +#define SFD_SELECT_E (-3) + +int wait_sfd(SOCKET_T socketfd, int to, int rx) { + fd_set fds, errfds; + fd_set* recvfds = NULL; + fd_set* sendfds = NULL; + SOCKET_T nfds = socketfd + 1; + struct timeval timeout; + int result; + + memset(&timeout, 0, sizeof(timeout)); + timeout.tv_sec = to; + + FD_ZERO(&fds); + FD_SET(socketfd, &fds); + FD_ZERO(&errfds); + FD_SET(socketfd, &errfds); + + if (rx) + recvfds = &fds; + else + sendfds = &fds; + + result = select(nfds, recvfds, sendfds, &errfds, &timeout); + + if (result == 0) + return SFD_TIMEOUT_E; + else if (result > 0) { + if (FD_ISSET(socketfd, &fds)) { + return 0; + } + else if(FD_ISSET(socketfd, &errfds)) + return SFD_SOCKET_E; + } + perror("select()"); + + return SFD_SELECT_E; +} + + +#endif /* DTLS_COMMON_H_ */ diff --git a/dtls/server-dtls13-event.c b/dtls/server-dtls13-event.c new file mode 100644 index 00000000..5f39bc8f --- /dev/null +++ b/dtls/server-dtls13-event.c @@ -0,0 +1,511 @@ +/* server-dtls13.c + * + * Copyright (C) 2006-2022 wolfSSL Inc. + * + * This file is part of wolfSSL. (formerly known as CyaSSL) + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + * + *============================================================================= + * + * Single threaded example of a DTLS 1.3 server for instructional/learning + * purposes. This example can handle multiple simultaneous connections by using + * the libevent library to handle the event loop. Please note that this example + * is not thread safe as access to global objects is not protected. + */ + +#include +#include /* standard in/out procedures */ +#include /* defines system calls */ +#include /* necessary for memset */ +#include +#include /* used for all socket calls */ +#include /* used for sockaddr_in */ +#include +#include +#include +#include +#include + +/* Requires libevent */ +#include + +#include "dtls-common.h" + +#define SERV_PORT 11111 /* define our server port number */ +#define MSGLEN 4096 +#define QUICK_MULT 4 /* Our quick timeout multiplier */ +#define CHGOODCB_E (-1000) /* An error outside the range of wolfSSL + * errors */ +#define CONN_TIMEOUT 5 /* How long we wait for peer data before + * closing the connection */ + +typedef struct conn_ctx { + WOLFSSL* ssl; + struct event* readEv; + struct event* writeEv; + char waitingOnData:1; +} conn_ctx; + +WOLFSSL_CTX* ctx = NULL; +struct event_base* base = NULL; +WOLFSSL* pendingSSL = NULL; +int listenfd = INVALID_SOCKET; /* Initialize our socket */ + +static void sig_handler(const int sig); +static void free_resources(void); +static void newConn(evutil_socket_t fd, short events, void* arg); +static void dataReady(evutil_socket_t fd, short events, void* arg); +static int chGoodCb(WOLFSSL* ssl, void*); +static int newPendingSSL(void); +static int newFD(void); + +int main(int argc, char** argv) +{ + /* Loc short for "location" */ + char caCertLoc[] = "../certs/ca-cert.pem"; + char servCertLoc[] = "../certs/server-cert.pem"; + char servKeyLoc[] = "../certs/server-key.pem"; + int exitVal = 1; + struct event* newConnEvent = NULL; + + /* Initialize wolfSSL before assigning ctx */ + if (wolfSSL_Init() != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_Init error.\n"); + return exitVal; + } + + /* No-op when debugging is not compiled in */ + wolfSSL_Debugging_ON(); + + /* Set ctx to DTLS 1.3 */ + if ((ctx = wolfSSL_CTX_new(wolfDTLSv1_3_server_method())) == NULL) { + fprintf(stderr, "wolfSSL_CTX_new error.\n"); + goto cleanup; + } + /* Load CA certificates */ + if (wolfSSL_CTX_load_verify_locations(ctx,caCertLoc,0) != + SSL_SUCCESS) { + fprintf(stderr, "Error loading %s, please check the file.\n", caCertLoc); + goto cleanup; + } + /* Load server certificates */ + if (wolfSSL_CTX_use_certificate_file(ctx, servCertLoc, SSL_FILETYPE_PEM) != + SSL_SUCCESS) { + fprintf(stderr, "Error loading %s, please check the file.\n", servCertLoc); + goto cleanup; + } + /* Load server Keys */ + if (wolfSSL_CTX_use_PrivateKey_file(ctx, servKeyLoc, + SSL_FILETYPE_PEM) != SSL_SUCCESS) { + fprintf(stderr, "Error loading %s, please check the file.\n", servKeyLoc); + goto cleanup; + } + + listenfd = newFD(); + if (listenfd == INVALID_SOCKET) + goto cleanup; + + if (!newPendingSSL()) + goto cleanup; + + signal(SIGINT, sig_handler); + + base = event_base_new(); + if (base == NULL) { + perror("event_base_new failed"); + exit(EXIT_FAILURE); + } + + newConnEvent = event_new(base, listenfd, EV_READ|EV_PERSIST, newConn, NULL); + if (newConnEvent == NULL) { + fprintf(stderr, "event_new failed for srvEvent\n"); + goto cleanup; + } + if (event_add(newConnEvent, NULL) != 0) { + fprintf(stderr, "event_add failed\n"); + goto cleanup; + } + + printf("running event loop\n"); + + if (event_base_dispatch(base) == -1) { + fprintf(stderr, "event_base_dispatch failed\n"); + goto cleanup; + } + + printf("done with dispatching\n"); + + + exitVal = 0; +cleanup: + free_resources(); + wolfSSL_Cleanup(); + + return exitVal; +} + +static int newFD(void) +{ + int fd; + int on = 1; + struct sockaddr_in servAddr; /* our server's address */ + + /* Create a UDP/IP socket */ + if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { + perror("socket()"); + return INVALID_SOCKET; + } + memset((char *)&servAddr, 0, sizeof(servAddr)); + /* host-to-network-long conversion (htonl) */ + /* host-to-network-short conversion (htons) */ + servAddr.sin_family = AF_INET; + servAddr.sin_addr.s_addr = htonl(INADDR_ANY); + servAddr.sin_port = htons(SERV_PORT); + + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) != 0) { + perror("setsockopt() with SO_REUSEADDR"); + goto cleanup; + } +#ifdef SO_REUSEPORT + if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (char*)&on, sizeof(on)) != 0) { + perror("setsockopt() with SO_REUSEPORT"); + goto cleanup; + } +#endif + if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) { + perror("fcntl"); + goto cleanup; + } + + /* Bind Socket */ + if (bind(fd, (struct sockaddr*)&servAddr, sizeof(servAddr)) < 0) { + perror("bind()"); + goto cleanup; + } + return fd; +cleanup: + if (fd != INVALID_SOCKET) { + close(fd); + fd = INVALID_SOCKET; + } + return INVALID_SOCKET; +} + +static int newPendingSSL(void) +{ + /* Create the pending WOLFSSL Object */ + if ((pendingSSL = wolfSSL_new(ctx)) == NULL) { + fprintf(stderr, "wolfSSL_new error.\n"); + return 0; + } + + wolfSSL_dtls_set_using_nonblock(pendingSSL, 1); + + if (wolfSSL_SetChGoodCb(pendingSSL, chGoodCb, NULL) != WOLFSSL_SUCCESS ) { + fprintf(stderr, "wolfSSL_SetChGoodCb error.\n"); + return 0; + } + + if (wolfSSL_set_fd(pendingSSL, listenfd) != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_set_fd error.\n"); + return 0; + } + + return 1; +} + +static void newConn(evutil_socket_t fd, short events, void* arg) +{ + struct sockaddr_in cliaddr; /* the client's address */ + socklen_t cliLen; + char b; + int ret; + int err; + int drop = 1; + /* Store pointer because pendingSSL can be modified in chGoodCb */ + WOLFSSL* ssl = pendingSSL; + + (void)events; + (void)arg; + + /* Get the incoming address */ + cliLen = sizeof(cliaddr); + ret = (int)recvfrom(listenfd, &b, sizeof(b), MSG_PEEK, + (struct sockaddr*)&cliaddr, &cliLen); + if (ret <= 0) { + perror("recvfrom()"); + goto error; + } + + if (wolfSSL_dtls_set_peer(ssl, &cliaddr, cliLen) != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_dtls_set_peer error.\n"); + goto error; + } + + drop = 0; + ret = wolfSSL_accept(ssl); + if (ret != WOLFSSL_SUCCESS) { + err = wolfSSL_get_error(ssl, 0); + if (err != WOLFSSL_ERROR_WANT_READ) { + fprintf(stderr, "error = %d, %s\n", err, + wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "SSL_accept failed.\n"); + free_resources(); + wolfSSL_Cleanup(); + exit(1); + } + } + +error: + /* Drop the datagram */ + if (drop) + (void)recv(listenfd, &b, sizeof(b), 0); +} + +/* Called when we have verified a connection */ +static int chGoodCb(WOLFSSL* ssl, void* arg) +{ + int fd = INVALID_SOCKET; + struct sockaddr_in cliaddr; /* the client's address */ + socklen_t cliLen = sizeof(cliaddr); + conn_ctx* new_ctx = (conn_ctx*)calloc(1, sizeof(conn_ctx)); + int timeout = wolfSSL_dtls_get_current_timeout(ssl); + struct timeval tv; + + (void)arg; + + if (new_ctx == NULL) { + fprintf(stderr, "Out of memory!\n"); + goto error; + } + + new_ctx->ssl = ssl; + + if (wolfSSL_dtls_get_peer(ssl, &cliaddr, &cliLen) != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_dtls_get_peer failed\n"); + goto error; + } + + /* Promote the pending connection to an active connection */ + if (!newPendingSSL()) + goto error; + + /* We need to change the sfd here so that the ssl object doesn't drop any + * new connections */ + fd = newFD(); + if (fd == INVALID_SOCKET) + goto error; + + /* Limit new SFD to only this connection */ + if (connect(fd, (const struct sockaddr*)&cliaddr, cliLen) != 0) { + perror("connect()"); + goto error; + } + + /* Have the ssl object use only the SFD without the peer address (since the + * SFD is now connected) */ + if (wolfSSL_dtls_set_peer(ssl, NULL, 0) != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_dtls_set_peer error.\n"); + goto error; + } + + if (wolfSSL_set_fd(ssl, fd) != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_set_fd error.\n"); + goto error; + } + + new_ctx->writeEv = event_new(base, fd, EV_WRITE, dataReady, new_ctx); + if (new_ctx->writeEv == NULL) { + fprintf(stderr, "event_new failed for srvEvent\n"); + goto error; + } + new_ctx->readEv = event_new(base, fd, EV_READ, dataReady, new_ctx); + if (new_ctx->readEv == NULL) { + fprintf(stderr, "event_new failed for srvEvent\n"); + goto error; + } + memset(&tv, 0, sizeof(tv)); + if (wolfSSL_dtls13_use_quick_timeout(ssl)) { + if (timeout >= QUICK_MULT) + tv.tv_sec = timeout / QUICK_MULT; + else + tv.tv_usec = timeout * 1000000 / QUICK_MULT; + } + else + tv.tv_sec = timeout; + /* We are using non-blocking sockets so we will definitely be waiting for + * the peer. Start the timer now. */ + if (event_add(new_ctx->readEv, &tv) != 0) { + fprintf(stderr, "event_add failed\n"); + goto error; + } + + return 0; +error: + if (fd != INVALID_SOCKET) { + close(fd); + fd = INVALID_SOCKET; + } + (void)wolfSSL_set_fd(ssl, INVALID_SOCKET); + return CHGOODCB_E; +} + +static void dataReady(evutil_socket_t fd, short events, void* arg) +{ + conn_ctx* connCtx = (conn_ctx*)arg; + int ret; + int err; + int timeout; + struct timeval tv; + char msg[100]; + int msgSz; + char* ack = "I hear you fashizzle!\n"; + + memset(&tv, 0, sizeof(tv)); + if (events & EV_TIMEOUT) { + /* A timeout occurred */ + if (!wolfSSL_is_init_finished(connCtx->ssl)) { + if (wolfSSL_dtls_got_timeout(connCtx->ssl) != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_dtls_got_timeout failed\n"); + goto error; + } + timeout = wolfSSL_dtls_get_current_timeout(connCtx->ssl); + if (wolfSSL_dtls13_use_quick_timeout(connCtx->ssl)) { + if (timeout >= QUICK_MULT) + tv.tv_sec = timeout / QUICK_MULT; + else + tv.tv_usec = timeout * 1000000 / QUICK_MULT; + } + else + tv.tv_sec = timeout; + if (event_add(connCtx->readEv, &tv) != 0) { + fprintf(stderr, "event_add failed\n"); + goto error; + } + } + else { + if (connCtx->waitingOnData) { + /* Too long waiting for peer data. Shutdown the connection. + * Don't wait for a response from the peer. */ + printf("Closing connection after timeout"); + (void)wolfSSL_shutdown(connCtx->ssl); + goto error; + } + else { + tv.tv_sec = CONN_TIMEOUT; + connCtx->waitingOnData = 1; + if (event_add(connCtx->readEv, &tv) != 0) { + fprintf(stderr, "event_add failed\n"); + goto error; + } + } + } + } + else if (events & (EV_READ|EV_WRITE)) { + ret = wolfSSL_read(connCtx->ssl, msg, sizeof(msg) - 1); + if (ret > 0) { + msgSz = ret; + msg[msgSz] = '\0'; + printf("Received message: %s\n", msg); + ret = wolfSSL_write(connCtx->ssl, ack, strlen(ack)); + } + + if (ret <= 0) { + err = wolfSSL_get_error(connCtx->ssl, 0); + if (err == WOLFSSL_ERROR_WANT_READ || + err == WOLFSSL_ERROR_WANT_WRITE) { + timeout = wolfSSL_dtls_get_current_timeout(connCtx->ssl); + if (wolfSSL_dtls13_use_quick_timeout(connCtx->ssl)) { + if (timeout >= QUICK_MULT) + tv.tv_sec = timeout / QUICK_MULT; + else + tv.tv_usec = timeout * 1000000 / QUICK_MULT; + } + else + tv.tv_sec = timeout; + if (event_add(err == WOLFSSL_ERROR_WANT_READ ? + connCtx->readEv : connCtx->writeEv, &tv) != 0) { + fprintf(stderr, "event_add failed\n"); + goto error; + } + } + else if (err == WOLFSSL_ERROR_ZERO_RETURN) { + /* Peer closed connection. Let's do the same. */ + printf("peer closed connection\n"); + ret = wolfSSL_shutdown(connCtx->ssl); + if (ret != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_shutdown failed (%d)\n", ret); + } + goto error; + } + else { + fprintf(stderr, "error = %d, %s\n", err, + wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "wolfSSL_read or wolfSSL_write failed\n"); + goto error; + } + } + else { + tv.tv_sec = CONN_TIMEOUT; + connCtx->waitingOnData = 1; + if (event_add(connCtx->readEv, &tv) != 0) { + fprintf(stderr, "event_add failed\n"); + goto error; + } + } + } + else { + fprintf(stderr, "Unexpected events %d\n", events); + goto error; + } + + + return; +error: + /* Free the connection */ + (void)event_del(connCtx->readEv); + (void)event_del(connCtx->writeEv); + event_free(connCtx->readEv); /* EV_PERSIST not used so safe to free here */ + event_free(connCtx->writeEv); /* EV_PERSIST not used so safe to free here */ + wolfSSL_Free(connCtx->ssl); + close(fd); + free(connCtx); +} + +void sig_handler(const int sig) +{ + (void)sig; + free_resources(); + wolfSSL_Cleanup(); + exit(0); +} + +void free_resources(void) +{ + if (pendingSSL != NULL) { + wolfSSL_shutdown(pendingSSL); + wolfSSL_free(pendingSSL); + pendingSSL = NULL; + } + if (ctx != NULL) { + wolfSSL_CTX_free(ctx); + ctx = NULL; + } + if (listenfd != INVALID_SOCKET) { + close(listenfd); + listenfd = INVALID_SOCKET; + } +} diff --git a/dtls/server-dtls13.c b/dtls/server-dtls13.c new file mode 100644 index 00000000..fc8d6621 --- /dev/null +++ b/dtls/server-dtls13.c @@ -0,0 +1,230 @@ +/* server-dtls13.c + * + * Copyright (C) 2006-2022 wolfSSL Inc. + * + * This file is part of wolfSSL. (formerly known as CyaSSL) + * + * wolfSSL is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + * + *============================================================================= + * + * Bare-bones example of a DTLS 1.3 server for instructional/learning purposes. + * This example can only accept one connection at a time. + */ + +#include +#include /* standard in/out procedures */ +#include /* defines system calls */ +#include /* necessary for memset */ +#include +#include /* used for all socket calls */ +#include /* used for sockaddr_in */ +#include +#include +#include +#include +#include + +#include "dtls-common.h" + +#define SERV_PORT 11111 /* define our server port number */ +#define MSGLEN 4096 + +WOLFSSL_CTX* ctx = NULL; +WOLFSSL* ssl = NULL; +int listenfd = INVALID_SOCKET; /* Initialize our socket */ + +void sig_handler(const int sig); +void free_resources(void); + +int main(int argc, char** argv) +{ + /* Loc short for "location" */ + char caCertLoc[] = "../certs/ca-cert.pem"; + char servCertLoc[] = "../certs/server-cert.pem"; + char servKeyLoc[] = "../certs/server-key.pem"; + int exitVal = 1; + struct sockaddr_in servAddr; /* our server's address */ + struct sockaddr_in cliaddr; /* the client's address */ + int ret; + int err; + int recvLen = 0; /* length of message */ + socklen_t cliLen; + unsigned char b[MSGLEN]; /* watch for incoming messages */ + char buff[MSGLEN]; /* the incoming message */ + char ack[] = "I hear you fashizzle!\n"; + + /* Initialize wolfSSL before assigning ctx */ + if (wolfSSL_Init() != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_Init error.\n"); + return exitVal; + } + + /* No-op when debugging is not compiled in */ + wolfSSL_Debugging_ON(); + + /* Set ctx to DTLS 1.3 */ + if ((ctx = wolfSSL_CTX_new(wolfDTLSv1_3_server_method())) == NULL) { + fprintf(stderr, "wolfSSL_CTX_new error.\n"); + goto cleanup; + } + /* Load CA certificates */ + if (wolfSSL_CTX_load_verify_locations(ctx,caCertLoc,0) != + SSL_SUCCESS) { + fprintf(stderr, "Error loading %s, please check the file.\n", caCertLoc); + goto cleanup; + } + /* Load server certificates */ + if (wolfSSL_CTX_use_certificate_file(ctx, servCertLoc, SSL_FILETYPE_PEM) != + SSL_SUCCESS) { + fprintf(stderr, "Error loading %s, please check the file.\n", servCertLoc); + goto cleanup; + } + /* Load server Keys */ + if (wolfSSL_CTX_use_PrivateKey_file(ctx, servKeyLoc, + SSL_FILETYPE_PEM) != SSL_SUCCESS) { + fprintf(stderr, "Error loading %s, please check the file.\n", servKeyLoc); + goto cleanup; + } + + /* Create a UDP/IP socket */ + if ((listenfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { + perror("socket()"); + goto cleanup; + } + printf("Socket allocated\n"); + memset((char *)&servAddr, 0, sizeof(servAddr)); + /* host-to-network-long conversion (htonl) */ + /* host-to-network-short conversion (htons) */ + servAddr.sin_family = AF_INET; + servAddr.sin_addr.s_addr = htonl(INADDR_ANY); + servAddr.sin_port = htons(SERV_PORT); + + /* Bind Socket */ + if (bind(listenfd, (struct sockaddr*)&servAddr, sizeof(servAddr)) < 0) { + perror("bind()"); + goto cleanup; + } + + signal(SIGINT, sig_handler); + + while (1) { + printf("Awaiting client connection on port %d\n", SERV_PORT); + + cliLen = sizeof(cliaddr); + ret = (int)recvfrom(listenfd, (char *)&b, sizeof(b), MSG_PEEK, + (struct sockaddr*)&cliaddr, &cliLen); + + if (ret < 0) { + perror("recvfrom()"); + goto cleanup; + } + else if (ret == 0) { + fprintf(stderr, "recvfrom zero return\n"); + goto cleanup; + } + + /* Create the WOLFSSL Object */ + if ((ssl = wolfSSL_new(ctx)) == NULL) { + fprintf(stderr, "wolfSSL_new error.\n"); + goto cleanup; + } + + if (wolfSSL_dtls_set_peer(ssl, &cliaddr, cliLen) != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_dtls_set_peer error.\n"); + goto cleanup; + } + + if (wolfSSL_set_fd(ssl, listenfd) != WOLFSSL_SUCCESS) { + fprintf(stderr, "wolfSSL_set_fd error.\n"); + break; + } + + if (wolfSSL_accept(ssl) != SSL_SUCCESS) { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "error = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "SSL_accept failed.\n"); + goto cleanup; + } + printf("Connected!\n"); + if ((recvLen = wolfSSL_read(ssl, buff, sizeof(buff)-1)) > 0) { + printf("heard %d bytes\n", recvLen); + + buff[recvLen] = '\0'; + printf("I heard this: \"%s\"\n", buff); + } + else if (recvLen <= 0) { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "error = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "SSL_read failed.\n"); + goto cleanup; + } + printf("Sending reply.\n"); + if (wolfSSL_write(ssl, ack, sizeof(ack)) < 0) { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "error = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "wolfSSL_write failed.\n"); + goto cleanup; + } + + printf("reply sent \"%s\"\n", ack); + + /* Attempt a full shutdown */ + ret = wolfSSL_shutdown(ssl); + if (ret == WOLFSSL_SHUTDOWN_NOT_DONE) + ret = wolfSSL_shutdown(ssl); + if (ret != WOLFSSL_SUCCESS) { + err = wolfSSL_get_error(ssl, 0); + fprintf(stderr, "err = %d, %s\n", err, wolfSSL_ERR_reason_error_string(err)); + fprintf(stderr, "wolfSSL_shutdown failed\n"); + } + wolfSSL_free(ssl); + ssl = NULL; + + printf("Client left cont to idle state\n"); + } + + exitVal = 0; +cleanup: + free_resources(); + wolfSSL_Cleanup(); + + return exitVal; +} + + +void sig_handler(const int sig) +{ + (void)sig; + free_resources(); + wolfSSL_Cleanup(); +} + +void free_resources(void) +{ + if (ssl != NULL) { + wolfSSL_shutdown(ssl); + wolfSSL_free(ssl); + ssl = NULL; + } + if (ctx != NULL) { + wolfSSL_CTX_free(ctx); + ctx = NULL; + } + if (listenfd != INVALID_SOCKET) { + close(listenfd); + listenfd = INVALID_SOCKET; + } +}