Advertisement
Guest User

Untitled

a guest
Dec 18th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.48 KB | None | 0 0
  1. #requires -version 2
  2.  
  3.  
  4. <#
  5. .SYNOPSIS
  6. Linux nmap for PowerShell (almost).
  7. Ping sweeps and scans a network for specified open ports. Can also perform DNS lookups.
  8. Port connect timeout is custom (milliseconds).
  9. Multithreaded with a default of 32 concurrent threads.
  10.  
  11. If you get over about 20-25,000 threads, you'll experience significant slowdowns
  12. towards the end, so avoiding that is recommended. This number may vary in your environment.
  13.  
  14. Svendsen Tech.
  15. Copyright (c) 2015, Joakim Svendsen
  16. All rights reserved.
  17.  
  18. BSD 3-clause license. http://www.opensource.org/licenses/BSD-3-Clause
  19.  
  20. Homepage/documentation:
  21. http://www.powershelladmin.com/wiki/Port_scan_subnets_with_PSnmap_for_PowerShell
  22.  
  23. .PARAMETER ComputerName
  24. List of CIDR, IP/subnet, IP or DNS/NetBIOS name.
  25. .PARAMETER PORT
  26. Port or ports to check.
  27. .PARAMETER Dns
  28. Perform a DNS lookup.
  29. .PARAMETER ScanOnPingFail
  30. Scan all hosts even if ping fails.
  31. .PARAMETER ThrottleLimit
  32. Number of concurrent threads. Default: 32.
  33. .PARAMETER HideProgress
  34. Do not display progress with Write-Progress
  35. .PARAMETER Timeout
  36. Timeout in seconds for each thread. Causes problems if too short. 30 as a default seems OK.
  37. .PARAMETER PortConnectTimeoutMs
  38. Port connect timeout in milliseconds. 5 seconds as a default for LAN scans. Increase for mobile/slow WAN.
  39. .PARAMETER NoSummary
  40. Do not display the end summary with start and end time, using Write-Host.
  41. #>
  42. function Invoke-PSnmap {
  43. [CmdletBinding()]
  44. param(
  45. # CIDR, IP/subnet, IP, or DNS/NetBIOS name.
  46. [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][Alias('PSComputerName', 'Cn')][string[]] $ComputerName,
  47. # Port or ports to check.
  48. [int[]] $Port,
  49. # Perform a DNS lookup.
  50. [switch] $Dns,
  51. # Scan all hosts even if ping fails.
  52. [switch] $ScanOnPingFail,
  53. # Number of concurrent threads.
  54. [int] $ThrottleLimit = 32,
  55. # Do not display progress with Write-Progress.
  56. [switch] $HideProgress,
  57. # Timeout in seconds. Causes problems if too short. 30 as a default seems OK.
  58. [int] $Timeout = 30,
  59. # Port connect timeout in milliseconds. 5000 as a default seems sane.
  60. [int] $PortConnectTimeoutMs = 5000,
  61. # Do not display the end summary with start and end time, using Write-Host.
  62. [switch] $NoSummary
  63. )
  64.  
  65. # PowerShell nmap-ish clone for Windows.
  66. # Copyright (c) 2015, Svendsen Tech, All rights reserved.
  67. # Author: Joakim Borger Svendsen
  68. # Runspace "framework" borrowed and adapted from Zachary Loeber's work.
  69. # BSD 3-clause license - http://www.opensource.org/licenses/BSD-3-Clause
  70.  
  71. # July 20, 2015. beta1
  72.  
  73. Set-StrictMode -Version Latest
  74. $MyEAP = 'Stop'
  75. $ErrorActionPreference = $MyEAP
  76. $StartTime = Get-Date
  77. #$MyScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition
  78. #Write-Verbose -Message "Creating script-scoped PSipcalc alias."
  79. #New-Alias -Name Invoke-PSipcalc -Scope Script -Value (Join-Path $MyScriptRoot $PSipcalc)
  80. $IPv4Regex = '(?:(?:0?0?\d|0?[1-9]\d|1\d\d|2[0-5][0-5]|2[0-4]\d)\.){3}(?:0?0?\d|0?[1-9]\d|1\d\d|2[0-5][0-5]|2[0-4]\d)'
  81. $RunspaceTimers = [HashTable]::Synchronized(@{})
  82. $PortData = [HashTable]::Synchronized(@{})
  83. $Runspaces = New-Object -TypeName System.Collections.ArrayList
  84. $RunspaceCounter = 0
  85. Write-Verbose -Message 'Creating initial session state.'
  86. $ISS = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
  87. $ISS.Variables.Add((New-Object -TypeName System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList 'RunspaceTimers', $RunspaceTimers, ''))
  88. $ISS.Variables.Add((New-Object -TypeName System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList 'PortData', $PortData, ''))
  89. Write-Verbose -Message 'Creating runspace pool.'
  90. $RunspacePool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1, $ThrottleLimit, $ISS, $Host)
  91. $RunspacePool.ApartmentState = 'STA'
  92. $RunspacePool.Open()
  93. $ScriptBlock =
  94. {
  95. [CmdletBinding()]
  96. param(
  97. [int] $ID,
  98. [string] $Computer,
  99. [int[]] $Port,
  100. [switch] $Dns,
  101. [int] $PortConnectTimeout
  102. )
  103. # Get the start time.
  104. $RunspaceTimers.$ID = Get-Date
  105. # The objects returned here are passed to the pipeline...
  106. if (-not $PortData.ContainsKey($Computer))
  107. {
  108. #'' | Select-Object -Property ComputerName, Error, Ping
  109. $PortData[$Computer] = New-Object -TypeName PSObject -Property @{
  110. ComputerName = $Computer
  111. }
  112. }
  113. # I'm lazy and just took this DNS stuff from the existing Get-PortState module...
  114. if ($Dns)
  115. {
  116. $ErrorActionPreference = 'SilentlyContinue'
  117. $HostEntry = [System.Net.Dns]::GetHostEntry($Computer)
  118. $Result = $?
  119. $ErrorActionPreference = 'Continue'
  120. # It looks like it's "successful" even when it isn't, for any practical purposes (pass in IP, get IP as .HostName)...
  121. if ($Result)
  122. {
  123. ## This is a best-effort attempt at handling things flexibly.
  124. ##
  125. # I think this should mostly work... If I pass in an IPv4 address that doesn't
  126. # resolve to a host name, the same IP seems to be used to populate the HostName property.
  127. # So this means that you'll get the IP address twice for IPs that don't resolve, but
  128. # it will still say it resolved. For IPs that do resolve to a host name, you will
  129. # correctly get the host name in the IP/DNS column. For host names or IPs that resolve to
  130. # one or more IP addresses, you will get the IPs joined together with semicolons.
  131. # Both IPv6 and IPv4 may be reported depending on your environment.
  132. if ($HostEntry.HostName.Split('.')[0] -ieq $Computer.Split('.')[0])
  133. {
  134. $IPDns = ($HostEntry | Select -Expand AddressList | Select -Expand IPAddressToString) -join ';'
  135. }
  136. else
  137. {
  138. $IPDns = $HostEntry.HostName, ($HostEntry.Aliases -join ';') -join ';' -replace ';\z'
  139. }
  140. $PortData[$Computer] | Add-Member -MemberType NoteProperty -Name 'IP/DNS' -Value $IPDns
  141. }
  142. else {
  143. $PortData[$Computer] | Add-Member -MemberType NoteProperty -Name 'IP/DNS' -Value $Null
  144. }
  145. continue
  146. } # end of if $Dns
  147. foreach ($p in $Port | Sort-Object) { # only one port per thread, legacy code...
  148. Write-Verbose -Message "Processing ${Computer}, port $p in thread."
  149. $MySock, $IASyncResult, $Result = $Null, $Null, $Null
  150. $MySock = New-Object Net.Sockets.TcpClient
  151. $IASyncResult = [IAsyncResult] $MySock.BeginConnect($Computer, $p, $null, $null)
  152. $Result = $IAsyncResult.AsyncWaitHandle.WaitOne($PortConnectTimeout, $true)
  153. if ($MySock.Connected)
  154. {
  155. $MySock.Close()
  156. $MySock.Dispose()
  157. $MySock = $Null
  158. Write-Verbose "${Computer}: Port $p is OPEN"
  159. $PortData[$Computer] | Add-Member -MemberType NoteProperty -Name "Port $p" -Value $True
  160. }
  161. else
  162. {
  163. $MySock.Close()
  164. $MySock.Dispose()
  165. $MySock = $Null
  166. Write-Verbose "${Computer}: Port $p is CLOSED"
  167. $PortData[$Computer] | Add-Member -MemberType NoteProperty -Name "Port $p" -Value $False
  168. }
  169. <#$MySocket = $Null
  170. $MySocket = New-Object Net.Sockets.TcpClient
  171. # Suppress error messages
  172. $ErrorActionPreference = 'SilentlyContinue'
  173. # Try to connect
  174. $MySocket.Connect($Computer, $p)
  175. # Make error messages visible again
  176. $ErrorActionPreference = 'Continue'
  177. if ($MySocket.Connected) {
  178. $MySocket.Close()
  179. $MySocket.Dispose()
  180. $MySocket = $Null
  181. Write-Verbose "${Computer}: Port $p is OPEN"
  182. $PortData[$Computer] | Add-Member -MemberType NoteProperty -Name "Port $p" -Value $True
  183. }
  184. else
  185. {
  186. $MySocket.Close()
  187. $MySocket.Dispose()
  188. $MySocket = $Null
  189. Write-Verbose "${Computer}: Port $p is CLOSED"
  190. $PortData[$Computer] | Add-Member -MemberType NoteProperty -Name "Port $p" -Value $False
  191. }#>
  192. }
  193. # Emit object to pipeline!
  194. #$o
  195. } # end of script block that's run for each host/port/DNS
  196.  
  197. function Get-Result
  198. {
  199. [CmdletBinding()]
  200. param(
  201. [switch] $Wait
  202. )
  203. do
  204. {
  205. $More = $false
  206. foreach ($Runspace in $Runspaces) {
  207. $StartTime = $RunspaceTimers[$Runspace.ID]
  208. if ($Runspace.Handle.IsCompleted)
  209. {
  210. #Write-Verbose -Message ('Thread done for {0}' -f $Runspace.IObject)
  211. $Runspace.PowerShell.EndInvoke($Runspace.Handle)
  212. $Runspace.PowerShell.Dispose()
  213. $Runspace.PowerShell = $null
  214. $Runspace.Handle = $null
  215. }
  216. elseif ($Runspace.Handle -ne $null)
  217. {
  218. $More = $true
  219. }
  220. if ($Timeout -and $StartTime)
  221. {
  222. if ((New-TimeSpan -Start $StartTime).TotalSeconds -ge $Timeout -and $Runspace.PowerShell) {
  223. Write-Warning -Message ('Timeout {0}' -f $Runspace.IObject)
  224. $Runspace.PowerShell.Dispose()
  225. $Runspace.PowerShell = $null
  226. $Runspace.Handle = $null
  227. }
  228. }
  229. }
  230. if ($More -and $PSBoundParameters['Wait'])
  231. {
  232. Start-Sleep -Milliseconds 100
  233. }
  234. foreach ($Thread in $Runspaces.Clone())
  235. {
  236. if (-not $Thread.Handle) {
  237. Write-Verbose -Message ('Removing {0} from runspaces' -f $Thread.IObject)
  238. $Runspaces.Remove($Thread)
  239. }
  240. }
  241. if (-not $HideProgress)
  242. {
  243. $ProgressSplatting = @{
  244. Activity = 'Processing'
  245. Status = 'Processing: {0} of {1} total threads done' -f ($RunspaceCounter - $Runspaces.Count), $RunspaceCounter
  246. PercentComplete = ($RunspaceCounter - $Runspaces.Count) / $RunspaceCounter * 100
  247. }
  248. Write-Progress @ProgressSplatting
  249. }
  250. }
  251. while ($More -and $PSBoundParameters['Wait'])
  252. } # end of Get-Result
  253. $PingScriptBlock =
  254. {
  255. [CmdletBinding()]
  256. param(
  257. [int] $ID,
  258. [string] $ComputerName
  259. )
  260. $RunspaceTimers.$ID = Get-Date
  261. if (-not $PortData.ContainsKey($ComputerName))
  262. {
  263. $PortData[$ComputerName] = New-Object -TypeName PSObject -Property @{ Ping = $Null }
  264. }
  265. $PortData[$ComputerName] | Add-Member -MemberType NoteProperty -Name Ping -Value (Test-Connection -ComputerName $ComputerName -Quiet -Count 1) -Force
  266. }
  267.  
  268. $AllComputerName = @()
  269. foreach ($Computer in $ComputerName)
  270. {
  271. if ($Computer -match "\A(?:${IPv4Regex}/\d{1,2}|${IPv4Regex}[\s/]+$IPv4Regex)\z")
  272. {
  273. Write-Verbose -Message "Detected CIDR notation or IP/subnet: '$Computer'. Expanding ..."
  274. $AllComputerName += @((Invoke-PSipcalc -NetworkAddress $Computer -Enumerate).IPEnumerated)
  275. }
  276. else {
  277. $AllComputerName += $Computer
  278. }
  279. }
  280. # Do a ping scan using the same thread engine as later, but don't run Get-Result.
  281. # We sort of need some type of feedback even without Write-Verbose at this step...
  282. # Abandoned support for pipeline input (I'm guessing "who cares" about that 99 % of the time with this script).
  283. Write-Verbose -Message "$(Get-Date): Doing a ping sweep. Please wait."
  284. foreach ($Computer in $AllComputerName)
  285. {
  286. ++$RunspaceCounter
  287. $psCMD = [System.Management.Automation.PowerShell]::Create().AddScript($PingScriptBlock)
  288. [void] $psCMD.AddParameter('ID', $RunspaceCounter)
  289. [void] $psCMD.AddParameter('Computer', $Computer) #
  290. [void] $psCMD.AddParameter('Verbose', $VerbosePreference)
  291. $psCMD.RunspacePool = $RunspacePool
  292. Write-Verbose -Message "Starting $Computer ping thread" #
  293. [void]$Runspaces.Add(@{
  294. Handle = $psCMD.BeginInvoke()
  295. PowerShell = $psCMD
  296. IObject = $Computer #
  297. ID = $RunspaceCounter
  298. })
  299. #Get-Result
  300. }
  301. [int] $Count = 1
  302. # Wait for pings to finish, so we have objects for all computernames/IPs.
  303. # This is pretty ugly, but works.
  304. while (1)
  305. {
  306. if ($Runspaces[($RunspaceCounter-1)].Handle.IsCompleted)
  307. {
  308. break
  309. }
  310. Start-Sleep -Milliseconds 500
  311. if ($Count % 4) {
  312. Write-Verbose -Message "Waiting for ping scan to finish... (iterations: $Count)."
  313. }
  314. ++$Count
  315. }
  316. # Ugh, wait for the last one. Damn off by one crap. :( Not even sure why.
  317. Start-Sleep -Milliseconds 3500
  318. # seems to work without now? # no, one missing result, damn it.
  319. if ($PSBoundParameters['ScanOnPingFail'])
  320. {
  321. $IterComputerName = $PortData.Keys
  322. }
  323. else {
  324. $IterComputerName = $PortData.GetEnumerator() | Where-Object { $_.Value.Ping -eq $True } | Select-Object -ExpandProperty Name
  325. }
  326. foreach ($Computer in $IterComputerName)
  327. {
  328. # Starting DNS thread if switch was specified.
  329. if ($PSBoundParameters['Dns']) {
  330. ++$RunspaceCounter
  331. $psCMD = [System.Management.Automation.PowerShell]::Create().AddScript($ScriptBlock)
  332. [void] $psCMD.AddParameter('ID', $RunspaceCounter)
  333. [void] $psCMD.AddParameter('Computer', $Computer)
  334. [void] $PSCMD.AddParameter('Port', $Null)
  335. [void] $PSCMD.AddParameter('Dns', $Dns)
  336. [void] $psCMD.AddParameter('Verbose', $VerbosePreference)
  337. $psCMD.RunspacePool = $RunspacePool
  338. Write-Verbose -Message "Starting $Computer DNS thread"
  339. [void]$Runspaces.Add(@{
  340. Handle = $psCMD.BeginInvoke()
  341. PowerShell = $psCMD
  342. IObject = $Computer
  343. ID = $RunspaceCounter
  344. })
  345. }
  346. Get-Result
  347. # Starting one thread for each port.
  348. foreach ($p in $Port)
  349. {
  350. #Start-Sleep -Milliseconds 25
  351. $RunspaceCounter++
  352. $psCMD = [System.Management.Automation.PowerShell]::Create().AddScript($ScriptBlock)
  353. [void] $psCMD.AddParameter('ID', $RunspaceCounter)
  354. [void] $psCMD.AddParameter('Computer', $Computer)
  355. [void] $psCMD.AddParameter('Port', $p)
  356. [void] $psCMD.AddParameter('Dns', $Null)
  357. [void] $psCMD.AddParameter('PortConnectTimeout', $PortConnectTimeoutMs)
  358. [void] $psCMD.AddParameter('Verbose', $VerbosePreference)
  359. $psCMD.RunspacePool = $RunspacePool
  360. Write-Verbose -Message "Starting $Computer, port $p"
  361. [void]$Runspaces.Add(@{
  362. Handle = $psCMD.BeginInvoke()
  363. PowerShell = $psCMD
  364. IObject = $Computer
  365. ID = $RunspaceCounter
  366. })
  367. Get-Result
  368. }
  369. }
  370. #Get-Result
  371. Get-Result -Wait
  372. if (-not $HideProgress)
  373. {
  374. Write-Progress -Activity 'Processing' -Status 'Done' -Completed
  375. }
  376. Write-Verbose -Message "Closing runspace pool."
  377. $RunspacePool.Close()
  378. $RunspacePool.Dispose()
  379. [hashtable[]] $Script:TestPortProperties = @{ Name = 'ComputerName'; Expression = { $_.Name } }
  380. if ($Dns)
  381. {
  382. $Script:TestPortProperties += @{ Name = 'IP/DNS'; Expression = { $_.Value.'IP/DNS' } }
  383. }
  384. $Script:TestPortProperties += @{ Name = 'Ping'; Expression = { $_.Value.Ping } }
  385. #$Script:TestPortProperties += @($Port | ForEach-Object { @{ Name = "Port $_"; Expression = { $_."Port $_" } } })
  386. foreach ($p in $Port | Sort-Object)
  387. {
  388. $Script:TestPortProperties += @{ Name = "Port $p"; Expression = [ScriptBlock]::Create("`$_.Value.'Port $p'") }
  389. }
  390. $PortData.GetEnumerator() |
  391. Sort-Object -Property @{ Expression ={ if ($_.Name -match "\A$IPv4Regex\z") { ($_.Name.Split('.') | ForEach-Object { '{0:D3}' -f [int] $_ }) -join '.' } else { $_.Name } } } |
  392. Select-Object -Property $Script:TestPortProperties
  393. Write-Verbose -Message '"Exporting" $Global:STTestPortData and $Global:STTestPortDataProperties'
  394. $Global:STTestPortData = $PortData
  395. $Global:STTestPortDataProperties = $Script:TestPortProperties
  396. if (-not $NoSummary)
  397. {
  398. Write-Host -ForegroundColor Green ('Start time: ' + $StartTime)
  399. Write-Host -ForegroundColor Green ('End time: ' + (Get-Date))
  400. }
  401. }
  402.  
  403. <#
  404. .SYNOPSIS
  405. Provides detailed network information. Accepts CIDR notation and IP / subnet mask.
  406. Inspired by the utility "ipcalc" on Linux.
  407.  
  408. Svendsen Tech.
  409. Copyright (c) 2015, Joakim Svendsen
  410. All rights reserved.
  411.  
  412. BSD 3-clause license. http://www.opensource.org/licenses/BSD-3-Clause
  413.  
  414. .PARAMETER NetworkAddress
  415. CIDR notation network address, or using subnet mask. Examples: '192.168.0.1/24', '10.20.30.40/255.255.0.0'.
  416. .PARAMETER Contains
  417. Causes PSipcalc to return a boolean value for whether the specified IP is in the specified network. Includes network address and broadcast address.
  418. .PARAMETER Enumerate
  419. Enumerates all IPs in subnet (potentially resource-expensive). Ignored if you use -Contains.
  420. #>
  421. function Invoke-PSipcalc {
  422. [CmdletBinding()]
  423. param(
  424. [Parameter(Mandatory=$True)][string[]] $NetworkAddress,
  425. [string] $Contains,
  426. [switch] $Enumerate
  427. )
  428.  
  429. # PowerShell ipcalc clone: PSipcalc.
  430. # Copyright (c), 2015, Svendsen Tech
  431. # All rights reserved.
  432.  
  433. ## Author: Joakim Svendsen
  434.  
  435. # BSD 3-clause license.
  436.  
  437. # Original release 2015-07-13 (ish) v1.0 (or whatever...)
  438. # 2015-07-16: v1.2. Standardized the TotalHosts and UsableHosts properties to always be of the type int64.
  439. # Formely TotalHosts was a string, except for network lengths of 30-32, when it was an int32. UsableHosts used to be int32.
  440.  
  441. # 2015-07-15: Added -Contains and fixed some comment bugs(!) plus commented a bit more and made minor tweaks. v1.1, I guess.
  442.  
  443. Set-StrictMode -Version Latest
  444. $ErrorActionPreference = 'Stop'
  445. # This is a regex I made to match an IPv4 address precisely ( http://www.powershelladmin.com/wiki/PowerShell_regex_to_accurately_match_IPv4_address_%280-255_only%29 )
  446. $IPv4Regex = '(?:(?:0?0?\d|0?[1-9]\d|1\d\d|2[0-5][0-5]|2[0-4]\d)\.){3}(?:0?0?\d|0?[1-9]\d|1\d\d|2[0-5][0-5]|2[0-4]\d)'
  447.  
  448. function Convert-IPToBinary
  449. {
  450. param(
  451. [string] $IP
  452. )
  453. $IP = $IP.Trim()
  454. if ($IP -match "\A${IPv4Regex}\z")
  455. {
  456. try
  457. {
  458. return ($IP.Split('.') | ForEach-Object { [System.Convert]::ToString([byte] $_, 2).PadLeft(8, '0') }) -join ''
  459. }
  460. catch
  461. {
  462. Write-Warning -Message "Error converting '$IP' to a binary string: $_"
  463. return $Null
  464. }
  465. }
  466. else
  467. {
  468. Write-Warning -Message "Invalid IP detected: '$IP'."
  469. return $Null
  470. }
  471. }
  472.  
  473. function Convert-BinaryToIP
  474. {
  475. param(
  476. [string] $Binary
  477. )
  478. $Binary = $Binary -replace '\s+'
  479. if ($Binary.Length % 8)
  480. {
  481. Write-Warning -Message "Binary string '$Binary' is not evenly divisible by 8."
  482. return $Null
  483. }
  484. [int] $NumberOfBytes = $Binary.Length / 8
  485. $Bytes = @(foreach ($i in 0..($NumberOfBytes-1))
  486. {
  487. try
  488. {
  489. #$Bytes += # skipping this and collecting "outside" seems to make it like 10 % faster
  490. [System.Convert]::ToByte($Binary.Substring(($i * 8), 8), 2)
  491. }
  492. catch
  493. {
  494. Write-Warning -Message "Error converting '$Binary' to bytes. `$i was $i."
  495. return $Null
  496. }
  497. })
  498. return $Bytes -join '.'
  499. }
  500.  
  501. function Get-ProperCIDR
  502. {
  503. param(
  504. [string] $CIDRString
  505. )
  506. $CIDRString = $CIDRString.Trim()
  507. $o = '' | Select-Object -Property IP, NetworkLength
  508. if ($CIDRString -match "\A(?<IP>${IPv4Regex})\s*/\s*(?<NetworkLength>\d{1,2})\z")
  509. {
  510. # Could have validated the CIDR in the regex, but this is more informative.
  511. if ([int] $Matches['NetworkLength'] -lt 0 -or [int] $Matches['NetworkLength'] -gt 32)
  512. {
  513. Write-Warning "Network length out of range (0-32) in CIDR string: '$CIDRString'."
  514. return
  515. }
  516. $o.IP = $Matches['IP']
  517. $o.NetworkLength = $Matches['NetworkLength']
  518. }
  519. elseif ($CIDRString -match "\A(?<IP>${IPv4Regex})[\s/]+(?<SubnetMask>${IPv4Regex})\z")
  520. {
  521. $o.IP = $Matches['IP']
  522. $SubnetMask = $Matches['SubnetMask']
  523. if (-not ($BinarySubnetMask = Convert-IPToBinary $SubnetMask))
  524. {
  525. return # warning displayed by Convert-IPToBinary, nothing here
  526. }
  527. # Some validation of the binary form of the subnet mask,
  528. # to check that there aren't ones after a zero has occurred (invalid subnet mask).
  529. # Strip all leading ones, which means you either eat 32 1s and go to the end (255.255.255.255),
  530. # or you hit a 0, and if there's a 1 after that, we've got a broken subnet mask, amirite.
  531. if ((($BinarySubnetMask) -replace '\A1+') -match '1')
  532. {
  533. Write-Warning -Message "Invalid subnet mask in CIDR string '$CIDRString'. Subnet mask: '$SubnetMask'."
  534. return
  535. }
  536. $o.NetworkLength = [regex]::Matches($BinarySubnetMask, '1').Count
  537. }
  538. else
  539. {
  540. Write-Warning -Message "Invalid CIDR string: '${CIDRString}'. Valid examples: '192.168.1.0/24', '10.0.0.0/255.0.0.0'."
  541. return
  542. }
  543. # Check if the IP is all ones or all zeroes (not allowed: http://www.cisco.com/c/en/us/support/docs/ip/routing-information-protocol-rip/13788-3.html )
  544. if ($o.IP -match '\A(?:(?:1\.){3}1|(?:0\.){3}0)\z')
  545. {
  546. Write-Warning "Invalid IP detected in CIDR string '${CIDRString}': '$($o.IP)'. An IP can not be all ones or all zeroes."
  547. return
  548. }
  549. return $o
  550. }
  551.  
  552. function Get-IPRange
  553. {
  554. param(
  555. [string] $StartBinary,
  556. [string] $EndBinary
  557. )
  558. [int64] $StartInt = [System.Convert]::ToInt64($StartBinary, 2)
  559. [int64] $EndInt = [System.Convert]::ToInt64($EndBinary, 2)
  560. for ($BinaryIP = $StartInt; $BinaryIP -le $EndInt; $BinaryIP++)
  561. {
  562. Convert-BinaryToIP ([System.Convert]::ToString($BinaryIP, 2).PadLeft(32, '0'))
  563. }
  564. }
  565.  
  566. function Test-IPIsInNetwork {
  567. param(
  568. [string] $IP,
  569. [string] $StartBinary,
  570. [string] $EndBinary
  571. )
  572. $TestIPBinary = Convert-IPToBinary $IP
  573. [int64] $TestIPInt64 = [System.Convert]::ToInt64($TestIPBinary, 2)
  574. [int64] $StartInt64 = [System.Convert]::ToInt64($StartBinary, 2)
  575. [int64] $EndInt64 = [System.Convert]::ToInt64($EndBinary, 2)
  576. if ($TestIPInt64 -ge $StartInt64 -and $TestIPInt64 -le $EndInt64)
  577. {
  578. return $True
  579. }
  580. else
  581. {
  582. return $False
  583. }
  584. }
  585.  
  586. function Get-NetworkInformationFromProperCIDR
  587. {
  588. param(
  589. [psobject] $CIDRObject
  590. )
  591. $o = '' | Select-Object -Property IP, NetworkLength, SubnetMask, NetworkAddress, HostMin, HostMax,
  592. Broadcast, UsableHosts, TotalHosts, IPEnumerated, BinaryIP, BinarySubnetMask, BinaryNetworkAddress,
  593. BinaryBroadcast
  594. $o.IP = [string] $CIDRObject.IP
  595. $o.BinaryIP = Convert-IPToBinary $o.IP
  596. $o.NetworkLength = [int32] $CIDRObject.NetworkLength
  597. $o.SubnetMask = Convert-BinaryToIP ('1' * $o.NetworkLength).PadRight(32, '0')
  598. $o.BinarySubnetMask = ('1' * $o.NetworkLength).PadRight(32, '0')
  599. $o.BinaryNetworkAddress = $o.BinaryIP.SubString(0, $o.NetworkLength).PadRight(32, '0')
  600. if ($Contains)
  601. {
  602. if ($Contains -match "\A${IPv4Regex}\z")
  603. {
  604. # Passing in IP to test, start binary and end binary.
  605. return Test-IPIsInNetwork $Contains $o.BinaryNetworkAddress $o.BinaryNetworkAddress.SubString(0, $o.NetworkLength).PadRight(32, '1')
  606. }
  607. else
  608. {
  609. Write-Error "Invalid IPv4 address specified with -Contains"
  610. return
  611. }
  612. }
  613. $o.NetworkAddress = Convert-BinaryToIP $o.BinaryNetworkAddress
  614. if ($o.NetworkLength -eq 32 -or $o.NetworkLength -eq 31)
  615. {
  616. $o.HostMin = $o.IP
  617. }
  618. else
  619. {
  620. $o.HostMin = Convert-BinaryToIP ([System.Convert]::ToString(([System.Convert]::ToInt64($o.BinaryNetworkAddress, 2) + 1), 2)).PadLeft(32, '0')
  621. }
  622. #$o.HostMax = Convert-BinaryToIP ([System.Convert]::ToString((([System.Convert]::ToInt64($o.BinaryNetworkAddress.SubString(0, $o.NetworkLength)).PadRight(32, '1'), 2) - 1), 2).PadLeft(32, '0'))
  623. #$o.HostMax =
  624. [string] $BinaryBroadcastIP = $o.BinaryNetworkAddress.SubString(0, $o.NetworkLength).PadRight(32, '1') # this gives broadcast... need minus one.
  625. $o.BinaryBroadcast = $BinaryBroadcastIP
  626. [int64] $DecimalHostMax = [System.Convert]::ToInt64($BinaryBroadcastIP, 2) - 1
  627. [string] $BinaryHostMax = [System.Convert]::ToString($DecimalHostMax, 2).PadLeft(32, '0')
  628. $o.HostMax = Convert-BinaryToIP $BinaryHostMax
  629. $o.TotalHosts = [int64][System.Convert]::ToString(([System.Convert]::ToInt64($BinaryBroadcastIP, 2) - [System.Convert]::ToInt64($o.BinaryNetworkAddress, 2) + 1))
  630. $o.UsableHosts = $o.TotalHosts - 2
  631. # ugh, exceptions for network lengths from 30..32
  632. if ($o.NetworkLength -eq 32)
  633. {
  634. $o.Broadcast = $Null
  635. $o.UsableHosts = [int64] 1
  636. $o.TotalHosts = [int64] 1
  637. $o.HostMax = $o.IP
  638. }
  639. elseif ($o.NetworkLength -eq 31)
  640. {
  641. $o.Broadcast = $Null
  642. $o.UsableHosts = [int64] 2
  643. $o.TotalHosts = [int64] 2
  644. # Override the earlier set value for this (bloody exceptions).
  645. [int64] $DecimalHostMax2 = [System.Convert]::ToInt64($BinaryBroadcastIP, 2) # not minus one here like for the others
  646. [string] $BinaryHostMax2 = [System.Convert]::ToString($DecimalHostMax2, 2).PadLeft(32, '0')
  647. $o.HostMax = Convert-BinaryToIP $BinaryHostMax2
  648. }
  649. elseif ($o.NetworkLength -eq 30)
  650. {
  651. $o.UsableHosts = [int64] 2
  652. $o.TotalHosts = [int64] 4
  653. $o.Broadcast = Convert-BinaryToIP $BinaryBroadcastIP
  654. }
  655. else
  656. {
  657. $o.Broadcast = Convert-BinaryToIP $BinaryBroadcastIP
  658. }
  659. if ($Enumerate)
  660. {
  661. $IPRange = @(Get-IPRange $o.BinaryNetworkAddress $o.BinaryNetworkAddress.SubString(0, $o.NetworkLength).PadRight(32, '1'))
  662. if ((31, 32) -notcontains $o.NetworkLength )
  663. {
  664. $IPRange = $IPRange[1..($IPRange.Count-1)] # remove first element
  665. $IPRange = $IPRange[0..($IPRange.Count-2)] # remove last element
  666. }
  667. $o.IPEnumerated = $IPRange
  668. }
  669. else {
  670. $o.IPEnumerated = @()
  671. }
  672. return $o
  673. }
  674. $NetworkAddress | ForEach-Object { Get-ProperCIDR $_ } | ForEach-Object { Get-NetworkInformationFromProperCIDR $_ }
  675. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement