s3:utils: Avoid integer overflow (CID 1035488)
[samba.git] / source3 / utils / log2pcaphex.c
1 /*
2    Unix SMB/CIFS implementation.
3    Utility to extract pcap files from samba (log level 10) log files
4
5    Copyright (C) Jelmer Vernooij 2003
6    Thanks to Tim Potter for the genial idea
7
8    Portions (from capconvert.c) (C) Andrew Tridgell 1997
9    Portions (from text2pcap.c) (C) Ashok Narayanan 2001
10
11    Example:
12         Output NBSS(SMB) packets in hex and convert to pcap adding
13         Eth/IP/TCP headers
14
15         log2pcap -h < samba.log | text2pcap -T 139,139 - samba.pcap
16
17         Output directly to pcap format without Eth headers or TCP
18         sequence numbers
19
20         log2pcap samba.log samba.pcap
21
22     TODO:
23         - Hex to text2pcap outputs are not properly parsed in Wireshark
24           the NBSS or SMB level.  This is a bug.
25         - Writing directly to pcap format doesn't include sequence numbers
26           in the TCP packets
27         - Check if a packet is a response or request and set IP to/from
28           addresses accordingly.  Currently all packets come from the same
29           dummy IP and go to the same dummy IP
30         - Add a message when done parsing about the number of pacekts
31           processed
32         - Parse NBSS packet header data from log file
33         - Have correct IP and TCP checksums.
34
35    Warning:
36         Samba log level 10 outputs a max of 512 bytes from the packet data
37         section.  Packets larger than this will be truncated.
38
39    This program is free software; you can redistribute it and/or modify
40    it under the terms of the GNU General Public License as published by
41    the Free Software Foundation; either version 3 of the License, or
42    (at your option) any later version.
43
44    This program is distributed in the hope that it will be useful,
45    but WITHOUT ANY WARRANTY; without even the implied warranty of
46    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
47    GNU General Public License for more details.
48
49    You should have received a copy of the GNU General Public License
50    along with this program.  If not, see <http://www.gnu.org/licenses/>.
51 */
52
53 #include "includes.h"
54 #include <popt.h>
55
56 /* We don't care about the paranoid malloc checker in this standalone
57    program */
58 #undef malloc
59
60 #include <assert.h>
61
62 int quiet = 0;
63 int hexformat = 0;
64
65 #define itoa(a) ((a) < 0xa?'0'+(a):'A' + (a-0xa))
66
67 #include <stdlib.h>
68 #include <unistd.h>
69 #include <sys/time.h>
70 #include <stdio.h>
71 #include <fcntl.h>
72
73 #define TCPDUMP_MAGIC 0xa1b2c3d4
74
75 /* tcpdump file format */
76 struct tcpdump_file_header {
77         uint32_t magic;
78         uint16_t major;
79         uint16_t minor;
80         int32_t zone;
81         uint32_t sigfigs;
82         uint32_t snaplen;
83         uint32_t linktype;
84 };
85
86 struct tcpdump_packet {
87         struct timeval ts;
88         uint32_t caplen;
89         uint32_t len;
90 };
91
92 typedef struct {
93     uint8_t  ver_hdrlen;
94     uint8_t  dscp;
95     uint16_t packet_length;
96     uint16_t identification;
97     uint8_t  flags;
98     uint8_t  fragment;
99     uint8_t  ttl;
100     uint8_t  protocol;
101     uint16_t hdr_checksum;
102     uint32_t src_addr;
103     uint32_t dest_addr;
104 } hdr_ip_t;
105
106 static hdr_ip_t HDR_IP = {0x45, 0, 0, 0x3412, 0, 0, 0xff, 6, 0, 0x01010101, 0x02020202};
107
108 typedef struct {
109     uint16_t source_port;
110     uint16_t dest_port;
111     uint32_t seq_num;
112     uint32_t ack_num;
113     uint8_t  hdr_length;
114     uint8_t  flags;
115     uint16_t window;
116     uint16_t checksum;
117     uint16_t urg;
118 } hdr_tcp_t;
119
120 static hdr_tcp_t HDR_TCP = {139, 139, 0, 0, 0x50, 0, 0, 0, 0};
121
122 static void print_pcap_header(FILE *out)
123 {
124         struct tcpdump_file_header h;
125         h.magic = TCPDUMP_MAGIC;
126         h.major = 2;
127         h.minor = 4;
128         h.zone = 0;
129         h.sigfigs = 0;
130         h.snaplen = 102400; /* As long packets as possible */
131         h.linktype = 101; /* Raw IP */
132         fwrite(&h, sizeof(struct tcpdump_file_header), 1, out);
133 }
134
135 static void print_pcap_packet(FILE *out, unsigned char *data, long length,
136                               long caplen)
137 {
138         struct tcpdump_packet p;
139         p.ts.tv_usec = 0;
140         p.ts.tv_sec = 0;
141         p.caplen = caplen;
142         p.len = length;
143         fwrite(&p, sizeof(struct tcpdump_packet), 1, out);
144         fwrite(data, sizeof(unsigned char), caplen, out);
145 }
146
147 static void print_hex_packet(FILE *out, unsigned char *data, long length)
148 {
149         long i,cur = 0;
150         while(cur < length) {
151                 fprintf(out, "%06lX ", cur);
152                 for(i = cur; i < length && i < cur + 16; i++) {
153                         fprintf(out, "%02x ", data[i]);
154                 }
155                 cur = i;
156                 fprintf(out, "\n");
157         }
158 }
159
160 static void print_netbios_packet(FILE *out, unsigned char *data, long length,
161                                  long actual_length)
162 {
163         unsigned char *newdata; long offset = 0;
164         long newlen;
165
166         newlen = length+sizeof(HDR_IP)+sizeof(HDR_TCP);
167         newdata = (unsigned char *)malloc(newlen);
168
169         HDR_IP.packet_length = htons(newlen);
170         HDR_TCP.window = htons(0x2000);
171         HDR_TCP.source_port = HDR_TCP.dest_port = htons(139);
172
173         memcpy(newdata+offset, &HDR_IP, sizeof(HDR_IP));offset+=sizeof(HDR_IP);
174         memcpy(newdata+offset, &HDR_TCP, sizeof(HDR_TCP));offset+=sizeof(HDR_TCP);
175         memcpy(newdata+offset,data,length);
176
177         print_pcap_packet(out, newdata, newlen, actual_length+offset);
178         free(newdata);
179 }
180
181 unsigned char *curpacket = NULL;
182 unsigned short curpacket_len = 0;
183 long line_num = 0;
184
185 /* Read the log message produced by lib/util.c:show_msg() containing the:
186  *  SMB_HEADER
187  *  SMB_PARAMETERS
188  *  SMB_DATA.ByteCount
189  *
190  * Example:
191  * [2007/04/08 20:41:39, 5] lib/util.c:show_msg(516)
192  *   size=144
193  *   smb_com=0x73
194  *   smb_rcls=0
195  *   smb_reh=0
196  *   smb_err=0
197  *   smb_flg=136
198  *   smb_flg2=49153
199  *   smb_tid=1
200  *   smb_pid=65279
201  *   smb_uid=0
202  *   smb_mid=64
203  *   smt_wct=3
204  *   smb_vwv[ 0]=  117 (0x75)
205  *   smb_vwv[ 1]=  128 (0x80)
206  *   smb_vwv[ 2]=    1 (0x1)
207  *   smb_bcc=87
208  */
209 static void read_log_msg(FILE *in, unsigned char **_buffer,
210                          unsigned short *buffersize, long *data_offset,
211                          long *data_length)
212 {
213         unsigned char *buffer;
214         int tmp; long i;
215         assert(fscanf(in, " size=%hu\n", buffersize)); line_num++;
216         buffer = (unsigned char *)malloc(*buffersize+4); /* +4 for NBSS Header */
217         memset(buffer, 0, *buffersize+4);
218         /* NetBIOS Session Service */
219         buffer[0] = 0x00;
220         buffer[1] = 0x00;
221         memcpy(buffer+2, &buffersize, 2); /* TODO: need to copy as little-endian regardless of platform */
222         /* SMB Packet */
223         buffer[4] = 0xFF;
224         buffer[5] = 'S';
225         buffer[6] = 'M';
226         buffer[7] = 'B';
227         assert(fscanf(in, "  smb_com=0x%x\n", &tmp)); buffer[smb_com] = tmp; line_num++;
228         assert(fscanf(in, "  smb_rcls=%d\n", &tmp)); buffer[smb_rcls] = tmp; line_num++;
229         assert(fscanf(in, "  smb_reh=%d\n", &tmp)); buffer[smb_reh] = tmp; line_num++;
230         assert(fscanf(in, "  smb_err=%d\n", &tmp)); memcpy(buffer+smb_err, &tmp, 2); line_num++;
231         assert(fscanf(in, "  smb_flg=%d\n", &tmp)); buffer[smb_flg] = tmp; line_num++;
232         assert(fscanf(in, "  smb_flg2=%d\n", &tmp)); memcpy(buffer+smb_flg2, &tmp, 2); line_num++;
233         assert(fscanf(in, "  smb_tid=%d\n", &tmp)); memcpy(buffer+smb_tid, &tmp, 2); line_num++;
234         assert(fscanf(in, "  smb_pid=%d\n", &tmp)); memcpy(buffer+smb_pid, &tmp, 2); line_num++;
235         assert(fscanf(in, "  smb_uid=%d\n", &tmp)); memcpy(buffer+smb_uid, &tmp, 2); line_num++;
236         assert(fscanf(in, "  smb_mid=%d\n", &tmp)); memcpy(buffer+smb_mid, &tmp, 2); line_num++;
237         assert(fscanf(in, "  smt_wct=%d\n", &tmp)); buffer[smb_wct] = tmp; line_num++;
238         for(i = 0; i < buffer[smb_wct]; i++) {
239                 assert(fscanf(in, "  smb_vwv[%*3d]=%*5d (0x%X)\n", &tmp)); line_num++;
240                 memcpy(buffer+smb_vwv+i*2, &tmp, 2);
241         }
242
243         *data_offset = smb_vwv+buffer[smb_wct]*2;
244         assert(fscanf(in, "  smb_bcc=%ld\n", data_length)); buffer[(*data_offset)] = *data_length; line_num++;
245         (*data_offset)+=2;
246         *_buffer = buffer;
247 }
248
249 /* Read the log message produced by lib/util.c:dump_data() containing:
250  *  SMB_DATA.Bytes
251  *
252  * Example:
253  * [2007/04/08 20:41:39, 10] lib/util.c:dump_data(2243)
254  *   [000] 00 55 00 6E 00 69 00 78  00 00 00 53 00 61 00 6D  .U.n.i.x ...S.a.m
255  *   [010] 00 62 00 61 00 20 00 33  00 2E 00 30 00 2E 00 32  .b.a. .3 ...0...2
256  *   [020] 00 34 00 2D 00 49 00 73  00 69 00 6C 00 6F 00 6E  .4.-.I.s .i.l.o.n
257  *   [030] 00 20 00 4F 00 6E 00 65  00 46 00 53 00 20 00 76  . .O.n.e .F.S. .v
258  *   [040] 00 34 00 2E 00 30 00 00  00 49 00 53 00 49 00 4C  .4...0.. .I.S.I.L
259  *   [050] 00 4F 00 4E 00 00 00                              .O.N...
260  */
261 static long read_log_data(FILE *in, unsigned char *buffer, long data_length)
262 {
263         long i, addr; char real[2][16]; int ret;
264         unsigned int tmp;
265         for(i = 0; i < data_length; i++) {
266                 if(i % 16 == 0){
267                         if(i != 0) {
268                                 /* Read and discard the ascii data after each line. */
269                                 assert(fscanf(in, "  %8c %8c\n", real[0], real[1]) == 2);
270                         }
271                         ret = fscanf(in, "  [%03lX]", &addr); line_num++;
272                         if(!ret) {
273                                 if(!quiet)
274                                         fprintf(stderr, "%ld: Only first %ld bytes are logged, "
275                                             "packet trace will be incomplete\n", line_num, i-1);
276                                 return i-1;
277                         }
278                         assert(addr == i);
279                 }
280                 if(!fscanf(in, "%02X", &tmp)) {
281                         if(!quiet)
282                                 fprintf(stderr, "%ld: Log message formatted incorrectly. "
283                                     "Only first %ld bytes are logged, packet trace will "
284                                     "be incomplete\n", line_num, i-1);
285                         while ((tmp = getc(in)) != '\n');
286                         return i-1;
287                 }
288                 buffer[i] = tmp;
289         }
290
291         /* Consume the newline so we don't increment num_lines twice */
292         while ((tmp = getc(in)) != '\n');
293         return data_length;
294 }
295
296 int main(int argc, const char **argv)
297 {
298         const char *infile, *outfile;
299         FILE *out, *in;
300         int opt;
301         poptContext pc;
302         char buffer[4096];
303         long data_offset = 0;
304         long data_length = 0;
305         long data_bytes_read = 0;
306         size_t in_packet = 0;
307         struct poptOption long_options[] = {
308                 POPT_AUTOHELP
309                 {
310                         .longName   = "quiet",
311                         .shortName  = 'q',
312                         .argInfo    = POPT_ARG_NONE,
313                         .arg        = &quiet,
314                         .val        = 0,
315                         .descrip    = "Be quiet, don't output warnings",
316                 },
317                 {
318                         .longName   = "hex",
319                         .shortName  = 'h',
320                         .argInfo    = POPT_ARG_NONE,
321                         .arg        = &hexformat,
322                         .val        = 0,
323                         .descrip    = "Output format readable by text2pcap",
324                 },
325                 POPT_TABLEEND
326         };
327
328         pc = poptGetContext(NULL, argc, argv, long_options,
329                             POPT_CONTEXT_KEEP_FIRST);
330         poptSetOtherOptionHelp(pc, "[<infile> [<outfile>]]");
331
332
333         while((opt = poptGetNextOpt(pc)) != -1) {
334                 switch (opt) {
335                 case POPT_ERROR_BADOPT:
336                         fprintf(stderr, "\nInvalid option %s: %s\n\n",
337                                 poptBadOption(pc, 0), poptStrerror(opt));
338                         poptPrintUsage(pc, stderr, 0);
339                         exit(1);
340                 }
341         }
342
343         poptGetArg(pc); /* Drop argv[0], the program name */
344
345         infile = poptGetArg(pc);
346
347         if(infile) {
348                 in  = fopen(infile, "r");
349                 if(!in) {
350                         perror("fopen");
351                         poptFreeContext(pc);
352                         return 1;
353                 }
354         } else in = stdin;
355
356         outfile = poptGetArg(pc);
357
358         if(outfile) {
359                 out = fopen(outfile, "w+");
360                 if(!out) {
361                         perror("fopen");
362                         fprintf(stderr, "Can't find %s, using stdout...\n", outfile);
363                         poptFreeContext(pc);
364                         return 1;
365                 }
366         }
367
368         if(!outfile) out = stdout;
369
370         if(!hexformat)print_pcap_header(out);
371
372         while(!feof(in)) {
373                 char *p;
374                 p = fgets(buffer, sizeof(buffer), in);
375                 if (p == NULL) {
376                         fprintf(stderr, "error reading from input file\n");
377                         break;
378                 }
379                 line_num++;
380                 if(buffer[0] == '[') { /* Header */
381                         if(strstr(buffer, "show_msg")) {
382                                 in_packet++;
383                                 if(in_packet == 1)continue;
384                                 read_log_msg(in, &curpacket, &curpacket_len, &data_offset, &data_length);
385                         } else if(in_packet && strstr(buffer, "dump_data")) {
386                                 data_bytes_read = read_log_data(in, curpacket+data_offset, data_length);
387                         }  else {
388                                 if(in_packet){
389                                         if(hexformat) print_hex_packet(out, curpacket, curpacket_len);
390                                         else print_netbios_packet(out, curpacket, curpacket_len, data_bytes_read+data_offset);
391                                         free(curpacket);
392                                 }
393                                 in_packet = 0;
394                         }
395                 }
396         }
397
398         if (in != stdin) {
399                 fclose(in);
400         }
401
402         if (out != stdout) {
403                 fclose(out);
404         }
405
406         poptFreeContext(pc);
407         return 0;
408 }