-
Notifications
You must be signed in to change notification settings - Fork 1
/
sshdrill.c
589 lines (517 loc) · 12.5 KB
/
sshdrill.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/*
* Copyright (c) 2015 Marco Pfatschbacher <[email protected]>
*
* 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.
*
* tty handling code taken from script(1)
*
* Copyright (c) 1980, 1992, 1993
* The Regents of the University of California. All rights reserved.
* Copyright (c) 2001 Theo de Raadt
*
* 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 <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <errno.h>
#include <fcntl.h>
#include <paths.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <ctype.h>
#include <err.h>
#ifdef HAVE_PTY_H
# include <pty.h>
#endif
#ifdef HAVE_UTIL_H
# include <util.h>
#endif
#ifdef HAVE_UTMP_H
# include <utmp.h>
#endif
#ifndef HAVE_STRLCPY
size_t strlcpy(char *dst, const char *src, size_t siz);
#endif
#define ESCAPE_CHAR '~'
#define ESCAPE_STR "~"
#define MAX_SSH_DEPTH 6
#define PROGNAME "sshdrill"
#define PROMPT "\r\nsshdrill> "
int master, slave;
volatile sig_atomic_t child;
struct termios tt;
struct termios rtt;
int runshell = 0;
volatile sig_atomic_t dead;
volatile sig_atomic_t sigdeadstatus;
volatile sig_atomic_t flush;
void done(int, int);
void execcmd(char *[]);
void dooutput(void);
void fail(void);
void finish(int);
void handlesigwinch(int);
int scan_for_escape(ssize_t, char*);
void command_prompt(void);
int setup_fwding(int, char *);
ssize_t do_write(int, char *, ssize_t);
int wait_for_str(char *);
int prepare_fwds(char *, char *, char *, char *);
void poke_through(char *, char *, char *, char *);
int
main(int argc, char *argv[])
{
struct sigaction sa;
struct winsize win;
char ibuf[BUFSIZ];
char obuf[BUFSIZ];
ssize_t cc, off;
fd_set rfdset;
int ret;
/* If not interactive, just exec ssh */
if (!isatty(STDIN_FILENO))
execvp("ssh", argv);
if (argc == 1)
runshell = 1;
(void)tcgetattr(STDIN_FILENO, &tt);
(void)ioctl(STDIN_FILENO, TIOCGWINSZ, &win);
if (openpty(&master, &slave, NULL, &tt, &win) == -1)
err(1, "openpty");
rtt = tt;
cfmakeraw(&rtt);
rtt.c_lflag &= ~ECHO;
(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
bzero(&sa, sizeof sa);
sigemptyset(&sa.sa_mask);
sa.sa_handler = finish;
(void)sigaction(SIGCHLD, &sa, NULL);
sa.sa_handler = handlesigwinch;
sa.sa_flags = SA_RESTART;
(void)sigaction(SIGWINCH, &sa, NULL);
child = fork();
if (child < 0) {
warn("fork");
fail();
}
if (child == 0) {
execcmd(argv);
}
for (;;) {
FD_ZERO(&rfdset);
FD_SET(STDIN_FILENO, &rfdset);
FD_SET(master, &rfdset);
if (dead)
break;
ret = select(master + 1, &rfdset, NULL, NULL, NULL);
if (ret < 0) {
if (errno == EINTR)
continue;
else
err(1, "select");
}
if (FD_ISSET(STDIN_FILENO, &rfdset)) {
cc = read(STDIN_FILENO, ibuf, BUFSIZ);
if (cc == -1 && errno == EINTR)
continue;
if (cc <= 0)
break;
if (scan_for_escape(cc, ibuf)) {
off = 1; /* jump over ~ */
} else {
off = 0;
}
do_write(master, ibuf + off, cc - off);
}
if (FD_ISSET(master, &rfdset)) {
cc = read(master, obuf, sizeof (obuf));
if (cc == -1 && errno == EINTR)
continue;
if (cc <= 0)
continue;
do_write(STDOUT_FILENO, obuf, cc);
}
}
done(sigdeadstatus, 0);
return 1; /* NOTREACHED */
}
void
command_prompt(void)
{
char orig_fwd[BUFSIZ], first_fwd[BUFSIZ];
char tunnel_fwd[BUFSIZ], last_fwd[BUFSIZ];
ssize_t nr;
char ch, *p, *fwd, buf[BUFSIZ];
struct termios ptt;
ptt = tt;
ptt.c_lflag &= ~ISIG;
(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &ptt);
if (do_write(STDOUT_FILENO, PROMPT, strlen(PROMPT)) <= 0)
goto abort;
p = buf;
while ((nr = read(STDIN_FILENO, &ch, 1)) == 1 &&
ch != '\n' && ch != '\r') {
if (p < buf + (sizeof(buf) - 1)) {
*p++ = ch;
}
}
*p = '\0';
p = buf;
while (isspace((u_char)*p))
p++;
if (*p == '\0')
goto abort;
if (*p == 'h' || *p == 'H' || *p == '?') {
char *help =
"\rCommands:\n"
" -L[bind_address:]port:host:hostport "
"Request local forward\n"
" -R[bind_address:]port:host:hostport "
"Request remote forward\n"
" -D[bind_address:]port "
"Request dynamic forward\n";
do_write(STDOUT_FILENO, help, strlen(help));
goto abort;
}
fwd = p;
snprintf(orig_fwd, BUFSIZ, "%s\r", fwd);
if (prepare_fwds(fwd, first_fwd, tunnel_fwd, last_fwd) == 0)
poke_through(orig_fwd, first_fwd, tunnel_fwd, last_fwd);
abort:
(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
}
int
prepare_fwds(char *cmd, char *first_fwd, char *tunnel_fwd, char *last_fwd)
{
char type, colcount, i;
char *s, *tok;
char buf[BUFSIZ], source[BUFSIZ], dest[BUFSIZ];
unsigned int lport;
s = cmd;
if (*s == '-')
s++; /* Skip cmdline '-', if any */
type = *s;
if (type != 'L' && type != 'R' && type != 'D')
goto parse_error;
s++;
if (type == 'D') {
strlcpy(source, s, BUFSIZ);
tok = s;
if ((tok = strchr(tok, ':')))
s = tok + 1;
if ((lport = strtoul(s, NULL, 10)) == 0)
goto parse_error;
snprintf(first_fwd, BUFSIZ, "-L%s:127.0.0.1:%u\r", source, lport);
snprintf(tunnel_fwd, BUFSIZ, "-L%u:127.0.0.1:%u\r", lport, lport);
snprintf(last_fwd, BUFSIZ, "-D:%u\r", lport);
return 0;
}
tok = s;
colcount = 0;
while ((tok = strchr(tok, ':'))) {
tok++;
colcount++;
}
if (colcount < 2 || colcount > 3)
goto parse_error;
strlcpy(source, s, BUFSIZ);
tok = s;
for (i = 0; i < colcount - 2; i++) {
tok = strchr(tok, ':');
tok++;
}
if (strlcpy(buf, tok, BUFSIZ) >= BUFSIZ)
goto parse_error;
tok = strchr(tok, ':');
*tok = '\0';
*(source + (tok - s)) = '\0';
if ((lport = strtoul(s, NULL, 10)) == 0)
goto parse_error;
strlcpy(dest, tok + 1, BUFSIZ);
if (type == 'L') {
snprintf(first_fwd, BUFSIZ, "-L%s:127.0.0.1:%u\r", source, lport);
snprintf(tunnel_fwd, BUFSIZ, "-L%u:127.0.0.1:%u\r", lport, lport);
snprintf(last_fwd, BUFSIZ, "-L%u:%s\r", lport, dest);
} else if (type == 'R') {
snprintf(first_fwd, BUFSIZ, "-R%u:%s\r", lport, dest);
snprintf(tunnel_fwd, BUFSIZ, "-R%u:127.0.0.1:%u\r", lport, lport);
snprintf(last_fwd, BUFSIZ, "-R%s:127.0.0.1:%u\r", source, lport);
}
return 0;
parse_error:
fprintf(stderr, "Invalid command.");
return 1;
}
#define SEND_PROBE 1
#define READ_PROBE 2
#define SEND_CLEANUP 3
#define PROBE_DONE 4
void
poke_through(char *orig_fwd, char *first_fwd, char *tunnel_fwd, char *last_fwd)
{
fd_set rfdset;
int ret;
char obuf[BUFSIZ];
struct timeval tout;
int state = SEND_PROBE;
int escapes_sent = 0;
int backspaces_sent = 0;
int escapes_rcvd = 0;
int nested_sshs = 0;
int current_hop;
tout.tv_sec = 1;
tout.tv_usec = 0;
for (;;) {
if (state == SEND_PROBE) {
if (do_write(master, ESCAPE_STR, 1)) {
if (++escapes_sent == MAX_SSH_DEPTH)
state = READ_PROBE;
}
}
if (state == READ_PROBE) {
FD_ZERO(&rfdset);
FD_SET(master, &rfdset);
ret = select(master + 1, &rfdset, NULL, NULL, &tout);
if (ret < 0 && errno != EINTR)
err(1, "select");
if (ret == 0) {
state = SEND_CLEANUP;
}
if (FD_ISSET(master, &rfdset)) {
ssize_t cc;
cc = read(master, obuf, sizeof (obuf));
if (cc == -1 && errno == EINTR)
continue;
if (cc <= 0)
break;
/*
* XXX Check for actual ~ chars
* This only works if there's no additional
* console output
*/
escapes_rcvd += cc;
}
}
if (state == SEND_CLEANUP) {
ssize_t n = write(master, "", 1);
if (n == -1 && errno != EAGAIN)
break;
if (n == 0)
break; /* skip writing */
if (n > 0) {
if (++backspaces_sent == MAX_SSH_DEPTH) {
state = PROBE_DONE;
break;
}
}
}
}
if (state == PROBE_DONE) {
nested_sshs = escapes_sent - escapes_rcvd;
if (nested_sshs < 0) {
fprintf(stderr, "Scan failure.\n");
return;
}
}
if (nested_sshs)
fprintf(stderr,
"Forwarding port through %d ssh sessions.\n", nested_sshs);
else
fprintf(stderr, "No ssh sessions found.\n");
for (current_hop = nested_sshs; current_hop; current_hop--) {
char *fwd;
if (current_hop == nested_sshs) {
if (do_write(master, "\r", 1) <= 0)
fprintf(stderr, "do_write error");
fwd = nested_sshs == 1 ? orig_fwd : last_fwd;
} else if (current_hop > 1)
fwd = tunnel_fwd;
else
fwd = first_fwd;
if (setup_fwding(current_hop, fwd))
fprintf(stderr, "setup_fwding error\n");
}
}
int
setup_fwding(int current_hop, char *fwd)
{
while (current_hop) {
if (do_write(master, "~", 1) > 0)
current_hop--;
else
return -1;
}
do_write(master, "C", 1);
if (wait_for_str("ssh>") != 0) {
fprintf(stderr, "timeout waiting for ssh> prompt\n");
return -1;
}
if (do_write(master, fwd, strlen(fwd)) > 0) {
wait_for_str(NULL);
return 0;
} else
return -1;
}
int
wait_for_str(char *searchstr)
{
fd_set rfdset;
int ret;
unsigned int cc = 0;
ssize_t n;
char obuf[BUFSIZ];
struct timeval tout;
tout.tv_sec = 1;
tout.tv_usec = 0;
while (cc < sizeof(obuf)) {
FD_ZERO(&rfdset);
FD_SET(master, &rfdset);
ret = select(master + 1, &rfdset, NULL, NULL, &tout);
if (ret < 0 && errno != EINTR)
err(1, "select");
if (ret == 0) {
return 1;
}
if (FD_ISSET(master, &rfdset)) {
n = read(master, obuf + cc, sizeof (obuf) - cc);
if (n == -1 && errno == EINTR)
continue;
do_write(STDOUT_FILENO, obuf + cc, n);
if (searchstr && strstr(obuf, searchstr))
return 0;
cc += n;
}
}
return 1;
}
ssize_t
do_write(int fd, char *buf, ssize_t cc) {
ssize_t off = 0;
ssize_t n = 0;
while (off < cc) {
n = write(fd, buf + off, cc - off);
if (n == -1 && errno != EAGAIN)
return n;
if (n == 0)
return n;
if (n > 0) {
off += n;
}
}
return off;
}
int
scan_for_escape(ssize_t cc, char *ibuf)
{
static int got_newline = 0;
static int got_escape = 0;
int i;
for (i = 0; i < cc; i++) {
if (got_escape && ibuf[i] == '.') {
done(255, 1);
} else if (got_escape && ibuf[i] == 'C') {
got_newline = got_escape = 0;
command_prompt();
return 1;
} else if (got_newline && ibuf[i] == ESCAPE_CHAR) {
got_escape = 1;
got_newline = 0;
return 1;
} else if (ibuf[i] == '\r') {
got_newline = 1;
got_escape = 0;
} else {
got_newline = got_escape = 0;
}
}
return 0;
}
/* ARGSUSED */
void
handlesigwinch(int signo)
{
int save_errno = errno;
struct winsize win;
pid_t pgrp;
if (ioctl(STDIN_FILENO, TIOCGWINSZ, &win) != -1) {
ioctl(slave, TIOCSWINSZ, &win);
if (ioctl(slave, TIOCGPGRP, &pgrp) != -1)
killpg(pgrp, SIGWINCH);
}
errno = save_errno;
}
/* ARGSUSED */
void
finish(int signo)
{
int save_errno = errno;
int status, e = 1;
pid_t pid;
while ((pid = wait3(&status, WNOHANG, 0)) > 0) {
if (pid == (pid_t)child) {
if (WIFEXITED(status))
e = WEXITSTATUS(status);
}
}
dead = 1;
sigdeadstatus = e;
errno = save_errno;
}
void
execcmd(char *argv[])
{
char *shell;
shell = getenv("SHELL");
if (shell == NULL)
shell = _PATH_BSHELL;
(void)close(master);
login_tty(slave);
if (runshell) {
fprintf(stderr, "Sshdrill shell session started.\n");
execl(shell, shell, "-il", (char *)NULL);
} else {
execvp("ssh", argv);
}
warn("%s", shell);
fail();
}
void
fail(void)
{
(void)kill(0, SIGTERM);
done(1, 0);
}
void
done(int eval, int msg)
{
(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
if (msg)
fprintf(stderr, "Terminating %s.\n", PROGNAME);
exit(eval);
}