forked from BornToBeRoot/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Invoke-IPv4PortScan.ps1
402 lines (325 loc) · 13.7 KB
/
Invoke-IPv4PortScan.ps1
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
###############################################################################################################
# Language : PowerShell 4.0
# Filename : Invoke-IPv4PortScan.ps1
# Autor : BornToBeRoot (https://github.com/BornToBeRoot)
# Description : Powerful asynchronus IPv4 Port Scanner
# Repository : https://github.com/BornToBeRoot/PowerShell
###############################################################################################################
<#
.SYNOPSIS
Powerful asynchronus IPv4 Port Scanner
.DESCRIPTION
This powerful asynchronus IPv4 Port Scanner allows you to scan every Port-Range you want (500 to 2600 would work). Only TCP-Ports are scanned.
The result will contain the Port number, Protocol, Service name, Description and the Status.
.EXAMPLE
Invoke-IPv4PortScan -ComputerName fritz.box -EndPort 500
Port Protocol ServiceName ServiceDescription Status
---- -------- ----------- ------------------ ------
21 tcp ftp File Transfer Protocol [Control] open
53 tcp domain Domain Name Server open
80 tcp http World Wide Web HTTP open
.LINK
https://github.com/BornToBeRoot/PowerShell/blob/master/Documentation/Function/Invoke-IPv4PortScan.README.md
#>
function Invoke-IPv4PortScan
{
[CmdletBinding()]
param(
[Parameter(
Position=0,
Mandatory=$true,
HelpMessage='ComputerName or IPv4-Address of the device which you want to scan')]
[String]$ComputerName,
[Parameter(
Position=1,
HelpMessage='First port which should be scanned (Default=1)')]
[ValidateRange(1,65535)]
[Int32]$StartPort=1,
[Parameter(
Position=2,
HelpMessage='Last port which should be scanned (Default=65535)')]
[ValidateRange(1,65535)]
[ValidateScript({
if($_ -lt $StartPort)
{
throw "Invalid Port-Range!"
}
else
{
return $true
}
})]
[Int32]$EndPort=65535,
[Parameter(
Position=3,
HelpMessage='Maximum number of threads at the same time (Default=500)')]
[Int32]$Threads=500,
[Parameter(
Position=4,
HelpMessage='Execute script without user interaction')]
[switch]$Force,
[Parameter(
Position=5,
HelpMessage='Update Service Name and Transport Protocol Port Number Registry from IANA.org')]
[switch]$UpdateList
)
Begin{
Write-Verbose -Message "Script started at $(Get-Date)"
# IANA --> Service Name and Transport Protocol Port Number Registry -> xml-file
$IANA_PortList_WebUri = "https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml"
# Port list path
$XML_PortList_Path = "$PSScriptRoot\Resources\IANA_ServiceName_and_TransportProtocolPortNumber_Registry.xml"
$XML_PortList_BackupPath = "$PSScriptRoot\Resources\IANA_ServiceName_and_TransportProtocolPortNumber_Registry.xml.bak"
# Function to update the list from IANA (Port list)
function UpdateListFromIANA
{
try{
Write-Verbose -Message "Create backup of the IANA Service Name and Transport Protocol Port Number Registry..."
# Backup file, before donload a new version
if(Test-Path -Path $XML_PortList_Path -PathType Leaf)
{
Rename-Item -Path $XML_PortList_Path -NewName $XML_PortList_BackupPath
}
Write-Verbose -Message "Updating Service Name and Transport Protocol Port Number Registry from IANA.org..."
# Download xml-file from IANA and save it
[xml]$New_XML_PortList = Invoke-WebRequest -Uri $IANA_PortList_WebUri -ErrorAction Stop
$New_XML_PortList.Save($XML_PortList_Path)
# Remove backup, if no error
if(Test-Path -Path $XML_PortList_BackupPath -PathType Leaf)
{
Remove-Item -Path $XML_PortList_BackupPath
}
}
catch{
Write-Verbose -Message "Cleanup downloaded file and restore backup..."
# On error: cleanup downloaded file and restore backup
if(Test-Path -Path $XML_PortList_Path -PathType Leaf)
{
Remove-Item -Path $XML_PortList_Path -Force
}
if(Test-Path -Path $XML_PortList_BackupPath -PathType Leaf)
{
Rename-Item -Path $XML_PortList_BackupPath -NewName $XML_PortList_Path
}
$_.Exception.Message
}
}
# Function to assign service with port
function AssignServiceWithPort
{
param(
$Result
)
Begin{
}
Process{
$Service = [String]::Empty
$Description = [String]::Empty
foreach($XML_Node in $XML_PortList.Registry.Record)
{
if(($Result.Protocol -eq $XML_Node.protocol) -and ($Result.Port -eq $XML_Node.number))
{
$Service = $XML_Node.name
$Description = $XML_Node.description
break
}
}
[pscustomobject] @{
Port = $Result.Port
Protocol = $Result.Protocol
ServiceName = $Service
ServiceDescription = $Description
Status = $Result.Status
}
}
End{
}
}
}
Process{
$XML_PortList_Available =Test-Path -Path $XML_PortList_Path -PathType Leaf
if($UpdateList)
{
UpdateListFromIANA
}
elseif($XML_PortList_Available -eq $false)
{
Write-Warning -Message "No xml-file to assign service with port found! Use the parameter ""-UpdateList"" to download the latest version from IANA.org. This warning doesn`t affect the scanning procedure."
}
# Check if it is possible to assign service with port --> import xml-file
if($XML_PortList_Available)
{
$AssignServiceWithPort = $true
$XML_PortList = [xml](Get-Content -Path $XML_PortList_Path)
}
else
{
$AssignServiceWithPort = $false
}
# Check if host is reachable
Write-Verbose -Message "Test if host is reachable..."
if(-not(Test-Connection -ComputerName $ComputerName -Count 2 -Quiet))
{
Write-Warning -Message "$ComputerName is not reachable!"
if($Force -eq $false)
{
$Title = "Continue"
$Info = "Would you like to continue? (perhaps only ICMP is blocked)"
$Options = [System.Management.Automation.Host.ChoiceDescription[]] @("&Yes", "&No")
[int]$DefaultChoice = 0
$Opt = $host.UI.PromptForChoice($Title , $Info, $Options, $DefaultChoice)
switch($Opt)
{
1 {
return
}
}
}
}
$PortsToScan = ($EndPort - $StartPort)
Write-Verbose -Message "Scanning range from $StartPort to $EndPort ($PortsToScan Ports)"
Write-Verbose -Message "Running with max $Threads threads"
# Check if ComputerName is already an IPv4-Address, if not... try to resolve it
$IPv4Address = [String]::Empty
if([bool]($ComputerName -as [IPAddress]))
{
$IPv4Address = $ComputerName
}
else
{
# Get IP from Hostname (IPv4 only)
try{
$AddressList = @(([System.Net.Dns]::GetHostEntry($ComputerName)).AddressList)
foreach($Address in $AddressList)
{
if($Address.AddressFamily -eq "InterNetwork")
{
$IPv4Address = $Address.IPAddressToString
break
}
}
}
catch{ } # Can't get IPAddressList
if([String]::IsNullOrEmpty($IPv4Address))
{
throw "Could not get IPv4-Address for $ComputerName. (Try to enter an IPv4-Address instead of the Hostname)"
}
}
# Scriptblock --> will run in runspaces (threads)...
[System.Management.Automation.ScriptBlock]$ScriptBlock = {
Param(
$IPv4Address,
$Port
)
try{
$Socket = New-Object System.Net.Sockets.TcpClient($IPv4Address,$Port)
if($Socket.Connected)
{
$Status = "Open"
$Socket.Close()
}
else
{
$Status = "Closed"
}
}
catch{
$Status = "Closed"
}
if($Status -eq "Open")
{
[pscustomobject] @{
Port = $Port
Protocol = "tcp"
Status = $Status
}
}
}
Write-Verbose -Message "Setting up RunspacePool..."
# Create RunspacePool and Jobs
$RunspacePool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1, $Threads, $Host)
$RunspacePool.Open()
[System.Collections.ArrayList]$Jobs = @()
Write-Verbose -Message "Setting up Jobs..."
#Set up job for each port...
foreach($Port in $StartPort..$EndPort)
{
$ScriptParams =@{
IPv4Address = $IPv4Address
Port = $Port
}
# Catch when trying to divide through zero
try {
$Progress_Percent = (($Port - $StartPort) / $PortsToScan) * 100
}
catch {
$Progress_Percent = 100
}
Write-Progress -Activity "Setting up jobs..." -Id 1 -Status "Current Port: $Port" -PercentComplete ($Progress_Percent)
# Create mew job
$Job = [System.Management.Automation.PowerShell]::Create().AddScript($ScriptBlock).AddParameters($ScriptParams)
$Job.RunspacePool = $RunspacePool
$JobObj = [pscustomobject] @{
RunNum = $Port - $StartPort
Pipe = $Job
Result = $Job.BeginInvoke()
}
# Add job to collection
[void]$Jobs.Add($JobObj)
}
Write-Verbose -Message "Waiting for jobs to complete & starting to process results..."
# Total jobs to calculate percent complete, because jobs are removed after they are processed
$Jobs_Total = $Jobs.Count
# Process results, while waiting for other jobs
Do {
# Get all jobs, which are completed
$Jobs_ToProcess = $Jobs | Where-Object -FilterScript {$_.Result.IsCompleted}
# If no jobs finished yet, wait 500 ms and try again
if($null -eq $Jobs_ToProcess)
{
Write-Verbose -Message "No jobs completed, wait 500ms..."
Start-Sleep -Milliseconds 500
continue
}
# Get jobs, which are not complete yet
$Jobs_Remaining = ($Jobs | Where-Object -FilterScript {$_.Result.IsCompleted -eq $false}).Count
# Catch when trying to divide through zero
try {
$Progress_Percent = 100 - (($Jobs_Remaining / $Jobs_Total) * 100)
}
catch {
$Progress_Percent = 100
}
Write-Progress -Activity "Waiting for jobs to complete... ($($Threads - $($RunspacePool.GetAvailableRunspaces())) of $Threads threads running)" -Id 1 -PercentComplete $Progress_Percent -Status "$Jobs_Remaining remaining..."
Write-Verbose -Message "Processing $(if($null -eq $Jobs_ToProcess.Count){"1"}else{$Jobs_ToProcess.Count}) job(s)..."
# Processing completed jobs
foreach($Job in $Jobs_ToProcess)
{
# Get the result...
$Job_Result = $Job.Pipe.EndInvoke($Job.Result)
$Job.Pipe.Dispose()
# Remove job from collection
$Jobs.Remove($Job)
# Check if result is null --> if not, return it
if($Job_Result.Status)
{
if($AssignServiceWithPort)
{
AssignServiceWithPort -Result $Job_Result
}
else
{
$Job_Result
}
}
}
} While ($Jobs.Count -gt 0)
Write-Verbose -Message "Closing RunspacePool and free resources..."
# Close the RunspacePool and free resources
$RunspacePool.Close()
$RunspacePool.Dispose()
Write-Verbose -Message "Script finished at $(Get-Date)"
}
End{
}
}