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 "config.h"
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/socket.h>
22 #include <sys/wait.h>
24 #include <ctype.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <netdb.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <syslog.h>
34 #include <unistd.h>
36 #include "log.h"
37 #include "lstun.h"
39 #define MAXSOCK 32
40 #define BACKOFF 1
41 #define RETRIES 16
43 const char *addr; /* our addr */
44 const char *ssh_tflag;
45 const char *ssh_dest;
47 char ssh_host[256];
48 char ssh_port[16];
50 struct event sockev[MAXSOCK];
51 int socks[MAXSOCK];
52 int nsock;
54 int debug;
55 int verbose;
57 struct event sighupev;
58 struct event sigintev;
59 struct event sigtermev;
60 struct event sigchldev;
61 struct event siginfoev;
63 struct timeval timeout = {600, 0}; /* 10 minutes */
64 struct event timeoutev;
66 pid_t ssh_pid = -1;
68 int conn;
70 static void
71 sig_handler(int sig, short event, void *data)
72 {
73 int status;
75 switch (sig) {
76 case SIGHUP:
77 case SIGINT:
78 case SIGTERM:
79 log_info("quitting");
80 event_loopbreak();
81 break;
82 case SIGCHLD:
83 if (waitpid(ssh_pid, &status, WNOHANG) == -1)
84 fatal("waitpid");
85 ssh_pid = -1;
86 break;
87 #ifdef SIGINFO
88 case SIGINFO:
89 #else
90 case SIGUSR1:
91 #endif
92 log_info("connections: %d", conn);
93 }
94 }
96 static int
97 spawn_ssh(void)
98 {
99 log_debug("spawning ssh");
101 switch (ssh_pid = fork()) {
102 case -1:
103 log_warnx("fork");
104 return -1;
105 case 0:
106 execl(SSH_PROG, "ssh", "-L", ssh_tflag, "-NTq", ssh_dest,
107 NULL);
108 fatal("exec");
109 default:
110 return 0;
114 static void
115 killing_time(int fd, short event, void *data)
117 if (ssh_pid == -1)
118 return;
120 log_debug("timeout expired, killing ssh (%d)", ssh_pid);
121 kill(ssh_pid, SIGTERM);
122 ssh_pid = -1;
125 void
126 conn_free(struct conn *c)
128 if (c->sourcebev != NULL)
129 bufferevent_free(c->sourcebev);
130 if (c->tobev != NULL)
131 bufferevent_free(c->tobev);
133 if (evtimer_pending(&c->waitev, NULL))
134 evtimer_del(&c->waitev);
136 close(c->source);
137 if (c->to != -1)
138 close(c->to);
140 free(c);
142 if (--conn == 0) {
143 log_debug("scheduling ssh termination (%llds)",
144 (long long)timeout.tv_sec);
145 if (timeout.tv_sec != 0) {
146 evtimer_set(&timeoutev, killing_time, NULL);
147 evtimer_add(&timeoutev, &timeout);
152 static int
153 connect_to_ssh(void)
155 struct addrinfo hints, *res, *res0;
156 int r, saved_errno, sock;
157 const char *cause;
159 memset(&hints, 0, sizeof(hints));
160 hints.ai_family = AF_UNSPEC;
161 hints.ai_socktype = SOCK_STREAM;
163 r = getaddrinfo(ssh_host, ssh_port, &hints, &res0);
164 if (r != 0) {
165 log_warnx("getaddrinfo(\"%s\", \"%s\"): %s",
166 ssh_host, ssh_port, gai_strerror(r));
167 return -1;
170 for (res = res0; res; res = res->ai_next) {
171 sock = socket(res->ai_family, res->ai_socktype,
172 res->ai_protocol);
173 if (sock == -1) {
174 cause = "socket";
175 continue;
178 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
179 cause = "connect";
180 saved_errno = errno;
181 close(sock);
182 errno = saved_errno;
183 sock = -1;
184 continue;
187 break;
190 if (sock == -1)
191 log_warn("%s", cause);
193 freeaddrinfo(res0);
194 return sock;
197 static void
198 try_to_connect(int fd, short event, void *d)
200 struct conn *c = d;
202 /* ssh may have died in the meantime */
203 if (ssh_pid == -1) {
204 conn_free(c);
205 return;
208 c->ntentative++;
209 log_info("trying to connect to %s:%s (%d/%d)", ssh_host, ssh_port,
210 c->ntentative, RETRIES);
212 if ((c->to = connect_to_ssh()) == -1) {
213 if (c->ntentative == RETRIES) {
214 log_warnx("giving up connecting");
215 conn_free(c);
216 return;
219 evtimer_set(&c->waitev, try_to_connect, c);
220 evtimer_add(&c->waitev, &c->retry);
221 return;
224 log_info("connected!");
226 if (conn_splice(c) == -1)
227 conn_free(c);
230 static void
231 do_accept(int fd, short event, void *data)
233 struct conn *c;
234 int s;
236 log_debug("incoming connection");
238 if ((s = accept(fd, NULL, 0)) == -1) {
239 log_warn("accept");
240 return;
243 if (ssh_pid == -1 && spawn_ssh() == -1) {
244 close(s);
245 return;
248 if ((c = calloc(1, sizeof(*c))) == NULL) {
249 log_warn("calloc");
250 close(s);
251 return;
254 conn++;
255 if (evtimer_pending(&timeoutev, NULL))
256 evtimer_del(&timeoutev);
258 c->source = s;
259 c->to = -1;
260 c->retry.tv_sec = BACKOFF;
261 evtimer_set(&c->waitev, try_to_connect, c);
262 evtimer_add(&c->waitev, &c->retry);
265 static const char *
266 copysec(const char *s, char *d, size_t len)
268 const char *c;
270 if ((c = strchr(s, ':')) == NULL)
271 return NULL;
272 if ((size_t)(c - s) >= len-1)
273 return NULL;
274 memset(d, 0, len);
275 memcpy(d, s, c - s);
276 return c;
279 static void
280 bind_socket(void)
282 struct addrinfo hints, *res, *res0;
283 int v, r, saved_errno;
284 char host[64];
285 const char *c, *h, *port, *cause;
287 if ((c = strchr(addr, ':')) == NULL) {
288 h = "localhost";
289 port = addr;
290 } else {
291 if ((c = copysec(addr, host, sizeof(host))) == NULL)
292 fatalx("name too long: %s", addr);
294 h = host;
295 port = c+1;
298 memset(&hints, 0, sizeof(hints));
299 hints.ai_family = AF_UNSPEC;
300 hints.ai_socktype = SOCK_STREAM;
301 hints.ai_flags = AI_PASSIVE;
303 r = getaddrinfo(h, port, &hints, &res0);
304 if (r != 0)
305 fatalx("getaddrinfo(%s): %s", addr, gai_strerror(r));
307 for (res = res0; res && nsock < MAXSOCK; res = res->ai_next) {
308 socks[nsock] = socket(res->ai_family, res->ai_socktype,
309 res->ai_protocol);
310 if (socks[nsock] == -1) {
311 cause = "socket";
312 continue;
315 v = 1;
316 if (setsockopt(socks[nsock], SOL_SOCKET, SO_REUSEADDR, &v,
317 sizeof(v)) == -1)
318 fatal("setsockopt(SO_REUSEADDR)");
320 v = 1;
321 if (setsockopt(socks[nsock], SOL_SOCKET, SO_REUSEPORT, &v,
322 sizeof(v)) == -1)
323 fatal("setsockopt(SO_REUSEPORT)");
325 if (bind(socks[nsock], res->ai_addr, res->ai_addrlen) == -1) {
326 cause = "bind";
327 saved_errno = errno;
328 close(socks[nsock]);
329 errno = saved_errno;
330 continue;
333 if (listen(socks[nsock], 5) == -1)
334 fatal("listen");
336 nsock++;
338 if (nsock == 0)
339 fatal("%s", cause);
341 freeaddrinfo(res0);
344 static void
345 parse_sshaddr(void)
347 const char *c;
349 if (isdigit((unsigned char)*ssh_tflag)) {
350 strlcpy(ssh_host, "localhost", sizeof(ssh_host));
351 if (copysec(ssh_tflag, ssh_port, sizeof(ssh_port)) == NULL)
352 goto err;
353 return;
356 if ((c = copysec(ssh_tflag, ssh_host, sizeof(ssh_host))) == NULL)
357 goto err;
358 if (copysec(c+1, ssh_port, sizeof(ssh_port)) == NULL)
359 goto err;
360 return;
362 err:
363 fatalx("wrong value for -B");
366 static void __dead
367 usage(void)
369 fprintf(stderr, "usage: %s [-dv] -B sshaddr -b addr [-t timeout]"
370 " destination\n", getprogname());
371 exit(1);
374 int
375 main(int argc, char **argv)
377 int ch, i, fd;
378 const char *errstr;
379 struct stat sb;
381 /*
382 * Ensure we have fds 0-2 open so that we have no issue with
383 * calling bind_socket before daemon(3).
384 */
385 for (i = 0; i < 3; ++i) {
386 if (fstat(i, &sb) == -1) {
387 if ((fd = open("/dev/null", O_RDWR)) != -1) {
388 if (dup2(fd, i) == -1)
389 exit(1);
390 if (fd > i)
391 close(fd);
392 } else
393 exit(1);
397 log_init(1, LOG_DAEMON);
398 log_setverbose(1);
400 while ((ch = getopt(argc, argv, "B:b:dt:v")) != -1) {
401 switch (ch) {
402 case 'B':
403 ssh_tflag = optarg;
404 parse_sshaddr();
405 break;
406 case 'b':
407 addr = optarg;
408 break;
409 case 'd':
410 debug = 1;
411 break;
412 case 't':
413 timeout.tv_sec = strtonum(optarg, 0, INT_MAX, &errstr);
414 if (errstr != NULL)
415 fatalx("timeout is %s: %s", errstr, optarg);
416 break;
417 case 'v':
418 verbose = 1;
419 break;
420 default:
421 usage();
424 argc -= optind;
425 argv += optind;
427 if (argc != 1 || addr == NULL || ssh_tflag == NULL)
428 usage();
430 ssh_dest = argv[0];
432 bind_socket();
434 log_init(debug, LOG_DAEMON);
435 log_setverbose(verbose);
437 if (!debug)
438 daemon(1, 0);
440 signal(SIGPIPE, SIG_IGN);
442 event_init();
444 /* initialize the timer */
445 evtimer_set(&timeoutev, killing_time, NULL);
447 signal_set(&sighupev, SIGHUP, sig_handler, NULL);
448 signal_set(&sigintev, SIGINT, sig_handler, NULL);
449 signal_set(&sigtermev, SIGTERM, sig_handler, NULL);
450 signal_set(&sigchldev, SIGCHLD, sig_handler, NULL);
451 #ifdef SIGINFO
452 signal_set(&siginfoev, SIGINFO, sig_handler, NULL);
453 #else
454 signal_set(&siginfoev, SIGUSR1, sig_handler, NULL);
455 #endif
457 signal_add(&sighupev, NULL);
458 signal_add(&sigintev, NULL);
459 signal_add(&sigtermev, NULL);
460 signal_add(&sigchldev, NULL);
461 signal_add(&siginfoev, NULL);
463 for (i = 0; i < nsock; ++i) {
464 event_set(&sockev[i], socks[i], EV_READ|EV_PERSIST,
465 do_accept, NULL);
466 event_add(&sockev[i], NULL);
469 if (unveil(SSH_PROG, "x") == -1)
470 fatal("unveil(%s)", SSH_PROG);
472 /*
473 * dns, inet: bind the socket and connect to the childs.
474 * proc, exec: execute ssh on demand.
475 */
476 if (pledge("stdio dns inet proc exec", NULL) == -1)
477 fatal("pledge");
479 log_info("starting");
480 event_dispatch();
482 if (ssh_pid != -1)
483 kill(ssh_pid, SIGINT);
485 return 0;