Just some refactoring
This commit is contained in:
@@ -25,3 +25,4 @@ venv3
|
||||
|
||||
# pycharm
|
||||
*.idea
|
||||
*.egg-info
|
||||
|
||||
@@ -12,7 +12,7 @@ from pwnlib.asm import asm
|
||||
import internalblue.hci as hci
|
||||
from internalblue.cli import InternalBlueCLI
|
||||
from internalblue.hcicore import HCICore
|
||||
from internalblue.utils import p32
|
||||
from internalblue.utils.packing import p32
|
||||
|
||||
"""
|
||||
Measure the RNG of the CYW20719 Evaluation Board.
|
||||
|
||||
@@ -12,7 +12,7 @@ from pwnlib.asm import asm
|
||||
import internalblue.hci as hci
|
||||
from internalblue.cli import InternalBlueCLI
|
||||
from internalblue.hcicore import HCICore
|
||||
from internalblue.utils import p32
|
||||
from internalblue.utils.packing import p32
|
||||
|
||||
"""
|
||||
Measure the RNG of the CYW20719 Evaluation Board.
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
from pwnlib.asm import asm
|
||||
|
||||
from internalblue.hcicore import HCICore
|
||||
from internalblue.utils import p32
|
||||
from internalblue.utils.packing import p32
|
||||
|
||||
"""
|
||||
This is a crash only test for CVE-2018-19860. Install this patch and connect
|
||||
|
||||
@@ -12,7 +12,7 @@ from pwnlib.asm import asm
|
||||
from internalblue import Address, hci
|
||||
from internalblue.cli import InternalBlueCLI, auto_int
|
||||
from internalblue.hcicore import HCICore
|
||||
from internalblue.utils import p16, u16
|
||||
from internalblue.utils.packing import p16, u16
|
||||
|
||||
"""
|
||||
This is a standalone PoC for the KNOB attack on a CYW20735 evaluation board.
|
||||
|
||||
@@ -12,7 +12,7 @@ from pwnlib.asm import asm
|
||||
import internalblue.hci as hci
|
||||
from internalblue.cli import InternalBlueCLI
|
||||
from internalblue.hcicore import HCICore
|
||||
from internalblue.utils import p32
|
||||
from internalblue.utils.packing import p32
|
||||
|
||||
"""
|
||||
Measure the RNG of the CYW20735 Evaluation Board.
|
||||
|
||||
@@ -13,7 +13,7 @@ from pwnlib.asm import asm
|
||||
import internalblue.hci as hci
|
||||
from internalblue.cli import InternalBlueCLI
|
||||
from internalblue.hcicore import HCICore
|
||||
from internalblue.utils import p32
|
||||
from internalblue.utils.packing import p32
|
||||
|
||||
"""
|
||||
Measure the RNG of the CYW20819 Evaluation Board.
|
||||
|
||||
@@ -11,7 +11,7 @@ import time
|
||||
from pwnlib import log
|
||||
|
||||
import internalblue.hci as hci
|
||||
from internalblue.utils import p16, p8
|
||||
from internalblue.utils.packing import p8, p16
|
||||
|
||||
CONNECTION_TYPE_CLASSIC = 0
|
||||
CONNECTION_TYPE_BLE = 1
|
||||
|
||||
@@ -7,7 +7,7 @@ import struct
|
||||
|
||||
from pwnlib import log
|
||||
|
||||
from internalblue.utils import p16
|
||||
from internalblue.utils.packing import p16
|
||||
|
||||
|
||||
class L2CAPManager:
|
||||
|
||||
@@ -9,7 +9,7 @@ from builtins import range
|
||||
import internalblue.hci as hci
|
||||
from internalblue.adbcore import ADBCore
|
||||
from internalblue.cli import InternalBlueCLI
|
||||
from internalblue.utils import u16
|
||||
from internalblue.utils.packing import u16
|
||||
from pwnlib.asm import asm
|
||||
|
||||
internalblue = ADBCore(serial=False)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
from pwnlib.asm import asm
|
||||
|
||||
from internalblue.adbcore import ADBCore
|
||||
from internalblue.utils import p32
|
||||
from internalblue.utils.packing import p32
|
||||
|
||||
"""
|
||||
This is a crash only test for CVE-2018-19860. Install this patch and connect
|
||||
|
||||
@@ -11,7 +11,7 @@ from cmd2 import CommandSet
|
||||
from internalblue import Address
|
||||
from internalblue.adbcore import ADBCore
|
||||
import internalblue.hci as hci
|
||||
from internalblue.utils import p16, u16
|
||||
from internalblue.utils.packing import p16, u16
|
||||
from internalblue.cli import auto_int
|
||||
from internalblue.cli import InternalBlueCLI
|
||||
from pwnlib.asm import asm
|
||||
|
||||
@@ -10,7 +10,7 @@ from cmd2 import CommandSet
|
||||
|
||||
from internalblue.adbcore import ADBCore
|
||||
import internalblue.hci as hci
|
||||
from internalblue.utils import p16, u16
|
||||
from internalblue.utils.packing import p16, u16
|
||||
from internalblue.cli import auto_int
|
||||
from internalblue.cli import InternalBlueCLI
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ from pwnlib.asm import asm
|
||||
from internalblue import Address, hci
|
||||
from internalblue.cli import InternalBlueCLI, auto_int
|
||||
from internalblue.hcicore import HCICore
|
||||
from internalblue.utils import p16, u16
|
||||
from internalblue.utils.packing import p16, u16
|
||||
|
||||
"""
|
||||
This is a standalone PoC for the KNOB attack on a Raspberry Pi 3.
|
||||
|
||||
@@ -12,7 +12,7 @@ from pwnlib.asm import asm
|
||||
from internalblue import Address, hci
|
||||
from internalblue.cli import InternalBlueCLI, auto_int
|
||||
from internalblue.hcicore import HCICore
|
||||
from internalblue.utils import p16, u16
|
||||
from internalblue.utils.packing import p16, u16
|
||||
|
||||
"""
|
||||
This is a standalone PoC for the KNOB attack on a Raspberry Pi 3+/4.
|
||||
|
||||
@@ -11,7 +11,7 @@ from pwnlib.asm import asm
|
||||
import internalblue.hci as hci
|
||||
from internalblue.adbcore import ADBCore
|
||||
from internalblue.cli import InternalBlueCLI
|
||||
from internalblue.utils import u8, u16
|
||||
from internalblue.utils.packing import u8, u16
|
||||
|
||||
internalblue = ADBCore(serial=True)
|
||||
device_list = internalblue.device_list()
|
||||
|
||||
@@ -13,7 +13,7 @@ from pwnlib.asm import asm
|
||||
from internalblue import Address, hci
|
||||
from internalblue.adbcore import ADBCore
|
||||
from internalblue.cli import InternalBlueCLI, auto_int
|
||||
from internalblue.utils import p16, u16
|
||||
from internalblue.utils.packing import p16, u16
|
||||
|
||||
"""
|
||||
This is a standalone PoC for the KNOB attack on a Samsung Galaxy S8.
|
||||
|
||||
@@ -16,7 +16,8 @@ from ppadb.connection import Connection
|
||||
from ppadb.client import Client as AdbClient
|
||||
|
||||
from . import hci
|
||||
from .utils import bytes_to_hex, u32
|
||||
from .utils import bytes_to_hex
|
||||
from .utils.packing import u32
|
||||
from .core import InternalBlue
|
||||
standard_library.install_aliases()
|
||||
|
||||
|
||||
+14
-15
@@ -4,10 +4,9 @@
|
||||
#
|
||||
# This file is meant to be executed by the user in order to start
|
||||
# an interactive CLI. It creates an instance of the framework and
|
||||
# enters a command loop which is implemented with the readline
|
||||
# interface. Commands entered by the user are matched to the
|
||||
# corresponding Cmd subclass in the cmds.py file and dispatched
|
||||
# accordingly.
|
||||
# enters a command loop which is implemented using cmd2.
|
||||
# Commands entered by the user are automatically matched
|
||||
# to functions starting with do_* and executed accordingly.
|
||||
#
|
||||
# Copyright (c) 2018 Dennis Mantz. (MIT License)
|
||||
#
|
||||
@@ -50,7 +49,8 @@ from cmd2 import fg, style
|
||||
|
||||
from . import Address
|
||||
from .hci import HCI_COMND
|
||||
from .utils import bytes_to_hex, p8, p16, p32, u32, flat, yesno
|
||||
from .utils import bytes_to_hex, flat, yesno
|
||||
from .utils.packing import p8, p16, p32, u32
|
||||
from .utils.progress_logger import ProgressLogger
|
||||
from .utils.internalblue_logger import getInternalBlueLogger
|
||||
from .hcicore import HCICore
|
||||
@@ -80,7 +80,7 @@ else:
|
||||
_has_pwnlib = True
|
||||
|
||||
|
||||
def needs_pwnlibs(func):
|
||||
def needs_pwnlib(func):
|
||||
# this decorator copies over
|
||||
# function name, docstring,
|
||||
# arguments list etc. so our
|
||||
@@ -88,7 +88,7 @@ def needs_pwnlibs(func):
|
||||
@wraps(func)
|
||||
def inner(*args, **kwargs):
|
||||
if not _has_pwnlib:
|
||||
raise ImportError("pwnlibs is required for this function.")
|
||||
raise ImportError("pwnlib is required for this function.")
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return inner
|
||||
@@ -404,8 +404,7 @@ class InternalBlueCLI(cmd2.Cmd):
|
||||
|
||||
@staticmethod
|
||||
def getCmdList():
|
||||
""" Returns a list of all commands which are defined in this cmds.py file.
|
||||
This is done by searching for all subclasses of Cmd """
|
||||
""" Returns a list of all CLI commands which are defined in this file."""
|
||||
return [name for name, obj in inspect.getmembers(InternalBlueCLI, predicate=inspect.isfunction) if name.startswith("do_")]
|
||||
|
||||
def findCmd(self, keyword):
|
||||
@@ -954,7 +953,7 @@ class InternalBlueCLI(cmd2.Cmd):
|
||||
disasm_parser.add_argument('address', type=auto_int, help='Start address of the disassembly.')
|
||||
|
||||
@cmd2.with_argparser(disasm_parser)
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def do_disasm(self, args):
|
||||
"""Display a disassembly of a specified region in the memory."""
|
||||
if not self.isAddressInSections(args.address, args.length):
|
||||
@@ -971,7 +970,7 @@ class InternalBlueCLI(cmd2.Cmd):
|
||||
return False
|
||||
else:
|
||||
# PyCharm thinks disasm wants a str and not bytes
|
||||
# so until pwnlibs gets type annotations we just trick the type checker to to prevent a false positive
|
||||
# so until pwnlib gets type annotations we just trick the type checker to to prevent a false positive
|
||||
if TYPE_CHECKING:
|
||||
d = str(dump)
|
||||
else:
|
||||
@@ -1034,7 +1033,7 @@ class InternalBlueCLI(cmd2.Cmd):
|
||||
writeasm_parser.add_argument('code', nargs='*', help='Assembler code as string')
|
||||
|
||||
@cmd2.with_argparser(writeasm_parser)
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def do_writeasm(self, args):
|
||||
"""Writes assembler instructions to a specified memory address."""
|
||||
if args.file is not None:
|
||||
@@ -1104,7 +1103,7 @@ class InternalBlueCLI(cmd2.Cmd):
|
||||
exec_parser.add_argument('cmd', help='Name of the command to execute (corresponds to file exec_<cmd>.s)')
|
||||
|
||||
@cmd2.with_argparser(exec_parser)
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def do_exec(self, args):
|
||||
"""Writes assembler instructions to RAM and jumps there."""
|
||||
filename = self.internalblue.data_directory + "/exec_%s.s" % args.cmd
|
||||
@@ -1200,7 +1199,7 @@ class InternalBlueCLI(cmd2.Cmd):
|
||||
patch_parser.add_argument('data', nargs='*', help='Data as string (or hexstring/integer/instruction, see --hex, --int, --asm)')
|
||||
|
||||
@cmd2.with_argparser(patch_parser)
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def do_patch(self, args):
|
||||
"""Patches 4 byte of data at a specified ROM address."""
|
||||
if args.slot is not None:
|
||||
@@ -1438,7 +1437,7 @@ class InternalBlueCLI(cmd2.Cmd):
|
||||
self.logger.info(" - Address: %s" % bt_addr_str)
|
||||
return None
|
||||
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def infoPatchram(_):
|
||||
if not hasattr(self.internalblue.fw, "PATCHRAM_NUMBER_OF_SLOTS"):
|
||||
self.logger.warning("PATCHRAM_NUMBER_OF_SLOTS not defined in fw.")
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+11
-10
@@ -47,7 +47,8 @@ from .fw.fw import Firmware
|
||||
from .hci import HCI, HCI_COMND
|
||||
from .objects.connection_information import ConnectionInformation
|
||||
from .objects.queue_element import QueueElement
|
||||
from .utils import p16, p8, u32, u16, p32, flat, bits, unbits, bytes_to_hex
|
||||
from .utils import flat, bytes_to_hex
|
||||
from .utils.packing import p8, p16, u16, p32, u32, bits, unbits
|
||||
from .utils.internalblue_logger import getInternalBlueLogger
|
||||
standard_library.install_aliases()
|
||||
|
||||
@@ -70,15 +71,15 @@ except ImportError:
|
||||
_has_pwnlib = False
|
||||
import warnings
|
||||
warnings.formatwarning = (lambda x, *args, **kwargs: f"\x1b[31m[!] {x}\x1b[0m\n")
|
||||
warnings.warn("pwnlibs is not installed. Some features will not work.")
|
||||
warnings.warn("pwnlib is not installed. Some features will not work.")
|
||||
else:
|
||||
_has_pwnlib = True
|
||||
|
||||
|
||||
def needs_pwnlibs(func):
|
||||
def needs_pwnlib(func):
|
||||
def inner(*args, **kwargs):
|
||||
if not _has_pwnlib:
|
||||
raise ImportError("pwnlibs is required for this function.")
|
||||
raise ImportError("pwnlib is required for this function.")
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return inner
|
||||
@@ -209,7 +210,7 @@ class InternalBlue(with_metaclass(ABCMeta, object)):
|
||||
# If the --replay flag was used and a chip is spoofed.
|
||||
self.replay = replay
|
||||
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def check_binutils(self, fix=True):
|
||||
"""
|
||||
Test if ARM binutils is in path so that asm and disasm (provided by
|
||||
@@ -484,7 +485,7 @@ class InternalBlue(with_metaclass(ABCMeta, object)):
|
||||
f.write(dump)
|
||||
f.close()
|
||||
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def addTracepoint(self, address):
|
||||
# type: (Address) -> bool
|
||||
# Check if constants are defined in fw.py
|
||||
@@ -1054,7 +1055,7 @@ class InternalBlue(with_metaclass(ABCMeta, object)):
|
||||
retry = 3 # this round worked, so we re-enable retries
|
||||
return outbuffer
|
||||
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def readMemAligned(
|
||||
self, address, length, progress_log=None, bytes_done=0, bytes_total=0
|
||||
):
|
||||
@@ -1626,7 +1627,7 @@ class InternalBlue(with_metaclass(ABCMeta, object)):
|
||||
|
||||
return True
|
||||
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def fuzzLmp(self):
|
||||
# type: ()-> bool
|
||||
"""
|
||||
@@ -1668,7 +1669,7 @@ class InternalBlue(with_metaclass(ABCMeta, object)):
|
||||
|
||||
return True
|
||||
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def sendLmpPacketLegacy(self, conn_nr, opcode, payload, extended_op=False):
|
||||
# type: (int, Opcode, bytes, bool) -> bool
|
||||
"""
|
||||
@@ -1731,7 +1732,7 @@ class InternalBlue(with_metaclass(ABCMeta, object)):
|
||||
self.logger.warning("sendLmpPacket: launchRam failed!")
|
||||
return False
|
||||
|
||||
@needs_pwnlibs
|
||||
@needs_pwnlib
|
||||
def sendLcpPacket(self, conn_idx, payload):
|
||||
# type: (ConnectionIndex, bytes) -> bool
|
||||
"""
|
||||
|
||||
+6
-16
@@ -26,26 +26,16 @@
|
||||
# Software.
|
||||
|
||||
from __future__ import absolute_import
|
||||
from builtins import hex
|
||||
from builtins import range
|
||||
from builtins import object
|
||||
from enum import Enum
|
||||
from datetime import datetime
|
||||
|
||||
from internalblue.utils import (
|
||||
p8,
|
||||
u16,
|
||||
p16,
|
||||
unbits,
|
||||
bits_str,
|
||||
u8,
|
||||
bits,
|
||||
p32,
|
||||
u32,
|
||||
)
|
||||
from builtins import hex
|
||||
from builtins import object
|
||||
from builtins import range
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
|
||||
from internalblue.utils import flat
|
||||
from internalblue.utils.internalblue_logger import getInternalBlueLogger
|
||||
from internalblue.utils.packing import p8, u8, p16, u16, p32, u32, bits, unbits, bits_str
|
||||
|
||||
|
||||
class HCI_COMND(Enum):
|
||||
|
||||
+10
-11
@@ -2,23 +2,22 @@
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import datetime
|
||||
import fcntl
|
||||
import queue as queue2k
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
from builtins import range
|
||||
from builtins import str
|
||||
from builtins import zip
|
||||
from typing import List, cast, TYPE_CHECKING
|
||||
|
||||
from future import standard_library
|
||||
|
||||
from builtins import str
|
||||
from builtins import zip
|
||||
from builtins import range
|
||||
import datetime
|
||||
from internalblue.utils import p32, u16, p16, u32
|
||||
import fcntl
|
||||
from .core import InternalBlue
|
||||
from . import hci
|
||||
import queue as queue2k
|
||||
import threading
|
||||
|
||||
from typing import List, cast, TYPE_CHECKING
|
||||
from .core import InternalBlue
|
||||
from .utils.packing import p16, u16, p32, u32
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from internalblue import Device
|
||||
|
||||
@@ -3,21 +3,19 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
import queue as queue2k
|
||||
import random
|
||||
import socket
|
||||
import time
|
||||
from builtins import str
|
||||
|
||||
from future import standard_library
|
||||
|
||||
from .utils import p8
|
||||
from . import hci
|
||||
from .core import InternalBlue
|
||||
from .utils.packing import p8
|
||||
|
||||
standard_library.install_aliases()
|
||||
from builtins import str
|
||||
import socket
|
||||
import queue as queue2k
|
||||
from . import hci
|
||||
|
||||
from .core import InternalBlue
|
||||
|
||||
filepath = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
IOBE = None
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
from builtins import object
|
||||
from internalblue.utils import u32, u16, u8
|
||||
from typing import Any
|
||||
|
||||
from internalblue.utils.packing import u8, u16, u32
|
||||
|
||||
|
||||
class ConnectionInformation(object):
|
||||
connection_handle = 0
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import struct
|
||||
import sys
|
||||
from typing import Union
|
||||
|
||||
@@ -10,54 +9,6 @@ def bytes_to_hex(data):
|
||||
return "".join(format(x, "02x") for x in bytearray(data))
|
||||
|
||||
|
||||
def p8(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.pack('>B', num)
|
||||
elif endian.lower() == 'little':
|
||||
return struct.pack('<B', num)
|
||||
return struct.pack('B', num)
|
||||
|
||||
|
||||
def u8(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.unpack('>B', num)[0]
|
||||
elif endian.lower() == 'little':
|
||||
return struct.unpack('<B', num)[0]
|
||||
return struct.unpack('B', num)[0]
|
||||
|
||||
|
||||
def p16(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.pack('>H', num)
|
||||
elif endian.lower() == 'little':
|
||||
return struct.pack('<H', num)
|
||||
return struct.pack('H', num)
|
||||
|
||||
|
||||
def u16(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.unpack('>H', num)[0]
|
||||
elif endian.lower() == 'little':
|
||||
return struct.unpack('<H', num)[0]
|
||||
return struct.unpack('H', num)[0]
|
||||
|
||||
|
||||
def p32(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.pack('>I', num)
|
||||
elif endian.lower() == 'little':
|
||||
return struct.pack('<I', num)
|
||||
return struct.pack('I', num)
|
||||
|
||||
|
||||
def u32(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.unpack('>I', num)[0]
|
||||
elif endian.lower() == 'little':
|
||||
return struct.unpack('<I', num)[0]
|
||||
return struct.unpack('I', num)[0]
|
||||
|
||||
|
||||
def flat(data: [Address, bytes], filler: int) -> bytes:
|
||||
res = bytes()
|
||||
last_section_end = 0
|
||||
@@ -81,93 +32,3 @@ def yesno(message):
|
||||
return False
|
||||
else:
|
||||
selection = input(f"[🦄] {message} [yes/no] ")
|
||||
|
||||
|
||||
def bits(s, endian='big') -> [int]:
|
||||
"""bits(s, endian = 'big', zero = 0, one = 1) -> list
|
||||
|
||||
Converts the argument a list of bits.
|
||||
|
||||
Arguments:
|
||||
s: A string or number to be converted into bits.
|
||||
endian (str): The binary endian, default 'big'.
|
||||
|
||||
Returns:
|
||||
A list consisting of the values specified in `zero` and `one`.
|
||||
|
||||
[!!!] Copied from PWN, only available for bytes.
|
||||
"""
|
||||
|
||||
if endian not in ['little', 'big']:
|
||||
raise ValueError("bits(): 'endian' must be either 'little' or 'big'")
|
||||
else:
|
||||
little = endian == 'little'
|
||||
|
||||
out = []
|
||||
if isinstance(s, bytes):
|
||||
for b in bytearray(s):
|
||||
byte = []
|
||||
for _ in range(8):
|
||||
byte.append(1 if b & 1 else 0)
|
||||
b >>= 1
|
||||
if little:
|
||||
out += byte
|
||||
else:
|
||||
out += byte[::-1]
|
||||
else:
|
||||
raise ValueError("bits(): 's' must be either a string or a number")
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def unbits(s, endian='big'):
|
||||
"""unbits(s, endian = 'big') -> str
|
||||
|
||||
Converts an iterable of bits into a string.
|
||||
|
||||
Arguments:
|
||||
s: Iterable of bits
|
||||
endian (str): The string "little" or "big", which specifies the bits endianness.
|
||||
|
||||
Returns:
|
||||
A string of the decoded bits.
|
||||
|
||||
[!!!] Coped from PWN.
|
||||
"""
|
||||
if endian == 'little':
|
||||
u = lambda s: p8(int(s[::-1], 2))
|
||||
elif endian == 'big':
|
||||
u = lambda s: p8(int(s, 2))
|
||||
else:
|
||||
raise ValueError("unbits(): 'endian' must be either 'little' or 'big'")
|
||||
|
||||
out = b''
|
||||
cur = b''
|
||||
|
||||
for c in s:
|
||||
if c in ['1', 1, True]:
|
||||
cur += b'1'
|
||||
elif c in ['0', 0, False]:
|
||||
cur += b'0'
|
||||
else:
|
||||
raise ValueError("unbits(): cannot decode the value %r into a bit" % c)
|
||||
|
||||
if len(cur) == 8:
|
||||
out += u(cur)
|
||||
cur = b''
|
||||
if cur:
|
||||
out += u(cur.ljust(8, b'0'))
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def bits_str(s, endian='big') -> str:
|
||||
"""bits_str(s, endian = 'big') -> str
|
||||
A wrapper around :func:`bits`, which converts the output into a string.
|
||||
Examples:
|
||||
>>> bits_str(511)
|
||||
'0000000111111111'
|
||||
>>> bits_str(b"bits_str", endian = "little")
|
||||
'0100011010010110001011101100111011111010110011100010111001001110'
|
||||
"""
|
||||
return ''.join(map(lambda x: str(x), bits(s, endian)))
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import struct
|
||||
|
||||
|
||||
def p8(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.pack('>B', num)
|
||||
elif endian.lower() == 'little':
|
||||
return struct.pack('<B', num)
|
||||
return struct.pack('B', num)
|
||||
|
||||
|
||||
def u8(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.unpack('>B', num)[0]
|
||||
elif endian.lower() == 'little':
|
||||
return struct.unpack('<B', num)[0]
|
||||
return struct.unpack('B', num)[0]
|
||||
|
||||
|
||||
def p16(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.pack('>H', num)
|
||||
elif endian.lower() == 'little':
|
||||
return struct.pack('<H', num)
|
||||
return struct.pack('H', num)
|
||||
|
||||
|
||||
def u16(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.unpack('>H', num)[0]
|
||||
elif endian.lower() == 'little':
|
||||
return struct.unpack('<H', num)[0]
|
||||
return struct.unpack('H', num)[0]
|
||||
|
||||
|
||||
def p32(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.pack('>I', num)
|
||||
elif endian.lower() == 'little':
|
||||
return struct.pack('<I', num)
|
||||
return struct.pack('I', num)
|
||||
|
||||
|
||||
def u32(num, endian: str = ''):
|
||||
if endian.lower() == 'big':
|
||||
return struct.unpack('>I', num)[0]
|
||||
elif endian.lower() == 'little':
|
||||
return struct.unpack('<I', num)[0]
|
||||
return struct.unpack('I', num)[0]
|
||||
|
||||
|
||||
def bits(s, endian='big') -> [int]:
|
||||
"""bits(s, endian = 'big', zero = 0, one = 1) -> list
|
||||
|
||||
Converts the argument a list of bits.
|
||||
|
||||
Arguments:
|
||||
s: A string or number to be converted into bits.
|
||||
endian (str): The binary endian, default 'big'.
|
||||
|
||||
Returns:
|
||||
A list consisting of the values specified in `zero` and `one`.
|
||||
|
||||
[!!!] Copied from PWN, only available for bytes.
|
||||
"""
|
||||
|
||||
if endian not in ['little', 'big']:
|
||||
raise ValueError("bits(): 'endian' must be either 'little' or 'big'")
|
||||
else:
|
||||
little = endian == 'little'
|
||||
|
||||
out = []
|
||||
if isinstance(s, bytes):
|
||||
for b in bytearray(s):
|
||||
byte = []
|
||||
for _ in range(8):
|
||||
byte.append(1 if b & 1 else 0)
|
||||
b >>= 1
|
||||
if little:
|
||||
out += byte
|
||||
else:
|
||||
out += byte[::-1]
|
||||
else:
|
||||
raise ValueError("bits(): 's' must be either a string or a number")
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def unbits(s, endian='big'):
|
||||
"""unbits(s, endian = 'big') -> str
|
||||
|
||||
Converts an iterable of bits into a string.
|
||||
|
||||
Arguments:
|
||||
s: Iterable of bits
|
||||
endian (str): The string "little" or "big", which specifies the bits endianness.
|
||||
|
||||
Returns:
|
||||
A string of the decoded bits.
|
||||
|
||||
[!!!] Coped from PWN.
|
||||
"""
|
||||
if endian == 'little':
|
||||
u = lambda s: p8(int(s[::-1], 2))
|
||||
elif endian == 'big':
|
||||
u = lambda s: p8(int(s, 2))
|
||||
else:
|
||||
raise ValueError("unbits(): 'endian' must be either 'little' or 'big'")
|
||||
|
||||
out = b''
|
||||
cur = b''
|
||||
|
||||
for c in s:
|
||||
if c in ['1', 1, True]:
|
||||
cur += b'1'
|
||||
elif c in ['0', 0, False]:
|
||||
cur += b'0'
|
||||
else:
|
||||
raise ValueError("unbits(): cannot decode the value %r into a bit" % c)
|
||||
|
||||
if len(cur) == 8:
|
||||
out += u(cur)
|
||||
cur = b''
|
||||
if cur:
|
||||
out += u(cur.ljust(8, b'0'))
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def bits_str(s, endian='big') -> str:
|
||||
"""bits_str(s, endian = 'big') -> str
|
||||
A wrapper around :func:`bits`, which converts the output into a string.
|
||||
Examples:
|
||||
>>> bits_str(511)
|
||||
'0000000111111111'
|
||||
>>> bits_str(b"bits_str", endian = "little")
|
||||
'0100011010010110001011101100111011111010110011100010111001001110'
|
||||
"""
|
||||
return ''.join(map(lambda x: str(x), bits(s, endian)))
|
||||
@@ -1,95 +0,0 @@
|
||||
# """
|
||||
# The following proxies various utilities from pwnlibs by explicitly importing them
|
||||
# To replace a "from pwn import *" remove it and let your IDE highlight all missing methods (Hint: F2 in PyCharm goes to next error)
|
||||
# import the missing (and only the missing!) methods from this module, e.g. with "from internalblue.utils import term, read, log, text, options"
|
||||
# In some cases like "from pwn import socket" this just imports another module.
|
||||
# Use an IPython shell to run "from pwn import *" and check where some method/module actually comes from and either import it directly or add it to this module
|
||||
# """
|
||||
#
|
||||
#
|
||||
# # Imports that used to be imported via 'from pwn import *'
|
||||
# import pwnlib
|
||||
# from pwnlib import term
|
||||
# from pwnlib.util import iters
|
||||
# from pwnlib.util.misc import read
|
||||
# from pwnlib.context import context
|
||||
#
|
||||
# # TODO: Logging via pwnlib doesn't work yet, so for now it is still used via pwn
|
||||
# # import pwnlib.log
|
||||
# # pwnlib.log.install_default_handler()
|
||||
# # log = pwnlib.log.getLogger('internalbue')
|
||||
#
|
||||
# from pwn import log
|
||||
#
|
||||
#
|
||||
# from pwnlib.term import text
|
||||
# from pwnlib.ui import options, yesno
|
||||
# from pwnlib.util.packing import flat
|
||||
# from pwnlib.asm import disasm, asm
|
||||
# from pwnlib.util.fiddling import isprint, unbits, bits_str, bits
|
||||
#
|
||||
#
|
||||
# """
|
||||
# The packers like u8 are generated in a fairly convoluted way that breaks IDE introspection.
|
||||
# The following code remedies this by:
|
||||
# - Explicitly defining a stub function with type annotations
|
||||
# - Generating all the packers like pwnlibs would
|
||||
# - Only if if the current module already has the name of the packer as an attribute (i.e. has a stub function defined) it will be replaced with the pwnlibs version
|
||||
#
|
||||
# This means:
|
||||
# - All import issues in the rest of the code are genuine as the imports are only available if an explicit stub function is added
|
||||
# - The functions can be easily replaced by just implementing them and removing the for loop at the end
|
||||
#
|
||||
# """
|
||||
#
|
||||
# # Imports needed for this hack
|
||||
# from pwnlib.util.packing import ops, sizes, make_multi
|
||||
# import sys
|
||||
#
|
||||
# try:
|
||||
# from typing import Union, Optional, Literal
|
||||
#
|
||||
# endianess = Union[Literal["big"]]
|
||||
#
|
||||
# except ImportError:
|
||||
# pass
|
||||
# mod = sys.modules[__name__]
|
||||
#
|
||||
#
|
||||
# _DEFINES = ["u8", "p8", "u32", "u16", "p32"]
|
||||
#
|
||||
#
|
||||
# def u8(data, endian=None):
|
||||
# # type: (bytes, Optional[endianess]) -> int
|
||||
# pass
|
||||
#
|
||||
#
|
||||
# def p8(number, endian=None):
|
||||
# # type: (int, Optional[endianess]) -> bytes
|
||||
# pass
|
||||
#
|
||||
#
|
||||
# def u16(data, endian=None):
|
||||
# # type: (bytes, Optional[endianess]) -> int
|
||||
# pass
|
||||
#
|
||||
#
|
||||
# def p16(number, endian=None):
|
||||
# # type: (int, Optional[endianess]) -> bytes
|
||||
# pass
|
||||
#
|
||||
#
|
||||
# def u32(data, endian=None):
|
||||
# # type: (bytes, Optional[endianess]) -> int
|
||||
# pass
|
||||
#
|
||||
#
|
||||
# def p32(number, endian=None):
|
||||
# # type: (int, Optional[endianess]) -> bytes
|
||||
# pass
|
||||
#
|
||||
#
|
||||
# for op, size in iters.product(ops, sizes):
|
||||
# name, routine = make_multi(op, size)
|
||||
# if hasattr(mod, name):
|
||||
# setattr(mod, name, routine)
|
||||
Reference in New Issue
Block a user