1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2002 Dag-Erling Smørgrav
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer
12 * in this position and unchanged.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #include <sys/cdefs.h>
32 #include <sys/param.h>
33 #include <sys/file.h>
34 #include <sys/socket.h>
35 #include <sys/socketvar.h>
36 #include <sys/sysctl.h>
37 #include <sys/jail.h>
38 #include <sys/user.h>
39 #include <sys/queue.h>
40 #include <sys/tree.h>
41
42 #include <sys/un.h>
43 #include <sys/unpcb.h>
44
45 #include <net/route.h>
46
47 #include <netinet/in.h>
48 #include <netinet/in_pcb.h>
49 #include <netinet/sctp.h>
50 #include <netinet/tcp.h>
51 #define TCPSTATES /* load state names */
52 #include <netinet/tcp_fsm.h>
53 #include <netinet/tcp_seq.h>
54 #include <netinet/tcp_var.h>
55 #include <arpa/inet.h>
56
57 #include <capsicum_helpers.h>
58 #include <ctype.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <inttypes.h>
62 #include <jail.h>
63 #include <netdb.h>
64 #include <pwd.h>
65 #include <stdarg.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
70
71 #include <libcasper.h>
72 #include <casper/cap_net.h>
73 #include <casper/cap_netdb.h>
74 #include <casper/cap_pwd.h>
75 #include <casper/cap_sysctl.h>
76
77 #define sstosin(ss) ((struct sockaddr_in *)(ss))
78 #define sstosin6(ss) ((struct sockaddr_in6 *)(ss))
79 #define sstosun(ss) ((struct sockaddr_un *)(ss))
80 #define sstosa(ss) ((struct sockaddr *)(ss))
81
82 static int opt_4; /* Show IPv4 sockets */
83 static int opt_6; /* Show IPv6 sockets */
84 static int opt_C; /* Show congestion control */
85 static int opt_c; /* Show connected sockets */
86 static int opt_I; /* Show spliced socket addresses */
87 static int opt_i; /* Show inp_gencnt */
88 static int opt_j; /* Show specified jail */
89 static int opt_L; /* Don't show IPv4 or IPv6 loopback sockets */
90 static int opt_l; /* Show listening sockets */
91 static int opt_n; /* Don't resolve UIDs to user names */
92 static int opt_q; /* Don't show header */
93 static int opt_S; /* Show protocol stack if applicable */
94 static int opt_s; /* Show protocol state if applicable */
95 static int opt_U; /* Show remote UDP encapsulation port number */
96 static int opt_u; /* Show Unix domain sockets */
97 static int opt_v; /* Verbose mode */
98 static int opt_w; /* Wide print area for addresses */
99
100 /*
101 * Default protocols to use if no -P was defined.
102 */
103 static const char *default_protos[] = {"sctp", "tcp", "udp", "divert" };
104 static size_t default_numprotos = nitems(default_protos);
105
106 static int *protos; /* protocols to use */
107 static size_t numprotos; /* allocated size of protos[] */
108
109 static int *ports;
110
111 #define INT_BIT (sizeof(int)*CHAR_BIT)
112 #define SET_PORT(p) do { ports[p / INT_BIT] |= 1 << (p % INT_BIT); } while (0)
113 #define CHK_PORT(p) (ports[p / INT_BIT] & (1 << (p % INT_BIT)))
114
115 struct addr {
116 union {
117 struct sockaddr_storage address;
118 struct { /* unix(4) faddr */
119 kvaddr_t conn;
120 kvaddr_t firstref;
121 kvaddr_t nextref;
122 };
123 };
124 unsigned int encaps_port;
125 int state;
126 struct addr *next;
127 };
128
129 struct sock {
130 union {
131 RB_ENTRY(sock) socket_tree; /* tree of pcbs with socket */
132 SLIST_ENTRY(sock) socket_list; /* list of pcbs w/o socket */
133 };
134 RB_ENTRY(sock) pcb_tree;
135 kvaddr_t socket;
136 kvaddr_t pcb;
137 kvaddr_t splice_socket;
138 uint64_t inp_gencnt;
139 int shown;
140 int vflag;
141 int family;
142 int proto;
143 int state;
144 const char *protoname;
145 char stack[TCP_FUNCTION_NAME_LEN_MAX];
146 char cc[TCP_CA_NAME_MAX];
147 struct addr *laddr;
148 struct addr *faddr;
149 };
150
151 static RB_HEAD(socks_t, sock) socks = RB_INITIALIZER(&socks);
152 static int64_t
socket_compare(const struct sock * a,const struct sock * b)153 socket_compare(const struct sock *a, const struct sock *b)
154 {
155 return ((int64_t)(a->socket/2 - b->socket/2));
156 }
157 RB_GENERATE_STATIC(socks_t, sock, socket_tree, socket_compare);
158
159 static RB_HEAD(pcbs_t, sock) pcbs = RB_INITIALIZER(&pcbs);
160 static int64_t
pcb_compare(const struct sock * a,const struct sock * b)161 pcb_compare(const struct sock *a, const struct sock *b)
162 {
163 return ((int64_t)(a->pcb/2 - b->pcb/2));
164 }
165 RB_GENERATE_STATIC(pcbs_t, sock, pcb_tree, pcb_compare);
166
167 static SLIST_HEAD(, sock) nosocks = SLIST_HEAD_INITIALIZER(&nosocks);
168
169 struct file {
170 RB_ENTRY(file) file_tree;
171 kvaddr_t xf_data;
172 pid_t xf_pid;
173 uid_t xf_uid;
174 int xf_fd;
175 };
176
177 static RB_HEAD(files_t, file) ftree = RB_INITIALIZER(&ftree);
178 static int64_t
file_compare(const struct file * a,const struct file * b)179 file_compare(const struct file *a, const struct file *b)
180 {
181 return ((int64_t)(a->xf_data/2 - b->xf_data/2));
182 }
183 RB_GENERATE_STATIC(files_t, file, file_tree, file_compare);
184
185 static struct file *files;
186 static int nfiles;
187
188 static cap_channel_t *capnet;
189 static cap_channel_t *capnetdb;
190 static cap_channel_t *capsysctl;
191 static cap_channel_t *cappwd;
192
193 static int
xprintf(const char * fmt,...)194 xprintf(const char *fmt, ...)
195 {
196 va_list ap;
197 int len;
198
199 va_start(ap, fmt);
200 len = vprintf(fmt, ap);
201 va_end(ap);
202 if (len < 0)
203 err(1, "printf()");
204 return (len);
205 }
206
207 static bool
_check_ksize(size_t received_size,size_t expected_size,const char * struct_name)208 _check_ksize(size_t received_size, size_t expected_size, const char *struct_name)
209 {
210 if (received_size != expected_size) {
211 warnx("%s size mismatch: expected %zd, received %zd",
212 struct_name, expected_size, received_size);
213 return false;
214 }
215 return true;
216 }
217 #define check_ksize(_sz, _struct) (_check_ksize(_sz, sizeof(_struct), #_struct))
218
219 static void
_enforce_ksize(size_t received_size,size_t expected_size,const char * struct_name)220 _enforce_ksize(size_t received_size, size_t expected_size, const char *struct_name)
221 {
222 if (received_size != expected_size) {
223 errx(1, "fatal: struct %s size mismatch: expected %zd, received %zd",
224 struct_name, expected_size, received_size);
225 }
226 }
227 #define enforce_ksize(_sz, _struct) (_enforce_ksize(_sz, sizeof(_struct), #_struct))
228
229 static int
get_proto_type(const char * proto)230 get_proto_type(const char *proto)
231 {
232 struct protoent *pent;
233
234 if (strlen(proto) == 0)
235 return (0);
236 if (capnetdb != NULL)
237 pent = cap_getprotobyname(capnetdb, proto);
238 else
239 pent = getprotobyname(proto);
240 if (pent == NULL) {
241 warn("cap_getprotobyname");
242 return (-1);
243 }
244 return (pent->p_proto);
245 }
246
247 static void
init_protos(int num)248 init_protos(int num)
249 {
250 int proto_count = 0;
251
252 if (num > 0) {
253 proto_count = num;
254 } else {
255 /* Find the maximum number of possible protocols. */
256 while (getprotoent() != NULL)
257 proto_count++;
258 endprotoent();
259 }
260
261 if ((protos = malloc(sizeof(int) * proto_count)) == NULL)
262 err(1, "malloc");
263 numprotos = proto_count;
264 }
265
266 static int
parse_protos(char * protospec)267 parse_protos(char *protospec)
268 {
269 char *prot;
270 int proto_type, proto_index;
271
272 if (protospec == NULL)
273 return (-1);
274
275 init_protos(0);
276 proto_index = 0;
277 while ((prot = strsep(&protospec, ",")) != NULL) {
278 if (strlen(prot) == 0)
279 continue;
280 proto_type = get_proto_type(prot);
281 if (proto_type != -1)
282 protos[proto_index++] = proto_type;
283 }
284 numprotos = proto_index;
285 return (proto_index);
286 }
287
288 static void
parse_ports(const char * portspec)289 parse_ports(const char *portspec)
290 {
291 const char *p, *q;
292 int port, end;
293
294 if (ports == NULL)
295 if ((ports = calloc(65536 / INT_BIT, sizeof(int))) == NULL)
296 err(1, "calloc()");
297 p = portspec;
298 while (*p != '\0') {
299 if (!isdigit(*p))
300 errx(1, "syntax error in port range");
301 for (q = p; *q != '\0' && isdigit(*q); ++q)
302 /* nothing */ ;
303 for (port = 0; p < q; ++p)
304 port = port * 10 + digittoint(*p);
305 if (port < 0 || port > 65535)
306 errx(1, "invalid port number");
307 SET_PORT(port);
308 switch (*p) {
309 case '-':
310 ++p;
311 break;
312 case ',':
313 ++p;
314 /* fall through */
315 case '\0':
316 default:
317 continue;
318 }
319 for (q = p; *q != '\0' && isdigit(*q); ++q)
320 /* nothing */ ;
321 for (end = 0; p < q; ++p)
322 end = end * 10 + digittoint(*p);
323 if (end < port || end > 65535)
324 errx(1, "invalid port number");
325 while (port++ < end)
326 SET_PORT(port);
327 if (*p == ',')
328 ++p;
329 }
330 }
331
332 static void
sockaddr(struct sockaddr_storage * ss,int af,void * addr,int port)333 sockaddr(struct sockaddr_storage *ss, int af, void *addr, int port)
334 {
335 struct sockaddr_in *sin4;
336 struct sockaddr_in6 *sin6;
337
338 bzero(ss, sizeof(*ss));
339 switch (af) {
340 case AF_INET:
341 sin4 = sstosin(ss);
342 sin4->sin_len = sizeof(*sin4);
343 sin4->sin_family = af;
344 sin4->sin_port = port;
345 sin4->sin_addr = *(struct in_addr *)addr;
346 break;
347 case AF_INET6:
348 sin6 = sstosin6(ss);
349 sin6->sin6_len = sizeof(*sin6);
350 sin6->sin6_family = af;
351 sin6->sin6_port = port;
352 sin6->sin6_addr = *(struct in6_addr *)addr;
353 #define s6_addr16 __u6_addr.__u6_addr16
354 if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
355 sin6->sin6_scope_id =
356 ntohs(sin6->sin6_addr.s6_addr16[1]);
357 sin6->sin6_addr.s6_addr16[1] = 0;
358 }
359 break;
360 default:
361 abort();
362 }
363 }
364
365 static void
free_socket(struct sock * sock)366 free_socket(struct sock *sock)
367 {
368 struct addr *cur, *next;
369
370 cur = sock->laddr;
371 while (cur != NULL) {
372 next = cur->next;
373 free(cur);
374 cur = next;
375 }
376 cur = sock->faddr;
377 while (cur != NULL) {
378 next = cur->next;
379 free(cur);
380 cur = next;
381 }
382 free(sock);
383 }
384
385 static void
gather_sctp(void)386 gather_sctp(void)
387 {
388 struct sock *sock;
389 struct addr *laddr, *prev_laddr, *faddr, *prev_faddr;
390 struct xsctp_inpcb *xinpcb;
391 struct xsctp_tcb *xstcb;
392 struct xsctp_raddr *xraddr;
393 struct xsctp_laddr *xladdr;
394 const char *varname;
395 size_t len, offset;
396 char *buf;
397 int vflag;
398 int no_stcb, local_all_loopback, foreign_all_loopback;
399
400 vflag = 0;
401 if (opt_4)
402 vflag |= INP_IPV4;
403 if (opt_6)
404 vflag |= INP_IPV6;
405
406 varname = "net.inet.sctp.assoclist";
407 if (cap_sysctlbyname(capsysctl, varname, 0, &len, 0, 0) < 0) {
408 if (errno != ENOENT)
409 err(1, "cap_sysctlbyname()");
410 return;
411 }
412 if ((buf = (char *)malloc(len)) == NULL) {
413 err(1, "malloc()");
414 return;
415 }
416 if (cap_sysctlbyname(capsysctl, varname, buf, &len, 0, 0) < 0) {
417 err(1, "cap_sysctlbyname()");
418 free(buf);
419 return;
420 }
421 xinpcb = (struct xsctp_inpcb *)(void *)buf;
422 offset = sizeof(struct xsctp_inpcb);
423 while ((offset < len) && (xinpcb->last == 0)) {
424 if ((sock = calloc(1, sizeof *sock)) == NULL)
425 err(1, "malloc()");
426 sock->socket = xinpcb->socket;
427 sock->proto = IPPROTO_SCTP;
428 sock->protoname = "sctp";
429 if (xinpcb->maxqlen == 0)
430 sock->state = SCTP_CLOSED;
431 else
432 sock->state = SCTP_LISTEN;
433 if (xinpcb->flags & SCTP_PCB_FLAGS_BOUND_V6) {
434 sock->family = AF_INET6;
435 /*
436 * Currently there is no way to distinguish between
437 * IPv6 only sockets or dual family sockets.
438 * So mark it as dual socket.
439 */
440 sock->vflag = INP_IPV6 | INP_IPV4;
441 } else {
442 sock->family = AF_INET;
443 sock->vflag = INP_IPV4;
444 }
445 prev_laddr = NULL;
446 local_all_loopback = 1;
447 while (offset < len) {
448 xladdr = (struct xsctp_laddr *)(void *)(buf + offset);
449 offset += sizeof(struct xsctp_laddr);
450 if (xladdr->last == 1)
451 break;
452 if ((laddr = calloc(1, sizeof(struct addr))) == NULL)
453 err(1, "malloc()");
454 switch (xladdr->address.sa.sa_family) {
455 case AF_INET:
456 #define __IN_IS_ADDR_LOOPBACK(pina) \
457 ((ntohl((pina)->s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
458 if (!__IN_IS_ADDR_LOOPBACK(
459 &xladdr->address.sin.sin_addr))
460 local_all_loopback = 0;
461 #undef __IN_IS_ADDR_LOOPBACK
462 sockaddr(&laddr->address, AF_INET,
463 &xladdr->address.sin.sin_addr,
464 htons(xinpcb->local_port));
465 break;
466 case AF_INET6:
467 if (!IN6_IS_ADDR_LOOPBACK(
468 &xladdr->address.sin6.sin6_addr))
469 local_all_loopback = 0;
470 sockaddr(&laddr->address, AF_INET6,
471 &xladdr->address.sin6.sin6_addr,
472 htons(xinpcb->local_port));
473 break;
474 default:
475 errx(1, "address family %d not supported",
476 xladdr->address.sa.sa_family);
477 }
478 laddr->next = NULL;
479 if (prev_laddr == NULL)
480 sock->laddr = laddr;
481 else
482 prev_laddr->next = laddr;
483 prev_laddr = laddr;
484 }
485 if (sock->laddr == NULL) {
486 if ((sock->laddr =
487 calloc(1, sizeof(struct addr))) == NULL)
488 err(1, "malloc()");
489 sock->laddr->address.ss_family = sock->family;
490 if (sock->family == AF_INET)
491 sock->laddr->address.ss_len =
492 sizeof(struct sockaddr_in);
493 else
494 sock->laddr->address.ss_len =
495 sizeof(struct sockaddr_in6);
496 local_all_loopback = 0;
497 }
498 if ((sock->faddr = calloc(1, sizeof(struct addr))) == NULL)
499 err(1, "malloc()");
500 sock->faddr->address.ss_family = sock->family;
501 if (sock->family == AF_INET)
502 sock->faddr->address.ss_len =
503 sizeof(struct sockaddr_in);
504 else
505 sock->faddr->address.ss_len =
506 sizeof(struct sockaddr_in6);
507 no_stcb = 1;
508 while (offset < len) {
509 xstcb = (struct xsctp_tcb *)(void *)(buf + offset);
510 offset += sizeof(struct xsctp_tcb);
511 if (no_stcb) {
512 if (opt_l && (sock->vflag & vflag) &&
513 (!opt_L || !local_all_loopback) &&
514 ((xinpcb->flags & SCTP_PCB_FLAGS_UDPTYPE) ||
515 (xstcb->last == 1))) {
516 RB_INSERT(socks_t, &socks, sock);
517 } else {
518 free_socket(sock);
519 }
520 }
521 if (xstcb->last == 1)
522 break;
523 no_stcb = 0;
524 if (opt_c) {
525 if ((sock = calloc(1, sizeof *sock)) == NULL)
526 err(1, "malloc()");
527 sock->socket = xinpcb->socket;
528 sock->proto = IPPROTO_SCTP;
529 sock->protoname = "sctp";
530 sock->state = (int)xstcb->state;
531 if (xinpcb->flags & SCTP_PCB_FLAGS_BOUND_V6) {
532 sock->family = AF_INET6;
533 /*
534 * Currently there is no way to distinguish
535 * between IPv6 only sockets or dual family
536 * sockets. So mark it as dual socket.
537 */
538 sock->vflag = INP_IPV6 | INP_IPV4;
539 } else {
540 sock->family = AF_INET;
541 sock->vflag = INP_IPV4;
542 }
543 }
544 prev_laddr = NULL;
545 local_all_loopback = 1;
546 while (offset < len) {
547 xladdr = (struct xsctp_laddr *)(void *)(buf +
548 offset);
549 offset += sizeof(struct xsctp_laddr);
550 if (xladdr->last == 1)
551 break;
552 if (!opt_c)
553 continue;
554 laddr = calloc(1, sizeof(struct addr));
555 if (laddr == NULL)
556 err(1, "malloc()");
557 switch (xladdr->address.sa.sa_family) {
558 case AF_INET:
559 #define __IN_IS_ADDR_LOOPBACK(pina) \
560 ((ntohl((pina)->s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
561 if (!__IN_IS_ADDR_LOOPBACK(
562 &xladdr->address.sin.sin_addr))
563 local_all_loopback = 0;
564 #undef __IN_IS_ADDR_LOOPBACK
565 sockaddr(&laddr->address, AF_INET,
566 &xladdr->address.sin.sin_addr,
567 htons(xstcb->local_port));
568 break;
569 case AF_INET6:
570 if (!IN6_IS_ADDR_LOOPBACK(
571 &xladdr->address.sin6.sin6_addr))
572 local_all_loopback = 0;
573 sockaddr(&laddr->address, AF_INET6,
574 &xladdr->address.sin6.sin6_addr,
575 htons(xstcb->local_port));
576 break;
577 default:
578 errx(1,
579 "address family %d not supported",
580 xladdr->address.sa.sa_family);
581 }
582 laddr->next = NULL;
583 if (prev_laddr == NULL)
584 sock->laddr = laddr;
585 else
586 prev_laddr->next = laddr;
587 prev_laddr = laddr;
588 }
589 prev_faddr = NULL;
590 foreign_all_loopback = 1;
591 while (offset < len) {
592 xraddr = (struct xsctp_raddr *)(void *)(buf +
593 offset);
594 offset += sizeof(struct xsctp_raddr);
595 if (xraddr->last == 1)
596 break;
597 if (!opt_c)
598 continue;
599 faddr = calloc(1, sizeof(struct addr));
600 if (faddr == NULL)
601 err(1, "malloc()");
602 switch (xraddr->address.sa.sa_family) {
603 case AF_INET:
604 #define __IN_IS_ADDR_LOOPBACK(pina) \
605 ((ntohl((pina)->s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
606 if (!__IN_IS_ADDR_LOOPBACK(
607 &xraddr->address.sin.sin_addr))
608 foreign_all_loopback = 0;
609 #undef __IN_IS_ADDR_LOOPBACK
610 sockaddr(&faddr->address, AF_INET,
611 &xraddr->address.sin.sin_addr,
612 htons(xstcb->remote_port));
613 break;
614 case AF_INET6:
615 if (!IN6_IS_ADDR_LOOPBACK(
616 &xraddr->address.sin6.sin6_addr))
617 foreign_all_loopback = 0;
618 sockaddr(&faddr->address, AF_INET6,
619 &xraddr->address.sin6.sin6_addr,
620 htons(xstcb->remote_port));
621 break;
622 default:
623 errx(1,
624 "address family %d not supported",
625 xraddr->address.sa.sa_family);
626 }
627 faddr->encaps_port = xraddr->encaps_port;
628 faddr->state = xraddr->state;
629 faddr->next = NULL;
630 if (prev_faddr == NULL)
631 sock->faddr = faddr;
632 else
633 prev_faddr->next = faddr;
634 prev_faddr = faddr;
635 }
636 if (opt_c) {
637 if ((sock->vflag & vflag) &&
638 (!opt_L ||
639 !(local_all_loopback ||
640 foreign_all_loopback))) {
641 RB_INSERT(socks_t, &socks, sock);
642 } else {
643 free_socket(sock);
644 }
645 }
646 }
647 xinpcb = (struct xsctp_inpcb *)(void *)(buf + offset);
648 offset += sizeof(struct xsctp_inpcb);
649 }
650 free(buf);
651 }
652
653 static void
gather_inet(int proto)654 gather_inet(int proto)
655 {
656 struct xinpgen *xig, *exig;
657 struct xinpcb *xip;
658 struct xtcpcb *xtp = NULL;
659 struct xsocket *so;
660 struct sock *sock;
661 struct addr *laddr, *faddr;
662 const char *varname, *protoname;
663 size_t len, bufsize;
664 void *buf;
665 int retry, vflag;
666
667 vflag = 0;
668 if (opt_4)
669 vflag |= INP_IPV4;
670 if (opt_6)
671 vflag |= INP_IPV6;
672
673 switch (proto) {
674 case IPPROTO_TCP:
675 varname = "net.inet.tcp.pcblist";
676 protoname = "tcp";
677 break;
678 case IPPROTO_UDP:
679 varname = "net.inet.udp.pcblist";
680 protoname = "udp";
681 break;
682 case IPPROTO_DIVERT:
683 varname = "net.inet.divert.pcblist";
684 protoname = "div";
685 break;
686 default:
687 errx(1, "protocol %d not supported", proto);
688 }
689
690 buf = NULL;
691 bufsize = 8192;
692 retry = 5;
693 do {
694 for (;;) {
695 if ((buf = realloc(buf, bufsize)) == NULL)
696 err(1, "realloc()");
697 len = bufsize;
698 if (cap_sysctlbyname(capsysctl, varname, buf, &len,
699 NULL, 0) == 0)
700 break;
701 if (errno == ENOENT)
702 goto out;
703 if (errno != ENOMEM || len != bufsize)
704 err(1, "cap_sysctlbyname()");
705 bufsize *= 2;
706 }
707 xig = (struct xinpgen *)buf;
708 exig = (struct xinpgen *)(void *)
709 ((char *)buf + len - sizeof *exig);
710 enforce_ksize(xig->xig_len, struct xinpgen);
711 enforce_ksize(exig->xig_len, struct xinpgen);
712 } while (xig->xig_gen != exig->xig_gen && retry--);
713
714 if (xig->xig_gen != exig->xig_gen && opt_v)
715 warnx("warning: data may be inconsistent");
716
717 for (;;) {
718 xig = (struct xinpgen *)(void *)((char *)xig + xig->xig_len);
719 if (xig >= exig)
720 break;
721 switch (proto) {
722 case IPPROTO_TCP:
723 xtp = (struct xtcpcb *)xig;
724 xip = &xtp->xt_inp;
725 if (!check_ksize(xtp->xt_len, struct xtcpcb))
726 goto out;
727 protoname = xtp->t_flags & TF_TOE ? "toe" : "tcp";
728 break;
729 case IPPROTO_UDP:
730 case IPPROTO_DIVERT:
731 xip = (struct xinpcb *)xig;
732 if (!check_ksize(xip->xi_len, struct xinpcb))
733 goto out;
734 break;
735 default:
736 errx(1, "protocol %d not supported", proto);
737 }
738 so = &xip->xi_socket;
739 if ((xip->inp_vflag & vflag) == 0)
740 continue;
741 if (xip->inp_vflag & INP_IPV4) {
742 if ((xip->inp_fport == 0 && !opt_l) ||
743 (xip->inp_fport != 0 && !opt_c))
744 continue;
745 #define __IN_IS_ADDR_LOOPBACK(pina) \
746 ((ntohl((pina)->s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
747 if (opt_L &&
748 (__IN_IS_ADDR_LOOPBACK(&xip->inp_faddr) ||
749 __IN_IS_ADDR_LOOPBACK(&xip->inp_laddr)))
750 continue;
751 #undef __IN_IS_ADDR_LOOPBACK
752 } else if (xip->inp_vflag & INP_IPV6) {
753 if ((xip->inp_fport == 0 && !opt_l) ||
754 (xip->inp_fport != 0 && !opt_c))
755 continue;
756 if (opt_L &&
757 (IN6_IS_ADDR_LOOPBACK(&xip->in6p_faddr) ||
758 IN6_IS_ADDR_LOOPBACK(&xip->in6p_laddr)))
759 continue;
760 } else {
761 if (opt_v)
762 warnx("invalid vflag 0x%x", xip->inp_vflag);
763 continue;
764 }
765 if ((sock = calloc(1, sizeof(*sock))) == NULL)
766 err(1, "malloc()");
767 if ((laddr = calloc(1, sizeof *laddr)) == NULL)
768 err(1, "malloc()");
769 if ((faddr = calloc(1, sizeof *faddr)) == NULL)
770 err(1, "malloc()");
771 sock->socket = so->xso_so;
772 sock->splice_socket = so->so_splice_so;
773 sock->proto = proto;
774 sock->inp_gencnt = xip->inp_gencnt;
775 if (xip->inp_vflag & INP_IPV4) {
776 sock->family = AF_INET;
777 sockaddr(&laddr->address, sock->family,
778 &xip->inp_laddr, xip->inp_lport);
779 sockaddr(&faddr->address, sock->family,
780 &xip->inp_faddr, xip->inp_fport);
781 } else if (xip->inp_vflag & INP_IPV6) {
782 sock->family = AF_INET6;
783 sockaddr(&laddr->address, sock->family,
784 &xip->in6p_laddr, xip->inp_lport);
785 sockaddr(&faddr->address, sock->family,
786 &xip->in6p_faddr, xip->inp_fport);
787 }
788 if (proto == IPPROTO_TCP)
789 faddr->encaps_port = xtp->xt_encaps_port;
790 laddr->next = NULL;
791 faddr->next = NULL;
792 sock->laddr = laddr;
793 sock->faddr = faddr;
794 sock->vflag = xip->inp_vflag;
795 if (proto == IPPROTO_TCP) {
796 sock->state = xtp->t_state;
797 memcpy(sock->stack, xtp->xt_stack,
798 TCP_FUNCTION_NAME_LEN_MAX);
799 memcpy(sock->cc, xtp->xt_cc, TCP_CA_NAME_MAX);
800 }
801 sock->protoname = protoname;
802 if (sock->socket != 0)
803 RB_INSERT(socks_t, &socks, sock);
804 else
805 SLIST_INSERT_HEAD(&nosocks, sock, socket_list);
806 }
807 out:
808 free(buf);
809 }
810
811 static void
gather_unix(int proto)812 gather_unix(int proto)
813 {
814 struct xunpgen *xug, *exug;
815 struct xunpcb *xup;
816 struct sock *sock;
817 struct addr *laddr, *faddr;
818 const char *varname, *protoname;
819 size_t len, bufsize;
820 void *buf;
821 int retry;
822
823 switch (proto) {
824 case SOCK_STREAM:
825 varname = "net.local.stream.pcblist";
826 protoname = "stream";
827 break;
828 case SOCK_DGRAM:
829 varname = "net.local.dgram.pcblist";
830 protoname = "dgram";
831 break;
832 case SOCK_SEQPACKET:
833 varname = "net.local.seqpacket.pcblist";
834 protoname = "seqpac";
835 break;
836 default:
837 abort();
838 }
839 buf = NULL;
840 bufsize = 8192;
841 retry = 5;
842 do {
843 for (;;) {
844 if ((buf = realloc(buf, bufsize)) == NULL)
845 err(1, "realloc()");
846 len = bufsize;
847 if (cap_sysctlbyname(capsysctl, varname, buf, &len,
848 NULL, 0) == 0)
849 break;
850 if (errno != ENOMEM || len != bufsize)
851 err(1, "cap_sysctlbyname()");
852 bufsize *= 2;
853 }
854 xug = (struct xunpgen *)buf;
855 exug = (struct xunpgen *)(void *)
856 ((char *)buf + len - sizeof(*exug));
857 if (!check_ksize(xug->xug_len, struct xunpgen) ||
858 !check_ksize(exug->xug_len, struct xunpgen))
859 goto out;
860 } while (xug->xug_gen != exug->xug_gen && retry--);
861
862 if (xug->xug_gen != exug->xug_gen && opt_v)
863 warnx("warning: data may be inconsistent");
864
865 for (;;) {
866 xug = (struct xunpgen *)(void *)((char *)xug + xug->xug_len);
867 if (xug >= exug)
868 break;
869 xup = (struct xunpcb *)xug;
870 if (!check_ksize(xup->xu_len, struct xunpcb))
871 goto out;
872 if ((xup->unp_conn == 0 && !opt_l) ||
873 (xup->unp_conn != 0 && !opt_c))
874 continue;
875 if ((sock = calloc(1, sizeof(*sock))) == NULL)
876 err(1, "malloc()");
877 if ((laddr = calloc(1, sizeof *laddr)) == NULL)
878 err(1, "malloc()");
879 if ((faddr = calloc(1, sizeof *faddr)) == NULL)
880 err(1, "malloc()");
881 sock->socket = xup->xu_socket.xso_so;
882 sock->pcb = xup->xu_unpp;
883 sock->proto = proto;
884 sock->family = AF_UNIX;
885 sock->protoname = protoname;
886 if (xup->xu_addr.sun_family == AF_UNIX)
887 laddr->address =
888 *(struct sockaddr_storage *)(void *)&xup->xu_addr;
889 faddr->conn = xup->unp_conn;
890 faddr->firstref = xup->xu_firstref;
891 faddr->nextref = xup->xu_nextref;
892 laddr->next = NULL;
893 faddr->next = NULL;
894 sock->laddr = laddr;
895 sock->faddr = faddr;
896 RB_INSERT(socks_t, &socks, sock);
897 RB_INSERT(pcbs_t, &pcbs, sock);
898 }
899 out:
900 free(buf);
901 }
902
903 static void
getfiles(void)904 getfiles(void)
905 {
906 struct xfile *xfiles;
907 size_t len, olen;
908
909 olen = len = sizeof(*xfiles);
910 if ((xfiles = malloc(len)) == NULL)
911 err(1, "malloc()");
912 while (cap_sysctlbyname(capsysctl, "kern.file", xfiles, &len, 0, 0)
913 == -1) {
914 if (errno != ENOMEM || len != olen)
915 err(1, "cap_sysctlbyname()");
916 olen = len *= 2;
917 if ((xfiles = realloc(xfiles, len)) == NULL)
918 err(1, "realloc()");
919 }
920 if (len > 0)
921 enforce_ksize(xfiles->xf_size, struct xfile);
922 nfiles = len / sizeof(*xfiles);
923
924 if ((files = malloc(nfiles * sizeof(struct file))) == NULL)
925 err(1, "malloc()");
926
927 for (int i = 0; i < nfiles; i++) {
928 files[i].xf_data = xfiles[i].xf_data;
929 files[i].xf_pid = xfiles[i].xf_pid;
930 files[i].xf_uid = xfiles[i].xf_uid;
931 files[i].xf_fd = xfiles[i].xf_fd;
932 RB_INSERT(files_t, &ftree, &files[i]);
933 }
934
935 free(xfiles);
936 }
937
938 static int
printaddr(struct sockaddr_storage * ss)939 printaddr(struct sockaddr_storage *ss)
940 {
941 struct sockaddr_un *sun;
942 char addrstr[NI_MAXHOST] = { '\0', '\0' };
943 int error, off, port = 0;
944
945 switch (ss->ss_family) {
946 case AF_INET:
947 if (sstosin(ss)->sin_addr.s_addr == INADDR_ANY)
948 addrstr[0] = '*';
949 port = ntohs(sstosin(ss)->sin_port);
950 break;
951 case AF_INET6:
952 if (IN6_IS_ADDR_UNSPECIFIED(&sstosin6(ss)->sin6_addr))
953 addrstr[0] = '*';
954 port = ntohs(sstosin6(ss)->sin6_port);
955 break;
956 case AF_UNIX:
957 sun = sstosun(ss);
958 off = (int)((char *)&sun->sun_path - (char *)sun);
959 return (xprintf("%.*s", sun->sun_len - off, sun->sun_path));
960 }
961 if (addrstr[0] == '\0') {
962 error = cap_getnameinfo(capnet, sstosa(ss), ss->ss_len,
963 addrstr, sizeof(addrstr), NULL, 0, NI_NUMERICHOST);
964 if (error)
965 errx(1, "cap_getnameinfo()");
966 }
967 if (port == 0)
968 return xprintf("%s:*", addrstr);
969 else
970 return xprintf("%s:%d", addrstr, port);
971 }
972
973 static const char *
getprocname(pid_t pid)974 getprocname(pid_t pid)
975 {
976 static struct kinfo_proc proc;
977 size_t len;
978 int mib[4];
979
980 mib[0] = CTL_KERN;
981 mib[1] = KERN_PROC;
982 mib[2] = KERN_PROC_PID;
983 mib[3] = (int)pid;
984 len = sizeof(proc);
985 if (cap_sysctl(capsysctl, mib, nitems(mib), &proc, &len, NULL, 0)
986 == -1) {
987 /* Do not warn if the process exits before we get its name. */
988 if (errno != ESRCH)
989 warn("cap_sysctl()");
990 return ("??");
991 }
992 return (proc.ki_comm);
993 }
994
995 static int
getprocjid(pid_t pid)996 getprocjid(pid_t pid)
997 {
998 static struct kinfo_proc proc;
999 size_t len;
1000 int mib[4];
1001
1002 mib[0] = CTL_KERN;
1003 mib[1] = KERN_PROC;
1004 mib[2] = KERN_PROC_PID;
1005 mib[3] = (int)pid;
1006 len = sizeof(proc);
1007 if (cap_sysctl(capsysctl, mib, nitems(mib), &proc, &len, NULL, 0)
1008 == -1) {
1009 /* Do not warn if the process exits before we get its jid. */
1010 if (errno != ESRCH)
1011 warn("cap_sysctl()");
1012 return (-1);
1013 }
1014 return (proc.ki_jid);
1015 }
1016
1017 static int
check_ports(struct sock * s)1018 check_ports(struct sock *s)
1019 {
1020 int port;
1021 struct addr *addr;
1022
1023 if (ports == NULL)
1024 return (1);
1025 if ((s->family != AF_INET) && (s->family != AF_INET6))
1026 return (1);
1027 for (addr = s->laddr; addr != NULL; addr = addr->next) {
1028 if (s->family == AF_INET)
1029 port = ntohs(sstosin(&addr->address)->sin_port);
1030 else
1031 port = ntohs(sstosin6(&addr->address)->sin6_port);
1032 if (CHK_PORT(port))
1033 return (1);
1034 }
1035 for (addr = s->faddr; addr != NULL; addr = addr->next) {
1036 if (s->family == AF_INET)
1037 port = ntohs(sstosin(&addr->address)->sin_port);
1038 else
1039 port = ntohs(sstosin6(&addr->address)->sin6_port);
1040 if (CHK_PORT(port))
1041 return (1);
1042 }
1043 return (0);
1044 }
1045
1046 static const char *
sctp_conn_state(int state)1047 sctp_conn_state(int state)
1048 {
1049 switch (state) {
1050 case SCTP_CLOSED:
1051 return "CLOSED";
1052 break;
1053 case SCTP_BOUND:
1054 return "BOUND";
1055 break;
1056 case SCTP_LISTEN:
1057 return "LISTEN";
1058 break;
1059 case SCTP_COOKIE_WAIT:
1060 return "COOKIE_WAIT";
1061 break;
1062 case SCTP_COOKIE_ECHOED:
1063 return "COOKIE_ECHOED";
1064 break;
1065 case SCTP_ESTABLISHED:
1066 return "ESTABLISHED";
1067 break;
1068 case SCTP_SHUTDOWN_SENT:
1069 return "SHUTDOWN_SENT";
1070 break;
1071 case SCTP_SHUTDOWN_RECEIVED:
1072 return "SHUTDOWN_RECEIVED";
1073 break;
1074 case SCTP_SHUTDOWN_ACK_SENT:
1075 return "SHUTDOWN_ACK_SENT";
1076 break;
1077 case SCTP_SHUTDOWN_PENDING:
1078 return "SHUTDOWN_PENDING";
1079 break;
1080 default:
1081 return "UNKNOWN";
1082 break;
1083 }
1084 }
1085
1086 static const char *
sctp_path_state(int state)1087 sctp_path_state(int state)
1088 {
1089 switch (state) {
1090 case SCTP_UNCONFIRMED:
1091 return "UNCONFIRMED";
1092 break;
1093 case SCTP_ACTIVE:
1094 return "ACTIVE";
1095 break;
1096 case SCTP_INACTIVE:
1097 return "INACTIVE";
1098 break;
1099 default:
1100 return "UNKNOWN";
1101 break;
1102 }
1103 }
1104
1105 static void
displaysock(struct sock * s,int pos)1106 displaysock(struct sock *s, int pos)
1107 {
1108 int first, offset;
1109 struct addr *laddr, *faddr;
1110
1111 while (pos < 30)
1112 pos += xprintf(" ");
1113 pos += xprintf("%s", s->protoname);
1114 if (s->vflag & INP_IPV4)
1115 pos += xprintf("4");
1116 if (s->vflag & INP_IPV6)
1117 pos += xprintf("6");
1118 if (s->vflag & (INP_IPV4 | INP_IPV6))
1119 pos += xprintf(" ");
1120 laddr = s->laddr;
1121 faddr = s->faddr;
1122 first = 1;
1123 while (laddr != NULL || faddr != NULL) {
1124 offset = 37;
1125 while (pos < offset)
1126 pos += xprintf(" ");
1127 switch (s->family) {
1128 case AF_INET:
1129 case AF_INET6:
1130 if (laddr != NULL) {
1131 pos += printaddr(&laddr->address);
1132 if (s->family == AF_INET6 && pos >= 58)
1133 pos += xprintf(" ");
1134 }
1135 offset += opt_w ? 46 : 22;
1136 while (pos < offset)
1137 pos += xprintf(" ");
1138 if (faddr != NULL)
1139 pos += printaddr(&faddr->address);
1140 offset += opt_w ? 46 : 22;
1141 break;
1142 case AF_UNIX:
1143 if ((laddr == NULL) || (faddr == NULL))
1144 errx(1, "laddr = %p or faddr = %p is NULL",
1145 (void *)laddr, (void *)faddr);
1146 if (laddr->address.ss_len == 0 && faddr->conn == 0) {
1147 pos += xprintf("(not connected)");
1148 offset += opt_w ? 92 : 44;
1149 break;
1150 }
1151 /* Local bind(2) address, if any. */
1152 if (laddr->address.ss_len > 0)
1153 pos += printaddr(&laddr->address);
1154 /* Remote peer we connect(2) to, if any. */
1155 if (faddr->conn != 0) {
1156 struct sock *p;
1157
1158 pos += xprintf("%s-> ",
1159 laddr->address.ss_len > 0 ? " " : "");
1160 p = RB_FIND(pcbs_t, &pcbs,
1161 &(struct sock){ .pcb = faddr->conn });
1162 if (__predict_false(p == NULL)) {
1163 /* XXGL: can this happen at all? */
1164 pos += xprintf("??");
1165 } else if (p->laddr->address.ss_len == 0) {
1166 struct file *f;
1167
1168 f = RB_FIND(files_t, &ftree,
1169 &(struct file){ .xf_data =
1170 p->socket });
1171 if (f != NULL) {
1172 pos += xprintf("[%lu %d]",
1173 (u_long)f->xf_pid,
1174 f->xf_fd);
1175 }
1176 } else
1177 pos += printaddr(&p->laddr->address);
1178 }
1179 /* Remote peer(s) connect(2)ed to us, if any. */
1180 if (faddr->firstref != 0) {
1181 struct sock *p;
1182 struct file *f;
1183 kvaddr_t ref = faddr->firstref;
1184 bool fref = true;
1185
1186 pos += xprintf(" <- ");
1187
1188 while ((p = RB_FIND(pcbs_t, &pcbs,
1189 &(struct sock){ .pcb = ref })) != 0) {
1190 f = RB_FIND(files_t, &ftree,
1191 &(struct file){ .xf_data =
1192 p->socket });
1193 if (f != NULL) {
1194 pos += xprintf("%s[%lu %d]",
1195 fref ? "" : ",",
1196 (u_long)f->xf_pid,
1197 f->xf_fd);
1198 }
1199 ref = p->faddr->nextref;
1200 fref = false;
1201 }
1202 }
1203 offset += opt_w ? 92 : 44;
1204 break;
1205 default:
1206 abort();
1207 }
1208 if (opt_I) {
1209 if (s->splice_socket != 0) {
1210 struct sock *sp;
1211
1212 sp = RB_FIND(socks_t, &socks, &(struct sock)
1213 { .socket = s->splice_socket });
1214 if (sp != NULL) {
1215 while (pos < offset)
1216 pos += xprintf(" ");
1217 pos += printaddr(&sp->laddr->address);
1218 } else {
1219 while (pos < offset)
1220 pos += xprintf(" ");
1221 pos += xprintf("??");
1222 offset += opt_w ? 46 : 22;
1223 }
1224 }
1225 offset += opt_w ? 46 : 22;
1226 }
1227 if (opt_i) {
1228 if (s->proto == IPPROTO_TCP ||
1229 s->proto == IPPROTO_UDP) {
1230 while (pos < offset)
1231 pos += xprintf(" ");
1232 pos += xprintf("%" PRIu64, s->inp_gencnt);
1233 }
1234 offset += 9;
1235 }
1236 if (opt_U) {
1237 if (faddr != NULL &&
1238 ((s->proto == IPPROTO_SCTP &&
1239 s->state != SCTP_CLOSED &&
1240 s->state != SCTP_BOUND &&
1241 s->state != SCTP_LISTEN) ||
1242 (s->proto == IPPROTO_TCP &&
1243 s->state != TCPS_CLOSED &&
1244 s->state != TCPS_LISTEN))) {
1245 while (pos < offset)
1246 pos += xprintf(" ");
1247 pos += xprintf("%u",
1248 ntohs(faddr->encaps_port));
1249 }
1250 offset += 7;
1251 }
1252 if (opt_s) {
1253 if (faddr != NULL &&
1254 s->proto == IPPROTO_SCTP &&
1255 s->state != SCTP_CLOSED &&
1256 s->state != SCTP_BOUND &&
1257 s->state != SCTP_LISTEN) {
1258 while (pos < offset)
1259 pos += xprintf(" ");
1260 pos += xprintf("%s",
1261 sctp_path_state(faddr->state));
1262 }
1263 offset += 13;
1264 }
1265 if (first) {
1266 if (opt_s) {
1267 if (s->proto == IPPROTO_SCTP ||
1268 s->proto == IPPROTO_TCP) {
1269 while (pos < offset)
1270 pos += xprintf(" ");
1271 switch (s->proto) {
1272 case IPPROTO_SCTP:
1273 pos += xprintf("%s",
1274 sctp_conn_state(s->state));
1275 break;
1276 case IPPROTO_TCP:
1277 if (s->state >= 0 &&
1278 s->state < TCP_NSTATES)
1279 pos += xprintf("%s",
1280 tcpstates[s->state]);
1281 else
1282 pos += xprintf("?");
1283 break;
1284 }
1285 }
1286 offset += 13;
1287 }
1288 if (opt_S) {
1289 if (s->proto == IPPROTO_TCP) {
1290 while (pos < offset)
1291 pos += xprintf(" ");
1292 pos += xprintf("%.*s",
1293 TCP_FUNCTION_NAME_LEN_MAX,
1294 s->stack);
1295 }
1296 offset += TCP_FUNCTION_NAME_LEN_MAX + 1;
1297 }
1298 if (opt_C) {
1299 if (s->proto == IPPROTO_TCP) {
1300 while (pos < offset)
1301 pos += xprintf(" ");
1302 xprintf("%.*s", TCP_CA_NAME_MAX, s->cc);
1303 }
1304 offset += TCP_CA_NAME_MAX + 1;
1305 }
1306 }
1307 if (laddr != NULL)
1308 laddr = laddr->next;
1309 if (faddr != NULL)
1310 faddr = faddr->next;
1311 if ((laddr != NULL) || (faddr != NULL)) {
1312 xprintf("\n");
1313 pos = 0;
1314 }
1315 first = 0;
1316 }
1317 xprintf("\n");
1318 }
1319
1320 static void
display(void)1321 display(void)
1322 {
1323 struct passwd *pwd;
1324 struct file *xf;
1325 struct sock *s;
1326 int n, pos;
1327
1328 if (opt_q != 1) {
1329 printf("%-8s %-10s %-5s %-3s %-6s %-*s %-*s",
1330 "USER", "COMMAND", "PID", "FD", "PROTO",
1331 opt_w ? 45 : 21, "LOCAL ADDRESS",
1332 opt_w ? 45 : 21, "FOREIGN ADDRESS");
1333 if (opt_I)
1334 printf(" %-*s", opt_w ? 45 : 21, "SPLICE ADDRESS");
1335 if (opt_i)
1336 printf(" %-8s", "ID");
1337 if (opt_U)
1338 printf(" %-6s", "ENCAPS");
1339 if (opt_s) {
1340 printf(" %-12s", "PATH STATE");
1341 printf(" %-12s", "CONN STATE");
1342 }
1343 if (opt_S)
1344 printf(" %-*.*s", TCP_FUNCTION_NAME_LEN_MAX,
1345 TCP_FUNCTION_NAME_LEN_MAX, "STACK");
1346 if (opt_C)
1347 printf(" %-.*s", TCP_CA_NAME_MAX, "CC");
1348 printf("\n");
1349 }
1350 cap_setpassent(cappwd, 1);
1351 for (xf = files, n = 0; n < nfiles; ++n, ++xf) {
1352 if (xf->xf_data == 0)
1353 continue;
1354 if (opt_j >= 0 && opt_j != getprocjid(xf->xf_pid))
1355 continue;
1356 s = RB_FIND(socks_t, &socks,
1357 &(struct sock){ .socket = xf->xf_data});
1358 if (s != NULL && check_ports(s)) {
1359 s->shown = 1;
1360 pos = 0;
1361 if (opt_n ||
1362 (pwd = cap_getpwuid(cappwd, xf->xf_uid)) == NULL)
1363 pos += xprintf("%lu ", (u_long)xf->xf_uid);
1364 else
1365 pos += xprintf("%s ", pwd->pw_name);
1366 while (pos < 9)
1367 pos += xprintf(" ");
1368 pos += xprintf("%.10s", getprocname(xf->xf_pid));
1369 while (pos < 20)
1370 pos += xprintf(" ");
1371 pos += xprintf("%5lu ", (u_long)xf->xf_pid);
1372 while (pos < 26)
1373 pos += xprintf(" ");
1374 pos += xprintf("%-3d ", xf->xf_fd);
1375 displaysock(s, pos);
1376 }
1377 }
1378 if (opt_j >= 0)
1379 return;
1380 SLIST_FOREACH(s, &nosocks, socket_list) {
1381 if (!check_ports(s))
1382 continue;
1383 pos = xprintf("%-8s %-10s %-5s %-2s ",
1384 "?", "?", "?", "?");
1385 displaysock(s, pos);
1386 }
1387 RB_FOREACH(s, socks_t, &socks) {
1388 if (s->shown)
1389 continue;
1390 if (!check_ports(s))
1391 continue;
1392 pos = xprintf("%-8s %-10s %-5s %-2s ",
1393 "?", "?", "?", "?");
1394 displaysock(s, pos);
1395 }
1396 }
1397
1398 static int
set_default_protos(void)1399 set_default_protos(void)
1400 {
1401 struct protoent *prot;
1402 const char *pname;
1403 size_t pindex;
1404
1405 init_protos(default_numprotos);
1406
1407 for (pindex = 0; pindex < default_numprotos; pindex++) {
1408 pname = default_protos[pindex];
1409 prot = cap_getprotobyname(capnetdb, pname);
1410 if (prot == NULL)
1411 err(1, "cap_getprotobyname: %s", pname);
1412 protos[pindex] = prot->p_proto;
1413 }
1414 numprotos = pindex;
1415 return (pindex);
1416 }
1417
1418 /*
1419 * Return the vnet property of the jail, or -1 on error.
1420 */
1421 static int
jail_getvnet(int jid)1422 jail_getvnet(int jid)
1423 {
1424 struct iovec jiov[6];
1425 int vnet;
1426 size_t len = sizeof(vnet);
1427
1428 if (sysctlbyname("kern.features.vimage", &vnet, &len, NULL, 0) != 0)
1429 return (0);
1430
1431 vnet = -1;
1432 jiov[0].iov_base = __DECONST(char *, "jid");
1433 jiov[0].iov_len = sizeof("jid");
1434 jiov[1].iov_base = &jid;
1435 jiov[1].iov_len = sizeof(jid);
1436 jiov[2].iov_base = __DECONST(char *, "vnet");
1437 jiov[2].iov_len = sizeof("vnet");
1438 jiov[3].iov_base = &vnet;
1439 jiov[3].iov_len = sizeof(vnet);
1440 jiov[4].iov_base = __DECONST(char *, "errmsg");
1441 jiov[4].iov_len = sizeof("errmsg");
1442 jiov[5].iov_base = jail_errmsg;
1443 jiov[5].iov_len = JAIL_ERRMSGLEN;
1444 jail_errmsg[0] = '\0';
1445 if (jail_get(jiov, nitems(jiov), 0) < 0) {
1446 if (!jail_errmsg[0])
1447 snprintf(jail_errmsg, JAIL_ERRMSGLEN,
1448 "jail_get: %s", strerror(errno));
1449 return (-1);
1450 }
1451 return (vnet);
1452 }
1453
1454 static void
usage(void)1455 usage(void)
1456 {
1457 fprintf(stderr,
1458 "usage: sockstat [-46CcIiLlnqSsUuvw] [-j jid] [-p ports] [-P protocols]\n");
1459 exit(1);
1460 }
1461
1462 int
main(int argc,char * argv[])1463 main(int argc, char *argv[])
1464 {
1465 cap_channel_t *capcas;
1466 cap_net_limit_t *limit;
1467 const char *pwdcmds[] = { "setpassent", "getpwuid" };
1468 const char *pwdfields[] = { "pw_name" };
1469 int protos_defined = -1;
1470 int o, i;
1471
1472 opt_j = -1;
1473 while ((o = getopt(argc, argv, "46CcIij:Llnp:P:qSsUuvw")) != -1)
1474 switch (o) {
1475 case '4':
1476 opt_4 = 1;
1477 break;
1478 case '6':
1479 opt_6 = 1;
1480 break;
1481 case 'C':
1482 opt_C = 1;
1483 break;
1484 case 'c':
1485 opt_c = 1;
1486 break;
1487 case 'I':
1488 opt_I = 1;
1489 break;
1490 case 'i':
1491 opt_i = 1;
1492 break;
1493 case 'j':
1494 opt_j = jail_getid(optarg);
1495 if (opt_j < 0)
1496 errx(1, "jail_getid: %s", jail_errmsg);
1497 break;
1498 case 'L':
1499 opt_L = 1;
1500 break;
1501 case 'l':
1502 opt_l = 1;
1503 break;
1504 case 'n':
1505 opt_n = 1;
1506 break;
1507 case 'p':
1508 parse_ports(optarg);
1509 break;
1510 case 'P':
1511 protos_defined = parse_protos(optarg);
1512 break;
1513 case 'q':
1514 opt_q = 1;
1515 break;
1516 case 'S':
1517 opt_S = 1;
1518 break;
1519 case 's':
1520 opt_s = 1;
1521 break;
1522 case 'U':
1523 opt_U = 1;
1524 break;
1525 case 'u':
1526 opt_u = 1;
1527 break;
1528 case 'v':
1529 ++opt_v;
1530 break;
1531 case 'w':
1532 opt_w = 1;
1533 break;
1534 default:
1535 usage();
1536 }
1537
1538 argc -= optind;
1539 argv += optind;
1540
1541 if (argc > 0)
1542 usage();
1543
1544 if (opt_j > 0) {
1545 switch (jail_getvnet(opt_j)) {
1546 case -1:
1547 errx(2, "jail_getvnet: %s", jail_errmsg);
1548 case JAIL_SYS_NEW:
1549 if (jail_attach(opt_j) < 0)
1550 err(3, "jail_attach()");
1551 /* Set back to -1 for normal output in vnet jail. */
1552 opt_j = -1;
1553 break;
1554 default:
1555 break;
1556 }
1557 }
1558
1559 capcas = cap_init();
1560 if (capcas == NULL)
1561 err(1, "Unable to contact Casper");
1562 if (caph_enter_casper() < 0)
1563 err(1, "Unable to enter capability mode");
1564 capnet = cap_service_open(capcas, "system.net");
1565 if (capnet == NULL)
1566 err(1, "Unable to open system.net service");
1567 capnetdb = cap_service_open(capcas, "system.netdb");
1568 if (capnetdb == NULL)
1569 err(1, "Unable to open system.netdb service");
1570 capsysctl = cap_service_open(capcas, "system.sysctl");
1571 if (capsysctl == NULL)
1572 err(1, "Unable to open system.sysctl service");
1573 cappwd = cap_service_open(capcas, "system.pwd");
1574 if (cappwd == NULL)
1575 err(1, "Unable to open system.pwd service");
1576 cap_close(capcas);
1577 limit = cap_net_limit_init(capnet, CAPNET_ADDR2NAME);
1578 if (limit == NULL)
1579 err(1, "Unable to init cap_net limits");
1580 if (cap_net_limit(limit) < 0)
1581 err(1, "Unable to apply limits");
1582 if (cap_pwd_limit_cmds(cappwd, pwdcmds, nitems(pwdcmds)) < 0)
1583 err(1, "Unable to apply pwd commands limits");
1584 if (cap_pwd_limit_fields(cappwd, pwdfields, nitems(pwdfields)) < 0)
1585 err(1, "Unable to apply pwd commands limits");
1586
1587 if ((!opt_4 && !opt_6) && protos_defined != -1)
1588 opt_4 = opt_6 = 1;
1589 if (!opt_4 && !opt_6 && !opt_u)
1590 opt_4 = opt_6 = opt_u = 1;
1591 if ((opt_4 || opt_6) && protos_defined == -1)
1592 protos_defined = set_default_protos();
1593 if (!opt_c && !opt_l)
1594 opt_c = opt_l = 1;
1595
1596 if (opt_4 || opt_6) {
1597 for (i = 0; i < protos_defined; i++)
1598 if (protos[i] == IPPROTO_SCTP)
1599 gather_sctp();
1600 else
1601 gather_inet(protos[i]);
1602 }
1603
1604 if (opt_u || (protos_defined == -1 && !opt_4 && !opt_6)) {
1605 gather_unix(SOCK_STREAM);
1606 gather_unix(SOCK_DGRAM);
1607 gather_unix(SOCK_SEQPACKET);
1608 }
1609 getfiles();
1610 display();
1611 exit(0);
1612 }
1613