forked from apache/drill
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Packet.java
559 lines (482 loc) · 15.6 KB
/
Packet.java
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.store.pcap.decoder;
import org.apache.drill.shaded.guava.com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Formatter;
import static org.apache.drill.exec.store.pcap.PcapFormatUtils.convertInt;
import static org.apache.drill.exec.store.pcap.PcapFormatUtils.convertShort;
import static org.apache.drill.exec.store.pcap.PcapFormatUtils.getByte;
import static org.apache.drill.exec.store.pcap.PcapFormatUtils.getIntFileOrder;
import static org.apache.drill.exec.store.pcap.PcapFormatUtils.getShort;
public class Packet implements Comparable<Packet> {
// pcap header
// typedef struct pcaprec_hdr_s {
// guint32 ts_sec; // timestamp seconds
// guint32 ts_usec; // timestamp microseconds */
// guint32 incl_len; // number of octets of packet saved in file */
// guint32 orig_len; // actual length of packet */
// } pcaprec_hdr_t;
private long timestamp;
private long timestampMicro;
private int originalLength;
protected byte[] raw;
// index into the raw data where the current ethernet packet starts
private int etherOffset;
// index into the raw data where the current IP packet starts. Should be just after etherOffset
protected int ipOffset;
private int packetLength;
protected int etherProtocol;
protected int protocol;
protected boolean isRoutingV6;
protected boolean isCorrupt = false;
private static final Logger logger = LoggerFactory.getLogger(Packet.class);
@SuppressWarnings("WeakerAccess")
public boolean readPcap(final InputStream in, final boolean byteOrder, final int maxLength) throws IOException {
byte[] pcapHeader = new byte[PacketConstants.PCAP_HEADER_SIZE];
int n = in.read(pcapHeader);
if (n < pcapHeader.length) {
return false;
}
decodePcapHeader(pcapHeader, byteOrder, maxLength, 0);
raw = new byte[originalLength];
n = in.read(raw);
if (n < 0) {
return false;
}
etherOffset = 0;
decodeEtherPacket();
return true;
}
@SuppressWarnings("WeakerAccess")
public int decodePcap(final byte[] buffer, final int offset, final boolean byteOrder, final int maxLength) {
raw = buffer;
etherOffset = offset + PacketConstants.PCAP_HEADER_SIZE;
decodePcapHeader(raw, byteOrder, maxLength, offset);
decodeEtherPacket();
return offset + PacketConstants.PCAP_HEADER_SIZE + originalLength;
}
public String getPacketType() {
if (isTcpPacket()) {
return "TCP";
} else if (isUdpPacket()) {
return "UDP";
} else if (isArpPacket()) {
return "ARP";
} else if (isIcmpPacket()) {
return "ICMP";
} else {
return "unknown";
}
}
@SuppressWarnings("WeakerAccess")
public boolean isIpV4Packet() {
return etherProtocol == PacketConstants.IPv4_TYPE;
}
@SuppressWarnings("WeakerAccess")
public boolean isIpV6Packet() {
return etherProtocol == PacketConstants.IPv6_TYPE;
}
@SuppressWarnings("WeakerAccess")
public boolean isPPPoV6Packet() {
return etherProtocol == PacketConstants.PPPoV6_TYPE;
}
@SuppressWarnings("WeakerAccess")
public boolean isTcpPacket() {
return protocol == PacketConstants.TCP_PROTOCOL;
}
@SuppressWarnings("WeakerAccess")
public boolean isUdpPacket() {
return protocol == PacketConstants.UDP_PROTOCOL;
}
@SuppressWarnings("WeakerAccess")
public boolean isArpPacket() {
return protocol == PacketConstants.ARP_PROTOCOL;
}
@SuppressWarnings("WeakerAccess")
public boolean isIcmpPacket() {
return protocol == PacketConstants.ICMP_PROTOCOL;
}
public long getSessionHash() {
if (isTcpPacket()) {
Murmur128 h1 = new Murmur128(1, 2);
byte[] buf = getIpAddressBytes(true);
if (buf == null) {
return 0;
}
h1.hash(buf, 0, buf.length);
h1.hash(getSrc_port());
Murmur128 h2 = new Murmur128(1, 2);
buf = getIpAddressBytes(false);
if (buf == null) {
return 0;
}
h2.hash(buf, 0, buf.length);
h2.hash(getDst_port());
return h1.digest64() ^ h2.digest64();
} else {
return 0;
}
}
public long getTimestamp() {
return timestamp;
}
public long getTimestampMicro() {
return timestampMicro;
}
public int getPacketLength() {
return packetLength;
}
public InetAddress getSrc_ip() {
return getIPAddress(true);
}
public InetAddress getDst_ip() {
return getIPAddress(false);
}
public String getSrc_ip_String() {
InetAddress address = getSrc_ip();
if (address == null) {
return "";
} else {
return address.getHostAddress();
}
}
public String getDst_ip_String() {
InetAddress address = getDst_ip();
if (address == null) {
return "";
} else {
return address.getHostAddress();
}
}
public String getEthernetSource() {
return getEthernetAddress(PacketConstants.ETHER_SRC_OFFSET);
}
public String getEthernetDestination() {
return getEthernetAddress(PacketConstants.ETHER_DST_OFFSET);
}
public int getSequenceNumber() {
if (isTcpPacket()) {
return convertInt(raw, ipOffset + getIPHeaderLength() + PacketConstants.TCP_SEQUENCE_OFFSET);
} else {
return 0;
}
}
public int getAckNumber() {
if (isTcpPacket()) {
return convertInt(raw, ipOffset + getIPHeaderLength() + PacketConstants.TCP_ACK_OFFSET);
} else {
return 0;
}
}
public int getFlags() {
if (isTcpPacket()) {
return convertShort(raw, ipOffset + getIPHeaderLength() + PacketConstants.TCP_FLAG_OFFSET) & 0xfff;
} else {
return 0;
}
}
public String getParsedFlags() {
return formatFlags(getFlags());
}
public void setIsCorrupt(boolean value) {
isCorrupt = value;
}
public boolean getUrgFlag() {
return (getFlags() & 0x20) != 0;
}
public boolean getPshFlag() {
return (getFlags() & 0x8) != 0;
}
public boolean getEceFlag() {
return (getFlags() & 0x40) != 0;
}
public boolean getSynFlag() {
return (getFlags() & 0x2) != 0;
}
public boolean getAckFlag() {
return (getFlags() & 0x10) != 0;
}
public boolean getRstFlag() {
return (getFlags() & 0x4) != 0;
}
public boolean getFinFlag() {
return (getFlags() & 0x1) != 0;
}
public boolean getNSFlag() {
return (getFlags() & 0x100) != 0;
}
public boolean getCwrFlag() {
return (getFlags() & 0x80) != 0;
}
public static String formatFlags(int flags) {
int mask = 0x100;
StringBuilder r = new StringBuilder();
String separator = "";
if ((flags & mask) != 0) {
r.append(separator);
r.append("NS");
separator = "|";
}
mask = mask >> 1;
if ((flags & mask) != 0) {
r.append(separator);
r.append("CWR");
separator = "|";
}
mask = mask >> 1;
if ((flags & mask) != 0) {
r.append(separator);
r.append("ECE");
if ((flags & 2) != 0) {
r.append(" (ECN capable)");
} else {
r.append(" (Congestion experienced)");
}
separator = "|";
}
mask = mask >> 1;
if ((flags & mask) != 0) {
r.append(separator);
r.append("URG");
separator = "|";
}
mask = mask >> 1;
if ((flags & mask) != 0) {
r.append(separator);
r.append("ACK");
separator = "|";
}
mask = mask >> 1;
if ((flags & mask) != 0) {
r.append(separator);
r.append("PSH");
separator = "|";
}
mask = mask >> 1;
if ((flags & mask) != 0) {
r.append(separator);
r.append("RST");
separator = "|";
}
mask = mask >> 1;
if ((flags & mask) != 0) {
r.append(separator);
r.append("SYN");
separator = "|";
}
mask = mask >> 1;
if ((flags & mask) != 0) {
r.append(separator);
r.append("FIN");
}
return r.toString();
}
public int getSrc_port() {
if (isPPPoV6Packet()) {
return getPort(64);
}
if (isIpV6Packet()) {
if (isRoutingV6) {
return getPort(136);
}
return getPort(40);
}
return getPort(0);
}
public int getDst_port() {
if (isPPPoV6Packet()) {
return getPort(66);
}
if (isIpV6Packet()) {
if (isRoutingV6) {
return getPort(138);
}
return getPort(42);
}
return getPort(2);
}
public boolean isCorrupt(){
return isCorrupt;
}
public byte[] getData() {
int payloadDataStart = getIPHeaderLength();
if (isTcpPacket()) {
payloadDataStart += this.getTCPHeaderLength(raw);
} else if (isUdpPacket()) {
payloadDataStart += this.getUDPHeaderLength();
} else {
return null;
}
byte[] data = null;
if (packetLength >= payloadDataStart) {
data = new byte[packetLength - payloadDataStart];
try {
System.arraycopy(raw, ipOffset + payloadDataStart, data, 0, data.length);
} catch (Exception e) {
isCorrupt = true;
String message = "Error while parsing PCAP data: {}";
logger.debug(message, e.getMessage());
logger.trace(message, e); }
}
return data;
}
private InetAddress getIPAddress(final boolean src) {
byte[] ipBuffer = getIpAddressBytes(src);
if (ipBuffer == null) {
return null;
}
try {
return InetAddress.getByAddress(ipBuffer);
} catch (UnknownHostException e) {
return null;
}
}
private byte[] getIpAddressBytes(final boolean src) {
int srcPos;
byte[] ipBuffer;
int byteShift = 0;
if (isIpV4Packet()) {
ipBuffer = new byte[4];
srcPos = src ? PacketConstants.IP4_SRC_OFFSET : PacketConstants.IP4_DST_OFFSET;
} else if (isIpV6Packet()) {
ipBuffer = new byte[16];
if (isRoutingV6) {
byteShift = 96;
}
srcPos = src ? PacketConstants.IP6_SRC_OFFSET + byteShift : PacketConstants.IP6_DST_OFFSET + byteShift;
} else if (isPPPoV6Packet()) {
ipBuffer = new byte[16];
srcPos = src ? PacketConstants.IP6_SRC_OFFSET + PacketConstants.PPPoV6_IP_OFFSET : PacketConstants.IP6_DST_OFFSET + PacketConstants.PPPoV6_IP_OFFSET;
} else {
return null;
}
System.arraycopy(raw, etherOffset + srcPos, ipBuffer, 0, ipBuffer.length);
return ipBuffer;
}
private int getIPHeaderLength() {
return (raw[etherOffset + PacketConstants.VER_IHL_OFFSET] & 0xF) * 4;
}
private int getTCPHeaderLength(final byte[] packet) {
final int inTCPHeaderDataOffset = 12;
// tcp packet header can have options
int dataOffset = etherOffset + getIPHeaderLength() + inTCPHeaderDataOffset;
return 20 + ((packet[dataOffset] >> 4) & 0xF) * 4;
}
private int getUDPHeaderLength() {
return 8;
}
private int ipV4HeaderLength() {
return (getByte(raw, ipOffset) & 0xf) * 4;
}
protected int ipVersion() {
return getByte(raw, ipOffset) >>> 4;
}
private void decodePcapHeader(final byte[] header, final boolean byteOrder, final int maxLength, final int offset) {
timestampMicro = getTimestampMicro(header, byteOrder, offset);
timestamp = timestampMicro / 1000L;
originalLength = getIntFileOrder(byteOrder, header, offset + PacketConstants.ORIGINAL_LENGTH_OFFSET);
packetLength = getIntFileOrder(byteOrder, header, offset + PacketConstants.ACTUAL_LENGTH_OFFSET);
Preconditions.checkState(originalLength <= maxLength,
"Packet too long (%d bytes)", originalLength);
}
private long getTimestampMicro(final byte[] header, final boolean byteOrder, final int offset) {
return getIntFileOrder(byteOrder, header, offset + PacketConstants.TIMESTAMP_OFFSET) * 1000000L +
getIntFileOrder(byteOrder, header, offset + PacketConstants.TIMESTAMP_MICRO_OFFSET);
}
private void decodeEtherPacket() {
etherProtocol = getShort(raw, etherOffset + PacketConstants.PACKET_PROTOCOL_OFFSET);
ipOffset = etherOffset + PacketConstants.IP_OFFSET;
if (isIpV4Packet()) {
protocol = processIpV4Packet();
} else if (isIpV6Packet()) {
protocol = processIpV6Packet();
} else if (isPPPoV6Packet()) {
protocol = getByte(raw, etherOffset + 48);
}
// everything is decoded lazily
}
protected int processIpV4Packet() {
validateIpV4Packet();
return getByte(raw, ipOffset + 9);
}
protected int processIpV6Packet() {
Preconditions.checkState(ipVersion() == 6, "Should have seen IP version 6, got %d", ipVersion());
int headerLength = 40;
int nextHeader = raw[ipOffset + 6] & 0xff;
while (nextHeader != PacketConstants.TCP_PROTOCOL && nextHeader != PacketConstants.UDP_PROTOCOL && nextHeader != PacketConstants.NO_NEXT_HEADER) {
switch (nextHeader) {
case PacketConstants.FRAGMENT_V6:
nextHeader = getByte(raw, ipOffset + headerLength);
headerLength += 8;
break;
case PacketConstants.ROUTING_V6:
isRoutingV6 = true;
nextHeader = getByte(raw, ipOffset + headerLength + 15);
headerLength += (getByte(raw, ipOffset + headerLength) + 1) * 8;
break;
case PacketConstants.HOP_BY_HOP_EXTENSION_V6:
case PacketConstants.DESTINATION_OPTIONS_V6:
case PacketConstants.AUTHENTICATION_V6:
case PacketConstants.ENCAPSULATING_SECURITY_V6:
case PacketConstants.MOBILITY_EXTENSION_V6:
nextHeader = getByte(raw, ipOffset + headerLength);
headerLength += (getByte(raw, ipOffset + headerLength) + 1) * 8;
break;
default:
//noinspection ConstantConditions
Preconditions.checkState(false, "Unknown V6 extension or protocol: ", nextHeader);
return getByte(raw, ipOffset + headerLength);
}
}
return nextHeader;
}
private void validateIpV4Packet() {
Preconditions.checkState(ipVersion() == 4, "Should have seen IP version 4, got %d", ipVersion());
int n = ipV4HeaderLength();
Preconditions.checkState(n >= 20 && n < 200, "Invalid header length: ", n);
}
private String getEthernetAddress(int offset) {
byte[] r = new byte[6];
System.arraycopy(raw, etherOffset + offset, r, 0, 6);
Formatter sb = new Formatter();
for (int i = 0; i < r.length; i++) {
sb.format("%02X%s", r[i], (i < r.length - 1) ? ":" : "");
}
return sb.toString();
}
private int getPort(int offset) {
int dstPortOffset = ipOffset + getIPHeaderLength() + offset;
return convertShort(raw, dstPortOffset);
}
/**
* This function is here so that packets can be sorted for re-sessionization. Packets in TCP streams
* are ordered by the sequence number, so being able to order the packets is necessary to reassemble the
* TCP session.
* @param o The packet to which the current packet is compared to.
* @return Returns the difference in sequence number.
*/
public int compareTo(Packet o) {
return this.getSequenceNumber() - (o).getSequenceNumber();
}
}