-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebscan.js
421 lines (369 loc) · 11.7 KB
/
webscan.js
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
/*
* cross-browser/cross-platform browser-based network scanner and local ip detector
* by samy kamkar 2020/11/07
* https://samy.pl
*/
(function(window) {
function clog(...args)
{
console.log(...args)
}
// scanned ips
let scanned = {}
// subnets to scan for
let subnets = [
'10.0.0.1',
'10.0.0.138',
'10.0.0.2',
'10.0.1.1',
'10.1.1.1',
'10.1.10.1',
'10.10.1.1',
'10.90.90.90',
'192.168.100.1',
'192.168.30.1',
'192.168.30.*',
'192.168.*.1',
'192.168.0.10',
'192.168.0.100',
'192.168.0.101',
'192.168.0.227',
'192.168.0.254',
'192.168.0.3',
'192.168.0.30',
'192.168.0.50',
'192.168.1.10',
'192.168.1.100',
'192.168.1.20',
'192.168.1.200',
'192.168.1.210',
'192.168.1.254',
'192.168.1.99',
'192.168.10.10',
'192.168.10.100',
'192.168.10.50',
'192.168.100.100',
'192.168.123.254',
'192.168.168.168',
'192.168.2.254',
'192.168.223.100',
'192.168.254.254',
//'200.200.200.5',
]
let candidateKeys = ["address", "candidate", "component", "foundation", "port", "priority", "protocol", "relatedAddress", "relatedPort", "sdpMLineIndex", "sdpMid", "tcpType", "type", "usernameFragment"]
// ascii to hex
function a2h(str)
{
let hex = []
for (let n = 0; n < str.length; n++)
{
let hbyte = Number(str.charCodeAt(n)).toString(16)
if (hbyte.length == 1)
hbyte = "0" + hbyte
hex.push(hbyte)
}
return hex.join('')
}
// Connect the two peers. Normally you look for and connect to a remote
// machine here, but we're just connecting two local objects, so we can
// bypass that step.
window.connectPeers = async function(ip, success)
{
let localConnection = null // RTCPeerConnection for our "local" connection
let remoteConnection = null // RTCPeerConnection for the "remote"
let sendChannel = null // RTCDataChannel for the local (sender)
let receiveChannel = null // RTCDataChannel for the remote (receiver)
// Handles clicks on the "Send" button by transmitting
// a message to the remote peer.
function sendMessage()
{
if (sendChannel)
sendChannel.send('test')
}
// Handle status changes on the local end of the data
// channel this is the end doing the sending of data
// in this example.
function handleSendChannelStatusChange(event)
{
clog('handleSendChannelStatusChange', sendChannel)
if (sendChannel)
{
clog('sendChannel state: ' + sendChannel.readyState)
if (sendChannel.readyState === 'open')
sendMessage()
}
}
// Handle onmessage events for the receiving channel.
// These are the data messages sent by the sending channel.
let handleReceiveMessage = async function(event)
{
clog(`handleReceiveMessage: ${ip} ${event}: ${event.data}`)
success(ip)
clog(event.ice)
}
// Called when the connection opens and the data
// channel is ready to be connected to the remote.
let receiveChannelCallback = async function(event)
{
clog(`receiveChannelCallback: ${event}`, event)
receiveChannel = event.channel
receiveChannel.onmessage = handleReceiveMessage
receiveChannel.onopen = handleReceiveChannelStatusChange
receiveChannel.onclose = handleReceiveChannelStatusChange
}
// Handle status changes on the receiver's channel.
function handleReceiveChannelStatusChange(event)
{
clog(`handleReceiveChannelStatusChange`)
if (receiveChannel)
clog("Receive channel's status has changed to " + receiveChannel.readyState)
}
// Close the connection, including data channels if they're open
// Also update the UI to reflect the disconnected status
function disconnectPeers()
{
clog(`disconnectPeers`)
// Close the RTCDataChannels if they're open
if (sendChannel) sendChannel.close()
if (receiveChannel) receiveChannel.close()
// Close the RTCPeerConnections
localConnection.close()
remoteConnection.close()
sendChannel = null
receiveChannel = null
localConnection = null
remoteConnection = null
}
// Create the local connection and its event listeners
const config = {
iceServers: [],
iceTransportPolicy: 'all',
iceCandidatePoolSize: 0
}
localConnection = new RTCPeerConnection(config)
// Create the data channel and establish its event listeners
// XXX is there an alternative of this for older browsers that doesn't require mic?
if (localConnection.createDataChannel)
{
sendChannel = localConnection.createDataChannel("sendChannel")
//sendChannel.onopen = async function(e) { success(ip) }
sendChannel.onopen = handleSendChannelStatusChange
sendChannel.onclose = handleSendChannelStatusChange
}
// Create the remote connection and its event listeners
remoteConnection = new RTCPeerConnection(config)
remoteConnection.ondatachannel = receiveChannelCallback
// generate onicecandidate function for local and remote connections
let iceCan = function(con) {
return function(e)
{
let ret = 0
try
{
if (e.candidate)
{
let newcan = {}
for (let key of candidateKeys)
newcan[key] = e.candidate[key]
newcan.candidate = newcan.candidate.replaceAll(/[\w\-]+\.local|127\.0\.0\.1/g, ip)
newcan.address = ip
//clog('newcan', newcan)
//clog(con)
ret = con.addIceCandidate(newcan)
return ret
}
ret = !e.candidate || con.addIceCandidate(e.candidate)
} catch(e) { clog('err', e) }
return ret
}
}
// Set up the ICE candidates for the two peers
localConnection.onicecandidate = iceCan(remoteConnection)
remoteConnection.onicecandidate = iceCan(localConnection)
// Now create an offer to connect this starts the process
localConnection.createOffer()
.then(offer => localConnection.setLocalDescription(offer))
.then(() => remoteConnection.setRemoteDescription(localConnection.localDescription))
.then(() => remoteConnection.createAnswer())
.then(answer => remoteConnection.setLocalDescription(answer))
.then(() => localConnection.setRemoteDescription(remoteConnection.localDescription))
.catch(handleCreateDescriptionError)
}
// Handle errors attempting to create a description
// this can happen both when creating an offer and when
// creating an answer. In this simple example, we handle
// both the same way.
function handleCreateDescriptionError(error)
{
clog("Unable to create an offer: " + error.toString())
}
// Handle successful addition of the ICE candidate
// on the "local" end of the connection.
function handleLocalAddCandidateSuccess()
{
clog('handleLocalAddCandidateSuccess')
}
// Handle successful addition of the ICE candidate
// on the "remote" end of the connection.
function handleRemoteAddCandidateSuccess()
{
clog('handleRemoteAddCandidateSuccess')
}
// Handle an error that occurs during addition of ICE candidate.
function handleAddCandidateError()
{
clog(`handleAddCandidateError - FAIL`)
}
// convert * in ips to 0..255
window.unroll_ips = function(ips, min, max)
{
let newips = []
// convert single ip to array
if (typeof(ips) === 'string')
ips = [ips]
// flatten * (older Edge doesn't support flatMap)
for (let ip of ips)
newips = newips.concat(
ip.indexOf('*') != -1 ?
[...Array((max-(min||0)||256)-(min||0)).keys()].map(i => ip.replace('*', (min || 0) + i)) :
ip
)
return newips
}
// hit blocks of ips, timeout after ms
window.scanIps = async function(ips, conf, subnet)
{
if (!conf) conf = { }
if (!conf.block) conf.block = 10
if (conf.logger) conf.logger(`scanIps() started, subnet=${!!subnet}`)
let liveIps = {}
// scan blocks of IPs
for (let i = 0; i < ips.length; i += conf.block)
liveIps = Object.assign(liveIps, await scanIpsBlock(ips.slice(i, i+conf.block), conf, subnet))
return liveIps
}
window.scanIpsBlock = async function(ips, conf, subnet)
{
if (!conf) conf = { }
if (!conf.timeout) conf.timeout = 2000
if (conf.logger) conf.logger(`scanIpsBlock(${ips})`)
let promises = {}
let liveIps = {}
let scans = []
const controller = new AbortController()
const { signal } = controller
// this is built for high speed and about 200x faster than standard fetch
let fetchConf = {
signal: signal,
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'omit', // include, *same-origin, omit
headers: { },
redirect: 'manual', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
}
// add ip to our live IPs
let addLive = async function(lip, time)
{
liveIps[lip] = time
if (conf.networkCallback)
conf.networkCallback(lip)
if (conf.logger)
conf.logger(`<b>found host: ${lip}</b> ${liveIps[lip]-scanned[lip]}ms (networkCallback called)`)
// now validate which ips are actually local via webrtc
if (conf.rtc !== false)
await connectPeers(lip, function(tip)
{
if (conf.logger)
conf.logger(`<b><span style='color:tomato;'>found LOCAL ip address: ${tip}</span> (localCallback called)</b>`)
if (conf.localCallback)
conf.localCallback(tip)
liveIps[tip] = 0
})
}
// generate success/fail promises first to speed things up
for (let ip of ips)
promises[ip] =
function(e)
{
// if we didn't abort, this ip is live!
if (e.name !== 'AbortError')
addLive(ip, epoch())
}
// stop all fetches after timeout
let timer = setTimeout(function()
{
controller.abort()
}, conf.timeout)
// scan our ips
for (let ip of ips)
{
// if we haven't scanned it yet
if (!scanned[ip])
{
//clog(epoch(), ip)
scans.push(fetch(`//${ip}:1337/samyscan`, fetchConf).catch(promises[ip]))
scanned[ip] = epoch()
}
}
// when everything's done scanning, get time in ms
await Promise.all(scans.map(p => p.catch(e => e))).then(v => {
for (let [ip, end] of Object.entries(liveIps))
if (liveIps[ip])
liveIps[ip] -= scanned[ip]
})
// end timer in case it wasn't already
clearTimeout(timer)
// if we found subnets, let's scan them
if (subnet)
for (let net of Object.keys(liveIps))
{
if (conf.subnetCallback)
conf.subnetCallback(net)
if (conf.logger) conf.logger(`scanIps(${getSubnet(net)}, subnet=false) (subnetCallback called)`)
Object.assign(liveIps, await scanIps(unroll_ips(getSubnet(net)+'*', 1, 254), conf))
}
// return ip: time
return liveIps
}
// return time
function epoch()
{
//return performance.now()
return new Date().getTime()
}
// return subnet from ip address
function getSubnet(ip)
{
return ip.substr(0, ip.indexOf('.', ip.indexOf('.', ip.indexOf('.')+1)+1)+1)
}
// scan for subnets, then scan discovered subnets for IPs
window.webScanAll = async function(nets, conf)
{
// XXX Chrome acting funky on https, need to investigate
if (location.protocol === 'https:' && !conf.noRedirect)
{
location.protocol = 'http:'
return
}
let ips = {}
if (!conf) conf = { }
if (!nets) nets = subnets
if (conf.logger) conf.logger(`webScanAll() started`)
// scan possible networks
ips.network = await scanIps(unroll_ips(nets), conf, true)
ips.local = Object.keys(ips.network).filter(ip => ips.network[ip] == 0)
// no local ip? try once more
if (!ips.local.length)
{
if (conf.logger) conf.logger('no local ips found, scanning once more')
// delete old times
scanned = {}
// scan once more
ips.network = await scanIps(unroll_ips(nets), conf, true)
ips.local = Object.keys(ips.network).filter(ip => ips.network[ip] == 0)
}
return ips
}
})(window)