Skip to content

Commit

Permalink
Cleanning and refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
whattheslime committed Jan 6, 2021
1 parent dec2cbd commit 36b5a83
Show file tree
Hide file tree
Showing 15 changed files with 685 additions and 103 deletions.
518 changes: 518 additions & 0 deletions LICENSE

Large diffs are not rendered by default.

64 changes: 42 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,41 @@
# H4ckTools
# h4cktools

## Purpose
h4cktools is a library containing usefull helpers for penetration testing, security challenges and CTF.
h4cktools is a python library containing usefull helpers for penetration testing and security challenges.
It include all python library that can be useful, implements several new functions ond objects and add shorcuts for functions and payloads.

h4cktools was developped by a random pentester who loves python language <3

The project is compatible with Windows and Unix based systems.

It is Web Pentest Oriented, it is not inclding pwntools and it does not have not the same purpose.
It is Web Pentest Oriented, it is not inclding [pwntools](https://pypi.org/project/pwntools/) and it does not have not the same purpose.

## Disclaimer
This project is in not intended to be used for illegal purpose and h4cktools developers are in no way responsible for its use.
This project is in not intended to be used for illegal purpose and h4cktools developers are in no way responsible for its use etc...

## Summary
- [How to install](#installation)
- [How to Use](#usage)

## Installation
Install from pip
```bash
$ pip install h4cktools
```

## Install
Install from github
```bash
$ pip3 install git+https://github.com/WhatTheSlime/h4cktools.git
$ pip install git+https://github.com/WhatTheSlime/h4cktools.git
```

## How to use
h4cktools library has been developped for be used in a python prompt like [IPython](https://ipython.org/)
## Usage
h4cktools library has been developped for be used in a python prompt like [IPython](https://ipython.org/).

To use it just open a python prompt and import all components of the library:
```python
>>> from h4cktools import *
```
Of course it can also be used in scripts but it is not recommended to use h4cktools in long-term project.

## HTTPSession
HTTP library aims to execute HTTP requests and parse its content easily. It is override requests library to be use quicker and addapt it to pentesting
HTTP library aims to execute HTTP requests and parse its content easily. It overrides [requests library](https://requests.readthedocs.io/en/master/) to be quicker and addapted to pentesting.

### Initialization:
```python
Expand Down Expand Up @@ -68,11 +73,15 @@ When the *host* is set, you can navigate into the host using local path:
Scope can also be initialize at HTTPSession declaration or set after without doing any requests:
```python
>>> s = HTTPSession("https://www.google.com")

>>> s.host
'https://www.google.com'

>>> s.host = "https://facebook.com"

>>> s.host
'https://facebook.com'

```

Note that redirection following is disable by default. When a response must redirect, you can use *follow* method to go on:
Expand All @@ -82,23 +91,27 @@ Note that redirection following is disable by default. When a response must redi

>>> s.follow()
<[200] https://www.google.com/>

```

#### Web tree navigation

*goin* and *goout* methods allow you to navigate in web tree, similar to cd <Local_Path> and cd ../ unix commands:
*goin* and *goout* methods allow you to navigate in web tree, similar to **cd <Local_Path>** and cd ../ unix commands (but using goin with a paramater starting with a / will not bring you to the url root):
```python
>>> s.goto("https://google.com")
<[200] https://www.google.com/>
>>> s = HTTPSession("https://www.google.com")

>>> s.goto("search")
<[302] https://www.google.com/search>

>>> s.goin("test") # or s.goin("/test")
<[404] https://www.google.com/search/test>

>>> s.goout()
<[302] https://www.google.com/search>

>>> s.follow()
<[200] https://www.google.com/webhp>

>>> s.goout()
<[200] https://www.google.com/>
```

To check your current path, simply check the *page* attribute or, if you only want the path, use the page.path attribute:
Expand All @@ -108,8 +121,10 @@ To check your current path, simply check the *page* attribute or, if you only wa

>>> s.page
<[200] https://www.google.com/>

>>> s.page.path
'/'

```

#### Historic
Expand Down Expand Up @@ -168,11 +183,6 @@ Futures object allow you to send requests concurrently:
<[404] https://google.com/3>]
```

If you want to use specific actions on each response, it is also possible by declaring functions with async syntax
```python
TODO
```

You can define worker number at HTTPSession initialization or after:
```python
>>> s = HTTPSession(workers=5)
Expand All @@ -182,6 +192,16 @@ You can define worker number at HTTPSession initialization or after:
Note that doing requests in this way will note populate the history and set current page of th HTTPSession.

### Responses Parsing
Every requests method of **HTTPSession** will return an **HTTPResponse** object and store it in the **page** attribute:
```python
>>> r = s.goto("search")

>>> s.page
>>> <[302] https://www.google.com/search>
```

The HTTPResponse Object is a wrapper of **requests.Response** object and add new attributes and methods.


## Encoder

Expand Down
26 changes: 8 additions & 18 deletions h4cktools/__init__.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
# Import built in libraries
import urllib3
from pathlib import Path
from urllib.parse import (
urlparse,
urljoin,
urlencode as qurlencode,
)

## Import hashlib
from hashlib import *
# Import hmac
import hmac
#!/usr/bin/env python3

"""h4cktools is a library containing usefull helpers for penetration testing
and security challenges. It implements several functions ond objects and add
shorcuts for functions and payloads.
"""

# Import custom libraries

## Import http libs
# Import http libs
from .http.httpsession import HTTPSession

## Import versions libs
Expand All @@ -36,6 +28,4 @@
from .encode import *

# Import display utils
from .display import Logger, progressbar

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from .display import Logger
60 changes: 21 additions & 39 deletions h4cktools/display.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import logging
import os
import progressbar as pgb
import yaml


__all__ = ["Logger"]


class Logger:
"""Simple Logger Object"""
def __init__(self, filename=None, colors=True, verbosity=0):
self.filename = filename
self.colors = colors
Expand All @@ -14,86 +17,65 @@ def __init__(self, filename=None, colors=True, verbosity=0):
f.write("")

def info(self, msg):
"""
"""
self._log(f"[*] {msg}")

def success(self, msg):
"""
"""
_msg = f"[+] {msg}"
if self.colors:
_msg = _msg.join(["\033[32m", "\033[0m"])
self._log(_msg)

def partial(self, msg):
"""
"""
if self.verbosity >= 1:
_msg = f"[-] {msg}"
if self.colors:
_msg = _msg.join(["\033[36m", "\033[0m"])
self._log(_msg)

def fail(self, msg):
"""
"""
if self.verbosity >= 2:
_msg = f"[.] {msg}"
if self.colors:
_msg = _msg.join(["\033[34m", "\033[0m"])
self._log(_msg)

def debug(self, msg):
"""
"""
if self.verbosity >= 3:
_msg = f"[=] {msg}"
if self.colors:
_msg = _msg.join(["\033[2;37m", "\033[0m"])
self._log(_msg)

def warning(self, msg):
"""
"""
_msg = f"[Warning] {msg}"
if self.colors:
_msg = _msg.join(["\033[33m", "\033[0m"])
self._log(_msg)

def error(self, msg):
"""
"""
_msg = f"[Error] {msg}"
if self.colors:
_msg = _msg.join(["\033[31m", "\033[0m"])
self._log(_msg)

def _log(self, msg):
"""
"""
if self.filename:
with open(self.filename, "a") as f:
f.write(f"{msg}{os.linesep}")
print(msg)

pgb.streams.wrap_stderr()

def progressbar(
max_value=0,
title="[=]",
counter=True,
percent=False,
timer=False,
eta=False
):
widgets = []

if title:
widgets.append(f"{title} ")

widgets.append(
pgb.Bar(marker=f"=", left="[", right="]", fill='-')
)

if counter:
widgets.append(pgb.Counter(format=" %(value)02d/%(max_value)d"))

if percent:
widgets.append(pgb.Percentage(format=" %(percentage)3d%%"))

if timer:
widgets += [" [", pgb.Timer(), "]"]

if eta:
widgets += [" (", pgb.ETA(), ")"]

return pgb.ProgressBar(
widgets=widgets,
max_value=max_value,
redirect_stdout=True,
)
19 changes: 19 additions & 0 deletions h4cktools/encode.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,25 @@
unquote_plus
)

__all__ = [
"b64encode",
"hexencode",
"uhexencode",
"octencode",
"urlencode",
"urlb64encode",
"furlencode",
"durlencode",
"htmlencode",
"fhtmlencode",

"b64decode",
"htmldecode",
"urldecode",
"urlb64decode",
"autodecode"
]

## Encoding
def b64encode(obj: Union[str, bytes], encoding="utf-8") -> str:
"""Base64 encode characters of a string
Expand Down
9 changes: 7 additions & 2 deletions h4cktools/generate/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
from subprocess import call


__all__ = [
"randnum", "phpserialize", "phpwebshell", "jspwebshell", "warwebshell"
]


def randnum(length: int) -> str:
"""Generate random number of certain length.
It can generate numbers starting with 0.
Expand Down Expand Up @@ -72,10 +77,10 @@ def phpserialize(obj, null_byte: str = "\0") -> str:
elif k.startswith("_"):
nk = "".join([null_byte, "*", null_byte, k[1:]])


s = phpserialize(nk).join([s, phpserialize(v)])

return s.join([f"O:{len(n)}:\"{n}\":{len(attrs)}:{{", "}"])
# raise TypeError(f"{type(obj)} not serializable")


def phpwebshell(password: str = "", command="echo shell_exec") -> str:
Expand Down
4 changes: 4 additions & 0 deletions h4cktools/generate/user.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
from random import randint, choice
from string import ascii_lowercase, ascii_uppercase, digits, punctuation


__all__ = ["password"]


def password(
length: int = 20, punc: str = punctuation
) -> str:
Expand Down
3 changes: 3 additions & 0 deletions h4cktools/http/asyncsession.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
from functools import partial


__all__ = ["AsyncSession"]


class AsyncSession(requests.Session):
"""request.Session wrapper to make asynchronous requests
"""
Expand Down
Loading

0 comments on commit 36b5a83

Please sign in to comment.