The login
registered
Write an article
Home page
Download the APP

Discover the Python technology used by hackers and enjoy a different “scenic spot”!

Loose Jue

Discover the Python technology used by hackers and enjoy a different “scenic spot”!

For hackers, most people think they are mysterious and cool, so that they worship them blindly. It is not known what techniques the hackers use, so let’s take a look at some of the Python techniques they use in this episode.


Python has reached the industry standard for vulnerability development, and you’ll find most proof-of-concept tools written in Python (with the exception of the Metasploit framework written in Ruby). Python allows you to write scripts that handle remote services, fiddle with binary data, and interact with C libraries (or Java using Jython /.NET in IronPython) in a quick and easy way. The large standard library with the “include battery” principle removes some of the dependencies known in other frameworks/languages. I’d like to share some personal python coding experience with you, and maybe it will give you some useful tips for your future work on making the world a little safer


Set up your environment

For most of the projects/scripts you will write, it is useful to have all the dependencies in one place (and only those that are needed for a particular project). To meet these requirements, there exists a tool/library called VirtualEnv (which has been included in Python since version 3.3). This tool has the neat ability to generate isolated environments for Python projects without messing up your global environment. The creation of a new environment is as simple as that

$ virtualenv <path to new environment>

Or in Python> = 3.3:

$ python3 -mvenv <path to new environment>

To use this environment, you must enable it:

$ source <path to new environment>/bin/activate

Deactivating/leaving the environment is also easy:

$ deactivate

Install dependencies

In most cases, you’ll find libraries from the large Python community that can help you get fast results using tools. You can install them using your distribution package manager or using one of the Pythone package managers available. Perhaps the most powerful is PIP. With PIP, you can install dependencies global (# PIP install), per user ($PIP install –user) or virtual environments ((venv) $PIP install). You can install PIP manually using your distribution package manager or using the library provided by Python 3.4 Avoid ($PYTHon3-Mensurepip).

One of the must-have packages I usually install when I’m not 100% sure how to tackle the task at hand and want to try a bit is IPython. IPython is an impressive Python shell, programmed in Python. To name a few features:

Dynamic object introspection.

Do this in the local namespace by typing TAB at the prompt.

Persistent command history.

Session records.

Path complete.

JIT debugger.

Auto indent.

Installing via PIP is easy: $PIP install ipython

If you want to create tutorials or other documentation files, ipython’s notebook functionality (now provided by Jupyter) allows you to interact with ipython Shell through a browser, including Markdown, MathJax and inline Matplotlib support.

Use them by installing Jupyter (PIP install Jupyter) and start the Notebook server (Jupyter Notebook).

If you want to interact with HTTP services, including JSON/XML-API, I recommend using a great request library. This library handles most of the encoded/decoded/parameter/cookie/redirect content that you will face during your interaction with a website. For example, requesting and parsing JSON resources is done by:

r = requests.get(‘https://api.github.com/user’, auth=(‘user’, ‘pass’))

r.json()

{u’private_gists’: 419, u’total_private_repos’: 77, … }

HTML parsing and interaction can be done in most cases using the BeautifulSoup library. The library can handle HTML input from existing browsers as well, including attempts to fix broken code.

Interacting with the network

Most of your targets are accessible over the network, so I’ll briefly cover common/useful Python libraries that are included with standard Python installations.

For lower network-level interactions, the library provides you with sockets and SSL modules. The socket module is a thin wrapper around the BSD socket API available on all common operating systems. Therefore, if you already have experience with socket programming in C, you can easily convert your code to Python. There are some compelling features, such as create_Connection’s ability to create a TCP socket, resolve a host name and connect to a given host/port. Another wrapper is the sendall method, which tries to retransmit data that could not be transmitted over the wire before all the given data was sent or an error occurred.

from __future__ import unicode_literals

import socket

s = socket.create_connection((‘www.ernw.de’, 80))

S.s endall (b ‘GET/HTTP / 1.1 Host: www.ernw.de’)

print(s.recv(1024))

Adding a TLS tunnel to a connection is also very simple:

from __future__ import unicode_literals

import socket

import ssl

s = socket.create_connection((‘www.ernw.de’, 443))

s = ssl.wrap_socket(s)

S.s endall (b ‘GET/HTTP / 1.1 Host: www.ernw.de’)

print(s.recv(1024))

You can even do this during an already used connection:

from __future__ import unicode_literals

import socket

import ssl

s = socket.create_connection((‘smtp.example.com’, 25))

s.sendall(b’HELO smtp.example.comSTARTTLS’)

print(s.recv(1024))

s = ssl.wrap_socket(s)

s.sendall(b’MAIL FROM:’)

print(s.recv(1024))

If you don’t need to interact with services at such a low level, you can use multiple modules to interact at a higher level:

The smtplib

FTPLIB

Poplib module

imaplib

Httplib (http.client in Python 3.x)

nntplib

Telnetlib (useful if you have to leverage a service and want to have an interactive shell session later)

Xmlrpclib (xmlrpc.client in Python 3.x)

Binary processing/encoding

When developing scripts that must interact with services or files, you often find yourself needing to convert data between different formats/encodings. In Python 2.x, most of the time this is as simple as execution, with encode or decode converting it on a string in different formats:

“Hello World”.encode(“hex”)

“AAA=”.decode(“base64”)

Unfortunately, this shortcut was removed in Python 3.x, encode and decode methods can now only convert between UTF-8, CP1250, ISO8859, BIG5, etc.

Instead, you must now use two methods for hexadecimal encoding on byte types:

bytes.fromhex(‘414141’)

B ‘AAA’. Hex () # starting with Python 3.5

For Base64 encoding, you will have to use other modules (which also exist in Python 2.x BTW) :

import base64

base64.b64encode(b’Hello World’)

import codecs

codecs.encode(b’Hello World’, ‘base64’)

import binascii

binascii.b2a_base64(b’Hello World’)

The urllib.parse module (or urllib in Python 2.x) can be used to encode/parse urls:

from urllib.parse import quote_plus, unquote_plus

quote_plus(‘Hello World+1=1337’) # Hello+World%2B1%3D1337

unquote_plus(‘Hello+World’) # Hello World

Regular conversions between Python’s simple types (int, float, STR) and binaries can be done with structural modules:

import struct

struct.pack(‘

struct.unpack(‘ get only the first result

struct.unpack(‘

Starting with Python 3.2, you can also use the type directly with int to get its binary representation:

a = 1337

a.to_bytes(4, ‘little’) # 32 bit little endian

a.to_bytes(2, ‘big’) # 16 bit big endian

int.from_bytes(b’\x10\x00′, ‘little’) # 16

Another nice feature is the structure in the CTypes module. If you use CPython as an interpreter (and most of the time you do), you can use the ctypes.structure type to describe c-class structures and get their binary representation as if they were dumped from a C application:

from ctypes import *

import io

class TestStructure(Structure):

_fields_ = ((‘foo’, c_int), (‘bar’, c_char))

t = Test()

t.foo = 1337

t.bar = b’A’

b = io.BytesIO()

b.write(t)

b.seek(0)

print(b.getvalue()) # \x39\x05\x00\x00\x41

t2 = Test()

b = io.BytesIO(b’\x10\x00\x00\x00\x42′)

b.readinto(t2)

print(t2.foo) # 16

print(t2.bar) # B

This cTypes module is typically used as a cue between Python programs and C libraries, and no Python wrappers are written. Using the CTypes module, you can access any C library and its derived functions:

from ctypes import *

libc = ctypes.CDLL(‘libc.so.6’)

libc.printf(b’Hello World’)

Structure The types mentioned above are used to interact with C libraries that pass/expect structures during function calls.


Exploitation of assistant

Many CTF teams provide their own frameworks for development and CTF solutions. I find Gallopsled’s PwnTools framework very useful, especially in leveraging remote ELF binaries. It contains functions for computing offsets (via loop mode), format string utilization (simple feeds in the data to be written and offsets generated for the format string), Rop links (using ropgadget to parse elf binaries and provide a wrapper) which results in a simple ROP chain call) and an entire API for different transport channels called tubes. This allows you to exploit vulnerabilities, such as using the GDB back end, with a single line change to transfer the exploit to the target service:

from pwn import *

r = gdb.debug(‘./level3’)

#r = remote(IP, PORT) # simply uncomment to interact with a remote service

r.recvuntil(‘: ‘)

r.sendline(EXPLOIT)

r.interactive() # start interactive session

The original English articles address: https://insinuator.net/2015/09/python-for-hackers/

The above is the content of this article, xiaobian also selected a few examples. If you like this article or think it is helpful to you, please follow or forward it on demand. If you have good comments or suggestions, please leave a comment below. Links to selected examples are found below.

Case: 1, https://www.ernw.de/download/python-for-hackers/Pitfalls%202.html

2, https://www.ernw.de/download/python-for-hackers/Pitfalls%203.html

3, https://www.ernw.de/download/python-for-hackers/Network.html

This article comes from the network, if there is infringement, please contact xiaobian to delete!

Recommended readingMore highlights

  • Introduction to Python: Python is a… _ Tiger _ Read 2,218 comments 0 likes 1
  • Python has been an object-oriented language since it was designed. It is for this reason that creating a class in Python and a class for… Read 2,620 comments 3 likes 16
  • What is the planning process of large event planning company hangzhou event planning in the formulation of each process to strive for precision, layer upon layer of checks. Activity flow largely determines the direction of the activity, but also reflects the effect of an activity… Yichuang Culture Read 165 Comments 0 likes 0
  • A tree in full bloom big flowers in the sky rainy day the hands of the earth ah umbrella for us, though it may leak rain can shelter from the rain children grateful for such a gift 2 that fine… Read 27 Reviews 0 Upvotes 1
  • You are so lonely, say a person is good you are so lonely, say a person is good. Xiao He is such a hard mouth of a person. I just walked out of a movie theater and stood in a theater full of popcorn… Uncle Katydid Read 204 Comments 0 likes 2