1#!/usr/bin/ksh
2#
3# tcpsnoop - snoop TCP network packets by process. 
4#            Written using DTrace (Solaris 10 3/05)
5#
6# This analyses TCP network packets and prints the responsible PID and UID,
7# plus standard details such as IP address and port. This captures traffic
8# of newly created TCP connections that were established while this program
9# was running. It can help identify which processes is causing TCP traffic.
10#
11# 20-Apr-2006, ver 0.81        (check for newer versions)
12#
13# USAGE:       tcpsnoop [-a|hjsvZ] [-n name] [-p pid]
14#
15#		-a             # print all data
16#		-j             # print project ID
17#		-s             # print time, us
18#		-v             # print time, string
19#		-Z             # print zone ID
20#		-n name        # command name to snoop
21#		-p pid         # PID to snoop
22#	eg,
23#		tcpsnoop -v              # human readable timestamps
24#		tcpsnoop -Z              # print zonename
25#		tcpsnoop -n sshd         # snoop sshd traffic only
26#
27# FIELDS:
28#		UID     	user ID
29#		PID     	process ID
30#		CMD     	command
31#		LADDR		local IP address
32#		RADDR		remote IP address
33#		LPORT		local port number
34#		RPORT		remote port number
35#		DR      	direction
36#		SIZE    	packet size, bytes
37#		TIME    	timestamp, us
38#		STRTIME    	human readable timestamp, string
39#		ZONE    	zone ID
40#		PROJ    	project ID
41#
42# SEE ALSO: snoop -rS
43#
44# COPYRIGHT: Copyright (c) 2005, 2006 Brendan Gregg.
45#
46# CDDL HEADER START
47#
48#  The contents of this file are subject to the terms of the
49#  Common Development and Distribution License, Version 1.0 only
50#  (the "License").  You may not use this file except in compliance
51#  with the License.
52#
53#  You can obtain a copy of the license at Docs/cddl1.txt
54#  or http://www.opensolaris.org/os/licensing.
55#  See the License for the specific language governing permissions
56#  and limitations under the License.
57#
58# CDDL HEADER END
59#
60# Author: Brendan Gregg  [Sydney, Australia]
61#
62# TODO: IPv6
63#
64# CODE:
65#  The FILTER syntax matches on packets rather than initial 
66#  connections, so that it can follow inetd connections properly.
67#
68# 09-Jul-2004  Brendan Gregg	Created this.
69# 12-Mar-2005     "      "	Changed probes, size info now printed.
70# 02-Jul-2005     "      "	Many more probes. Renamed "tcpsnoop.d".
71# 04-Jul-2005     "      "	Now wrapped in shell, called "tcpsnoop".
72# 03-Dec-2005	  "	 "	Fixed tcp_accept_finish bug, now 100% correct
73#				execname. Thanks Kias Belgaied for expertise.
74# 20-Apr-2006     "      "      Fixed SS_TCP_FAST_ACCEPT bug in build 31+.
75#
76
77##############################
78# --- Process Arguments ---
79#
80
81### default variables
82opt_name=0; opt_time=0; opt_timestr=0; filter=0; pname=.
83opt_zone=0; opt_proj=0; opt_pid=0; pid=0
84
85### process options
86while getopts ahjsvZn:p: name
87do
88	case $name in
89	a)      opt_time=1; opt_timestr=1; opt_zone=1; opt_proj=1 ;;
90	n)      opt_name=1; pname=$OPTARG ;;
91	p)      opt_pid=1; pid=$OPTARG ;;
92	j)      opt_proj=1 ;;
93	s)      opt_time=1 ;;
94	v)      opt_timestr=1 ;;
95	Z)      opt_zone=1 ;;
96	h|?)    cat <<-END >&2
97		USAGE: tcpsnoop [-a|hjsvZ] [-n name] [-p pid]
98		       tcpsnoop                # default output
99		                -a             # print all data
100		                -j             # print project ID
101		                -s             # print start time, us
102		                -v             # print start time, string
103		                -Z             # print zonename
104		                -n name        # command name to snoop
105		                -p pid         # PID to snoop
106		  eg,
107		      tcpsnoop -v              # human readable timestamps
108		      tcpsnoop -Z              # print zonename
109		      tcpsnoop -n sshd         # snoop sshd traffic only
110		END
111		exit 1
112	esac
113done
114
115### option logic
116if (( opt_name || opt_pid )); then
117	filter=1
118fi
119
120#################################
121# --- Main Program, DTrace ---
122#
123/usr/sbin/dtrace -Cs <( print -r '
124 /*
125  * Command line arguments
126  */
127 inline int OPT_name    = '$opt_name';
128 inline int OPT_pid     = '$opt_pid';
129 inline int OPT_time    = '$opt_time';
130 inline int OPT_timestr = '$opt_timestr';
131 inline int OPT_zone    = '$opt_zone';
132 inline int OPT_proj    = '$opt_proj';
133 inline int PID         = '$pid';
134 inline int FILTER      = '$filter';
135 inline string NAME     = "'$pname'";
136
137#pragma D option quiet
138#pragma D option switchrate=10hz
139
140#include <sys/file.h>
141#include <inet/common.h>
142#include <sys/byteorder.h>
143#include <sys/socket.h>
144#include <sys/socketvar.h>
145
146/*
147 * Print header
148 */
149dtrace:::BEGIN
150{
151	/* print optional headers */
152	OPT_time    ? printf("%-14s ", "TIME") : 1;
153	OPT_timestr ? printf("%-20s ", "STRTIME") : 1;
154	OPT_zone    ? printf("%4s ", "ZONE") : 1;
155	OPT_proj    ? printf("%4s ", "PROJ") : 1;
156
157	/* print main headers */
158	printf("%5s %6s %-15s %5s %2s %-15s %5s %5s %s\n",
159	    "UID", "PID", "LADDR", "LPORT", "DR", "RADDR", "RPORT", 
160	    "SIZE", "CMD");
161}
162
163
164/*
165 * TCP Process inbound connections
166 *
167 * 0x00200000 has been hardcoded. It was SS_TCP_FAST_ACCEPT, but was
168 * renamed to SS_DIRECT around build 31.
169 */
170fbt:sockfs:sotpi_accept:entry
171/(arg1 & FREAD) && (arg1 & FWRITE) && (args[0]->so_state & 0x00200000)/
172{
173	self->sop = args[0];
174}
175
176fbt:sockfs:sotpi_create:return
177/self->sop/
178{
179	self->nsop = (struct sonode *)arg1;
180}
181
182fbt:sockfs:sotpi_accept:return
183/self->nsop/
184{
185	this->tcpp = (tcp_t *)self->nsop->so_priv;
186	self->connp = (conn_t *)this->tcpp->tcp_connp;
187	tname[(int)self->connp] = execname;
188	tpid[(int)self->connp] = pid;
189	tuid[(int)self->connp] = uid;
190}
191
192fbt:sockfs:sotpi_accept:return
193{
194	self->nsop = 0;
195	self->sop = 0;
196}
197
198/*
199 * TCP Process outbound connections
200 */
201fbt:ip:tcp_connect:entry
202{
203	this->tcpp = (tcp_t *)arg0;
204	self->connp = (conn_t *)this->tcpp->tcp_connp;
205	tname[(int)self->connp] = execname;
206	tpid[(int)self->connp] = pid;
207	tuid[(int)self->connp] = uid;
208	OPT_proj ? tproj[(int)self->connp] = curpsinfo->pr_projid : 1;
209}
210
211/*
212 * TCP Data translations
213 */
214fbt:sockfs:sotpi_accept:return,
215fbt:ip:tcp_connect:return
216/self->connp/
217{
218	/* fetch ports */
219#if defined(_BIG_ENDIAN)
220	self->lport = self->connp->u_port.tcpu_ports.tcpu_lport;
221	self->fport = self->connp->u_port.tcpu_ports.tcpu_fport;
222#else
223	self->lport = BSWAP_16(self->connp->u_port.tcpu_ports.tcpu_lport);
224	self->fport = BSWAP_16(self->connp->u_port.tcpu_ports.tcpu_fport);
225#endif
226
227	/* fetch IPv4 addresses */
228	this->fad12 =
229	    (int)self->connp->connua_v6addr.connua_faddr._S6_un._S6_u8[12];
230	this->fad13 =
231	    (int)self->connp->connua_v6addr.connua_faddr._S6_un._S6_u8[13];
232	this->fad14 =
233	    (int)self->connp->connua_v6addr.connua_faddr._S6_un._S6_u8[14];
234	this->fad15 =
235	    (int)self->connp->connua_v6addr.connua_faddr._S6_un._S6_u8[15];
236	this->lad12 =
237	    (int)self->connp->connua_v6addr.connua_laddr._S6_un._S6_u8[12];
238	this->lad13 =
239	    (int)self->connp->connua_v6addr.connua_laddr._S6_un._S6_u8[13];
240	this->lad14 =
241	    (int)self->connp->connua_v6addr.connua_laddr._S6_un._S6_u8[14];
242	this->lad15 =
243	    (int)self->connp->connua_v6addr.connua_laddr._S6_un._S6_u8[15];
244
245	/* convert type for use with lltostr() */
246	this->fad12 = this->fad12 < 0 ? 256 + this->fad12 : this->fad12;
247	this->fad13 = this->fad13 < 0 ? 256 + this->fad13 : this->fad13;
248	this->fad14 = this->fad14 < 0 ? 256 + this->fad14 : this->fad14;
249	this->fad15 = this->fad15 < 0 ? 256 + this->fad15 : this->fad15;
250	this->lad12 = this->lad12 < 0 ? 256 + this->lad12 : this->lad12;
251	this->lad13 = this->lad13 < 0 ? 256 + this->lad13 : this->lad13;
252	this->lad14 = this->lad14 < 0 ? 256 + this->lad14 : this->lad14;
253	this->lad15 = this->lad15 < 0 ? 256 + this->lad15 : this->lad15;
254
255	/* stringify addresses */
256	self->faddr = strjoin(lltostr(this->fad12), ".");
257	self->faddr = strjoin(self->faddr, strjoin(lltostr(this->fad13), "."));
258	self->faddr = strjoin(self->faddr, strjoin(lltostr(this->fad14), "."));
259	self->faddr = strjoin(self->faddr, lltostr(this->fad15 + 0));
260	self->laddr = strjoin(lltostr(this->lad12), ".");
261	self->laddr = strjoin(self->laddr, strjoin(lltostr(this->lad13), "."));
262	self->laddr = strjoin(self->laddr, strjoin(lltostr(this->lad14), "."));
263	self->laddr = strjoin(self->laddr, lltostr(this->lad15 + 0));
264
265	/* fix direction and save values */
266	tladdr[(int)self->connp] = self->laddr;
267	tfaddr[(int)self->connp] = self->faddr;
268	tlport[(int)self->connp] = self->lport;
269	tfport[(int)self->connp] = self->fport;
270
271	/* all systems go */
272	tok[(int)self->connp] = 1;
273}
274
275/*
276 * TCP Clear connp
277 */
278fbt:ip:tcp_get_conn:return
279{
280	/* Q_TO_CONN */
281	this->connp = (conn_t *)arg1;
282	tok[(int)this->connp] = 0;
283	tpid[(int)this->connp] = 0;
284	tuid[(int)this->connp] = 0;
285	tname[(int)this->connp] = 0;
286	tproj[(int)this->connp] = 0;
287}
288
289/*
290 * TCP Process "port closed"
291 */
292fbt:ip:tcp_xmit_early_reset:entry
293/FILTER == 0/
294{
295	this->queuep = (queue_t *)`tcp_g_q; /* ` */
296	this->connp = (conn_t *)this->queuep->q_ptr;
297	this->tcpp = (tcp_t *)this->connp->conn_tcp;
298	self->zoneid = this->connp->conn_zoneid;
299
300	/* split addresses */
301	this->ipha = (ipha_t *)args[1]->b_rptr;
302	this->fad15 = (this->ipha->ipha_src & 0xff000000) >> 24;
303	this->fad14 = (this->ipha->ipha_src & 0x00ff0000) >> 16;
304	this->fad13 = (this->ipha->ipha_src & 0x0000ff00) >> 8;
305	this->fad12 = (this->ipha->ipha_src & 0x000000ff);
306	this->lad15 = (this->ipha->ipha_dst & 0xff000000) >> 24;
307	this->lad14 = (this->ipha->ipha_dst & 0x00ff0000) >> 16;
308	this->lad13 = (this->ipha->ipha_dst & 0x0000ff00) >> 8;
309	this->lad12 = (this->ipha->ipha_dst & 0x000000ff);
310
311	/* stringify addresses */
312	self->faddr = strjoin(lltostr(this->fad12), ".");
313	self->faddr = strjoin(self->faddr, strjoin(lltostr(this->fad13), "."));
314	self->faddr = strjoin(self->faddr, strjoin(lltostr(this->fad14), "."));
315	self->faddr = strjoin(self->faddr, lltostr(this->fad15 + 0));
316	self->laddr = strjoin(lltostr(this->lad12), ".");
317	self->laddr = strjoin(self->laddr, strjoin(lltostr(this->lad13), "."));
318	self->laddr = strjoin(self->laddr, strjoin(lltostr(this->lad14), "."));
319	self->laddr = strjoin(self->laddr, lltostr(this->lad15 + 0));
320
321	self->reset = 1;
322}
323
324/*
325 * TCP Fetch "port closed" ports
326 */
327fbt:ip:tcp_xchg:entry
328/self->reset/
329{
330#if defined(_BIG_ENDIAN)
331	self->lport = (uint16_t)arg0;
332	self->fport = (uint16_t)arg1;
333#else
334	self->lport = BSWAP_16((uint16_t)arg0);
335	self->fport = BSWAP_16((uint16_t)arg1);
336#endif
337	self->lport = BE16_TO_U16(arg0);
338	self->fport = BE16_TO_U16(arg1);
339}
340
341/*
342 * TCP Print "port closed"
343 */
344fbt:ip:tcp_xmit_early_reset:return
345/FILTER == 0/
346{
347	self->name = "<closed>";
348	self->pid = 0;
349	self->uid = 0;
350	self->proj = 0;
351	self->size = 54;	/* should check trailers */
352	self->dir = "<-";
353	OPT_time ? printf("%-14d ", timestamp/1000) : 1;
354	OPT_timestr ? printf("%-20Y ", walltimestamp) : 1;
355	OPT_zone ? printf("%4d ", self->zoneid) : 1;
356	OPT_proj ? printf("%4d ", self->proj) : 1;
357        printf("%5d %6d %-15s %5d %2s %-15s %5d %5d %s\n",
358	    self->uid, self->pid, self->laddr, self->lport, self->dir,
359	    self->faddr, self->fport, self->size, self->name);
360	self->dir = "->";
361	OPT_time ? printf("%-14d ", timestamp/1000) : 1;
362	OPT_timestr ? printf("%-20Y ", walltimestamp) : 1;
363	OPT_zone ? printf("%4d ", self->zoneid) : 1;
364	OPT_proj ? printf("%4d ", self->proj) : 1;
365        printf("%5d %6d %-15s %5d %2s %-15s %5d %5d %s\n",
366	    self->uid, self->pid, self->laddr, self->lport, self->dir,
367	    self->faddr, self->fport, self->size, self->name);
368	self->reset = 0;
369	self->size = 0;
370	self->name = 0;
371	self->zoneid = 0;
372}
373
374/*
375 * TCP Process Write
376 */
377fbt:ip:tcp_send_data:entry
378{
379	self->conn_p = (conn_t *)args[0]->tcp_connp;
380}
381
382fbt:ip:tcp_send_data:entry
383/tok[(int)self->conn_p]/
384{
385        self->dir = "->";
386        self->size = msgdsize(args[2]) + 14;	/* should check trailers */
387	self->uid = tuid[(int)self->conn_p];
388	self->laddr = tladdr[(int)self->conn_p];
389	self->faddr = tfaddr[(int)self->conn_p];
390	self->lport = tlport[(int)self->conn_p];
391	self->fport = tfport[(int)self->conn_p];
392	OPT_proj ? self->proj = tproj[(int)self->conn_p] : 1;
393	self->zoneid = self->conn_p->conn_zoneid;
394        self->ok = 2;
395
396	/* follow inetd -> in.* transitions */
397	self->name = pid && (tname[(int)self->conn_p] == "inetd") ?
398	    execname : tname[(int)self->conn_p];
399	self->pid = pid && (tname[(int)self->conn_p] == "inetd") ?
400	    pid : tpid[(int)self->conn_p];
401	tname[(int)self->conn_p] = self->name;
402	tpid[(int)self->conn_p] = self->pid;
403}
404
405/*
406 * TCP Process Read
407 */
408fbt:ip:tcp_rput_data:entry
409{
410	self->conn_p = (conn_t *)arg0;
411        self->size = msgdsize(args[1]) + 14;	/* should check trailers */
412}
413
414fbt:ip:tcp_rput_data:entry
415/tok[(int)self->conn_p]/
416{
417	self->dir = "<-";
418	self->uid = tuid[(int)self->conn_p];
419	self->laddr = tladdr[(int)self->conn_p];
420	self->faddr = tfaddr[(int)self->conn_p];
421	self->lport = tlport[(int)self->conn_p];
422	self->fport = tfport[(int)self->conn_p];
423	OPT_proj ? self->proj = tproj[(int)self->conn_p] : 1;
424	self->zoneid = self->conn_p->conn_zoneid;
425	self->ok = 2;
426
427	/* follow inetd -> in.* transitions */
428	self->name = pid && (tname[(int)self->conn_p] == "inetd") ?
429	    execname : tname[(int)self->conn_p];
430	self->pid = pid && (tname[(int)self->conn_p] == "inetd") ?
431	    pid : tpid[(int)self->conn_p];
432	tname[(int)self->conn_p] = self->name;
433	tpid[(int)self->conn_p] = self->pid;
434}
435
436/*
437 * TCP Complete printing outbound handshake
438 */
439fbt:ip:tcp_connect:return
440/self->connp/
441{
442	self->name = tname[(int)self->connp];
443	self->pid = tpid[(int)self->connp];
444	self->uid = tuid[(int)self->connp];
445	self->zoneid = self->connp->conn_zoneid;
446	OPT_proj ? self->proj = tproj[(int)self->connp] : 1;
447	self->size = 54;	/* should check trailers */
448	self->dir = "->";
449}
450
451fbt:ip:tcp_connect:return
452/(self->connp) &&
453 ((FILTER == 0) ||
454 (OPT_pid && self->pid == PID) ||
455 (OPT_name && self->name == NAME))/
456{
457	/* this packet occured before connp was fully established */
458	OPT_time ? printf("%-14d ", timestamp/1000) : 1;
459	OPT_timestr ? printf("%-20Y ", walltimestamp) : 1;
460	OPT_zone ? printf("%4d ", self->zoneid) : 1;
461	OPT_proj ? printf("%4d ", self->proj) : 1;
462        printf("%5d %6d %-15s %5d %2s %-15s %5d %5d %s\n",
463	    self->uid, self->pid, self->laddr, self->lport, self->dir,
464	    self->faddr, self->fport, self->size, self->name);
465}
466
467/*
468 * TCP Complete printing inbound handshake
469 */
470fbt:sockfs:sotpi_accept:return
471/self->connp/
472{
473	self->name = tname[(int)self->connp];
474	self->pid = tpid[(int)self->connp];
475	self->uid = tuid[(int)self->connp];
476	self->zoneid = self->connp->conn_zoneid;
477	OPT_proj ? self->proj = tproj[(int)self->connp] : 1;
478	self->size = 54;	/* should check trailers */
479	self->dir = "<-";
480}
481
482fbt:sockfs:sotpi_accept:return
483/(self->connp) &&
484 ((FILTER == 0) ||
485 (OPT_pid && self->pid == PID) ||
486 (OPT_name && self->name == NAME))/
487{
488	/* these packets occured before connp was fully established */
489	OPT_time ? printf("%-14d ", timestamp/1000) : 1;
490	OPT_timestr ? printf("%-20Y ", walltimestamp) : 1;
491	OPT_zone ? printf("%4d ", self->zoneid) : 1;
492	OPT_proj ? printf("%4d ", self->proj) : 1;
493        printf("%5d %6d %-15s %5d %2s %-15s %5d %5d %s\n",
494	    self->uid, self->pid, self->laddr, self->lport, self->dir,
495	    self->faddr, self->fport, self->size, self->name);
496	self->dir = "->";
497	OPT_time ? printf("%-14d ", timestamp/1000) : 1;
498	OPT_timestr ? printf("%-20Y ", walltimestamp) : 1;
499	OPT_zone ? printf("%4d ", self->zoneid) : 1;
500	OPT_proj ? printf("%4d ", self->proj) : 1;
501        printf("%5d %6d %-15s %5d %2s %-15s %5d %5d %s\n",
502	    self->uid, self->pid, self->laddr, self->lport, self->dir,
503	    self->faddr, self->fport, self->size, self->name);
504	self->dir = "<-";
505	OPT_time ? printf("%-14d ", timestamp/1000) : 1;
506	OPT_timestr ? printf("%-20Y ", walltimestamp) : 1;
507	OPT_zone ? printf("%4d ", self->zoneid) : 1;
508	OPT_proj ? printf("%4d ", self->proj) : 1;
509        printf("%5d %6d %-15s %5d %2s %-15s %5d %5d %s\n",
510	    self->uid, self->pid, self->laddr, self->lport, self->dir,
511	    self->faddr, self->fport, self->size, self->name);
512}
513
514/*
515 * Print output
516 */
517fbt:ip:tcp_send_data:entry,
518fbt:ip:tcp_rput_data:entry
519/(self->ok == 2) && 
520 ((FILTER == 0) ||
521 (OPT_pid && self->pid == PID) ||
522 (OPT_name && self->name == NAME))/
523{
524	/* print optional fields */
525	OPT_time ? printf("%-14d ", timestamp/1000) : 1;
526	OPT_timestr ? printf("%-20Y ", walltimestamp) : 1;
527	OPT_zone ? printf("%4d ", self->zoneid) : 1;
528	OPT_proj ? printf("%4d ", self->proj) : 1;
529
530	/* print output line */
531        printf("%5d %6d %-15s %5d %2s %-15s %5d %5d %s\n",
532	    self->uid, self->pid, self->laddr, self->lport, self->dir,
533	    self->faddr, self->fport, self->size, self->name);
534}
535
536/* 
537 * TCP Clear connect variables
538 */
539fbt:sockfs:sotpi_accept:return,
540fbt:ip:tcp_connect:return
541/self->connp/
542{
543	self->faddr = 0;
544	self->laddr = 0;
545	self->fport = 0;
546	self->lport = 0;
547	self->connp = 0;
548	self->name = 0;
549	self->pid = 0;
550	self->uid = 0;
551}
552
553/* 
554 * TCP Clear r/w variables
555 */
556fbt:ip:tcp_send_data:entry,
557fbt:ip:tcp_rput_data:entry
558{
559	self->ok = 0;
560	self->dir = 0;
561	self->uid = 0;
562	self->pid = 0;
563	self->size = 0;
564	self->name = 0;
565	self->lport = 0;
566	self->fport = 0;
567	self->laddr = 0;
568	self->faddr = 0;
569	self->conn_p = 0;
570	self->zoneid = 0;
571	self->proj = 0;
572}
573')
574