Blob


1 /*
2 * Copyright (c) 2021, 2022 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <sys/socket.h>
20 #include <sys/wait.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <event.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <netdb.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <syslog.h>
33 #include <unistd.h>
35 #include "log.h"
37 #ifndef SSH_PATH
38 #define SSH_PATH "/usr/bin/ssh"
39 #endif
41 #define MAXSOCK 32
42 #define BACKOFF 1
43 #define RETRIES 16
45 #ifndef __OpenBSD__
46 #define pledge(p, e) 0
47 #endif
49 const char *addr; /* our addr */
50 const char *ssh_tflag;
51 const char *ssh_dest;
53 char ssh_host[256];
54 char ssh_port[16];
56 struct event sockev[MAXSOCK];
57 int socks[MAXSOCK];
58 int nsock;
60 int debug;
61 int verbose;
63 struct event sighupev;
64 struct event sigintev;
65 struct event sigtermev;
66 struct event sigchldev;
67 struct event siginfoev;
69 struct timeval timeout = {600, 0}; /* 10 minutes */
70 struct event timeoutev;
72 pid_t ssh_pid = -1;
74 int conn;
76 struct conn {
77 int ntentative;
78 struct timeval retry;
79 struct event waitev;
80 int source;
81 struct bufferevent *sourcebev;
82 int to;
83 struct bufferevent *tobev;
84 };
86 static void
87 sig_handler(int sig, short event, void *data)
88 {
89 int status;
91 switch (sig) {
92 case SIGHUP:
93 case SIGINT:
94 case SIGTERM:
95 log_info("quitting");
96 event_loopbreak();
97 break;
98 case SIGCHLD:
99 if (waitpid(ssh_pid, &status, WNOHANG) == -1)
100 fatal("waitpid");
101 ssh_pid = -1;
102 break;
103 #ifdef SIGINFO
104 case SIGINFO:
105 #else
106 case SIGUSR1:
107 #endif
108 log_info("connections: %d", conn);
112 static void
113 spawn_ssh(void)
115 log_debug("spawning ssh");
117 switch (ssh_pid = fork()) {
118 case -1:
119 fatal("fork");
120 case 0:
121 execl(SSH_PATH, "ssh", "-L", ssh_tflag, "-NTq", ssh_dest,
122 NULL);
123 fatal("exec");
124 default:
125 return;
129 static void
130 conn_free(struct conn *c)
132 if (c->sourcebev != NULL)
133 bufferevent_free(c->sourcebev);
134 if (c->tobev != NULL)
135 bufferevent_free(c->tobev);
137 if (evtimer_pending(&c->waitev, NULL))
138 evtimer_del(&c->waitev);
140 close(c->source);
141 if (c->to != -1)
142 close(c->to);
144 free(c);
147 static void
148 killing_time(int fd, short event, void *data)
150 if (ssh_pid == -1)
151 return;
153 log_debug("timeout expired, killing ssh (%d)", ssh_pid);
154 kill(ssh_pid, SIGTERM);
155 ssh_pid = -1;
158 static void
159 nopcb(struct bufferevent *bev, void *d)
161 return;
164 static void
165 sreadcb(struct bufferevent *bev, void *d)
167 struct conn *c = d;
169 bufferevent_write_buffer(c->tobev, EVBUFFER_INPUT(bev));
172 static void
173 treadcb(struct bufferevent *bev, void *d)
175 struct conn *c = d;
177 bufferevent_write_buffer(c->sourcebev, EVBUFFER_INPUT(bev));
180 static void
181 errcb(struct bufferevent *bev, short event, void *d)
183 struct conn *c = d;
185 log_info("closing connection (event=%x)", event);
187 conn_free(c);
189 if (--conn == 0) {
190 log_debug("scheduling ssh termination (%llds)",
191 (long long)timeout.tv_sec);
192 if (timeout.tv_sec != 0) {
193 evtimer_set(&timeoutev, killing_time, NULL);
194 evtimer_add(&timeoutev, &timeout);
199 static int
200 connect_to_ssh(void)
202 struct addrinfo hints, *res, *res0;
203 int r, saved_errno, sock;
204 const char *cause;
206 memset(&hints, 0, sizeof(hints));
207 hints.ai_family = AF_UNSPEC;
208 hints.ai_socktype = SOCK_STREAM;
210 r = getaddrinfo(ssh_host, ssh_port, &hints, &res0);
211 if (r != 0) {
212 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
213 ssh_host, ssh_port, gai_strerror(r));
214 return -1;
217 for (res = res0; res; res = res->ai_next) {
218 sock = socket(res->ai_family, res->ai_socktype,
219 res->ai_protocol);
220 if (sock == -1) {
221 cause = "socket";
222 continue;
225 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
226 cause = "connect";
227 saved_errno = errno;
228 close(sock);
229 errno = saved_errno;
230 sock = -1;
231 continue;
234 break;
237 if (sock == -1)
238 log_warn("%s", cause);
240 freeaddrinfo(res0);
241 return sock;
244 static void
245 try_to_connect(int fd, short event, void *d)
247 struct conn *c = d;
249 /* ssh may die in the meantime */
250 if (ssh_pid == -1) {
251 close(c->source);
252 c->source = -1;
253 return;
256 c->ntentative++;
257 log_info("trying to connect to %s:%s (%d/%d)", ssh_host, ssh_port,
258 c->ntentative, RETRIES);
260 if ((c->to = connect_to_ssh()) == -1) {
261 if (c->ntentative == RETRIES) {
262 log_warnx("giving up connecting");
263 close(c->source);
264 c->source = -1;
265 return;
268 evtimer_set(&c->waitev, try_to_connect, c);
269 evtimer_add(&c->waitev, &c->retry);
270 return;
273 log_info("connected!");
275 c->sourcebev = bufferevent_new(c->source, sreadcb, nopcb, errcb, c);
276 c->tobev = bufferevent_new(c->to, treadcb, nopcb, errcb, c);
277 if (c->sourcebev == NULL || c->tobev == NULL) {
278 log_warn("bufferevent_new");
279 conn_free(c);
280 return;
283 bufferevent_enable(c->sourcebev, EV_READ|EV_WRITE);
284 bufferevent_enable(c->tobev, EV_READ|EV_WRITE);
287 static void
288 do_accept(int fd, short event, void *data)
290 struct conn *c;
291 int s;
293 log_debug("incoming connection");
295 if (evtimer_pending(&timeoutev, NULL))
296 evtimer_del(&timeoutev);
298 if ((s = accept(fd, NULL, 0)) == -1)
299 fatal("accept");
301 conn++;
303 if (ssh_pid == -1)
304 spawn_ssh();
306 if ((c = calloc(1, sizeof(*c))) == NULL) {
307 log_warn("calloc");
308 close(s);
309 return;
312 c->source = s;
313 c->to = -1;
314 c->retry.tv_sec = BACKOFF;
315 evtimer_set(&c->waitev, try_to_connect, c);
316 evtimer_add(&c->waitev, &c->retry);
319 static const char *
320 copysec(const char *s, char *d, size_t len)
322 const char *c;
324 if ((c = strchr(s, ':')) == NULL)
325 return NULL;
326 if ((size_t)(c - s) >= len-1)
327 return NULL;
328 memset(d, 0, len);
329 memcpy(d, s, c - s);
330 return c;
333 static void
334 bind_socket(void)
336 struct addrinfo hints, *res, *res0;
337 int v, r, saved_errno;
338 char host[64];
339 const char *c, *h, *port, *cause;
341 if ((c = strchr(addr, ':')) == NULL) {
342 h = NULL;
343 port = addr;
344 } else {
345 if ((c = copysec(addr, host, sizeof(host))) == NULL)
346 fatalx("name too long: %s", addr);
348 h = host;
349 port = c+1;
352 memset(&hints, 0, sizeof(hints));
353 hints.ai_family = AF_UNSPEC;
354 hints.ai_socktype = SOCK_STREAM;
355 hints.ai_flags = AI_PASSIVE;
357 r = getaddrinfo(h, port, &hints, &res0);
358 if (r != 0)
359 fatalx("getaddrinfo(%s): %s", addr, gai_strerror(r));
361 for (res = res0; res && nsock < MAXSOCK; res = res->ai_next) {
362 socks[nsock] = socket(res->ai_family, res->ai_socktype,
363 res->ai_protocol);
364 if (socks[nsock] == -1) {
365 cause = "socket";
366 continue;
369 if (bind(socks[nsock], res->ai_addr, res->ai_addrlen) == -1) {
370 cause = "bind";
371 saved_errno = errno;
372 close(socks[nsock]);
373 errno = saved_errno;
374 continue;
377 v = 1;
378 if (setsockopt(socks[nsock], SOL_SOCKET, SO_REUSEADDR, &v,
379 sizeof(v)) == -1)
380 fatal("setsockopt(SO_REUSEADDR)");
382 v = 1;
383 if (setsockopt(socks[nsock], SOL_SOCKET, SO_REUSEPORT, &v,
384 sizeof(v)) == -1)
385 fatal("setsockopt(SO_REUSEPORT)");
387 listen(socks[nsock], 5);
389 nsock++;
391 if (nsock == 0)
392 fatal("%s", cause);
394 freeaddrinfo(res0);
397 static void
398 parse_sshaddr(void)
400 const char *c;
402 if (isdigit((unsigned char)*ssh_tflag)) {
403 strlcpy(ssh_host, "localhost", sizeof(ssh_host));
404 if (copysec(ssh_tflag, ssh_port, sizeof(ssh_port)) == NULL)
405 goto err;
406 return;
409 if ((c = copysec(ssh_tflag, ssh_host, sizeof(ssh_host))) == NULL)
410 goto err;
411 if (copysec(c+1, ssh_port, sizeof(ssh_port)) == NULL)
412 goto err;
413 return;
415 err:
416 fatal("wrong value for -B");
419 static void __dead
420 usage(void)
422 fprintf(stderr, "usage: %s [-dv] -B sshaddr -b addr [-t timeout]"
423 " destination\n", getprogname());
424 exit(1);
427 int
428 main(int argc, char **argv)
430 int ch, i, fd;
431 const char *errstr;
432 struct stat sb;
434 /*
435 * Ensure we have fds 0-2 open so that we have no issue with
436 * calling bind_socket before daemon(3).
437 */
438 for (i = 0; i < 3; ++i) {
439 if (fstat(i, &sb) == -1) {
440 if ((fd = open("/dev/null", O_RDWR)) != -1) {
441 if (dup2(fd, i) == -1)
442 exit(1);
443 if (fd > i)
444 close(fd);
445 } else
446 exit(1);
450 log_init(1, LOG_DAEMON);
451 log_setverbose(1);
453 while ((ch = getopt(argc, argv, "B:b:dt:v")) != -1) {
454 switch (ch) {
455 case 'B':
456 ssh_tflag = optarg;
457 parse_sshaddr();
458 break;
459 case 'b':
460 addr = optarg;
461 break;
462 case 'd':
463 debug = 1;
464 break;
465 case 't':
466 timeout.tv_sec = strtonum(optarg, 0, INT_MAX, &errstr);
467 if (errstr != NULL)
468 fatalx("timeout is %s: %s", errstr, optarg);
469 break;
470 case 'v':
471 verbose = 1;
472 break;
473 default:
474 usage();
477 argc -= optind;
478 argv += optind;
480 if (argc != 1 || addr == NULL || ssh_tflag == NULL)
481 usage();
483 ssh_dest = argv[0];
485 bind_socket();
487 log_init(debug, LOG_DAEMON);
488 log_setverbose(verbose);
490 if (!debug)
491 daemon(1, 0);
493 signal(SIGPIPE, SIG_IGN);
495 event_init();
497 /* initialize the timer */
498 evtimer_set(&timeoutev, killing_time, NULL);
500 signal_set(&sighupev, SIGHUP, sig_handler, NULL);
501 signal_set(&sigintev, SIGINT, sig_handler, NULL);
502 signal_set(&sigtermev, SIGTERM, sig_handler, NULL);
503 signal_set(&sigchldev, SIGCHLD, sig_handler, NULL);
504 #ifdef SIGINFO
505 signal_set(&siginfoev, SIGINFO, sig_handler, NULL);
506 #else
507 signal_set(&siginfoev, SIGUSR1, sig_handler, NULL);
508 #endif
510 signal_add(&sighupev, NULL);
511 signal_add(&sigintev, NULL);
512 signal_add(&sigtermev, NULL);
513 signal_add(&sigchldev, NULL);
514 signal_add(&siginfoev, NULL);
516 for (i = 0; i < nsock; ++i) {
517 event_set(&sockev[i], socks[i], EV_READ|EV_PERSIST,
518 do_accept, NULL);
519 event_add(&sockev[i], NULL);
522 /*
523 * dns, inet: bind the socket and connect to the childs.
524 * proc, exec: execute ssh on demand.
525 */
526 if (pledge("stdio dns inet proc exec", NULL) == -1)
527 fatal("pledge");
529 log_info("starting");
530 event_dispatch();
532 if (ssh_pid != -1)
533 kill(ssh_pid, SIGINT);
535 return 0;