-
Notifications
You must be signed in to change notification settings - Fork 30
/
netcat.c
1371 lines (1186 loc) · 35.2 KB
/
netcat.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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Netcat 2.0
A damn useful little "backend" utility begun 950915 or thereabouts,
as *Hobbit*'s first real stab at some sockets programming. Something that
should have and indeed may have existed ten years ago, but never became a
standard Unix utility. IMHO, "nc" could take its place right next to cat,
cp, rm, mv, dd, ls, and all those other cryptic and Unix-like things.
Read the README for the whole story, doc, applications, etc.
Layout:
configury:
handy defines:
globals:
cmd-flag globals:
support routines:
readwrite poll loop:
main:
bluesky:
RAW mode
parse ranges of IP address as well as ports, perhaps (subnet masks?)
*/
/* configury: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <stdarg.h>
#include <limits.h>
#include <setjmp.h>
#include <unistd.h>
#include <sys/socket.h> /* basics, SO_ and AF_ defs, sockaddr, ... */
#include <netinet/in.h> /* sockaddr_in, htons, in_addr */
#include <poll.h>
#include <netdb.h> /* hostent, gethostby*, getservby* */
#include <arpa/inet.h> /* inet_ntoa */
#include <arpa/telnet.h> /* IAC, DO, DONT, WILL, WONT */
#ifdef HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif
#ifndef HAVE_STRCHR
#define strchr index
#define strrchr rindex
#endif
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h> /* O_WRONLY et al */
#endif
#ifdef HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
#ifndef SO_REUSEPORT
#define SO_REUSEPORT SO_REUSEADDR
#endif
#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#endif
#ifndef NI_MAXSERV
#define NI_MAXSERV 32
#endif
#ifndef HAVE_SIGSETJMP
#define sigjmp_buf jmp_buf
#define sigsetjmp(buf, n) setjmp(buf)
#define siglongjmp longjmp
#endif
/* Aficionados of ?rand48() should realize that this doesn't need *strong*
random numbers just to mix up port numbers!! */
#ifndef HAVE_RANDOM
#define srandom srand
#define random rand
#endif /* !HAVE_RANDOM */
/* handy stuff: */
#define SLEAZE_PORT "31337"
#define BUF_SIZE 8192
#define ADDR_STRING(x) ((x) ? (x) : "any")
/* globals: */
/* getaddrinfo mode */
struct addrinfo gai_hints;
/* getaddrinfo error */
int gai_errno = 0;
/* sigjmp_buf for timeouts */
sigjmp_buf jbuf;
/* Socket descriptor */
int sock_fd = -1;
/* Hexdump output file descriptor */
int dump_fd = -1; /* hexdump output fd */
unsigned short port_scan = 0; /* zero if scanning */
unsigned int wrote_out = 0; /* total stdout bytes */
unsigned int wrote_net = 0; /* total net bytes */
/* global cmd flags: */
int o_interval = -1;
int o_broadcast = 0;
int o_quit = -1;
int o_numeric = 0;
int o_proto = IPPROTO_TCP;
int o_verbose = 0;
int o_wait = 0;
int o_telnet = 0;
int o_random = 0;
int o_nostdin = 0;
/* Prototypes. */
static int test_udp_port (int fd, char *where);
static void va_msg (int verbosity, const char *str, va_list ap);
static void debug_msg (const char *str, ...);
static void msg (int verbosity, const char *str, ...);
static void verbose_msg (const char *str, ...);
static void write_byte_counts ();
static RETSIGTYPE timeout_handler (int sig);
static void set_timeout (int secs);
static int find_nl (char *buf, int n);
static unsigned short *make_port_block (int lo, int hi);
static void exec_child_pr00gie (char *pr00gie, int shell);
static int bind_socket (char *local_addr, char *local_port, int proto);
static int connect_socket (char *remote_addr, char *remote_port,
char *local_addr, char *local_port, int proto);
static int connect_server_socket (char *remote_addr, char *remote_port,
char *local_addr, char *local_port, int proto);
static int test_udp_port (int fd, char *host);
static void hex_dump (char dir, int obc, char *buf, int bc);
static int answer_telnet_negotiation (char *buf, int size);
static int socket_loop ();
static void usage (int exit_code);
int main (int argc, char **argv);
#define FROM_NET(buf, n) \
do \
{ \
debug_msg ("wrote %d to stdout", n); \
if (dump_fd != -1) \
hex_dump ('>', wrote_out, (char *)buf, n); \
wrote_out += n; \
} \
while(0)
#define FROM_USER(buf, n) \
do \
{ \
debug_msg ("wrote %d to net", n); \
if (dump_fd != -1) \
hex_dump ('<', wrote_net, (char *)buf, n); \
wrote_net += n; \
} \
while(0)
/* support routines -- the bulk of this thing. */
void
va_msg (int verbosity, const char *str, va_list ap)
{
if (o_verbose < verbosity)
return;
#ifndef HAVE_VPRINTF
# ifndef HAVE_DOPRNT
fputs (str, stderr); /* not great, but perhaps better than nothing... */
# else /* HAVE_DOPRNT */
_doprnt (str, &ap, stderr);
# endif /* HAVE_DOPRNT */
#else /* HAVE_VFPRINTF */
vfprintf (stderr, str, ap);
#endif /* HAVE_VFPRINTF */
putc ('\n', stderr);
/* Check if host-lookup variety of error */
if (gai_errno && gai_errno != EAI_SYSTEM)
{
fprintf (stderr, "netcat: %s\n", gai_strerror (gai_errno));
gai_errno = 0;
}
if (errno)
{
perror ("netcat");
errno = 0;
}
fflush (stderr);
}
void
debug_msg (const char *str, ...)
{
va_list ap;
va_start (ap, str);
va_msg (3, str, ap);
va_end (ap);
}
void
msg (int verbosity, const char *str, ...)
{
va_list ap;
va_start (ap, str);
va_msg (verbosity, str, ap);
va_end (ap);
}
void
verbose_msg (const char *str, ...)
{
va_list ap;
va_start (ap, str);
va_msg (1, str, ap);
va_end (ap);
}
/* bail :
error-exit handler, callable from anywhere */
void
#ifdef __GNUC__
__attribute__ ((noreturn))
#endif
bail (const char *str, ...)
{
va_list ap;
va_start (ap, str);
va_msg (0, str, ap);
va_end (ap);
if (sock_fd > -1)
close (sock_fd);
exit (1);
} /* bail */
/* write_byte_counts:
called on exit, but outputs only if very verbose */
void
write_byte_counts ()
{
errno = 0;
if (wrote_net || wrote_out)
msg (2, "sent %d, rcvd %d", wrote_net, wrote_out);
}
/* timeout and other signal handling cruft */
RETSIGTYPE
timeout_handler (int sig)
{
signal (sig, SIG_IGN);
alarm (0);
errno = ETIMEDOUT; /* fake it */
siglongjmp (jbuf, 1);
}
/* set_timeout :
set the timer. Zero secs arg means reset */
void
set_timeout (int secs)
{
if (secs == 0)
/* reset */
signal (SIGALRM, SIG_IGN);
else
signal (SIGALRM, timeout_handler);
alarm (secs);
} /* set_timeout */
/* find_nl :
find the next newline in a buffer; return inclusive size of that "line",
or the entire buffer size, so the caller knows how much to then write(). */
int
find_nl (char *buf, int n)
{
char *p;
int x;
for (p = buf, x = n; x > 0; x--, p++)
if (*p == '\n')
{
debug_msg ("find_nl returning %d", p - buf + 1);
return (p - buf + 1);
}
debug_msg ("find_nl returning whole thing: %d", n);
return (n);
}
/* make_port_block :
make a list of possibly randomized ports, from LO to HI. */
unsigned short *
make_port_block (int lo, int hi)
{
unsigned short x, y, c;
unsigned short *block;
block = (unsigned short *) malloc (sizeof (short) * (hi - lo + 1));
if (!block)
bail ("malloc for %d ports failed", hi - lo + 1);
/* This is actually a hack; since ports are tested downwards, we also
fill the array downwards. */
for (x = lo; x <= hi; x++)
block[hi - x] = x;
/* Swap 'em randomly. */
if (o_random)
for (x = lo; x < hi; x++)
{
y = random () % (hi - x + 1);
c = block[x - lo];
block[x - lo] = block[x - lo + y];
block[x - lo + y] = c;
}
return block;
}
/* exec_child_pr00gie :
fiddle all the file descriptors around, and hand off to another prog. Sort
of like a one-off "poor man's inetd". This is the only section of code
that would be security-critical: use at your own hairy risk, if you leave
shells lying around behind open listening ports you deserve to lose!! */
void
#ifdef __GNUC__
__attribute__ ((noreturn))
#endif
exec_child_pr00gie (char *pr00gie, int shell)
{
char *p;
/* the precise order of fiddlage seems to be crucial; this is swiped
directly out of "inetd". */
dup2 (sock_fd, 0);
close (sock_fd);
dup2 (0, 1);
dup2 (0, 2);
sock_fd = 0;
if (shell)
{
debug_msg ("gonna exec %s using /bin/sh...", pr00gie);
execl ("/bin/sh", "sh", "-c", pr00gie, NULL);
}
else
{
/* Prepare a shorter argv[0] */
p = strrchr (pr00gie, '/');
if (p)
p++;
else
p = pr00gie;
debug_msg ("gonna exec %s as %s...", pr00gie, p);
execl (pr00gie, p, NULL);
}
bail ("failed to exec %s", pr00gie);
}
/* bind_socket :
do all the socket stuff, and return an fd for one of
an open outbound TCP connection
a UDP stub-socket thingie
with appropriate socket options set up if we wanted source-routing, or
an unconnected TCP or UDP socket to listen on.
Examines various global o_blah flags to figure out what-all to do. */
int
bind_socket (char *local_addr, char *local_port, int proto)
{
struct addrinfo *wherefrom;
int fd;
int rc;
int x;
if (!local_addr && gai_hints.ai_family == AF_UNSPEC)
gai_hints.ai_family = AF_INET;
gai_hints.ai_socktype = proto == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
gai_hints.ai_protocol = 0;
gai_hints.ai_flags |= AI_PASSIVE;
if (local_addr || local_port)
{
if ((gai_errno =
getaddrinfo (local_addr, local_port, &gai_hints, &wherefrom)))
bail ("cannot resolve %s:%s", ADDR_STRING (local_addr),
ADDR_STRING (local_port));
else
errno = 0;
}
else
wherefrom = &gai_hints;
/* grab a socket; set opts. */
errno = 0;
fd = socket (wherefrom->ai_family, wherefrom->ai_socktype, 0);
if (fd < 0)
bail ("Can't get socket");
x = 1;
rc = setsockopt (fd, SOL_SOCKET, SO_REUSEPORT, &x, sizeof (x));
if (rc == -1)
verbose_msg ("failed to set SO_REUSEPORT");
if (proto == IPPROTO_TCP)
{
rc = setsockopt (fd, SOL_SOCKET, SO_OOBINLINE, &x, sizeof (x));
if (rc == -1)
verbose_msg ("failed to set SO_OOBINLINE");
}
else
{
rc = setsockopt (fd, SOL_SOCKET, SO_BROADCAST, &o_broadcast, sizeof (o_broadcast));
if (rc == -1)
verbose_msg ("failed to %s SO_BROADCAST", o_broadcast ? "set" : "reset");
}
#if 0
/* If you want to screw with RCVBUF/SNDBUF, do it here. Liudvikas Bukys at
Rochester sent this example, which would involve YET MORE options and is
just archived here in case you want to mess with it. o_xxxbuf are global
integers set in main() getopt loop, and check for rc == 0 afterward. */
rc = setsockopt (fd, SOL_SOCKET, SO_RCVBUF, &o_rcvbuf, sizeof o_rcvbuf);
rc = setsockopt (fd, SOL_SOCKET, SO_SNDBUF, &o_sndbuf, sizeof o_sndbuf);
#endif
rc = 0;
if (local_addr || local_port)
{
errno = 0;
rc = bind (fd, wherefrom->ai_addr, wherefrom->ai_addrlen);
if (rc >= 0)
verbose_msg ("local address %s:%s open", ADDR_STRING (local_addr),
ADDR_STRING (local_port));
freeaddrinfo (wherefrom);
}
if (rc < 0)
bail ("Can't grab %s:%s with bind", ADDR_STRING (local_addr),
ADDR_STRING (local_port));
return (fd);
}
void
get_sock_name (struct sockaddr *sa, int salen, char *host, char *serv,
char *name, char *default_name, char *default_serv)
{
int flags = o_proto == IPPROTO_UDP ? NI_DGRAM : 0;
gai_errno = getnameinfo (sa, salen, host, NI_MAXHOST, serv, NI_MAXSERV,
flags | NI_NUMERICSERV | NI_NUMERICHOST);
errno = 0;
if (gai_errno)
{
strcpy (host, ADDR_STRING (default_name));
strcpy (serv, ADDR_STRING (default_serv));
}
/* IPv6 host addresses are printed in brackets when they are followed by
a port -- which is always true in netcat. */
if (strchr (host, ':'))
{
int len = strlen (host);
memmove (host + 1, host, len + 1);
host[0] = '[';
host[len+1] = ']';
host[len+2] = '\0';
}
if (name && !o_numeric)
{
gai_errno = getnameinfo (sa, salen, name, NI_MAXHOST, NULL, 0,
flags | NI_NAMEREQD);
if (gai_errno)
strcpy (name, ADDR_STRING (default_name));
}
errno = gai_errno = 0;
}
/* connect_socket :
do all the socket stuff, and return an fd for one of
an open outbound TCP connection
a UDP stub-socket thingie
with appropriate socket options set up if we wanted source-routing, or
an unconnected TCP or UDP socket to listen on.
Examines various global o_blah flags to figure out what-all to do. */
int
connect_socket (char *remote_addr, char *remote_port,
char *local_addr, char *local_port, int proto)
{
char host[NI_MAXHOST+1], serv[NI_MAXSERV+1], remote_host_name[NI_MAXHOST+1];
struct addrinfo *whereto;
struct sockaddr sai_remote;
int fd, rc;
socklen_t x;
errno = 0;
gai_hints.ai_socktype = proto == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
gai_hints.ai_protocol = proto;
gai_hints.ai_flags &= ~AI_PASSIVE;
/* Do our getaddrinfo before opening the socket, so that ai_family is
set to AF_INET6 if necessary. */
if ((gai_errno =
getaddrinfo (remote_addr, remote_port, &gai_hints, &whereto)))
bail ("cannot resolve %s:%s", ADDR_STRING (remote_addr),
ADDR_STRING (remote_port));
else
errno = 0;
/* grab a socket; set opts. */
rc = fd = bind_socket (local_addr, local_port, proto);
if (fd >= 0)
{
/* wrap connect inside a timer, and hit it */
if (sigsetjmp (jbuf, 1) == 0)
{
set_timeout (o_wait);
rc = connect (fd, whereto->ai_addr, whereto->ai_addrlen);
}
else
rc = -1;
set_timeout (0);
}
if (rc < 0 ||
(o_nostdin && proto == IPPROTO_UDP && !test_udp_port (fd, remote_addr)))
{
/* Clean up junked socket FD!! */
if (fd >= 0)
close (fd);
fd = -1;
sai_remote = *whereto->ai_addr;
x = whereto->ai_addrlen;
}
else
{
x = sizeof (struct sockaddr);
rc = getpeername (fd, (struct sockaddr *) &sai_remote, &x);
if (rc < 0)
bail ("cannot retrieve peer socket address");
}
get_sock_name (&sai_remote, x, host, serv, remote_host_name,
remote_addr, remote_port);
if (fd == -1)
{
/* if we're scanning at a "one -v" verbosity level, don't print refusals.
Give it another -v if you want to see everything. But if we're not
scanning, we always want an error to be printed for refused connects. */
int level = !port_scan || errno != ECONNREFUSED ? 0 : 2;
if (o_numeric)
msg (level, "cannot connect to %s:%s", host, serv);
else
msg (level, "cannot connect to %s:%s (%s)", host, serv,
remote_host_name);
}
else
{
if (o_numeric)
verbose_msg ("%s:%s open", host, serv);
else
verbose_msg ("%s:%s (%s) open", host, serv, remote_host_name);
}
freeaddrinfo (whereto);
return (fd);
}
/* connect_server_socket :
just like connect_socket, and in fact both call bind_socket, but listens for
incoming and returns an open connection *from* someplace. If we were
given host/port args, any connections from elsewhere are rejected. This
in conjunction with local-address binding should limit things nicely... */
int
connect_server_socket (char *remote_addr, char *remote_port,
char *local_addr, char *local_port, int proto)
{
struct addrinfo *whereto;
struct sockaddr sai_remote, sai_local;
char remote_host[NI_MAXHOST+1], remote_serv[NI_MAXSERV+1];
char remote_host_name[NI_MAXHOST+1];
char host[NI_MAXHOST+1], serv[NI_MAXSERV+1], local_host_name[NI_MAXHOST+1];
int fd;
int rc = 0;
socklen_t x;
errno = 0;
/* Pass everything off to bind_socket */
if ((fd = bind_socket (local_addr, local_port, proto)) < 0)
return (fd);
gai_hints.ai_socktype = proto == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
gai_hints.ai_protocol = proto;
gai_hints.ai_flags &= ~AI_PASSIVE;
if (proto == IPPROTO_UDP)
{
if (!local_port)
bail ("UDP listen needs -p arg");
}
else
{
rc = listen (fd, 1);
if (rc < 0)
bail ("cannot open passive socket");
}
if (o_verbose || !local_port)
{
x = sizeof (struct sockaddr);
rc = getsockname (fd, (struct sockaddr *) &sai_local, &x);
if (rc < 0)
verbose_msg ("local getsockname failed");
else
{
get_sock_name (&sai_local, x, host, serv, NULL,
ADDR_STRING (local_addr), ADDR_STRING (local_port));
errno = 0;
verbose_msg ("listening on %s:%s...", host, serv);
}
}
if (remote_addr || remote_port)
{
if ((gai_errno =
getaddrinfo (remote_addr, remote_port, &gai_hints, &whereto)))
bail ("cannot resolve %s:%s", ADDR_STRING (remote_addr),
ADDR_STRING (remote_port));
else
errno = 0;
if (proto == IPPROTO_UDP)
rc = connect (fd, whereto->ai_addr, whereto->ai_addrlen);
}
else
{
/* UDP is a speeeeecial case -- we have to do I/O *and* get the calling
party's particulars, listen() and accept() don't apply. However,
recvfrom/PEEK is enough to tell us something came in, and we can set
things up so straight read/write actually does work after all. Yow. */
if (proto == IPPROTO_UDP)
{
struct sockaddr whozis;
socklen_t x;
/* Do timeout for initial connect */
if (sigsetjmp (jbuf, 1) == 0)
{
char small_buf[32];
set_timeout (o_wait);
/* Prepare return value for recvfrom */
x = sizeof (whozis);
rc = recvfrom (fd, small_buf, 32, MSG_PEEK, &whozis, &x);
debug_msg ("connect_server_socket: recvfrom/connect, read %d bytes", rc);
}
else
bail ("no connection");
set_timeout (0);
rc = connect (fd, &whozis, x);
}
}
if (proto == IPPROTO_TCP)
{
/* Fall here for TCP. */
/* Prepare parameters and return value for accept. */
if (remote_addr || remote_port)
{
x = whereto->ai_addrlen;
sai_remote = *whereto->ai_addr;
}
else
{
x = sizeof (sai_remote);
memset (&sai_remote, 0, x);
}
if (sigsetjmp (jbuf, 1) == 0)
{
/* Wrap this in a timer, too. */
set_timeout (o_wait);
rc = accept (fd, (struct sockaddr *) &sai_remote, &x);
}
else
bail ("no connection");
set_timeout (0);
/* Dump the old socket, here's our new one. */
close (fd);
fd = rc;
}
if (rc < 0)
bail ("no connection"); /* bail out if any errors so far */
/* find out what address the connection was *to* on our end, in case we're
doing a listen-on-any on a multihomed machine. This allows one to
offer different services via different alias addresses, such as with
FTP virtual hosts. */
x = sizeof (struct sockaddr);
rc = getpeername (fd, (struct sockaddr *) &sai_remote, &x);
if (rc < 0)
verbose_msg ("getpeername on active socket failed");
get_sock_name (&sai_remote, x, remote_host, remote_serv, remote_host_name,
remote_addr, remote_port);
x = sizeof (struct sockaddr);
rc = getsockname (fd, (struct sockaddr *) &sai_local, &x);
if (rc < 0)
verbose_msg ("getsockname on active socket failed");
get_sock_name (&sai_local, x, host, serv, local_host_name,
local_addr, local_port);
if (o_numeric)
verbose_msg ("connect to %s:%s from %s:%s",
remote_host, remote_serv, host, serv);
else
verbose_msg ("connect to %s:%s (%s) from %s:%s (%s)",
remote_host, remote_serv, remote_host_name,
host, serv, local_host_name);
if (remote_addr || remote_port)
freeaddrinfo (whereto);
return (fd);
}
/* test_udp_port :
fire a couple of packets at a UDP target port, just to see if it's really
there. On BSD kernels, ICMP host/port-unreachable errors get delivered to
our socket as ECONNREFUSED write errors. On SV kernels, we lose; we'll have
to collect and analyze raw ICMP ourselves a la satan's probe_udp_ports
backend. Guess where one could swipe the appropriate code from...
Use the time delay between writes if given, otherwise use the "tcp ping"
trick for getting the RTT. [I got that idea from pluvius, and warped it.]
Return either the original fd, or clean up and return -1. */
int
test_udp_port (int fd, char *host)
{
int rc;
char c = 0;
rc = write (fd, &c, 1);
if (rc != 1)
verbose_msg ("test_udp_port first write failed");
if (o_wait)
sleep (o_wait);
else
{
/* use the tcp-ping trick: try connecting to a normally refused port, which
causes us to block for the time that SYN gets there and RST gets back.
Not completely reliable, but it *does* mostly work. */
/* Set a temporary connect timeout, so packet filtration doesnt cause
us to hang forever, and hit it */
o_wait = 5;
rc = connect_socket (host, SLEAZE_PORT, 0, 0, IPPROTO_TCP);
o_wait = 0;
/* Close if it *did* open. */
if (rc > 0)
close (rc);
}
errno = 0;
rc = write (fd, &c, 1);
return (rc == 1) ? fd : -1;
}
/* hex_dump :
Hexdump bytes shoveled either way to a running logfile, in the format:
D offset - - - - --- 16 bytes --- - - - - # .... ascii .....
where "dir" sets the direction indicator, D:
and "buf" and "n" are data-block and length. If the current block generates
a partial line, so be it; we *want* that lockstep indication of who sent
what when. Adapted from dgaudet's original example -- but must be ripping
*fast*, since we don't want to be too disk-bound... */
void
hex_dump (char dir, int obc, char *buf, int bc)
{
static char hexnibs[] = "0123456789abcdef";
static char stage[100]; /* line buffer */
char *op; /* out hex-dump ptr */
char *a; /* out asc-dump ptr */
int x;
stage[0] = dir;
stage[1] = ' ';
stage[10] = ' ';
stage[59] = '|';
stage[60] = ' ';
while (bc > 0)
{
/* write address */
for (x = 0, op = &stage[9]; x < 8 * sizeof (obc); x += 4)
*op-- = hexnibs[(int) ((obc >> x) & 0x0f)];
/* write data */
for (x = 16, op = &stage[11], a = &stage[61];
bc && x; bc--, x--, buf++, obc++)
{
unsigned char ch = *buf;
*op++ = hexnibs[ch >> 4];
*op++ = hexnibs[ch & 15];
*op++ = ' ';
*a++ = ((*buf >= ' ') && (*buf < 127)) ? *buf : '.';
}
/* write filler spaces */
while (x--)
{
*op++ = ' ';
*op++ = ' ';
*op++ = ' ';
}
*a = '\n';
x = write (dump_fd, stage, a + 1 - stage);
if (x < 0)
bail ("dump_fd write err");
}
}
/* answer_telnet_negotiation :
Answer anything that looks like telnet negotiation with don't/won't.
This doesn't modify any data buffers -- it just puts that onto
the outgoing stream. Idea and codebase from Mudge@l0pht.com. */
int
answer_telnet_negotiation (char *buf, int size)
{
unsigned char *p, *end, *dest;
dest = p = memchr (buf, IAC, size);
if (!p)
return size;
for (end = (unsigned char *) buf + size; p < end;)
{
if (*p != IAC) /* check for TIAC */
{
*dest++ = *p++;
continue;
}
FROM_NET (p, 3);
if ((p[1] == WILL) || (p[1] == WONT))
p[1] = DONT;
else if ((p[1] == DO) || (p[1] == DONT))
p[1] = WONT;
else
continue;
FROM_USER (p, 3);
write (sock_fd, p, 3);
p += 3;
}
return dest - (unsigned char *)buf;
}
/* socket_loop :
handle stdin/stdout/network I/O. Bwahaha!! -- the poll loop from hell.
In this instance, return what might become our exit status. */
int
socket_loop ()
{
static char buf_stdin[BUF_SIZE]; /* data buffers */
static char buf_socket[BUF_SIZE];
static int saved_count = 0; /* stdin-buffer size for multi-mode */
char *out_p = buf_stdin; /* stdin buf ptr */
char *in_p = buf_socket; /* net-in buf ptr */
unsigned int outgoing = 0;
unsigned int incoming = 0;
struct pollfd pfd[2]; /* for poll loop */
int rc;
/* Setup network fd */
pfd[0].fd = sock_fd;
pfd[0].events = POLLIN;
/* Setup stdin fd */
pfd[1].fd = 0;
pfd[1].events = POLLIN;
/* clear from sleep, close, whatever */
errno = 0;
/* and now the big ol' poll loop ... */
while (1)
{ /* i.e. till the *net* closes! */
pfd[0].revents = 0;
pfd[1].revents = 0;
if (out_p == buf_stdin && saved_count)
{
/* We are at the beginning of a fake stdin; disable reading further
stdin junk from stdin and use no timeout because we do have something
to send. */
pfd[1].fd = -1;
outgoing = saved_count;
rc = poll (pfd, 1, 0);
}
else
rc = poll (pfd, 2, o_wait ? o_wait * 1000 : -1);
/* Always check for errors */
if (rc < 0 && errno != EINTR)
{
verbose_msg ("error in poll");
close (sock_fd);
sock_fd = -1;
return (-1);
}
/* if we have a timeout and we haven't heard anything during that
time, assume the net is dead and be done with it. But it is not
an error. */
if (rc == 0)
{
msg (2, "net timeout");
break;
}
/* if o_interval is set, or if we're scanning, there's already stuff in the
stdin buffer, so don't read unless we really need more input.
Note: if scanning, then pfd[1].revents will always be zero, so we never
read anymore after being done with the first port! */
if (!outgoing
&& (pfd[1].revents & (POLLIN | POLLERR)) == POLLIN)
{
debug_msg ("reading from stdin up to %d bytes", buf_stdin + BUF_SIZE - out_p);
outgoing = read (0, out_p, buf_stdin + BUF_SIZE - out_p);
/* special case for multi-mode -- we'll want to send this one buffer to
every open TCP port or every UDP attempt, so save its size */
if (port_scan)
saved_count += outgoing;
}
/* If there was an error, or if we did not read anything, shut down this
side of the socket, and possibly quit depending on the -q option. */
if ((pfd[1].revents & (POLLIN | POLLERR | POLLHUP)) && !outgoing)
{
pfd[1].fd = -1;
shutdown (sock_fd, 1);
if (o_quit >= 0)
{