Skip to content

Commit

Permalink
First commit!
Browse files Browse the repository at this point in the history
  • Loading branch information
thewhiteninja committed Apr 3, 2021
0 parents commit 5df8f22
Show file tree
Hide file tree
Showing 29 changed files with 2,296 additions and 0 deletions.
133 changes: 133 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
data/

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/
/.idea/
/tmp.ps1
/tmp.xml
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 thewhiteninja

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
108 changes: 108 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# DeobShell

[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE.MIT)
[![Language: Python](https://img.shields.io/badge/Language-Python-brightgreen.svg?tyle=flat-square)](#)
[![Cross-platform](https://img.shields.io/badge/Platform-All-0078d7.svg)](#)
[![v1.0](https://img.shields.io/badge/Version-1.0-ff5733.svg)](#)

<br />

DeobShell is PoC to deobfuscate Powershell using Abstract Syntax Tree (AST) manipulation in Python.
The AST is extracted using a Powershell script by calling `System.Management.Automation.Language.Parser` and
writing relevant nodes to an XML file.

AST manipulation and optimization is based on a set of rules (ex: concat constant string, apply format operator ...).

From the deobfuscated AST, a ps1 script is rebuilt using Python.
See the diagram below.

*It's a PoC ... only a subset of Powershell is supported*

## How

<p align="center">
<img alt="diagram" src="assets/diagram.png" width="600">
</p>

### Example of rules

- Format

#### In
```xml
<BinaryExpressionAst Operator="Format" StaticType="System.Object">
<StringConstantExpressionAst StringConstantType="DoubleQuoted" StaticType="string">{0}{1}</StringConstantExpressionAst>
<ArrayLiteralAst StaticType="System.Object[]">
<Elements>
<StringConstantExpressionAst StringConstantType="SingleQuoted" StaticType="string">c</StringConstantExpressionAst>
<StringConstantExpressionAst StringConstantType="SingleQuoted" StaticType="string">AcA</StringConstantExpressionAst>
</Elements>
</ArrayLiteralAst>
</BinaryExpressionAst>
```
#### Out
```xml
<StringConstantExpressionAst StringConstantType="SingleQuoted" StaticType="string">cAcA</StringConstantExpressionAst>
```

### Examples of script

- a CTF chall

#### In

```powershell
$mRSp73 = [ChaR[] ]" ))43]raHc[]gNIRtS[,)38]raHc[+98]raHc[+611]raHc[((eCAlper.)421]raHc[]gNIRtS[,'5IP'(eCAlper.)'$',)09]raHc[+99]raHc[+701]raHc[((eCAlper.)93]raHc[]gNIRtS[,'vzW'(eCAlper.)'
2halB.tcejboZck tuptuO-etirW
7halB.tcejboZck +'+' 6halB.tcejboZck + halB.tc'+'ejboZck '+'= 2galFFT'+'C:'+'vneZck
SYt!eciNSYt = 1galFFTC:vneZck
SYt...aedi dab yre'+'v'+' ,yre'+'v a yllacipyt svzWtaht ,ton fI .ti gninnur erofeb siht detacsufbo-ed uoy epoh ISYt eulaV- 2halB emaN- '+'ytreporPetoN epy'+'TrebmeM- rebmeM-ddA 5IP tcejboZck
SYt'+'.uoy tresed dna dnuora nur annog reveNSYt eulaV- 9hal'+'B emaN- ytreporPetoN epyTrebmeM- rebmeM-ddA 5'+'IP tcejboZck
SYt.nwod uo'+'y tel annog '+'re'+'veN .'+'pu uoy evig annog reveNSYt eulaV- 8halB emaN- ytreporPetoN epyTrebm'+'eM- rebmeM-d'+'dA 5IP tcejboZck
SYt}f1j9kdSYt eulaV- 7halB emaN- y'+'treporPetoN ep'+'yTrebmeM- rebmeM-ddA 5IP tcejboZck
SYtg4lf_3ht_t0nSYt eulaV- 4halB emaN- yt'+'reporPetoN epyTrebmeM- rebmeM-ddA 5IP tcejboZck
SYt1#f!J{SYt eulaV- 6halB emaN- ytreporPetoN epyTrebmeM- rebmeM-'+'ddA 5IP tcejboZck
SYtgalF,ehT,toN,oslASYt eulaV- 5halB emaN- ytreporPetoN epyTrebmeM- rebmeM-ddA 5IP tcejboZck
SY'+'t}fdjfkslfdSYt eulaV- 3halB emaN- ytrepor'+'PetoN e'+'pyTrebmeM- rebmeM-ddA 5IP tcejboZ'+'ck
SYtgalfSYt eulaV- halB em'+'aN- ytreporPetoN e'+'pyTrebmeM- rebmeM-ddA 5IP tcej'+'boZck
tc'+'ejbO'+'SP tcejbO-weN = tc'+'ejboZck'( ()''nioJ-'x'+]3,1[)eCNERefErpESoBreV$]GniRTS[( (. " ;[aRRAy]::REVerse($MrSp73);. ( 'IeX') ( -JoiN$MrSp73)
```

#### Out

```powershell
$object = New-Object PSObject;
$object | Add-Member NoteProperty Blah "flag";
$object | Add-Member NoteProperty Blah3 "dflskfjdf}";
$object | Add-Member NoteProperty Blah5 "Also,Not,The,Flag";
$object | Add-Member NoteProperty Blah6 "{J!f`#1";
$object | Add-Member NoteProperty Blah4 "n0t_th3_fl4g";
$object | Add-Member NoteProperty Blah7 "dk9j1f}";
$object | Add-Member NoteProperty Blah8 "Never gonna give you up. Never gonna let you down.";
$object | Add-Member NoteProperty Blah9 "Never gonna run around and desert you.";
$object | Add-Member NoteProperty Blah2 "I hope you de-obfuscated this before running it. If not, that''s typically a very, very bad idea...";
$env:CTFFlag1 = "Nice!";
$env:CTFFlag2 = $object.Blah + $object.Blah6 + $object.Blah7;
Write-Output $object.Blah2;
```

### References

- https://github.com/R3MRUM/PSDecode
- https://robwillis.info/2020/08/invoke-decoder-a-powershell-script-to-decode-deobfuscate-malware-samples/
- https://www.varonis.com/blog/adventures-malware-free-hacking-part-ii/
- https://gist.github.com/notdodo/3d5ac56cd837c3f79d2c687f3e75cac1
1 change: 1 addition & 0 deletions assets/diagram.drawio

Large diffs are not rendered by default.

Binary file added assets/diagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data.zip
Binary file not shown.
69 changes: 69 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# coding=utf-8
import os
import pathlib
import sys

from modules.ast import create_ast_file, read_ast_file
from modules.logger import set_log_level, LogLevel
from modules.optimize import Optimizer
from modules.rebuilder import Rebuilder
from modules.utils import welcome

OPTIONS = {}


def usage():
print("Usage: " + os.path.basename(sys.argv[0]) + ' [options]')
print()
print("Command:")
print(" deob : Optimize PowerShell AST")
print()
print("Options:")
print(" -h, --help : Show help")
print()
sys.exit(0)


def parse_args():
global OPTIONS
i = 1
while i < len(sys.argv):
if sys.argv[i] in ["-h", "--help"]:
usage()
elif sys.argv[i] in ["-a", "--ast"]:
OPTIONS["input"] = sys.argv[i + 1]
i += 1
else:
OPTIONS["command"] = sys.argv[i]
i += 1


def deob(ps1_file):
p = pathlib.Path(ps1_file)

if create_ast_file(p):

if ast := read_ast_file(p.with_suffix(".xml")):

o = Optimizer()
o.optimize(ast)

with open(p.with_suffix(".deob.xml"), "wb") as output:
ast.write(output)

r = Rebuilder(p.with_suffix(".deob.ps1"))
r.rebuild(ast.getroot())


def main():
if OPTIONS.setdefault("command", None) == "deob":
deob(OPTIONS['input'])
else:
usage()


if __name__ == '__main__':
welcome()
set_log_level(LogLevel.DEBUG)
parse_args()
main()
1 change: 1 addition & 0 deletions modules/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# coding=utf-8
35 changes: 35 additions & 0 deletions modules/ast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# coding=utf-8
import os
import subprocess
# noinspection PyPep8Naming
import xml.etree.ElementTree as ET

from modules.logger import log_info, log_debug, log_err


def read_ast_file(filename):
log_info(f"Reading input AST: {filename}")
try:
ast = ET.parse(filename)
return ast
except IOError as e:
log_err(e.args[1])
return None
except Exception as e:
log_err(str(e))
return None


def create_ast_file(ps1_file):
log_info(f"Creating AST for: {ps1_file}")

cmd = ["PowerShell", "-ExecutionPolicy", "Unrestricted", "-File",
os.path.abspath(os.path.join("tools", "Get-AST.ps1")),
"-ps1", os.path.abspath(ps1_file)]

result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

for line in result.stdout.splitlines():
log_debug(line)

return result.returncode == 0
Loading

0 comments on commit 5df8f22

Please sign in to comment.