Advertisement
Guest User

Untitled

a guest
Nov 11th, 2023
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.29 KB | Source Code | 0 0
  1. # If you need a web proxy to download blocklists, uncomment the next line and modify the proxy URL
  2. # $WebProxy = "http://example.notarealproxyserveraddress.com:8080"
  3.  
  4. # Change this path to the folder you want to store files in during processing, usually the script's directory
  5. # All downloaded blocklists and final merged files will be stored here before copying to final destination
  6. $ScriptDir = "C:\Scripts\Merge-Blocklists\"
  7.  
  8. # Path to file containing list of IP Blocklist URLs
  9. # Create this text file with one URL per line for the blocklists you want to download and merge
  10. $URLfile = $ScriptDir + "blocklist-URLs.txt"
  11.  
  12. # Path / filenames for the final output files
  13. $IPOutputFile = $ScriptDir + "iplist.txt"
  14. $NetOutputFile = $ScriptDir + "netlist.txt"
  15.  
  16. # Path to the script log file
  17. $LogFile = $ScriptDir + "log.txt"
  18.  
  19. # Create blank log file
  20. $null | Out-File $LogFile
  21.  
  22. # Path to merged file the script creates
  23. $MergedFile = $ScriptDir + "BL_merged-list.txt"
  24.  
  25. # Create blank merged file
  26. $null | Out-File $MergedFile
  27.  
  28. # Regex to validate IPv4 addresses, CIDR ranges, and blocklist URLs
  29. $IPregex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
  30. $CIDRregex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/(3[0-2]|[1-2][0-9]|[0-9]))$"
  31.  
  32. # Function to validate blocklist URLs
  33. function ValidateURL{
  34. param(
  35. [string]$URL
  36. )
  37.  
  38. $URLcheck = $URL -as [System.URI]
  39. if($null -ne $URLcheck -and $URL -match "^http(s?)://") {
  40. return $True
  41. }
  42. else{
  43. return $False
  44. }
  45. }
  46.  
  47. # Function to see if an IP is inside a CIDR
  48. Function CIDRcontainsIP {
  49. param(
  50. $IPAddress,
  51. $CIDR
  52. )
  53.  
  54. [System.Net.IPAddress]$IP = $IPAddress
  55. [System.Net.IPAddress]$Subnet = $CIDR.Split("/")[0]
  56. $C = $CIDR.Split("/")[1]
  57. [System.Net.IPAddress]$Mask = ''+[ipaddress](4.GB-(4GB-shr$C))
  58.  
  59. Return ($Subnet.Address -eq ($IP.Address -band $Mask.Address))
  60. }
  61.  
  62. # Function to write to log and show in console
  63. Function LogThis {
  64. $TimeStamp = Get-Date -format HH:mm:ss
  65. $LogData = $TimeStamp + " - " + $log
  66. Out-File -FilePath $LogFile -InputObject $LogData -Append
  67. Write-Host $log
  68. }
  69.  
  70. # Get the list of IP blocklist URLs to pull from (ignoring lines that don't start with http)
  71. try{
  72. $BlockListURLs = Get-Content $URLfile -ErrorAction Stop | Where-Object {$_ -match "^http"}
  73. }
  74. catch{
  75. $log = "Failed to load blocklist URLs from file $BlockListURLs"; LogThis
  76. exit
  77. }
  78.  
  79. # Validate BlockList URLs
  80. foreach($bURL in $BlockListURLs) {
  81. if(!(ValidateURL -URL $bURL)) {
  82. $log = "BlockList URL $bURL is invalid"; LogThis
  83. $InvalidURLDetected = $true
  84. }
  85. }
  86.  
  87. # Exit if any invalid URLs were detected
  88. if($InvalidURLDetected) {
  89. $log = "Invalid URLs were detected in file $URLfile - remove or correct invalid entries and rerun script"; LogThis
  90. exit
  91. }
  92.  
  93. # Clean up any pre-existing blocklist files
  94. $PreviousFiles = Get-ChildItem -Path $ScriptDir -Filter "BL_*.txt"
  95. if($PreviousFiles) {
  96. foreach($file in $PreviousFiles){
  97. Remove-Item $file
  98. }
  99. }
  100.  
  101. # Download the Blocklist files
  102. foreach($URL in $BlockListURLs) {
  103. # Generate a filename from the domain name and target filename - strip the extension and add .txt
  104. $BlockListFile = $ScriptDir + "BL_" + $URL.Split("/")[2] + "-" + ($URL.Split("/")[-1]).Split(".")[0] + ".txt"
  105.  
  106. # Download the file
  107. try {
  108. if($WebProxy) {
  109. Invoke-WebRequest $URL -Proxy $WebProxy -OutFile $BlockListFile -ErrorAction Stop
  110. }
  111. else{
  112. Invoke-WebRequest $URL -OutFile $BlockListFile -ErrorAction Stop
  113. }
  114. }
  115. catch {
  116. $log = "Failed to download blocklist file from $URL"; LogThis
  117. }
  118. }
  119.  
  120. # Import all the downloaded files and merge into a single file
  121. $BlockListFiles = Get-ChildItem -Path $ScriptDir -Filter "BL_*.txt"
  122.  
  123. foreach($File in $BlockListFiles) {
  124. # Special handling for SpamHaus since they comment each line
  125. if($File.Name -match 'spamhaus') {
  126. $FileAppend = Get-Content $File | % {$_.split(" ")[0]} | Where-Object {$_ -match $IPregex -or $_ -match $CIDRregex}
  127. }
  128. else{
  129. $FileAppend = Get-Content $File | Where-Object {$_ -match $IPregex -or $_ -match $CIDRregex}
  130. }
  131. $log = "Adding $($FileAppend | Measure-Object | Select-Object -ExpandProperty count) lines from $($File.Name) to merge file"; LogThis
  132. $FileAppend | Out-File $MergedFile -Append
  133. }
  134.  
  135. # Read in the merged file contents so it can be deduplicated
  136. $MergedList = Get-Content $MergedFile
  137. $PreDedupeCount = $MergedList | Measure-Object | Select-Object -ExpandProperty count
  138. $MergedList = $MergedList | Select-Object -Unique
  139. $PostDedupeCount = $MergedList | Measure-Object | Select-Object -ExpandProperty count
  140. $log = "Removed $($PreDedupeCount - $PostDedupeCount) entries via deduplication"; LogThis
  141.  
  142. # Separate the results into hashtables for IP addresses and CIDR ranges
  143. $IPList = @{}
  144. $CIDRList = @{}
  145.  
  146. foreach($val in $MergedList) {
  147. if($val -match $CIDRregex){
  148. $CIDRList.Add("$val",1)
  149. }
  150. elseif($val -match $IPregex) {
  151. $IPList.Add("$val",1)
  152. }
  153. else{
  154. $log = "Merged list value $val does not match IP or CIDR regex"; LogThis
  155. }
  156. }
  157.  
  158. $IPcount = $IPList.GetEnumerator() | Measure-Object | Select-Object -ExpandProperty count
  159. $CIDRcount = $CIDRList.GetEnumerator() | Measure-Object | Select-Object -ExpandProperty count
  160.  
  161. $log = "Found $IPcount unique IP addresses and $CIDRcount unique CIDR ranges to evaluate"; LogThis
  162.  
  163. # Build an array from $IPList hashtable so we can modify the hashtable without ending the foreach loop
  164. $IPListCopy = $IPList.GetEnumerator() | Select-Object -ExpandProperty Name
  165.  
  166. # Evaluate all the individual IPs to see if they are contained in an existing CIDR
  167. # If they are, set them for removal by making the hashtable value 0
  168. $ProcessedIPs = 0
  169. foreach($val in $IPListCopy) {
  170. foreach($CIDR in $CIDRList.Keys) {
  171. if(CIDRcontainsIP -IPAddress $val -CIDR $CIDR){
  172. write-host "IP $val is in CIDR $CIDR" -fore Yellow
  173. $IPList.$val = 0
  174. }
  175. }
  176. $ProcessedIPs++
  177. if(($ProcessedIPs % 100) -eq 0) {
  178. Write-Host "Evaluated $ProcessedIPs of $IPcount IP addresses"
  179. }
  180. }
  181.  
  182. $RemovedIPcount = $IPList.GetEnumerator() | Where-Object {$_.Value -eq 0} | Measure-Object | Select-Object -ExpandProperty count
  183. $log = "IP Address analysis found $RemovedIPCount IP addresses that were already contained in existing CIDR ranges"; LogThis
  184.  
  185. # Write the remaining IPs and CIDRs to the final output files
  186. $FileHeader = "# Last Updated $(Get-Date)"
  187. $FileHeader | Out-File $IPOutputFile -Encoding ASCII
  188. $FileHeader | Out-File $NetOutputFile -Encoding ASCII
  189. $IPList.GetEnumerator() | Where-Object {$_.Value -eq 1} | Select-Object -ExpandProperty Name | Sort-Object | Out-File -FilePath $IPOutputFile -Encoding ASCII -Append
  190. $CIDRList.GetEnumerator() | Where-Object {$_.Value -eq 1} | Select-Object -ExpandProperty Name | Sort-Object | Out-File -FilePath $NetOutputFile -Encoding ASCII -Append
  191.  
  192. # Change these paths to wherever you want the final files to go
  193. Copy-Item $IPOutputFile C:\web\blocklist\iplist.ipset -Force
  194. Copy-Item $NetOutputFile C:\web\blocklist\netlist.netset -Force
  195.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement