-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
207 lines (174 loc) · 8.29 KB
/
Copy pathMain.java
File metadata and controls
207 lines (174 loc) · 8.29 KB
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
package com.packetanalyzer;
import com.packetanalyzer.dpi.ConnectionTracker;
import com.packetanalyzer.dpi.DpiEngine;
import com.packetanalyzer.model.*;
import com.packetanalyzer.parser.PacketParser;
import com.packetanalyzer.reader.PcapReader;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* Entry point for the Java Packet Analyzer.
*
* Usage:
* java -jar packet-analyzer.jar <pcap_file> [max_packets] [--dpi]
*
* Arguments:
* pcap_file - Path to a .pcap file
* max_packets - (Optional) Maximum number of packets to display; 0 = no limit
* --dpi - (Optional) Enable Deep Packet Inspection / flow tracking
*/
public class Main {
private static final DateTimeFormatter TS_FMT =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
public static void main(String[] args) {
System.out.println("====================================");
System.out.println(" Packet Analyzer v1.0 (Java)");
System.out.println("====================================");
System.out.println();
if (args.length < 1) {
printUsage();
System.exit(1);
}
String filename = args[0];
int maxPackets = 0;
boolean enableDpi = false;
for (int i = 1; i < args.length; i++) {
if ("--dpi".equalsIgnoreCase(args[i])) {
enableDpi = true;
} else {
try { maxPackets = Integer.parseInt(args[i]); }
catch (NumberFormatException e) {
System.err.println("Invalid argument: " + args[i]);
System.exit(1);
}
}
}
DpiEngine dpi = enableDpi ? new DpiEngine() : null;
try (PcapReader reader = new PcapReader()) {
reader.open(filename);
System.out.println("\n--- Reading packets ---");
RawPacket raw = new RawPacket();
ParsedPacket parsed = new ParsedPacket();
int packetCount = 0;
int parseErrors = 0;
while (reader.readNextPacket(raw)) {
packetCount++;
if (PacketParser.parse(raw, parsed)) {
printPacketSummary(parsed, packetCount);
if (dpi != null) {
Connection.Action action = dpi.processPacket(parsed, raw);
System.out.printf(" [DPI] Action: %s%n", action);
}
} else {
System.err.printf("Warning: Failed to parse packet #%d%n", packetCount);
parseErrors++;
}
if (maxPackets > 0 && packetCount >= maxPackets) {
System.out.printf("%n(Stopped after %d packets)%n", maxPackets);
break;
}
}
// Summary
System.out.println("\n====================================");
System.out.println("Summary:");
System.out.printf(" Total packets read: %d%n", packetCount);
System.out.printf(" Parse errors: %d%n", parseErrors);
if (dpi != null) {
printDpiSummary(dpi.getTracker());
}
System.out.println("====================================");
} catch (Exception e) {
System.err.println("Fatal error: " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
}
// =========================================================================
// Packet pretty-printer
// =========================================================================
private static void printPacketSummary(ParsedPacket pkt, int num) {
System.out.printf("%n========== Packet #%d ==========%n", num);
// Timestamp
Instant ts = Instant.ofEpochSecond(pkt.timestampSec, pkt.timestampUsec * 1000L);
System.out.printf("Time: %s.%06d%n", TS_FMT.format(ts), pkt.timestampUsec);
// Ethernet
System.out.println("\n[Ethernet]");
System.out.printf(" Source MAC: %s%n", pkt.srcMac);
System.out.printf(" Destination MAC: %s%n", pkt.destMac);
String etherDesc = "";
if (pkt.etherType == PacketParser.EtherType.IPv4) etherDesc = " (IPv4)";
else if (pkt.etherType == PacketParser.EtherType.IPv6) etherDesc = " (IPv6)";
else if (pkt.etherType == PacketParser.EtherType.ARP) etherDesc = " (ARP)";
System.out.printf(" EtherType: 0x%04X%s%n", pkt.etherType, etherDesc);
// IP
if (pkt.hasIp) {
System.out.printf("%n[IPv%d]%n", pkt.ipVersion);
System.out.printf(" Source IP: %s%n", pkt.srcIp);
System.out.printf(" Destination IP: %s%n", pkt.destIp);
System.out.printf(" Protocol: %s%n", PacketParser.protocolToString(pkt.protocol));
System.out.printf(" TTL: %d%n", pkt.ttl);
}
// TCP
if (pkt.hasTcp) {
System.out.println("\n[TCP]");
System.out.printf(" Source Port: %d%n", pkt.srcPort);
System.out.printf(" Destination Port: %d%n", pkt.destPort);
System.out.printf(" Sequence Number: %d%n", pkt.seqNumber);
System.out.printf(" Ack Number: %d%n", pkt.ackNumber);
System.out.printf(" Flags: %s%n", PacketParser.tcpFlagsToString(pkt.tcpFlags));
}
// UDP
if (pkt.hasUdp) {
System.out.println("\n[UDP]");
System.out.printf(" Source Port: %d%n", pkt.srcPort);
System.out.printf(" Destination Port: %d%n", pkt.destPort);
}
// Payload preview
if (pkt.payloadLength > 0 && pkt.payloadData != null) {
System.out.println("\n[Payload]");
System.out.printf(" Length: %d bytes%n", pkt.payloadLength);
int previewLen = Math.min(pkt.payloadLength, 32);
System.out.print(" Preview: ");
for (int i = 0; i < previewLen; i++) {
System.out.printf("%02x ", pkt.payloadData[pkt.payloadOffset + i] & 0xFF);
}
if (pkt.payloadLength > 32) System.out.print("...");
System.out.println();
}
}
// =========================================================================
// DPI summary
// =========================================================================
private static void printDpiSummary(ConnectionTracker tracker) {
System.out.println("\n--- DPI Flow Summary ---");
ConnectionTracker.TrackerStats stats = tracker.getStats();
System.out.printf(" Active connections: %d%n", stats.activeConnections);
System.out.printf(" Total connections seen: %d%n", stats.totalConnectionsSeen);
System.out.printf(" Classified: %d%n", stats.classifiedConnections);
System.out.printf(" Blocked: %d%n", stats.blockedConnections);
Map<AppType, Long> dist = new LinkedHashMap<>();
tracker.forEach(conn -> dist.merge(conn.appType, 1L, Long::sum));
if (!dist.isEmpty()) {
System.out.println("\n Application distribution:");
dist.entrySet().stream()
.sorted(Map.Entry.<AppType, Long>comparingByValue().reversed())
.forEach(e -> System.out.printf(" %-15s %d flows%n",
e.getKey().displayName(), e.getValue()));
}
}
private static void printUsage() {
System.out.println("Usage: java -jar packet-analyzer.jar <pcap_file> [max_packets] [--dpi]");
System.out.println();
System.out.println("Arguments:");
System.out.println(" pcap_file - Path to a .pcap file captured by Wireshark");
System.out.println(" max_packets - (Optional) Maximum packets to display (0 = no limit)");
System.out.println(" --dpi - (Optional) Enable Deep Packet Inspection");
System.out.println();
System.out.println("Examples:");
System.out.println(" java -jar packet-analyzer.jar capture.pcap");
System.out.println(" java -jar packet-analyzer.jar capture.pcap 10");
System.out.println(" java -jar packet-analyzer.jar capture.pcap 0 --dpi");
}
}