-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPortScanner.cpp
More file actions
358 lines (313 loc) · 13.5 KB
/
Copy pathPortScanner.cpp
File metadata and controls
358 lines (313 loc) · 13.5 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
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
// ============================================================
// Project 6: Port Scanner Simulator
// OOP: Scanner, Host, Port, Report classes
// DSA: BFS over port range, Priority Queue, unordered_map
// Domain: Cybersecurity / Ethical Hacking
// ============================================================
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <queue>
#include <unordered_map>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
// ---------- Port State ----------
enum class PortState { OPEN, CLOSED, FILTERED, OPEN_FILTERED };
string portStateStr(PortState s) {
switch(s) {
case PortState::OPEN: return "open";
case PortState::CLOSED: return "closed";
case PortState::FILTERED: return "filtered";
case PortState::OPEN_FILTERED: return "open|filtered";
}
return "unknown";
}
// ---------- Well-Known Services ----------
unordered_map<int, string> WELL_KNOWN_SERVICES = {
{21,"FTP"},{22,"SSH"},{23,"Telnet"},{25,"SMTP"},{53,"DNS"},
{80,"HTTP"},{110,"POP3"},{143,"IMAP"},{443,"HTTPS"},{445,"SMB"},
{3306,"MySQL"},{3389,"RDP"},{5432,"PostgreSQL"},{5900,"VNC"},
{6379,"Redis"},{8080,"HTTP-Alt"},{8443,"HTTPS-Alt"},{27017,"MongoDB"},
{9200,"Elasticsearch"},{11211,"Memcached"},{2181,"Zookeeper"},
{6667,"IRC"},{4444,"Metasploit"},{1433,"MSSQL"},{1521,"Oracle"}
};
string getService(int port) {
auto it = WELL_KNOWN_SERVICES.find(port);
return it != WELL_KNOWN_SERVICES.end() ? it->second : "unknown";
}
// ---------- CVE Database (simplified) ----------
struct CVE {
string id;
string description;
double cvssScore;
string severity;
};
map<string, vector<CVE>> SERVICE_CVES = {
{"FTP", {{"CVE-2021-46477","Anonymous FTP login enabled",7.5,"HIGH"},
{"CVE-2019-12345","ProFTPD buffer overflow",9.8,"CRITICAL"}}},
{"SSH", {{"CVE-2023-38408","OpenSSH remote code exec",10.0,"CRITICAL"},
{"CVE-2022-44567","SSH weak key exchange",5.3,"MEDIUM"}}},
{"Telnet", {{"CVE-2020-10188","Unencrypted protocol - plaintext creds",9.8,"CRITICAL"}}},
{"HTTP", {{"CVE-2021-41773","Apache path traversal",7.5,"HIGH"},
{"CVE-2022-22965","Spring4Shell RCE",9.8,"CRITICAL"}}},
{"SMB", {{"CVE-2017-0144","EternalBlue (WannaCry vector)",9.3,"CRITICAL"},
{"CVE-2020-0796","SMBGhost RCE",10.0,"CRITICAL"}}},
{"RDP", {{"CVE-2019-0708","BlueKeep RCE",9.8,"CRITICAL"},
{"CVE-2020-0609","RDP Gateway pre-auth RCE",9.8,"CRITICAL"}}},
{"MySQL", {{"CVE-2022-21417","MySQL unauth access",5.5,"MEDIUM"}}},
{"Redis", {{"CVE-2022-0543","Redis Lua sandbox escape",10.0,"CRITICAL"}}},
};
// ---------- Port Result ----------
struct PortResult {
int port;
PortState state;
string service;
string version;
double responseTime; // ms
PortResult(int p, PortState s, string svc, string ver, double rt)
: port(p), state(s), service(svc), version(ver), responseTime(rt) {}
};
// ---------- Host ----------
class Host {
public:
string ip;
string hostname;
string os;
vector<PortResult> ports;
bool isAlive;
Host(string ip, string hostname = "") : ip(ip), hostname(hostname), isAlive(false) {}
void addPort(const PortResult& pr) { ports.push_back(pr); }
int openPortCount() const {
return count_if(ports.begin(), ports.end(),
[](const PortResult& p){ return p.state == PortState::OPEN; });
}
void print() const {
cout << "\nHost: " << ip;
if (!hostname.empty()) cout << " (" << hostname << ")";
cout << "\n Status : " << (isAlive ? "Up" : "Down") << "\n";
if (!os.empty()) cout << " OS : " << os << "\n";
cout << " Ports : " << openPortCount() << " open\n";
}
};
// ---------- Scanner ----------
class PortScanner {
private:
// Simulate host "network" - which ports would be "open"
map<string, vector<int>> simulatedOpenPorts = {
{"192.168.1.1", {22, 80, 443, 8080}},
{"192.168.1.10", {22, 3306, 8080, 6379}},
{"192.168.1.20", {21, 22, 23, 80, 443, 3389}}, // very vulnerable!
{"10.0.0.5", {80, 443, 8443}},
{"172.16.0.1", {22, 53, 8080, 27017}},
};
map<string, vector<int>> simulatedFilteredPorts = {
{"192.168.1.1", {23, 25, 3389}},
{"192.168.1.10", {23, 3389}},
};
double randomLatency(bool isOpen) {
return isOpen ? (1.0 + rand() % 50) : (0.1 + rand() % 5);
}
PortState checkPort(const string& ip, int port) {
auto& openList = simulatedOpenPorts[ip];
auto& filtList = simulatedFilteredPorts[ip];
if (find(openList.begin(), openList.end(), port) != openList.end())
return PortState::OPEN;
if (find(filtList.begin(), filtList.end(), port) != filtList.end())
return PortState::FILTERED;
return PortState::CLOSED;
}
string guessVersion(const string& service) {
map<string, vector<string>> versions = {
{"SSH", {"OpenSSH 7.4", "OpenSSH 8.9p1", "Dropbear SSH 2022.82"}},
{"HTTP", {"Apache httpd 2.4.54", "nginx 1.22.0", "Microsoft IIS 10.0"}},
{"FTP", {"vsftpd 3.0.3", "ProFTPD 1.3.5", "Pure-FTPd"}},
{"MySQL", {"MySQL 8.0.31", "MariaDB 10.6.11"}},
{"RDP", {"Microsoft Terminal Services"}},
{"Telnet", {"Linux telnetd"}},
};
auto it = versions.find(service);
if (it == versions.end()) return "";
return it->second[rand() % it->second.size()];
}
public:
// TCP Connect Scan (BFS-like: scan in batches)
Host tcpConnectScan(const string& targetIP, int startPort, int endPort, bool verbose = false) {
Host host(targetIP);
host.isAlive = simulatedOpenPorts.count(targetIP) > 0 ||
simulatedFilteredPorts.count(targetIP) > 0;
cout << "\n[*] TCP Connect Scan: " << targetIP
<< " ports " << startPort << "-" << endPort << "\n";
// BFS queue - process ports in batches of 10
queue<int> portQueue;
for (int p = startPort; p <= endPort; p++) portQueue.push(p);
int batchSize = 10;
int scanned = 0;
while (!portQueue.empty()) {
vector<int> batch;
for (int i = 0; i < batchSize && !portQueue.empty(); i++) {
batch.push_back(portQueue.front());
portQueue.pop();
}
// Process batch
for (int port : batch) {
PortState state = checkPort(targetIP, port);
double latency = randomLatency(state == PortState::OPEN);
string svc = getService(port);
string ver = (state == PortState::OPEN) ? guessVersion(svc) : "";
if (state == PortState::OPEN || state == PortState::FILTERED) {
host.addPort({port, state, svc, ver, latency});
if (verbose || state == PortState::OPEN) {
cout << " " << setw(5) << port << "/tcp "
<< setw(13) << portStateStr(state)
<< " " << setw(12) << svc
<< " " << ver << "\n";
}
}
scanned++;
}
}
// Detect OS by open ports heuristic
auto& open = simulatedOpenPorts[targetIP];
if (find(open.begin(), open.end(), 3389) != open.end())
host.os = "Windows Server";
else if (find(open.begin(), open.end(), 22) != open.end())
host.os = "Linux/Unix";
else
host.os = "Unknown";
cout << " Scanned " << scanned << " ports | " << host.openPortCount() << " open\n";
return host;
}
// Quick scan of common ports only
Host quickScan(const string& targetIP) {
vector<int> commonPorts = {21,22,23,25,53,80,110,143,443,445,
3306,3389,5432,5900,6379,8080,8443,27017};
Host host(targetIP);
host.isAlive = simulatedOpenPorts.count(targetIP) > 0;
cout << "\n[*] Quick Scan (top " << commonPorts.size() << " ports): " << targetIP << "\n";
for (int port : commonPorts) {
PortState state = checkPort(targetIP, port);
if (state == PortState::OPEN || state == PortState::FILTERED) {
string svc = getService(port);
string ver = (state == PortState::OPEN) ? guessVersion(svc) : "";
double latency = randomLatency(state == PortState::OPEN);
host.addPort({port, state, svc, ver, latency});
cout << " " << setw(5) << port << "/tcp "
<< setw(13) << portStateStr(state)
<< " " << setw(12) << svc
<< " " << ver << "\n";
}
}
return host;
}
};
// ---------- Vulnerability Scanner ----------
class VulnScanner {
public:
struct Finding {
int severity; // for priority queue
string cveId;
string service;
int port;
string description;
double cvssScore;
bool operator<(const Finding& o) const { return cvssScore < o.cvssScore; }
};
priority_queue<Finding> scan(const Host& host) {
priority_queue<Finding> findings;
cout << "\n[*] Vulnerability Scan: " << host.ip << "\n";
cout << string(70, '-') << "\n";
for (auto& pr : host.ports) {
if (pr.state != PortState::OPEN) continue;
auto it = SERVICE_CVES.find(pr.service);
if (it == SERVICE_CVES.end()) continue;
for (auto& cve : it->second) {
int sev = (int)(cve.cvssScore >= 9.0 ? 4 :
cve.cvssScore >= 7.0 ? 3 :
cve.cvssScore >= 4.0 ? 2 : 1);
findings.push({sev, cve.id, pr.service, pr.port,
cve.description, cve.cvssScore});
}
}
return findings;
}
};
// ---------- Report ----------
class ScanReport {
public:
static void generate(const Host& host, priority_queue<VulnScanner::Finding> findings) {
cout << "\n========================================\n";
cout << " SCAN REPORT\n";
cout << "========================================\n";
cout << "Target : " << host.ip << "\n";
cout << "Status : " << (host.isAlive ? "Host Up" : "Host Down") << "\n";
cout << "OS Guess : " << host.os << "\n";
cout << "Open Ports: " << host.openPortCount() << "\n";
cout << "\n--- Open Ports Summary ---\n";
for (auto& p : host.ports) {
if (p.state == PortState::OPEN) {
cout << " " << setw(5) << p.port << "/tcp "
<< setw(12) << p.service << " " << p.version << "\n";
}
}
cout << "\n--- Vulnerabilities (sorted by CVSS) ---\n";
if (findings.empty()) {
cout << " No known vulnerabilities found.\n";
}
while (!findings.empty()) {
auto f = findings.top(); findings.pop();
string risk = f.cvssScore >= 9.0 ? "CRITICAL" :
f.cvssScore >= 7.0 ? "HIGH" :
f.cvssScore >= 4.0 ? "MEDIUM" : "LOW";
cout << " [" << setw(8) << risk << "] "
<< setw(16) << f.cveId
<< " CVSS:" << fixed << setprecision(1) << f.cvssScore
<< " Port:" << f.port << "/" << f.service << "\n"
<< " >> " << f.description << "\n";
}
cout << "\n--- Risk Summary ---\n";
cout << " HIGH/CRITICAL ports exposed: ";
vector<string> riskySvcs = {"Telnet","FTP","SMB","RDP"};
bool any = false;
for (auto& p : host.ports)
if (find(riskySvcs.begin(), riskySvcs.end(), p.service) != riskySvcs.end()) {
cout << p.service << "(" << p.port << ") ";
any = true;
}
if (!any) cout << "None";
cout << "\n";
}
};
// ---------- Main ----------
int main() {
srand(42);
cout << "========================================\n";
cout << " Port Scanner & Vulnerability Tool\n";
cout << " (Educational Simulator)\n";
cout << "========================================\n";
cout << "\nDISCLAIMER: Simulation only. Never scan\n";
cout << "systems without explicit permission.\n";
PortScanner scanner;
VulnScanner vulnScanner;
// Scan 1: Quick scan of server with many open ports
Host h1 = scanner.quickScan("192.168.1.20");
auto findings1 = vulnScanner.scan(h1);
cout << "\n--- Findings for 192.168.1.20 ---\n";
{
auto copy = findings1;
while (!copy.empty()) {
auto f = copy.top(); copy.pop();
cout << " " << f.cveId << " | " << f.service
<< " | CVSS:" << f.cvssScore << " | " << f.description << "\n";
}
}
ScanReport::generate(h1, findings1);
// Scan 2: TCP Connect Scan on a different target
Host h2 = scanner.tcpConnectScan("192.168.1.10", 1, 9999, true);
auto findings2 = vulnScanner.scan(h2);
ScanReport::generate(h2, findings2);
return 0;
}