Commit Diff


commit - 56554c0e3238a06dff7acbec972dfac045cd0661
commit + 50aa154efbb5f29b80721541e8d876bb58adc54b
blob - dd84c43f77625c298ccc9d44d5790cefc0ac3504
blob + 14e9e5885f37df972b18488564014fe3d5b4acd4
--- Makefile	
+++ Makefile	
@@ -1,3 +1,4 @@
-SUBDIR = thingsd thingsctl
+#SUBDIR = thingsd thingsctl
+SUBDIR = thingsd
 
 .include <bsd.subdir.mk>
blob - 804d2c255a8554427d6634ca665b7af05b619c5c
blob + 46b344e7a3bb2a0d5325c95e7b4f63e1aedbb90d
--- README.md	
+++ README.md	
@@ -3,10 +3,21 @@ thingsd for OpenBSD
 
 The thingsd OpenBSD proxy daemon provides a mechanism for clients and client
 processes to communicate with an array of serial and IoT things. At its core,
-thingsd is primarily a packet repeater in that it waits for packets to swap
-between subscriber clients and things. However, thingsd also provides password
-control over those connections, including client limits.
+thingsd is primarily a data aggregator and repeater, in that it waits for
+packets to swap between subscriber clients and things. However, thingsd also
+provides password control over those connections, including client limits.
 
+On the client side, thingsd sets up TCP/IP sockets to transmit packets to and
+from things. On the server side, thingsd can connect to any serial device which
+has a viable file descriptor, create a persistent connection to the IP address
+of a device transmitting packets on the same network, or setup a UDP listener
+on the network to receive broadcasted packets. Devices tested include:
+ESP8266/ESP32 modules, on both the serial and network sides, XBee Series 2
+coordinators connected in a mesh network, and NF24 devices. To transmit to an
+IP address, which does not allow persistence, thingsd will create an ad hoc
+connection, transmit a packet, and detach. The thingsd proxy daemon is agnostic
+about packet data.
+
 Prerequisites
 -------------
 
@@ -50,13 +61,14 @@ Then paste in a subscription packet for your setup:
 
 You should start receiving packets from your setup thing.
 
+See the examples for more testing options.
+
 Further examples can be found in the src/examples directory above.
 
 Todo
 ----
 
 * Finish thingsctl functions
-* Implement TLS
 
 Author
 ------
blob - 13d5a2d73351ea3fb91fa5c43e382db20ef6bad6
blob + 6cd0f872e8b251c2243065f7bb1e1860f2fc8e6e
--- thingsctl/thingsctl.8	
+++ thingsctl/thingsctl.8	
@@ -14,7 +14,7 @@
 .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 .\"
 
-.Dd $Mdocdate: January 26 2016 $
+.Dd $Mdocdate: January 26 2019 $
 .Dt THINGSCTL 1
 .Os
 .Sh NAME
blob - a49d06e6233b26b7dcda3483638f6e5e01b90b8d
blob + 044c23967594d24108770faa501ff2dbc33e411c
--- thingsd/Makefile	
+++ thingsd/Makefile	
@@ -1,7 +1,7 @@
 PROG=		thingsd
 
 SRCS=		parse.y
-SRCS+=		log.c serial.c sockets.c client.c events.c
+SRCS+=		log.c serial.c sockets.c client.c events.c tls.c
 
 SRCS+=		thingsd.c
 
blob - bb83d862fe41a0626f999563a51e045c68add687
blob + c766554f0f8749d09b579e9a5d4708e1e4a00fd0
--- thingsd/client.c	
+++ thingsd/client.c	
@@ -28,15 +28,16 @@
 
 #include "thingsd.h"
 
-void
+extern void	 bufferevent_read_pressure_cb(struct evbuffer *, size_t,
+		    size_t, void *);
+
+	void
 clt_conn(int fd, short event, void *arg)
 {
 	struct sockaddr_storage	 ss;
 	struct clt		*clt;
 	struct thgsd		*pthgsd = (struct thgsd *)arg;
 	struct sock		*sock = NULL;
-	evbuffercb		 cltrd = clt_rd;
-	evbuffercb		 cltwr = clt_wr;
 	int			 clt_fd;
 	socklen_t		 len = sizeof(ss);
 
@@ -47,8 +48,18 @@ clt_conn(int fd, short event, void *arg)
 	}
 	if ((clt = calloc(1, sizeof(*clt))) == NULL)
 		goto err;
+	if ((clt->ev = calloc(1, sizeof(*clt->ev))) == NULL)
+		goto err;
 	if ((sock = get_sock(pthgsd, fd)) == NULL)
 		goto err;
+	if (sock->tls) {
+		if (tls_accept_socket(sock->tls_ctx, &clt->tls_ctx, clt_fd)
+		    == -1) {
+			log_info("tls accept failed: %s",
+			    tls_error(sock->tls_ctx));
+			goto err;
+		}
+	}
 	if ((clt->sub_names = (char **)malloc(pthgsd->max_sub *
 	    sizeof(char *))) == NULL)
 		fatalx("no client subscription names malloc");
@@ -65,26 +76,71 @@ clt_conn(int fd, short event, void *arg)
 	clt->sock = sock;
 	clt->subscribed = false;
 	clt->evb = evbuffer_new();
-	if (clt->evb == NULL)
+	if (clt->evb == NULL) {
+		sock->clt_cnt--;
+		pthgsd->clt_cnt--;
 		goto err;
+	}
 	clt->fd = clt_fd;
+	clt->join_time = time(NULL);
+	TAILQ_INSERT_TAIL(&pthgsd->clts, clt, entry);
+	if (sock->tls) {
+		clt->tls = true;
+		event_del(clt->ev);
+		event_set(clt->ev, clt->fd, EV_READ|EV_PERSIST,
+			    sock_tls_handshake, pthgsd);
+		if (event_add(clt->ev, NULL))
+			goto err;
+		return;
+	}
+	clt_add(pthgsd, clt);
+	return;
+ err:
+	log_info("client error");
+	if (clt_fd != -1) {
+		close(clt_fd);
+		if (sock->tls) {
+			tls_free(clt->tls_ctx);
+			free(clt->ev);
+		}
+		free(clt);
+	}
+}
+
+void
+clt_add(struct thgsd *pthgsd, struct clt *pclt)
+{
+	struct clt		*clt = pclt;
+	struct sock 		*sock = clt->sock;
+	evbuffercb		 cltrd = clt_rd;
+	evbuffercb		 cltwr = clt_wr;
+
+	log_info("client connected");
 	clt->bev = bufferevent_new(clt->fd, cltrd, cltwr, clt_err, pthgsd);
-	if (clt->bev == NULL)
+	if (clt->bev == NULL) {
+		sock->clt_cnt--;
+		pthgsd->clt_cnt--;
 		goto err;
+	}
+	if (clt->tls) {
+		event_set(&clt->bev->ev_read, clt->fd, EV_READ,
+		    clt_tls_readcb, clt->bev);
+		event_set(&clt->bev->ev_write, clt->fd, EV_WRITE,
+		    clt_tls_writecb, clt->bev);
+	}
 	bufferevent_base_set(pthgsd->eb, clt->bev);
 	bufferevent_setwatermark(clt->bev, EV_READ, 0, BUFF);
 	bufferevent_enable(clt->bev, EV_READ);
-	clt->join_time = time(NULL);
-	log_info("client connected");
 	start_clt_chk(pthgsd);
-	TAILQ_INSERT_TAIL(&pthgsd->clts, clt, entry);
 	return;
  err:
 	log_info("client error");
-	sock->clt_cnt--;
-	pthgsd->clt_cnt--;
-	if (clt_fd != -1) {
-		close(clt_fd);
+	if (clt->fd != -1) {
+		close(clt->fd);
+		if (sock->tls) {
+			tls_free(clt->tls_ctx);
+			free(clt->ev);
+		}
 		free(clt);
 	}
 }
@@ -98,8 +154,10 @@ clt_del(struct thgsd *pthgsd, struct clt *pclt)
 
 	TAILQ_FOREACH_SAFE(clt, &pthgsd->clts, entry, tclt) {
 		if (clt == pclt) {
-			if (clt->bev != NULL)
-				bufferevent_free(clt->bev);
+			if (clt->tls) {
+				tls_free(clt->tls_ctx);
+				free(clt->ev);
+			}
 			close(clt->fd);
 			for (n = 0; n < clt->le; n++)
 				TAILQ_FOREACH(thg, &pthgsd->thgs, entry)
@@ -113,6 +171,8 @@ clt_del(struct thgsd *pthgsd, struct clt *pclt)
 			else
 				log_info("client disconnected: %s", clt->name);
 			TAILQ_REMOVE(&pthgsd->clts, clt, entry);
+			if (clt->bev != NULL)
+				bufferevent_free(clt->bev);
 			free(clt);
 			break;
 		}
@@ -173,6 +233,59 @@ clt_rd(struct bufferevent *bev, void *arg)
 }
 
 void
+clt_tls_readcb(int fd, short event, void *arg)
+{
+	struct bufferevent	*bufev = (struct bufferevent *)arg;
+	struct thgsd		*pthgsd = bufev->cbarg;
+	struct clt		*clt = NULL, *tclt;
+	char			 pkt[BUFF];
+	ssize_t			 ret;
+	size_t			 len;
+	int			 toread = EVBUFFER_READ;
+
+	TAILQ_FOREACH(tclt, &pthgsd->clts, entry) {
+		if (tclt->fd == fd)
+			clt = tclt;
+	}
+	memset(pkt, 0, sizeof(pkt));
+	ret = tls_read(clt->tls_ctx, pkt, BUFF);
+	if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
+		goto retry;
+	} else if (ret < 0) {
+		toread |= EVBUFFER_ERROR;
+		goto err;
+	}
+	len = ret;
+	if (len == 0) {
+		toread |= EVBUFFER_EOF;
+		goto err;
+	}
+	if (evbuffer_add(bufev->input, pkt, len) == -1) {
+		toread |= EVBUFFER_ERROR;
+		goto err;
+	}
+	event_add(&bufev->ev_read, NULL);
+	len = EVBUFFER_LENGTH(bufev->input);
+	if (bufev->wm_read.low != 0 && len < bufev->wm_read.low)
+		return;
+	if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) {
+		struct evbuffer *buf = bufev->input;
+		event_del(&bufev->ev_read);
+		evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev);
+		return;
+	}
+	if (bufev->readcb != NULL)
+		(*bufev->readcb)(bufev, bufev->cbarg);
+	return;
+ retry:
+	event_del(&bufev->ev_read);
+	event_add(&bufev->ev_read, NULL);
+	return;
+ err:
+	(*bufev->errorcb)(bufev, toread, bufev->cbarg);
+}
+
+void
 clt_wr_thgs(struct clt *clt, struct thg *thg, size_t len)
 {
 	char			*pkt;
@@ -214,6 +327,49 @@ clt_wr(struct bufferevent *bev, void *arg)
 }
 
 void
+clt_tls_writecb(int fd, short event, void *arg)
+{
+	struct bufferevent	*bufev = (struct bufferevent *)arg;
+	struct thgsd		*pthgsd = bufev->cbarg;
+	struct clt		*clt = NULL, *tclt;
+	ssize_t			 ret;
+	size_t			 len;
+	int			 towrite = EVBUFFER_WRITE;
+
+	TAILQ_FOREACH(tclt, &pthgsd->clts, entry) {
+		if (tclt->fd == fd)
+			clt = tclt;
+	}
+	if (EVBUFFER_LENGTH(bufev->output)) {
+		ret = tls_write(clt->tls_ctx,
+		    EVBUFFER_DATA(bufev->output),
+		    EVBUFFER_LENGTH(bufev->output));
+		if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) {
+			goto retry;
+		} else if (ret < 0) {
+			towrite |= EVBUFFER_ERROR;
+			goto err;
+		}
+		len = ret;
+		evbuffer_drain(bufev->output, len);
+	}
+	if (EVBUFFER_LENGTH(bufev->output) != 0) {
+		event_del(&bufev->ev_write);
+		event_add(&bufev->ev_write, NULL);
+	}
+	if (bufev->writecb != NULL && EVBUFFER_LENGTH(bufev->output) <=
+	    bufev->wm_write.low)
+		(*bufev->writecb)(bufev, bufev->cbarg);
+	return;
+ retry:
+	event_del(&bufev->ev_write);
+	event_add(&bufev->ev_write, NULL);
+	return;
+ err:
+	(*bufev->errorcb)(bufev, towrite, bufev->cbarg);
+}
+
+void
 clt_err(struct bufferevent *bev, short error, void *arg)
 {
 	struct thgsd		*pthgsd = (struct thgsd *)arg;
blob - /dev/null
blob + 01eca781d7e44c4aef20680a8a1d16e55dec3d28 (mode 644)
--- /dev/null	
+++ thingsd/examples/clients/c/tls_client.c	
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2015 Bob Beck <beck@obtuse.com>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+/* client.c  - the "classic" example of a socket client */
+/*  edited to work with thingsd */
+
+#include <arpa/inet.h>
+
+#include <netinet/in.h>
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <err.h>
+#include <errno.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <tls.h>
+
+
+
+static void usage()
+{
+	extern char * __progname;
+	fprintf(stderr, "usage: %s ipaddress portnumber certhash\n", __progname);
+	exit(1);
+}
+
+int main(int argc, char *argv[])
+{
+	struct sockaddr_in server_sa;
+	char buffer[80], *ep;
+	size_t maxread;
+	ssize_t r, rc;
+	u_short port;
+	u_long p;
+	int sd, i, w, written;
+	struct tls_config *tls_cfg = NULL;
+	struct tls *tls_ctx = NULL;
+	char pkt[] = "~~~subscribe{{name,\"thgtstr\"},{things{thing{\"thing2\",\"Mother\"}}}}";
+	if (argc != 4)
+		usage();
+
+        p = strtoul(argv[2], &ep, 10);
+        if (*argv[1] == '\0' || *ep != '\0') {
+		/* parameter wasn't a number, or was empty */
+		fprintf(stderr, "%s - not a number\n", argv[2]);
+		usage();
+	}
+        if ((errno == ERANGE && p == ULONG_MAX) || (p > USHRT_MAX)) {
+		/* It's a number, but it either can't fit in an unsigned
+		 * long, or is too big for an unsigned short
+		 */
+		fprintf(stderr, "%s - value out of range\n", argv[2]);
+		usage();
+	}
+	/* now safe to do this */
+	port = p;
+
+	/*
+	 * first set up "server_sa" to be the location of the thing socket
+	 */
+	memset(&server_sa, 0, sizeof(server_sa));
+	server_sa.sin_family = AF_INET;
+	server_sa.sin_port = htons(port);
+	server_sa.sin_addr.s_addr = inet_addr(argv[1]);
+	if (server_sa.sin_addr.s_addr == INADDR_NONE) {
+		fprintf(stderr, "Invalid IP address %s\n", argv[1]);
+		usage();
+	}
+
+	/* now set up TLS */
+	if (tls_init() == -1)
+		errx(1, "unable to initialize TLS");
+	if ((tls_cfg = tls_config_new()) == NULL)
+		errx(1, "unable to allocate TLS config");
+	if (tls_config_set_ca_file(tls_cfg, "thing.crt") == -1)
+		errx(1, "unable to set root CA file thing.crt");
+
+	/* ok now get a socket. we don't care where... */
+	if ((sd=socket(AF_INET,SOCK_STREAM,0)) == -1)
+		err(1, "socket failed");
+
+	/* connect the socket to the thing socket described in "server_sa" */
+	if (connect(sd, (struct sockaddr *)&server_sa, sizeof(server_sa)) == -1)
+		err(1, "connect failed");
+
+	if ((tls_ctx = tls_client()) == NULL)
+		errx(1, "tls client creation failed");
+	tls_config_insecure_noverifyname(tls_cfg);
+	if (tls_configure(tls_ctx, tls_cfg) == -1)
+		errx(1, "tls configuration failed (%s)",
+		    tls_error(tls_ctx));
+	if (tls_connect_socket(tls_ctx, sd, "name") == -1) {
+		errx(1, "tls connection failed (%s)",
+		    tls_error(tls_ctx));
+	}
+	do {
+		if ((i = tls_handshake(tls_ctx)) == -1)
+			errx(1, "tls handshake failed (%s)",
+			    tls_error(tls_ctx));
+	} while (i == TLS_WANT_POLLIN || i == TLS_WANT_POLLOUT);
+	if (strcmp(argv[3], tls_peer_cert_hash(tls_ctx)) != 0)
+		printf("Peer certificate is not %s\n", argv[3]);
+		/* errx(1, "Peer certificate is not %s", argv[3]); */
+
+	/*
+	 * finally, we are connected. find out what magnificent wisdom
+	 * our thing is going to send to us - since we really don't know
+	 * how much data the thing could send to us, we have decided
+	 * we'll stop reading when either our buffer is full, or when
+	 * we get an end of file condition from the read when we read
+	 * 0 bytes - which means that we pretty much assume the thing
+	 * is going to send us an entire message, then close the connection
+	 * to us, so that we see an end-of-file condition on the read.
+	 *
+	 * we also make sure we handle EINTR in case we got interrupted
+	 * by a signal.
+	 */
+	w = 0;
+	written = 0;
+	while (written < strlen(pkt)) {
+		w = tls_write(tls_ctx, pkt + written,
+		    strlen(pkt) - written);
+		if (w == TLS_WANT_POLLIN || w == TLS_WANT_POLLOUT)
+			continue;
+		if (w < 0)
+			errx(1, "tls_write failed (%s)", tls_error(tls_ctx));
+		else
+			written += w;
+	}
+	/* start receiving packets from thing */
+	for(;;) {
+		i = 0;
+		r = -1;
+		rc = 0;
+		maxread = sizeof(buffer) - 1; /* leave room for a 0 byte */
+		while ((r != 0) && rc < maxread) {
+			r = tls_read(tls_ctx, buffer + rc, maxread - rc);
+			if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT)
+				continue;
+			if (r < 0) {
+				errx(1, "tls_read failed (%s)", tls_error(tls_ctx));
+			} else {
+				rc += r;
+				break;
+			}
+		}
+		/*
+		 * we must make absolutely sure buffer has a terminating 0 byte
+		 * if we are to use it as a C string
+		 */
+		buffer[rc] = '\0';
+		printf("Thing sent:  %s\n",buffer);
+		sleep(1);
+	}
+	do {
+		i = tls_close(tls_ctx);
+	} while(i == TLS_WANT_POLLIN || i == TLS_WANT_POLLOUT);
+	close(sd);
+	exit(0);
+	return(0);
+}
blob - 604fe6ee2b67c775cc7bf97b040d0a960ad66993
blob + b51f3c5ea0f7308f8f8ba5119863583596dd65bd
--- thingsd/parse.y	
+++ thingsd/parse.y	
@@ -1,5 +1,6 @@
 /*
  * Copyright (c) 2016-2019 Tracey Emery <tracey@traceyemery.net>
+ * Copyright (c) 2007 - 2015 Reyk Floeter <reyk@openbsd.org>
  * Copyright (c) 2002, 2003, 2004 Henning Brauer <henning@openbsd.org>
  * Copyright (c) 2001 Markus Friedl.  All rights reserved.
  * Copyright (c) 2001 Daniel Hartmeier.  All rights reserved.
@@ -74,6 +75,7 @@ int				 lookup(char *);
 int				 lgetc(int);
 int				 lungetc(int);
 int				 findeol(void);
+int				 load_tls(struct thg *);
 
 size_t				 n;
 
@@ -90,10 +92,12 @@ typedef struct {
 
 %token	BAUD DATA PARITY STOP HARDWARE SOFTWARE PASSWORD NAME RETRY PERSISTENT
 %token	LOG VERBOSE CONNECT THING LISTEN LOCATION IPADDR UDP THINGS CONNECTION
-%token	DEFAULT PORT MAX CLIENTS SUBSCRIPTIONS BIND INTERFACE SUBSCRIBE ERROR
-%token	RECEIVE
+%token	DEFAULT PORT MAX CLIENTS SUBSCRIPTIONS BIND INTERFACE SUBSCRIBE TLS
+%token	ERROR RECEIVE CERTIFICATE CIPHERS CLIENT CA CRL OPTIONAL DHE ECDHE KEY
+%token	OCSP PROTOCOLS ON
 %token	<v.string>		STRING
 %token	<v.number>		NUMBER
+%type	<v.number>		opttls
 
 %%
 grammar		: /* empty */
@@ -102,6 +106,15 @@ grammar		: /* empty */
 		| grammar dosub
 		| grammar error '\n' { file->errors++; }
 		;
+opttls		: /*empty*/ {
+			$$ = 0;
+			newthg->tls = false;
+		}
+		| TLS {
+			$$ = 1;
+			newthg->tls = true;
+		}
+		;
 main		: DEFAULT PORT NUMBER {
 			pthgsd->port = $3;
 		}
@@ -169,8 +182,8 @@ subthgs		: THING '{' STRING ',' STRING '}' optcomma {
 					if (strcmp(thg->password, $5) == 0) {
 						if (clt->subs++ >=
 						    pthgsd->max_sub) {
-						    	log_info("max " \
-							    "subscriptions " \
+						    	log_info("max "
+							    "subscriptions "
 							    "reached");
 							continue;
 						}
@@ -179,17 +192,14 @@ subthgs		: THING '{' STRING ',' STRING '}' optcomma {
 						    = thg->name;
 						clt->le++;
 						thg->clt_cnt++;
-						log_info("client %s subscribed" \
-						    " to %s", clt->name,
+						log_info("client %s subscribed "
+						    "to %s", clt->name,
 						    thg->name);
 						continue;
 					}
 			}
 		}
 		;
-optcomma	: ',' optcomma
-		| /* emtpy */
-		;
 logging		: LOG VERBOSE NUMBER {
 	 		if (pthgsd->debug == 0)
 				pthgsd->verbose = $3;
@@ -226,8 +236,16 @@ locopts		: /* empty */
 locopts2	: locopts2 locopts1 nl
 		| locopts1 optnl
 		;
-locopts1	: LISTEN STRING PORT NUMBER {
-	 		newthg->port = $4;
+locopts1	: LISTEN ON opttls PORT NUMBER {
+			struct thg		*thg;
+
+			TAILQ_FOREACH(thg, &pthgsd->thgs, entry) {
+				if (thg->port == $5 && (thg->tls || $3)) {
+					yyerror("tls port already used");
+					YYERROR;
+				}
+			}
+	 		newthg->port = $5;
 		}
 		| BAUD NUMBER {
 			newthg->baud = -1;
@@ -283,25 +301,43 @@ locopts1	: LISTEN STRING PORT NUMBER {
 				newthg->sw_ctl = true;
 		}
 		| PASSWORD STRING {
-			newthg->password = $2;
+			if ((newthg->password = strdup($2)) == NULL)
+				fatal("out of memory");
+			free($2);
 		}
 		| bindopts2
 		| maxclientssub
+		| TLS tlsopts {
+			if (newthg->tls == false) {
+				yyerror("tls options without tls listener");
+				YYERROR;
+			}
+		}
 		;
 socopts2	: socopts2 socopts1 nl
 		| socopts1 optnl
 		;
-socopts1	: LISTEN STRING PORT NUMBER {
-			newthg->port = $4;
+socopts1	: LISTEN ON opttls PORT NUMBER {
+			struct thg		*thg;
+
+			TAILQ_FOREACH(thg, &pthgsd->thgs, entry) {
+				if (thg->port == $5 && (thg->tls || $3)) {
+					yyerror("tls port already used");
+					YYERROR;
+				}
+			}
+			newthg->port = $5;
 		}
-		| CONNECT STRING PORT NUMBER {
+		| CONNECT ON PORT NUMBER {
 			newthg->conn_port = $4;
 		}
 		| RECEIVE STRING PORT NUMBER {
 			newthg->conn_port = $4;
 		}
 		| PASSWORD STRING {
-			newthg->password = $2;
+			if ((newthg->password = strdup($2)) == NULL)
+				fatal("out of memory");
+			free($2);
 		}
 		| PERSISTENT NUMBER {
 			if ($2)
@@ -311,6 +347,12 @@ socopts1	: LISTEN STRING PORT NUMBER {
 		}
 		| bindopts2
 		| maxclientssub
+		| TLS tlsopts {
+			if (newthg->tls == false) {
+				yyerror("tls options without tls listener");
+				YYERROR;
+			}
+		}
 		;
 thingopts2	: thingopts2 thingopts1 nl
 		| thingopts1 optnl
@@ -340,8 +382,21 @@ thing		: THING STRING	 {
 			newthg->stop_bits = -1;
 			newthg->hw_ctl = false;
 			newthg->sw_ctl = false;
-			newthg->password = "";
 			newthg->persist = true;
+			newthg->password = "";
+
+			newthg->tls_protocols = TLS_PROTOCOLS_DEFAULT;
+			newthg->tls_flags = 0;
+			if ((newthg->tls_cert_file = strdup(TLS_CERT)) == NULL)
+				fatal("out of memory");
+			if ((newthg->tls_key_file = strdup(TLS_KEY)) == NULL)
+				fatal("out of memory");
+			strlcpy(newthg->tls_ciphers, TLS_CIPHERS,
+			    sizeof(newthg->tls_ciphers));
+			strlcpy(newthg->tls_dhe_params, TLS_DHE_PARAMS,
+			    sizeof(newthg->tls_dhe_params));
+			strlcpy(newthg->tls_ecdhe_curves, TLS_ECDHE_CURVES,
+			    sizeof(newthg->tls_ecdhe_curves));
 		} '{' optnl thingopts2 '}' {
 			if (newthg->ipaddr != NULL && newthg->conn_port == -1) {
 				yyerror("ipaddr connect port empty");
@@ -364,9 +419,92 @@ thing		: THING STRING	 {
 				yyerror("could not set default port");
 				YYERROR;
 			}
+			if (newthg->tls)
+				if (load_tls(newthg) == -2)
+					YYABORT;
 			TAILQ_INSERT_TAIL(&pthgsd->thgs, newthg, entry);
 		}
 		;
+tlsopts		: CERTIFICATE STRING {
+			free(newthg->tls_cert_file);
+			if ((newthg->tls_cert_file = strdup($2)) == NULL)
+				fatal("out of memory");
+			free($2);
+		}
+		| KEY STRING {
+			free(newthg->tls_key_file);
+			if ((newthg->tls_key_file = strdup($2)) == NULL)
+				fatal("out of memory");
+			free($2);
+		}
+		| OCSP STRING {
+			free(newthg->tls_ocsp_staple_file);
+			if ((newthg->tls_ocsp_staple_file = strdup($2)) == NULL)
+				fatal("out of memory");
+			free($2);
+		}
+		| CIPHERS STRING {
+			if (strlcpy(newthg->tls_ciphers, $2,
+			    sizeof(newthg->tls_ciphers)) >=
+			    sizeof(newthg->tls_ciphers)) {
+				yyerror("ciphers too long");
+				free($2);
+				YYERROR;
+			}
+			free($2);
+		}
+		| CLIENT CA STRING tlscltopt {
+			newthg->tls_flags |= TLSFLAG_CA;
+			free(newthg->tls_ca_file);
+			if ((newthg->tls_ca_file = strdup($3)) == NULL)
+				fatal("out of memory");
+			free($3);
+		}
+		| DHE STRING {
+			if (strlcpy(newthg->tls_dhe_params, $2,
+			    sizeof(newthg->tls_dhe_params)) >=
+			    sizeof(newthg->tls_dhe_params)) {
+				yyerror("dhe too long");
+				free($2);
+				YYERROR;
+			}
+			free($2);
+		}
+		| ECDHE STRING {
+			if (strlcpy(newthg->tls_ecdhe_curves, $2,
+			    sizeof(newthg->tls_ecdhe_curves)) >=
+			    sizeof(newthg->tls_ecdhe_curves)) {
+				yyerror("ecdhe too long");
+				free($2);
+				YYERROR;
+			}
+			free($2);
+		}
+		| PROTOCOLS STRING {
+			if (tls_config_parse_protocols(
+			    &newthg->tls_protocols, $2) != 0) {
+				yyerror("invalid tls protocols");
+				free($2);
+				YYERROR;
+			}
+			free($2);
+		}
+		;
+tlscltopt	: /* empty */
+		| tlscltopt CRL STRING {
+			newthg->tls_flags = TLSFLAG_CRL;
+			free(newthg->tls_crl_file);
+			if ((newthg->tls_crl_file = strdup($3)) == NULL)
+				fatal("out of memory");
+			free($3);
+		}
+		| tlscltopt OPTIONAL {
+			newthg->tls_flags |= TLSFLAG_OPTIONAL;
+		}
+		;
+optcomma	: ',' optcomma
+		| /* emtpy */
+		;
 optnl		: '\n' optnl
 		| /* empty */
 		;
@@ -403,35 +541,47 @@ kw_cmp(const void *k, const void *e)
 int lookup(char *s) {
 	/* this has to be sorted always */
 	static const struct keywords keywords[] = {
-		{"baud",		BAUD},
-		{"bind",		BIND},
-		{"clients",		CLIENTS},
-		{"connect",		CONNECT},
-		{"connection",		CONNECTION},
-		{"data",		DATA},
-		{"default",		DEFAULT},
-		{"hardware",		HARDWARE},
-		{"interface",		INTERFACE},
-		{"ipaddr",		IPADDR},
-		{"listen",		LISTEN},
-		{"location",		LOCATION},
-		{"log",			LOG},
-		{"max",			MAX},
-		{"name",		NAME},
-		{"parity",		PARITY},
-		{"password",		PASSWORD},
-		{"persistent",		PERSISTENT},
-		{"port",		PORT},
-		{"receive",		RECEIVE},
-		{"retry",		RETRY},
-		{"software",		SOFTWARE},
-		{"stop",		STOP},
-		{"subscribe",		SUBSCRIBE},
-		{"subscriptions",	SUBSCRIPTIONS},
-		{"thing",		THING},
-		{"things",		THINGS},
-		{"udp",			UDP},
-		{"verbose",		VERBOSE}
+		{ "baud",		BAUD },
+		{ "bind",		BIND },
+		{ "ca",			CA },
+		{ "certificate",	CERTIFICATE },
+		{ "ciphers",		CIPHERS },
+		{ "clients",		CLIENTS },
+		{ "connect",		CONNECT },
+		{ "connection",		CONNECTION },
+		{ "crl",		CRL },
+		{ "data",		DATA },
+		{ "default",		DEFAULT },
+		{ "dhe",		DHE },
+		{ "ecdhe",		ECDHE },
+		{ "hardware",		HARDWARE },
+		{ "interface",		INTERFACE },
+		{ "ipaddr",		IPADDR },
+		{ "key",		KEY },
+		{ "listen",		LISTEN },
+		{ "location",		LOCATION },
+		{ "log",		LOG },
+		{ "max",		MAX },
+		{ "name",		NAME },
+		{ "ocsp",		OCSP },
+		{ "on",			ON },
+		{ "optional",		OPTIONAL },
+		{ "parity",		PARITY },
+		{ "password",		PASSWORD },
+		{ "persistent",		PERSISTENT },
+		{ "protocols",		PROTOCOLS },
+		{ "port",		PORT },
+		{ "receive",		RECEIVE },
+		{ "retry",		RETRY },
+		{ "software",		SOFTWARE },
+		{ "stop",		STOP },
+		{ "subscribe",		SUBSCRIBE },
+		{ "subscriptions",	SUBSCRIPTIONS },
+		{ "thing",		THING },
+		{ "things",		THINGS },
+		{ "tls",		TLS },
+		{ "udp",		UDP },
+		{ "verbose",		VERBOSE}
 	};
 	const struct keywords	*p;
 	p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]),
@@ -790,3 +940,28 @@ new_thg(char *name)
 		fatalx("no thg name");
 	return (thg);
 };
+
+int
+load_tls(struct thg *pthg)
+{
+	if (tls_load_keypair(pthg) == -1) {
+		log_warnx("%s:%d: thing \"%s\": failed to load public/private"
+		    " keys", file->name, yylval.lineno, pthg->name);
+		return -1;
+	}
+	if (tls_load_ca(pthg) == -1) {
+		yyerror("failed to load ca cert(s) for thing %s", pthg->name);
+		return -2;
+	}
+	if (tls_load_crl(pthg) == -1) {
+		yyerror("failed to load crl(s) for thing %s", pthg->name);
+		free(pthg);
+		return -2;
+	}
+	if (tls_load_ocsp(pthg) == -1) {
+		yyerror("failed to load ocsp staple for thing %s", pthg->name);
+		free(pthg);
+		return -2;
+	}
+	return 0;
+}
blob - e778477a08f35d0e09b228c6c7be4731104e4779
blob + c77a6d9e7c9b21b6e441603f5ea8d8bbc4da990e
--- thingsd/sockets.c	
+++ thingsd/sockets.c	
@@ -53,6 +53,10 @@ create_socks(struct thgsd *pthgsd, bool reconn)
 				continue;
 		}
 		sock = new_sock(thg->port);
+		if (thg->tls)
+			sock_tls_init(sock, thg);
+		else
+			sock->tls = false;
 		sock->max_clts += thg->max_clt;
 		sock->name = thg->name;
 		if (thg->iface != NULL)
blob - 418656b87bdd36387603c2350460f6a57ab5f73a
blob + 7f4a2ee4b47f6889c937c000e0c2d3ff05432d11
--- thingsd/thingsd.8	
+++ thingsd/thingsd.8	
@@ -18,31 +18,49 @@
 .Os
 .Sh NAME
 .Nm thingsd
-.Nd things proxy daemon
+.Nd things OpenBSD proxy daemon
 .Sh SYNOPSIS
 .Nm thingsd
 .Bk -words
-.Op Fl d
+.Op Fl dv
 .Ek
 .Sh DESCRIPTION
 The
 .Nm
-proxy daemon provides a mechanism for clients and client processes to
-communicate with an array of serial and IoT things. At its core,
+OpenBSD proxy daemon provides a mechanism for clients and client
+processes to communicate with an array of serial and IoT things.
+At its core,
 .Nm
-is primarily a packet repeater in that it waits for packets to swap between
-subscriber clients and things. However,
+is primarily a data aggregator and repeater, in that it waits for
+packets to swap between subscriber clients and things.
+However,
 .Nm
-also provides password control over those connections, including client limits.
+also provides TLS and password control over those connections, including
+client limits.
 .Pp
+On the client side,
 .Nm
-can connect directly to serial things, IoT IP things, and single socket
-connections. It also provides for UDP listeners.
+sets up TCP/IP sockets to transmit packets to and from things.
+On the server side,
+.Nm
+can connect to any serial device which has a viable file descriptor, create a
+persistent connection to the IP address of a device transmitting packets,
+or setup a UDP listener on the network to receive broadcasted packets.
+Devices tested include: ESP8266/ESP32 modules, on both the serial and network
+sides, XBee Series 2 coordinators connected in a mesh network, and NF24
+devices.
+To transmit to an IP address, which does not allow persistence,
+.Nm
+will create an ad hoc connection, transmit a packet, and detach.
+The
+.Nm
+proxy daemon is agnostic about packet data.
 .Pp
 The options are as follows:
 .Bl -tag -width "-f fileXXX"
 .It Fl d
-Do not daemonize. If this option is specified,
+Do not daemonize.
+If this option is specified,
 .Nm
 will run in the foreground and log to
 .Em stderr .
@@ -52,11 +70,9 @@ This option allows
 to send DEBUG priority messages to syslog.
 .El
 .Pp
-Example things tested: XBee, NF24, ESP8266, ESP32.
-.Pp
 Subscribers to a thing pass a simple, human-readable packet to
 .Nm .
-. The format is as follows, without the line breaks and tabs.
+The format is as follows, without the line breaks and tabs.
 This example is only for initial readability and help in understanding
 the format!
 .Pp
@@ -72,10 +88,7 @@ Subscription packets must begin with 3 * 0x7E
 }
 .Ed
 .Pp
-An accurate example packet without linebreaks:
-.Bd -literal -offset indent
-~~~subscribe{{name,"CLIENTNAME"},{things{thing{"dev1","pass"}}}}
-.Ed
+An accurate packet would not include linebreaks.
 .Pp
 .Nm
 is usually started at boot time, and can be enabled by adding
@@ -105,9 +118,9 @@ Socket file for communication with
 .El
 .Sh SEE ALSO
 .Xr thingsd.conf 5 ,
-.Xr thingsctl 8 ,
 .Xr rc 8 ,
-.Xr rc.conf 8
+.Xr rc.conf 8 ,
+.Xr thingsctl 8
 .Sh HISTORY
 The busybeed program first began development on
 .Ox 5.9 . The
@@ -117,6 +130,6 @@ program refactoring and rename began on
 .Sh AUTHORS
 .An -nosplit
 The
-.Xr thingsd 8
+.Nm
 program was written by
 .An Tracey Emery Aq Mt tracey@traceyemery.net .
blob - /dev/null
blob + 4f0f6655d8f9d4d791099928d58d309213c815ea (mode 644)
--- /dev/null	
+++ thingsd/thingsctl.8	
@@ -0,0 +1,33 @@
+.\"
+.\" Copyright (c) 2016 Tracey Emery <tracey@traceyemery.net>
+.\"
+.\" Permission to use, copy, modify, and distribute this software for any
+.\" purpose with or without fee is hereby granted, provided that the above
+.\" copyright notice and this permission notice appear in all copies.
+.\"
+.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+.\"
+
+.Dd $Mdocdate: January 26 2016 $
+.Dt THINGSCTL 1
+.Os
+.Sh NAME
+.Nm thingsctl
+.Nd thingsd control utility
+.Sh SYNOPSIS
+.Nm thingsctl
+.Op Fl sv
+.Op Fl d Ar host : Ns Ar port
+.Op Fl f Ar device
+.Op Ar command args ...
+.Sh DESCRIPTION
+The
+.Nm
+program is a control utility for the thingsd proxy daemon.
+.Pp
blob - 9568051c1559591083d75ddb9e23f13d875a4fed
blob + 749666fbf597fd806cfc25e2e6276ba4ff5c7591
--- thingsd/thingsd.c	
+++ thingsd/thingsd.c	
@@ -241,7 +241,12 @@ thingsd_shutdown(struct dthgs *zdthgs)
 	}
 	/* clean up sockets */
 	TAILQ_FOREACH_SAFE(sock, &pthgsd->socks, entry, tsock) {
+		if (sock->tls) {
+			tls_config_free(sock->tls_config);
+			tls_free(sock->tls_ctx);
+		}
 		close(sock->fd);
+		free(sock->ev);
 		TAILQ_REMOVE(&pthgsd->socks, sock, entry);
 		free(sock);
 	}
@@ -253,7 +258,7 @@ thingsd_shutdown(struct dthgs *zdthgs)
 		free(clt);
 	}
 	log_info("%s terminated", progname);
-	event_base_free(pthgsd->eb);
+	/* event_base_free(pthgsd->eb); */
 	free(pdthgs);
 	free(pthgsd);
 	exit(0);
blob - 4c295ba3bd2f90a6ff046f1de26310c9179da69d
blob + 7bb22a0affe9150f2b9c6c63a7d535c38952c430
--- thingsd/thingsd.conf.5	
+++ thingsd/thingsd.conf.5	
@@ -18,7 +18,7 @@
 .Os
 .Sh NAME
 .Nm thingsd.conf
-.Nd thingsd proxy daemon configuration file
+.Nd thingsd OpenBSD proxy daemon configuration file
 .Sh DESCRIPTION
 .Nm
 is the configuration file for the things proxy daemon,
@@ -47,14 +47,15 @@ the comment is effective until the end of the entire b
 .Pp
 Argument names not beginning with a letter, digit, or underscore
 must be quoted.
-.Ed
 .Sh GLOBAL CONFIGURATION
 Here are the settings that can be set globally:
 .Bl -tag -width Ds
 .It Ic default port Ar number
-Set the default port for things to communicate on. This is a required setting.
+Set the default port for things to communicate on.
+This is a required setting.
 .It Ic bind interface Ar string
-Specify a single interface to create sockets on. If this is not set,
+Specify a single interface to create sockets on.
+If this is not set,
 .Xr thingsd 8
 will attempt to open the default port on all network interfaces.
 .It Ic max clients Ar number
@@ -63,13 +64,14 @@ Set the default maximum number of clients allowed to c
 .It Ic max subscriptions Ar number
 Set the maximum number of things a client can subscribe to at a time.
 .It Ic connection retry Ar number
-Set the lost connection thing watchdog interval. Default is 30
-seconds. Range is 30-600 seconds.
+Set the lost connection thing watchdog interval.
+Default is 30 seconds.
+Range is 30-600 seconds.
 .It Ic log verbose Ar number
-Turn on verbose logging. (This option is currently disabled.)
+Turn on verbose logging.
 .El
 .Sh THINGS
-things represent a serial thing or a TCP/IP host for
+things represent a serial, TCP/IP, or UDP listener thing for
 .Xr thingsd 8
 to communicate with.
 .Xr thingsd 8
@@ -91,7 +93,8 @@ Set the data bits for a serial thing
 .It Ic connect on port Ar number
 Set the TCP/IP port to connect to for an
 .Ar ipaddr
-thing. This setting is required for
+thing.
+This setting is required for
 .Ar ipaddr
 things.
 .It Ic thing Ar string Brq ...
@@ -107,18 +110,21 @@ Set to 1 to turn on hardware control for a serial thin
 Create a
 .Ar thing
 connection to a hostname or IP address.
-.It Ic listen on port Ar number
+.It Ic listen on Oo Ic tls Oc port Ar number
 Set a local socket port for a
 .Ar location ,
 .Ar udp ,
 or
 .Ar ipaddr
 thing, other than the global default port.
+If TLS is used, the chosen port must be unique from the default port and all
+other things.
 .It Ic location Ar string Brq ...
 Create a
 .Ar thing
-connection to serial interface. These are any valid /dev things, for example
-/dev/ttyU0. Set the owner of a thing to _thingsd to allow for autoreconnect in
+connection to serial interface.
+These are any valid /dev things, for example /dev/ttyU0.
+Set the owner of a thing to _thingsd to allow for autoreconnect in
 a privdrop environment, in the event of a serial thing disconnect.
 .It Ic max clients Ar number
 Set the maximum clients allowed to connect to a thing
@@ -139,18 +145,20 @@ Set whether
 .Xr thingsd 8
 binds to an
 .Ar ipaddr
-thing. If
+thing.
+If
 .Ar persistent
 is set to 0,
 .Xr thingsd 8
-will create a socket, send a client packet, and close that socket. Clients
-cannot receive on a non-persistent
+will create a socket, send a client packet, and close that socket.
+Clients cannot receive on a non-persistent
 .Ar ipaddr
 thing.
 .It Ic receive on port Ar number
 Set the
 .Ar udp
-port to listen on for a UDP packet. This setting is required for
+port to listen on for a UDP packet.
+This setting is required for
 .Ar udp
 things.
 .It Ic software Ar number
@@ -159,6 +167,92 @@ Set to 1 to turn on software control for a serial thin
 .It Ic stop Ar number
 Set the stop bit for a serial thing
 .Ar location .
+.It Ic tls Ar option
+Set the TLS configuration for a thing.
+These options are only used if TLS has been enabled via the listen directive.
+Valid options are:
+.Bl -tag -width Ds
+.It Ic certificate Ar file
+Specify the certificate to use for this thing.
+The
+.Ar file
+should contain a PEM encoded certificate.
+The default is
+.Pa /etc/ssl/thing.crt .
+.It Ic ciphers Ar string
+Specify the TLS cipher string.
+If not specified, the default value
+.Qq HIGH:!aNULL
+will be used (strong crypto cipher suites without anonymous DH).
+See the CIPHERS section of
+.Xr openssl 1
+for information about SSL/TLS cipher suites and preference lists.
+.It Ic client ca Ar cafile Oo Ic crl Ar crlfile Oc Op Ic optional
+Require
+.Po
+or, if
+.Ic optional
+is specified, request but do not require
+.Pc
+TLS client certificates whose authenticity can be verified
+against the CA certificate(s) in
+.Ar cafile
+in order to proceed beyond the TLS handshake.
+With
+.Ic crl
+specified, additionally require that no certificate in the client chain be
+listed as revoked in the CRL(s) in
+.Ar crlfile .
+CA certificates and CRLs should be PEM encoded.
+.It Ic dhe Ar params
+Specify the DHE parameters to use for DHE cipher suites.
+Valid parameter values are none, legacy and auto.
+For legacy a fixed key length of 1024 bits is used, whereas for auto the key
+length is determined automatically.
+The default is none, which disables DHE cipher suites.
+.It Ic ecdhe Ar curves
+Specify a comma separated list of elliptic curves to use for ECDHE cipher suites,
+in order of preference.
+The special value of "default" will use the default curves; see
+.Xr tls_config_set_ecdhecurves 3
+for further details.
+.It Ic key Ar file
+Specify the private key to use for this thing.
+The
+.Ar file
+should contain a PEM encoded private key and reside outside of the
+.Xr chroot 2
+root directory of
+.Nm httpd .
+The default is
+.Pa /etc/ssl/private/thing.key .
+.It Ic ocsp Ar file
+Specify an OCSP response to be stapled during TLS handshakes
+with this thing.
+The
+.Ar file
+should contain a DER-format OCSP response retrieved from an
+OCSP server for the
+.Ar certificate
+in use,
+and can be created using
+.Xr ocspcheck 8 .
+The path to
+.Ar file
+is not relative to the chroot.
+If the OCSP response in
+.Ar file
+is empty, OCSP stapling will not be used.
+The default is to not use OCSP stapling.
+.It Ic protocols Ar string
+Specify the TLS protocols to enable for this thing.
+If not specified, the value
+.Qq default
+will be used (secure protocols; TLSv1.2-only).
+Refer to the
+.Xr tls_config_parse_protocols 3
+function for other valid protocol string values.
+.El
 .It Ic udp Ar string Brq ...
 Create a
 .Ar thing
@@ -182,11 +276,14 @@ max suscriptions 5
 
 thing "serial_thing" {
 	location "/dev/ttyU0" {
+		listen on tls port 50060
 		baud 9600
 		max clients 1
 		data 8
 		parity "none"
 		stop 1
+		tls certificate "/etc/ssl/my_thing.crt"
+		tls key "/etc/ssl/private/my_thing.key"
 		#no password required for our one allowed client
 	}
 }
@@ -194,7 +291,6 @@ thing "serial_thing" {
 thing "ipaddr_thing" {
 	ipaddr "10.0.0.1" {
 		connect on port 8080
-		listen on port 50010
 		password "password"
 	}
 }
@@ -207,12 +303,11 @@ thing "udp_thing" {
 	}
 }
 .Ed
-.Pp
-.El
 .Sh FILES
 .Bl -tag -width Ds -compact
 .It Pa /etc/thingsd.conf
 .Xr thingsd 8 configuration file.
+.El
 .Sh SEE ALSO
 .Xr thingsctl 8 ,
 .Xr thingsd 8
blob - 7519dfbc183ea0144b43aa8dc503500d041320c0
blob + d57c58997dcc926ac7dc9548e650fc6a25f92aa1
--- thingsd/thingsd.h	
+++ thingsd/thingsd.h	
@@ -24,9 +24,11 @@
 #include <pthread.h>
 #include <signal.h>
 #include <stdbool.h>
+#include <tls.h>
 
 #define PATH_CONF		 "/etc/thingsd.conf"
 #define TH_USER			 "_thingsd"
+#define THINGSD_SOCK		 "/var/run/httpd.sock"
 #define CONN_RTRY		 30
 #define MIN_RTRY		 10
 #define MAX_RTRY		 600
@@ -36,6 +38,17 @@
 #define DTHG_CHK		 2
 #define EB_TIMEOUT		 10
 
+#define TLS_CONFIG_MAX		 511
+#define TLS_CERT		"/etc/ssl/thing.crt"
+#define TLS_KEY			"/etc/ssl/private/thing.key"
+#define TLS_CIPHERS		"compat"
+#define TLS_DHE_PARAMS		"none"
+#define TLS_ECDHE_CURVES	"default"
+#define TLSFLAG_CA		0x01
+#define TLSFLAG_CRL		0x02
+#define TLSFLAG_OPTIONAL	0x04
+#define TLSFLAG_BITS		"\10\01CA\02CRL\03OPTIONAL"
+
 enum socktypes {
 	TCP,
 	UDP,
@@ -78,6 +91,28 @@ struct thg {
 	int			 stop_bits;
 	int			 type;
 	size_t			 clt_cnt;
+
+	bool			 tls;
+	uint8_t			 tls_flags;
+	uint8_t			*tls_cert;
+	size_t			 tls_cert_len;
+	char			*tls_cert_file;
+	uint8_t			*tls_key;
+	size_t			 tls_key_len;
+	char			*tls_key_file;
+	uint8_t			*tls_ca;
+	size_t			 tls_ca_len;
+	char			*tls_ca_file;
+	uint8_t			*tls_crl;
+	size_t			 tls_crl_len;
+	char			*tls_crl_file;
+	uint8_t			*tls_ocsp_staple;
+	size_t			 tls_ocsp_staple_len;
+	char			*tls_ocsp_staple_file;
+	char			 tls_ciphers[TLS_CONFIG_MAX];
+	char			 tls_dhe_params[TLS_CONFIG_MAX];
+	char			 tls_ecdhe_curves[TLS_CONFIG_MAX];
+	uint32_t		 tls_protocols;
 };
 
 struct sock {
@@ -90,10 +125,15 @@ struct sock {
 	int			 port;
 	size_t			 clt_cnt;
 	size_t			 max_clts;
+
+	bool			 tls;
+	struct tls_config	*tls_config;
+	struct tls		*tls_ctx;
 };
 
 struct clt {
 	TAILQ_ENTRY(clt)	 entry;
+	struct event		*ev;
 	struct evbuffer		*evb;
 	struct bufferevent	*bev;
 	struct sock		*sock;
@@ -105,6 +145,9 @@ struct clt {
 	time_t			 join_time;
 	size_t			 le;
 	size_t			 subs;
+
+	bool			 tls;
+	struct tls		*tls_ctx;
 };
 
 struct thgsd {
@@ -166,6 +209,7 @@ void				 udp_evt(int, short, void *);
 
 /* client.c */
 void				 clt_conn(int, short, void *);
+void				 clt_add(struct thgsd *, struct clt *);
 void				 clt_del(struct thgsd *, struct clt *);
 void				 clt_rd(struct bufferevent *, void *);
 void				 clt_wr(struct bufferevent *, void *);
@@ -175,7 +219,17 @@ void				*clt_chk(void *);
 void				 clt_do_chk(struct thgsd *);
 void				 clt_wr_thgs(struct clt *, struct thg *,
 				    size_t);
+void				 clt_tls_readcb(int, short, void *);
+void				 clt_tls_writecb(int, short, void *);
 
+/* tls.c */
+int				 tls_load_keypair(struct thg *);
+int				 tls_load_ca(struct thg *);
+int				 tls_load_crl(struct thg *);
+int				 tls_load_ocsp(struct thg *);
+int				 sock_tls_init(struct sock *, struct thg *);
+void				 sock_tls_handshake(int, short, void *);
+
 /* log.c */
 void	log_init(int, int);
 void	log_procinit(const char *);
blob - /dev/null
blob + 066f64f7210595514d0489dcc44dd084f388f408 (mode 644)
--- /dev/null	
+++ thingsd/tls.c	
@@ -0,0 +1,222 @@
+/*
+ * Copyright (c) 2019 Tracey Emery <tracey@traceyemery.net>
+ * Copyright (c) 2006 - 2015 Reyk Floeter <reyk@openbsd.org>
+ * 	(snippets from httpd functions)
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <event.h>
+#include <stdlib.h>
+#include <tls.h>
+
+#include "thingsd.h"
+
+int
+tls_load_keypair(struct thg *pthg)
+{
+	if (pthg->tls == false)
+		return (0);
+	if ((pthg->tls_cert = tls_load_file(pthg->tls_cert_file,
+	    &pthg->tls_cert_len, NULL)) == NULL)
+		return (-1);
+	log_debug("%s: using certificate %s", __func__, pthg->tls_cert_file);
+	/* XXX allow to specify password for encrypted key */
+	if ((pthg->tls_key = tls_load_file(pthg->tls_key_file,
+	    &pthg->tls_key_len, NULL)) == NULL)
+		return (-1);
+	log_debug("%s: using private key %s", __func__, pthg->tls_key_file);
+	return (0);
+}
+
+int
+tls_load_ca(struct thg *pthg)
+{
+	if ((pthg->tls_flags & TLSFLAG_CA) == 0 || pthg->tls_ca_file == NULL)
+		return (0);
+	if ((pthg->tls_ca = tls_load_file(pthg->tls_ca_file, &pthg->tls_ca_len,
+	    NULL)) == NULL)
+		return (-1);
+	log_debug("%s: using ca cert(s) from %s", __func__, pthg->tls_ca_file);
+	return (0);
+}
+
+int
+tls_load_ocsp(struct thg *pthg)
+{
+	if (pthg->tls == false)
+		return (0);
+	if (pthg->tls_ocsp_staple_file == NULL)
+		return (0);
+	if ((pthg->tls_ocsp_staple = tls_load_file(
+	    pthg->tls_ocsp_staple_file,
+	    &pthg->tls_ocsp_staple_len, NULL)) == NULL) {
+		log_warnx("%s: Failed to load ocsp staple from %s", __func__,
+		    pthg->tls_ocsp_staple_file);
+		return (-1);
+	}
+	if (pthg->tls_ocsp_staple_len == 0) {
+		log_warnx("%s: ignoring 0 length ocsp staple from %s", __func__,
+		    pthg->tls_ocsp_staple_file);
+		return (0);
+	}
+	log_debug("%s: using ocsp staple from %s", __func__,
+	    pthg->tls_ocsp_staple_file);
+	return (0);
+}
+
+int
+tls_load_crl(struct thg *pthg)
+{
+	if ((pthg->tls_flags & TLSFLAG_CA) == 0 || pthg->tls_crl_file == NULL)
+		return (0);
+	if ((pthg->tls_crl = tls_load_file(pthg->tls_crl_file,
+	    &pthg->tls_crl_len, NULL)) == NULL)
+		return (-1);
+	log_debug("%s: using crl(s) from %s", __func__, pthg->tls_crl_file);
+	return (0);
+}
+
+int
+sock_tls_init(struct sock *psock, struct thg *pthg)
+{
+	if (pthg->tls == false)
+		return 0;
+	if (pthg->tls_cert == NULL)
+		/* soft fail if cert is not there yet */
+		return (0);
+	log_debug("%s: setting up tls for %s", __func__, pthg->name);
+	if (tls_init() != 0) {
+		log_warnx("%s: failed to initialise tls", __func__);
+		return (-1);
+	}
+	if ((psock->tls_config = tls_config_new()) == NULL) {
+		log_warnx("%s: failed to get tls pthgig", __func__);
+		return (-1);
+	}
+	if ((psock->tls_ctx = tls_server()) == NULL) {
+		log_warnx("%s: failed to get tls server", __func__);
+		return (-1);
+	}
+	if (tls_config_set_protocols(psock->tls_config,
+	    pthg->tls_protocols) != 0) {
+		log_warnx("%s: failed to set tls protocols: %s", __func__,
+		    tls_config_error(psock->tls_config));
+		return (-1);
+	}
+	if (tls_config_set_ciphers(psock->tls_config, pthg->tls_ciphers) != 0) {
+		log_warnx("%s: failed to set tls ciphers: %s", __func__,
+		    tls_config_error(psock->tls_config));
+		return (-1);
+	}
+	if (tls_config_set_dheparams(psock->tls_config,
+	    pthg->tls_dhe_params) != 0) {
+		log_warnx("%s: failed to set tls dhe params: %s", __func__,
+		    tls_config_error(psock->tls_config));
+		return (-1);
+	}
+	if (tls_config_set_ecdhecurves(psock->tls_config,
+	    pthg->tls_ecdhe_curves) != 0) {
+		log_warnx("%s: failed to set tls ecdhe curves: %s", __func__,
+		    tls_config_error(psock->tls_config));
+		return (-1);
+	}
+	if (tls_config_set_keypair_ocsp_mem(psock->tls_config, pthg->tls_cert,
+	    pthg->tls_cert_len, pthg->tls_key, pthg->tls_key_len,
+	    pthg->tls_ocsp_staple, pthg->tls_ocsp_staple_len) != 0) {
+		log_warnx("%s: failed to set tls certificate/key: %s", __func__,
+		    tls_config_error(psock->tls_config));
+		return (-1);
+	}
+	if (pthg->tls_ca != NULL) {
+		if (tls_config_set_ca_mem(psock->tls_config, pthg->tls_ca,
+			pthg->tls_ca_len) != 0) {
+			log_warnx("%s: failed to add ca cert(s)", __func__);
+			return (-1);
+		}
+		if (tls_config_set_crl_mem(psock->tls_config, pthg->tls_crl,
+			pthg->tls_crl_len) != 0) {
+			log_warnx("%s: failed to add crl(s)", __func__);
+			return (-1);
+		}
+		if (pthg->tls_flags & TLSFLAG_OPTIONAL)
+			tls_config_verify_client_optional(psock->tls_config);
+		else
+			tls_config_verify_client(psock->tls_config);
+	}
+	log_debug("%s: adding keypair for server %s", __func__, pthg->name);
+	if (tls_config_add_keypair_ocsp_mem(psock->tls_config, pthg->tls_cert,
+	    pthg->tls_cert_len, pthg->tls_key, pthg->tls_key_len,
+	    pthg->tls_ocsp_staple, pthg->tls_ocsp_staple_len) != 0) {
+		log_warnx("%s: failed to add tls keypair", __func__);
+		return (-1);
+	}
+	if (tls_configure(psock->tls_ctx, psock->tls_config) != 0) {
+		log_warnx("%s: failed to configure tls - %s", __func__,
+		    tls_error(psock->tls_ctx));
+		return (-1);
+	}
+	/* We're now done with the public/private key & ca/crl... */
+	tls_config_clear_keys(psock->tls_config);
+	psock->tls = true;
+	freezero(pthg->tls_cert, pthg->tls_cert_len);
+	freezero(pthg->tls_key, pthg->tls_key_len);
+	free(pthg->tls_ca);
+	free(pthg->tls_crl);
+	pthg->tls_ca = NULL;
+	pthg->tls_cert = NULL;
+	pthg->tls_crl = NULL;
+	pthg->tls_key = NULL;
+	pthg->tls_ca_len = 0;
+	pthg->tls_cert_len = 0;
+	pthg->tls_crl_len = 0;
+	pthg->tls_key_len = 0;
+	return 0;
+}
+
+void
+sock_tls_handshake(int fd, short event, void *arg)
+{
+	struct thgsd		*pthgsd = (struct thgsd *)arg;
+	struct clt		*clt = NULL, *tclt;
+	ssize_t			 ret = 0;
+
+	TAILQ_FOREACH(tclt, &pthgsd->clts, entry) {
+		if (tclt->fd == fd) {
+			clt = tclt;
+			break;
+		}
+	}
+	ret = tls_handshake(clt->tls_ctx);
+	if (ret == 0) {
+		event_del(clt->ev);
+		log_debug("%s: tls handshake success", __func__);
+		clt_add(pthgsd, clt);
+	} else if (ret == TLS_WANT_POLLIN) {
+		event_del(clt->ev);
+		event_set(clt->ev, clt->fd, EV_READ|EV_PERSIST,
+			    sock_tls_handshake, pthgsd);
+		if (event_add(clt->ev, NULL))
+			log_info("event add clt");
+	} else if (ret == TLS_WANT_POLLOUT) {
+		event_del(clt->ev);
+		event_set(clt->ev, clt->fd, EV_WRITE|EV_PERSIST,
+			    sock_tls_handshake, pthgsd);
+		if (event_add(clt->ev, NULL))
+			log_info("event add clt");
+	} else {
+		event_del(clt->ev);
+		log_debug("%s: tls handshake failed - %s", __func__,
+		    tls_error(clt->tls_ctx));
+	}
+}