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
|
package com.it_jaros.jscanner;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.LockSupport;
import java.util.stream.Stream;
public class Scanner implements AutoCloseable {
private static final int READ_BUFFER_SIZE = 1024;
private volatile boolean cancelled = false;
private final Semaphore socketLimit;
private final boolean bannerRecognition;
private final boolean disableOnlineCheck;
private final boolean quiet;
private final int maxHostsLimit;
private final int maxWorkersPerHost;
private final int timeoutInMillis;
private final long delayInNanos;
public Scanner(
int socketLimit,
int timeoutInMillis,
int delayInMillis,
int maxWorkersPerHost,
int maxHostsLimit,
boolean disableOnlineCheck,
boolean quiet,
boolean bannerRecognition
) {
this.delayInNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(0, delayInMillis));
this.bannerRecognition = bannerRecognition;
this.disableOnlineCheck = disableOnlineCheck;
this.maxHostsLimit = maxHostsLimit;
this.maxWorkersPerHost = maxWorkersPerHost;
this.quiet = quiet;
this.socketLimit = new Semaphore(socketLimit);
this.timeoutInMillis = timeoutInMillis;
}
public Scanner(ScanOptions options) {
this(options.openSocketLimit(), options.timeoutInMillis(), options.delayInMillis(), options.maxWorkersPerHost(), options.maxHostsLimit(), options.disableHostCheck(), options.quiet(), options.bannerRecognition());
}
public Scan createScan(ScanOptions options) {
if (options.hostsFile() != null) {
return createScan(options.hostsFile(), options.ports());
}
return createScan(options.hostsArgv(), options.ports());
}
public Scan createScan(String sourceFile, String ports) {
try (BufferedReader reader = Files.newBufferedReader(Path.of(sourceFile))) {
return createScan(reader.lines(), ports);
} catch (FileNotFoundException | NoSuchFileException e) {
System.out.printf("Could not open file %s%n", sourceFile);
} catch (IOException e) {
System.out.printf("Error while trying to read hosts: %s -> %s %n", e.getClass().getSimpleName(), e.getMessage());
}
return null;
}
public Scan createScan(Stream<String> hosts, String ports) {
return new Scan(hosts.toList(), ports, new ScanState(new Counter(), new ProgressBar(quiet)));
}
public Scan createScan(List<String> hostsArgv, String ports) {
return new Scan(hostsArgv, ports, new ScanState(new Counter(), new ProgressBar(quiet)));
}
public List<ScanResult> runScan(Scan scan) {
if (scan == null) {
throw new IllegalArgumentException("Scan argument cannot be null");
}
ScanState scanState = scan.state();
scanState.getProgressBar().start();
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
CompletionService<ScanResult> completionService = new ExecutorCompletionService<>(executor);
Queue<String> hostsInQueue = new ArrayDeque<>(scan.hosts());
int hostsToProcess = hostsInQueue.size();
int activeHostWorkers = 0;
while (hostsToProcess > 0 && !cancelled) {
// process queue
while (!hostsInQueue.isEmpty() && activeHostWorkers < maxHostsLimit && !cancelled) {
activeHostWorkers++;
final String host = hostsInQueue.poll();
completionService.submit(() -> scanHostPorts(host, scan.ports(), scanState));
}
try {
Future<ScanResult> finishedHost = completionService.poll(10, TimeUnit.MILLISECONDS);
if (finishedHost == null) {
continue;
}
activeHostWorkers--;
hostsToProcess--;
scanState.addScanResult(finishedHost.get());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
System.out.printf("%s -> %s%n", e.getClass().getSimpleName(), e.getMessage());
}
}
if (cancelled) {
executor.shutdown();
}
}
scanState.getProgressBar().stop();
return scanState.getSnapshotOfScanResults();
}
private ScanResult scanHostPorts(String host, String ports, ScanState scanState) {
PortRange portRange = new PortRange(ports);
AtomicLong portSlotFactory = new AtomicLong(System.nanoTime());
BitSet openPorts = new BitSet(PortRange.MAX_PORT);
BitSet filteredPorts = new BitSet(PortRange.MAX_PORT);
HashMap<Integer, ServiceType> bannerRecognition = new HashMap<>();
// Give progressbar the current progress object which is then updated in the sub virtual threads
Progress progress = new Progress(host, portRange.getTotal(), new AtomicInteger(), new AtomicInteger(), new AtomicInteger());
scanState.getProgressBar().submit(progress);
if (!disableOnlineCheck && !checkHostOnline(host)) {
// Visually show that this host is basically done
progress.done().set(progress.total());
return new ScanResult(host, openPorts, filteredPorts, bannerRecognition);
}
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
CompletionService<PortResult> completionService = new ExecutorCompletionService<>(executor);
List<Throwable> errors = new ArrayList<>();
int activePerHostWorkers = 0;
int portsToProcess = portRange.getTotal();
while (portsToProcess > 0 && !cancelled) {
while (!cancelled && portRange.hasNext() && activePerHostWorkers < maxWorkersPerHost) {
activePerHostWorkers++;
final int currentPort = portRange.next();
completionService.submit(() -> {
waitForSlot(portSlotFactory);
return checkPort(host, currentPort, scanState);
});
}
try {
Future<PortResult> portResultFuture = completionService.poll(10, TimeUnit.MILLISECONDS);
if (portResultFuture == null) {
continue;
}
activePerHostWorkers--;
portsToProcess--;
progress.done().incrementAndGet();
// bitset is not thread-safe, so it is set
// outside the other virtual threads that update progress
PortResult portResult = portResultFuture.get();
switch (portResult.getState()) {
case OPEN -> {
openPorts.set(portResult.getPort());
bannerRecognition.put(portResult.getPort(), ServiceDetector.detect(portResult.getBanner()));
}
case FILTERED -> filteredPorts.set(portResult.getPort());
}
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
errors.add(e);
}
}
if (!cancelled) {
executor.shutdown();
}
if (!errors.isEmpty()) {
System.out.printf("Errors happened during scan of host %s%nErrors:%s -> %s", host, errors.size(), errors);
}
}
return new ScanResult(host, openPorts, filteredPorts, bannerRecognition);
}
private boolean checkHostOnline(String host) {
try {
return InetAddress.getByName(host).isReachable(timeoutInMillis);
} catch (IOException e) {
// something went wrong
}
return false;
}
private void waitForSlot(AtomicLong scanSlotFactory) {
if (delayInNanos > 0) {
long slot = scanSlotFactory.getAndAdd(delayInNanos);
long wait = slot - System.nanoTime();
if (wait > 0)
LockSupport.parkNanos(wait);
}
}
private PortResult checkPort(String host, int port, ScanState scanState) {
PortResult result = new PortResult();
result.setPort(port);
result.setState(PortState.UNKNOWN);
// don't allow more sockets then specified
socketLimit.acquireUninterruptibly();
// count how many ports are concurrently checked
scanState.getCounter().inc();
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeoutInMillis);
if (bannerRecognition) {
result.setBanner(getBanner(socket));
}
result.setState(PortState.OPEN);
} catch (SocketTimeoutException ignored) {
result.setState(PortState.FILTERED);
} catch (ConnectException ignored) {
result.setState(PortState.CLOSED);
} catch (IOException ignored) {
// NoRouteToHostException: this can be safely ignored because the port is closed if a host is unreachable
// Will happen a lot when scanning for open ports, so not needed
} finally {
scanState.getCounter().dec();
socketLimit.release();
}
return result;
}
private String getBanner(Socket socket) {
byte[] buffer = new byte[READ_BUFFER_SIZE];
try (InputStream input = socket.getInputStream()) {
socket.setSoTimeout(timeoutInMillis);
int bytesRead = input.read(buffer);
if (bytesRead <= 0) {
return null;
}
return new String(buffer, 0, bytesRead, StandardCharsets.UTF_8).trim();
} catch (IOException e) {
// we ignore this failure
}
return null;
}
public void cancel() {
cancelled = true;
}
@Override
public void close() throws Exception {
cancel();
}
}
|