Tuesday, October 7, 2014

Post Exploitation, Metasploit and Windows Hashes

What is a Windows hash?

A Windows hash is a non-salted algorithmic encoding of a plaintext password.  Windows has used two different algorithms for hashing to date, the result being an  LAN Manager (LM) hash, or an NT hash.  In a Microsoft Windows network, NT LAN Manager (NTLM) is a suite of protocols used to provide authentication, integrity and confidentiality to users.  NTLM is the successor to LAN Manager (LANMAN), and attempts to provide backwards compatibility with LANMAN.

In the world of cryptography, salting is a known piece of additional random data that is “mixed in” as an additional input to the one way hashing function.   The advantage of salting is that the hashed representation of a password will never be the same for the same plaintext string.   Unfortunately this technique is not used with stored hashes in Windows.

The LANMAN hash is constructed as follows:
  • The plaintext password is padded with NULL characters to a length of fourteen bytes, and converted to all uppercase.
  • The resulting string is split into two seven character strings.  Each string is used as a key to encrypt the constant string value of “KGS!@#$%”. The data encryption standard (DES) algorithm is used for encryption.
  •  The resulting ciphertext is concatenated into a sixteen byte hash value.

The NT hash is constructed by using the MD4 hashing algorithm over the plaintext string.   A plaintext password, used to construct the NT hash, can be up to 256 characters in length with mixed case and special characters.  Unlike the LM hash, special characters, upper and lower case are all preserved with an NT hash.

How is a Windows hash passed across the network?

From a network transmission perspective, there are two different challenge response algorithms in use.   The LANMAN, and NTLMv1 algorithm operates as follows:
1)    Workstation client initiates authentication
2)    Server responds with a random challenge
3)    Client formulates and sends a response to the challenge by:
a)    Padding the LANMAN/NT hash to 21 bytes
b)    Splitting the hash into three seven character pieces
c)    Using each piece as a DES key to encrypt the server challenge.

NTLMv2 challenge/response is significantly more secure, and operates as follows:
1)    Workstation client initiates authentication
2)    Server responds with a random challenge
3)    Client formulates/sends a response by:
a)    Creating an HMAC-MD5 string using the username, domain name, and NT hash as a key.  This result is called the NTLMv2 one way function (OWF)
b)    Combining the HMAC-MD5 string, server challenge, timestamp, and client challenge into a response. 

Obtaining Hashes during a Penetration Test

In a post exploitation scenario, and assuming you have administrative access, it is useful to be able to retrieve the hashed representation of passwords. Windows hashed passwords are stored in the Security Accounts Manager (SAM) registry hive which is a file named “%SystemRoot%\System32\Config\SAM”.   By default, the SAM file is locked on a running system, and inaccessible to all users including administrative users.  If an NT file system recovery was performed in the past, and the Administrator has not removed the backup data, you might be able to find the SAM file in the “%SystemRoot%\repair” directory.

Since you cannot read the file directly on the disk volume, there are a few alternative tricks to get hold of the data.   The local security authentication sub-system process (LSASS.EXE) on a running windows system reads this data and caches it in memory.

Method 1: Meterpreter “hashdump” command 

The hashdump command is an in-memory version of “pwdump”.   Hashdump allocates memory inside the LSASS process, injects assembly code, and executes it using the CreateThread() function.   The injected assembly code is designed to read the hashes out of LSASS memory, and print them out.   No files are written to disk, thus detecting the technique without using memory forensic techniques is difficult.

In January, 2010, HD Moore noted that Anti-Virus, and host intrusion prevention (HIPS) vendors had developed techniques to detect the API calls made by the meterpreter hashdump command, and block the calls.   In the process of detection however, LSASS will often crash leading to system instability.

Method 2: Meterpreter “hashdump” post module

The hashdump post module (post/windows/gather/hashdump.rb) uses a registry based technique to directly access the SYSKEY, and decrypt the raw LANMAN, and NT hashes.      The significant advantage of this technique is that there is no in-memory manipulation of LSASS with its potential for instability.

The caveat is that a SYSTEM token is required to use the technique.  An account in the local administrators group does not have read access to the SAM registry tree that contains the hashes.   If you have exploited a system service, or perhaps something like a DCERPC vulnerability, you are in great shape.   Alternatively you can consider migrating your meterpreter to a service process, or load the incognito module, and impersonate a token.

Method 3: Meterpreter “smart_hashdump” post module

Carlos Perez improved further on the hash extraction techniques in the sense of automating some of the additional steps, and logic required before the actual hashes are extracted.   The “smart_hashdump” post module works as follows:

  • Determine the privilege level, operating system, and test if the target is a domain controller
  •  If you have the right privileges, specifically a SYSTEM token, smart_hashdump will read the hashes from the SAM registry hive.
  • If the system is a Domain Controller, smart_hashdump will always inject assembly code into LSASS to obtain hashes.
  • If the target is a Windows 2008 server, and the process has administrative privileges, smart_hashdump will:
    • Attempt to gain SYSTEM by using “getsystem”.
    • If it fails to get system, smart_hashdump will attempt to automatically migrate to a process that has system privileges.
    • Inject the LSASS process with assembly code to dump the hashes
  • If the target is a Windows 7+ system with UAC disabled and the process has administrative privileges, smart_hashdump will run “getsystem” and use the registry reading method.If the target is a Windows 2000/2003/XP system, “getsystem” will be used followed by the registry reading method.
The take home point with “smart_hashdump” is that it will do the work for you to obtain SYSTEM privilege and prefer reading the SAM registry hive if at all possible.  The downside with this and all methods, is that within the context of a Domain Controller, you are still required to inject assembly code into LSASS in order to obtain hashes.   As pointed out above, this is a dangerous technique and can result in a crash which your client would certainly not appreciate.

Method 4: Extract hashes from Volume Shadow Copies of the file system

In 2011, Tim Tomes, and Mark Baggett were performing research on the topic of hiding malware in Volume Shadow Copies.   As a result of this work, they realized that by creating a volume shadow copy, or using a pre-existing volume shadow copy, the NTDS.DIT, SAM and SYSTEM files could be directly copied from a running system.

In summary, the process involves:
      Creating a volume shadow copy using system tool “vssadmin” or Tim’s visual basic script called “Vssown.vbs”
      Downloading the NTDS.DIT, SAM, and SYSTEM files
      Downloading and compiling tools from http://www.ntdsxtract.com/downloads/ntds_dump_hash.zip
      Using esedbdumphash to extract the database from NTDS.DIT
      Using dsdump.py, or bkhive2, and samdump2 to dump hashes.

The largest single advantage with using an offline method to extract hashes after copying from a volume shadow is the fact that you do not have to inject anything into the LSASS process on a running domain controller.   The disadvantage is that in a larger environment, you are faced with exfiltrating some potentially large files, and downloading them for analysis.  It is possible that network defenders might detect the network activity of a large data transfer, and/or a large file being written to disk on a workstation.

Choosing the right tool for the job

Which method of hash extraction you decide to use depends on the context of your test.  If you are dealing with an individual system that is not a domain controller, then the “smart_hashdump” module is a good solid choice.   If you are working with host based IPS or Anti-Virus that is detecting LSASS injection attempts, you are taking a significant risk when injecting assembly into this process.   In the context of a domain controller, a volume shadow copy extraction is the best approach to ensure stability.   It is apparent that the original LSASS injection process in meterpreter can be risky, and should probably be avoided.
While this article focuses on hashes, it would be remiss not to mention that LSASS also caches some plaintext data for other security service providers.  These include WDigest for HTTP authentication, Kerberos, and Terminal Services.  If you have administrative access on a local system, LSASS plaintext security service provider memory can be accessed using the Mimikatz or Kiwi extensions enabling the extraction of plaintext information to screen.  Kiwi can be thought of as the upgraded (version 2) release of Mimikatz and includes some excellent new functionality.

References




Monday, August 11, 2014

DEFCON 2014


Below are point form notes on a number of different DEFCON talks that I was able to attend.


1. 20140808-1100 Track 3 - Abusing Automated Systems

  • http://www.amazon.com/G%C3%B6del-Escher-Bach-Eternal-Golden/dp/0465026567/ref=sr_1_1?s=books&ie=UTF8&qid=1407521214&sr=1-1&keywords=godel+escher+bach
  • http://www.thingiverse.com/thing:311438  <-- barcode generator
  • Correlating goods with barcodes, and feeding data to things like health insurance providers.  Abusing the VIP card space and enjoying it!
  • Want a VIP card?  You can create your own.  Check out xlogic's site for Perl scripts.
  • Forensics: "Scalpel" - headers and footers searching for identifying files
    • Scalpel sigs:  "ext and title", "case sensitive", "max size", "head"
    • can abuse Scalpel --> magic bomb by xlogicx
    • https://github.com/sleuthkit/scalpel
  • Xlogic had a thing called Tumor which is an A/V denial of service / disk space grower.  Everytime the file was scanned, it grew in size!  weird..
  • Having fun with IDS consoles?  Send in XSS in attacks and watch the analyst get owned.
  • 8ball.pl - generates traffic from IDS rule file.
  • check out http://testmyids.com
    • reads a rules file and generates a packet for ALL of the rules.
  • regular expression denial of service (REDOS)
    • long circuiting - does not match but takes a long time to get there
2. 20140808-1200 Penn/Teller - OSSMAN (NSA playset, RF RetroReflectors)
  • RF Retro-Reflectors
    • an implant that is a low power small device; modulates a radio signal send to it, and reflects it back
    • irradiating a target is also called illumination.
  • Forward engineering tools based on the NSA ANT catalog
  • Passive Attacks
    • TEMPEST - refers to unintentional emissions
    • writings of Marcus Kuhn
  • Active Attacks
    • The Thing (great seal bug) - 1940's technology consisting of a microphone and an antenna
    • changes in air pressure modulate the impedance which modulates reflection coming back to a radar unit illuminating
    • uses NO local power supply
    • almost no research progress between 1960 and 2013.
    • soft tempest (Kuhn and Anderson) have a brief mention in one paper.  No implant installed in the target.  Equipment was vulnerable out of the box.
    • Hints that there might well be reflected returns possible without putting implants into devices such as video display, and keyboards.
  • Method of communication is called "RF Backscatter" (lots of public research)
    • very first public research paper in 1948 (well after the Thing was deployed)
    • lot more research especially around UHF RFID.  Design info on UHF RFID tags.
  • To see our returns we need a Radar system.  Which one?  Old police radar?  
    • police radars are above 20 Ghz which is high.
    • Hot Wheels radar gun operates at 10 Ghz which is much closer.
      • just need the radio board component.
    • also there is Arduino Radar on Ebay.
    • Coffee Can radar at 2.4Ghz is another possibility.
  • Mike Ossman is using HackRF One for his radar.  Software defined radio radar if you like.
    • Official range is 10Mhz - 6Ghz.  Baseband bandwidth is 20Mhz.
    • Half-duplex transceiver
    • using band right above 2.4Ghz 802.11 band.  A little used band area in the US.
  • Mike's first RF-RetroReflector is called "CONGAFLOCK"
    • hardware design - centered on a MOSFET
    • 10Kohm resistor to protect the MOSFET gate.
    • Antenna connector to the top, target connected to the left.
    • When the input signal is going up and down in voltage, the MOSFET switches on/off the antenna.   This creates an impedance changes which modulates a signal.
      • input must swing through +/- 3.3 - 5 volts
    • a kit to build your own in the HH village.
    • solder the gadget INTO something.   A PS/2 keyboard cable for example.
  • FLAMENCOFLOCK is version 2.
    • two PS/2 connectors and retroreflector in center
    • tap the clock line or data line.  ideally both.
    • tapping the data line.   Picking up the signal with HackRF one and doing AM demodulation.

3. 20140808-1300 Firewall Bypass Techniques
  • Context - I want access to an RDP server with persistant C2
    • in an ideal world, 
      • infect desktop client
      • steal RDP password
      • connect to RDP server
  • The challenge?   RDP server not reachable from Internet, and 2-Factor in use.
    • hardware firewall between users, and RDP server.
    • Very tight security - only single TCP inbound port of 3389 allowed, and no outbound traffic permitted.
    • This is post-exploitation technique - user workstation already owned.
  • Numerous different challenges
    • how can I drop the malware to the server?
    • how can I start it?
    • how do I elevate privs?
    • how do I get my traffic outbound?
  • Step 1: New tools we can use:
    • Windows key scripting tool
    • What does it do?
      • Waits for the user to connect to RDP server with 2 factor
      • After successful, tool creates screenshot and shows it to user
      • user thinks this is a screen freeze.
      • program starts typing in the background...  
      • starts winword, drop ascii encoded payload.  
        • create VB-Macro code, and start binary.
      • instruct A/V gui to add exclusion perhaps?
      • can also install custom software
    • Lots of possibilities for use.
  • Step 2: Bypass application whitelist?
    • set the flag to bypass applocker as Admin.
    • can also load DLL's directly from VB macro code.
    • DLL loads will bypass applocker already.
    • MS-Office is really useful.
  • Step 3: elevate privileges
    • exploit vulnerable 3rd party service
    • file replacement for doing so
    • interactively logged on users can stop/services
  • Step 4: Bypass hardware firewall?
    • how do we can shell's outbound with high level restriction?
    • why don't I use the TCP source to indicate that the traffic is special
    • used a kernel driver to inspect traffic and provide a covert carrying mechanism over the RDP traffic stream.   Author wrote a kernel driver that carried outbound traffic in the TCP source port.   This is a TCP covert channel.
      • Editorial:  Had I been doing this work, I would more likely have used a different header field (such as TCP timestamp option or similar)
      • TCP source port could still be stopped by firewall.
      • ?? Source port on egress will be 3389 - I think the author meant dest port assuming the firewall maintained state based on initial SYN/SYN-ACK on 3389 and ignored the ephemeral port in traffic stream


4. 20140808-1500 VEIL Framework
  • Veil Framework
    • bridge the gap between pen testing and red teaming
    • modular framework that generates A/V evading payloads
    • veil catapult - upload and execute binaries
    • helps to not waste time scripting.
    • Editorial note:
      • not to different from my own jofftools kit but more polished.
  • Goals
    • lot of trigger options
    • good modularity, easy to implement additional stuff
    • other tool integration, and flexibility.
    • good cleanup
  • Veil-Pillage
    • pth-wmis - no service created
    • pth-winexe - run as system, binary dropped
    • impacket-smbexec - service created, no binary dropped
    • all catapult functions as modules into veil-pillage
    • catapult will be obsoleted
  • exe delivery
    • EXE are uploaded/triggered with a  \\UNC path
    • hosted with an SMB server
    • stand up and host file on an SMB server.  trigger it and EXE is loaded direct into memory on the host.
    • check out the Schmoocon presentation for demo.
    • python injector is very similar to powershell injection.
      • the only files that touch disk are the trusted python libraries etc.
  • New modules
    • enumeration
      • host/credential_validation - what creds work?
      • domain/user_hunter - where is our high value user?
      • host/enum_host - basic host enumeration
    • management
      • enable/disable uac
      • enable/disable RDP
      • force logoff to trigger post exploitation actions
    • persistence
      • bitsadmin
      • registry/sticky_keys
      • registry/unc_dll - append UNC path to environment variable.
    • powersploit
      • standup temp web server
      • trigger download string, run in memory
      • easier to run powersploit across large number of machines
  • new features
    • pure powershell meterpreter stagers
    • chooses correct powershell binary to use for injection
  • output cleanup
    • universal activity log
    • breaks out by module
    • all actions have a reciprocal cleanup action as a script.
  • random features
    • state preservation
    • MSF database interaction
    • tab completion, error checking
  • hash dumping / plaintext grabbing (new hotness)
    • powerdump.ps1
    • WCE binaries
    • powershell integrated mimikat  (powersploit project)

5. DEFCON 20140809-1000 Mass Scanning
  • scanning the entire Internet
  • tool called masscan.  https://github.com/robertdavidgraham/masscan
  • NMAP is a synchronous scan.   Masscan transmits packets, and does not wait for the response.  Uses SYN cookies to validate the responses.
  • Masscan is design for large scale and is really aggressive.
  • Need to block TCP reset packets, or use another machine to receive the responses.
  • can do load testing.   '--infinite --banners --source-ip <range>'
  • spoof scan.  Receive on one IP address.   Send from co-lo data center that has no egress filtering.
    • have the receiver be a mobile phone for example!
  • Internet scanning result glimpses:
    • VNC scanning - setup a script to capture VNC connect screens
    • heartbleed scan - 300k systems still vulerable
    • TN3270 live mainframe scans

6. DEFCON 20140809-1100 Pawning ISP's like a boss  (TR-069)
  • residential gateway security sucks
  • TR-069
    • technical report (TR) by the broadband forum.
    • consortium of players in broadband market
    • This is a CPE-WAN Management Protocol
  • TR-069 provisioning sessions
    • TR-069 server is called an ACS.
    • they communicate in SOAP RPC initiated by the client side
  • Protocol description
    • client sends INFORM
    • ACS responds with GET/SET packets
    • all exchanges are SOAP
  • Widely used defacto device mgmt standard.
    • AT&T, Verizon, Comcast etc...
    • ZMAP guys (port 7547) is the second most popular open port in the word!
  • What can you do with ACS?
    • zero touch configuration
    • remote management
    • performance measurements, deploy firmware etc.
  • Who do you trust to run code on your devices no demand?
    • silently, remotely, without consent etc.
  • TR-069 was hidden in his router using HTML comments!!
  • How do we find ACS in the wild?
    • scanning for TCP 7547 and friends
    • Internet and DNS census
  • ACS authentication?  SSL recommended but not always used!
    • HTTP basic auth is common.
    • few hundred ISP's surveyed
    • 81% not encrypting!  
    • the ACS URL can be changed.
  • Recap:
    • protocol is dangerously powerful
    • servers are high value targets
    • lot of implementations are broken
  • OpenACS project
    • open source java
    • 3 days got remote code exec.
  • AUDIT your own TR-069 settings
    • ensure SSL certificate is turned on
    • add your own NAT/FW router on the inside of your net.
    • ACS vendors need to write MUCH better software







Wednesday, August 6, 2014

BSIDES Las Vegas 2014


Some brief notes from BSIDES LV 2014.

1. SAP is horribly broken.   Most passwords in most aspects of the application use XOR encryption with static keys that are included within the application / accessible somehow.     Talk was "All your SAP Passwords belong to us" (Dimitri / Alex)

2. Matthew Marx has released a dictionary generating tool called WordHound.  It is context specific (think Recon-NG) whereby it can yield data from domain websites, PDF meta-data and the like.  It is very language localized using Corpus Language set approach.    This will generate a really good context specific dictionary of words for a specific company etc.  For password guessing, and cracking, this rocks.     http://bitbucket.org/mattinfosec

3. Richard Thieme has been the highlight of my BSIDES experience.   A fierce intellect who has examined his path through spiritual, and scientific paths.   An individual that truly questions the meaning of what has, and is transpiring around us.    I bought his book "Mind Games" and he signed it.

Richard covered the new world reality across his lifetime that has transformed society post WWII and beyond.   Since the Edward Snowden disclosures, Richard is now more about to speak publicly about the ethical dilemmas faced by the intelligence agencies in a post 911 world.  How the directives that fly directly in the face of privacy became reality in the first decade of the 21st century.   Richard was also a UFO researcher, and does write about the idea that our society was technologically seeded by the much covered Roswell crash in 1947.

One of his many themes is that post modern society is largely an intellectually created construct of the intelligence driven state since the post WWII era.   One of many things expressed, and I paraphrase somewhat.   Please forgive any inaccuracies.
  • that which we fight, we become
  • democracy can only be defended by undermining democracy
  • truth is only attainable in a post event analysis through the reading of fiction
  • lies can only be fought with lies
  • fictional creations are created by the intelligence state to keep democracy in a certain belief state
Another book to check out.  "The Covert Sphere" by Tom Melley.   Truly an amazing and inspiring speaker that is closely connected to the Internet community, and feels a special connection to the security community because we question things.   






Thursday, January 16, 2014

Sending 802.11 Packets with Scapy


To accompany my recent technical segment on Paul Assadorian's Security Weekly show, here is a functional Python example of sending 802.11 beacons, probe requests, ARP and DNS requests.   Enjoy!



#!/usr/bin/env python

"""
802.11 Scapy Packet Example
Author: Joff Thyer, 2014
"""

# if we set logging to ERROR level, it supresses the warning message
# from Scapy about ipv6 routing
#   WARNING: No route found for IPv6 destination :: (no default route?)
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *


class Scapy80211():

    def  __init__(self,intf='wlan0',ssid='test',\
          source='00:00:de:ad:be:ef',\
          bssid='00:11:22:33:44:55',srcip='10.10.10.10'):

      self.rates = "\x03\x12\x96\x18\x24\x30\x48\x60"

      self.ssid    = ssid
      self.source  = source
      self.srcip   = srcip
      self.bssid   = bssid
      self.intf    = intf
      self.intfmon = intf + 'mon'

      # set Scapy conf.iface
      conf.iface = self.intfmon

      # create monitor interface using iw
      cmd = '/sbin/iw dev %s interface add %s type monitor >/dev/null 2>&1' \
        % (self.intf, self.intfmon)
      try:
        os.system(cmd)
      except:
        raise


    def Beacon(self,count=10,ssid='',dst='ff:ff:ff:ff:ff:ff'):
      if not ssid: ssid=self.ssid
      beacon = Dot11Beacon(cap=0x2104)
      essid  = Dot11Elt(ID='SSID',info=ssid)
      rates  = Dot11Elt(ID='Rates',info=self.rates)
      dsset  = Dot11Elt(ID='DSset',info='\x01')
      tim    = Dot11Elt(ID='TIM',info='\x00\x01\x00\x00')
      pkt = RadioTap()\
        /Dot11(type=0,subtype=8,addr1=dst,addr2=self.source,addr3=self.bssid)\
        /beacon/essid/rates/dsset/tim

      print '[*] 802.11 Beacon: SSID=[%s], count=%d' % (ssid,count)
      try:
        sendp(pkt,iface=self.intfmon,count=count,inter=0.1,verbose=0)
      except:
        raise


    def ProbeReq(self,count=10,ssid='',dst='ff:ff:ff:ff:ff:ff'):
      if not ssid: ssid=self.ssid
      param = Dot11ProbeReq()
      essid = Dot11Elt(ID='SSID',info=ssid)
      rates  = Dot11Elt(ID='Rates',info=self.rates)
      dsset = Dot11Elt(ID='DSset',info='\x01')
      pkt = RadioTap()\
        /Dot11(type=0,subtype=4,addr1=dst,addr2=self.source,addr3=self.bssid)\
        /param/essid/rates/dsset

      print '[*] 802.11 Probe Request: SSID=[%s], count=%d' % (ssid,count)
      try:
        sendp(pkt,count=count,inter=0.1,verbose=0)
      except:
        raise



    def ARP(self,targetip,count=1,toDS=False):
      if not targetip: return

      arp = LLC()/SNAP()/ARP(op='who-has',psrc=self.srcip,pdst=targetip,hwsrc=self.source)
      if toDS:
        pkt = RadioTap()\
                /Dot11(type=2,subtype=32,FCfield='to-DS',\
                addr1=self.bssid,addr2=self.source,addr3='ff:ff:ff:ff:ff:ff')\
                /arp
      else:
        pkt = RadioTap()\
                /Dot11(type=2,subtype=32,\
                addr1='ff:ff:ff:ff:ff:ff',addr2=self.source,addr3=self.bssid)\
                /arp

      print '[*] ARP Req: who-has %s' % (targetip)
      try:
        sendp(pkt,inter=0.1,verbose=0,count=count)
      except:
        raise

      ans = sniff(lfilter = lambda x: x.haslayer(ARP) and x.op == 2,
        store=1,count=1,timeout=1)

      if len(ans) > 0:
        return ans[0][ARP].hwsrc
      else:
        return None


    def DNSQuery(self,query='www.google.com',qtype='A',ns=None,count=1,toDS=False):
      if ns == None: return
      dstmac = self.ARP(ns)

      dns = LLC()/SNAP()/IP(src=self.srcip,dst=ns)/\
        UDP(sport=random.randint(49152,65535),dport=53)/\
        DNS(qd=DNSQR(qname=query,qtype=qtype))

      if toDS:
        pkt = RadioTap()\
                /Dot11(type=2,subtype=32,FCfield='to-DS',\
                addr1=self.bssid,addr2=self.source,addr3=dstmac)/dns
      else:
        pkt = RadioTap()\
                /Dot11(type=2,subtype=32,\
                addr1=dstmac,addr2=self.source,addr3=self.bssid)/dns

      print '[*] DNS query %s (%s) -> %s?' % (query,qtype,ns)
      try:
        sendp(pkt,count=count,verbose=0)
      except:
        raise

# main routine
if __name__ == "__main__":
    print """
[*] 802.11 Scapy Packet Crafting Example
[*] Assumes 'wlan0' is your wireless NIC!
[*] Author: Joff Thyer, 2014
"""
    sdot11 = Scapy80211(intf='wlan0')
    sdot11.Beacon()
    sdot11.ProbeReq()
    sdot11.DNSQuery(ns='10.10.10.2')


Wednesday, January 2, 2013

Remote Access VPN with Linux racoon and MAC-OSX


If you use a Linux based router gateway, and MAC-OSX Mountain Lion, being able to created an IPSEC VPN tunnel back to your home site can be very useful.     The MAC-OSX Lion IPSEC client will use ISAKMP over UDP port 500 to negotiate the appropriate phase one key exchange parameters in order to setup a UDP NAT-Traversal IPSEC tunnel over UDP port 4500 back to your home site.

Here I include a pre-shared key based example configuration of the Linux KAME “racoon” daemon to run as an IPSEC server, and configure the MAC-OSX native IPSEC client to connect to it.   The Linux based server system in this example is Ubuntu 12.04.1 server running on a Soekris NET6501-50.   For more information on what Soekris has to offer, visit the web URL http://www.soekris.com/.  

Under Ubuntu, you will need to install two different packages in order to get started.

# apt-get install ipsec-tools
# apt-get install racoon


For the remainder of this example, I will assume that your Ubuntu Linux based system has a public IP address of 240.9.9.9, and that your desired VPN address range is 10.222.1.0/24.   I will also assume that your router gateway is properly configured for Network Address Translation (NAT) using iptables for any address that is part of your internal network which I will consider as anything in the 10.0.0.0/8 address range.   I will also assume that you are running your own internal network DNS server at 10.1.1.1.   Proper configuration of iptables is not included in this blog entry.

Public network address: 240.9.9.9
Internal LAN Network:   10.0.0.0/8
VPN network pool:       10.222.1.0/24
DNS Server:             10.1.1.1
DNS domain:             “domain.tld”

After you have installed the “racoon” package, the configuration file should be located as the file path /etc/racoon/racoon.conf.

We will start with a fully commented racoon.conf example based on the above information in order to illustrate how to configure an IPSEC VPN.  This configuration is based on a pre-shared key rather than certificate based VPN for simplicity sake, and due to the additional complexity involved with setting up your own certifying authority, generating, signing, and importing a certificate for use.


Racoon Configuration File

# set syslog level and pre-shared key file
log notify;
path pre_shared_key "/etc/racoon/psk.txt";

listen {
  adminsock disabled;     #do not listen on the admin socket
  isakmp 240.9.9.9 [500]; #address for ISAKMP
  isakmp_natt 240.9.9.9 [4500]; #address for ISAKMP NAT-Traversal
  strict_address;         #strictly bind these addresses
}

remote anonymous {      #anonymous matches ANY ipsec client
  exchange_mode main;   #ISAKMP phase 1 exchange mode
  ph1id 16;             #phase 1 proposal identifier
  proposal_check claim; #claim our own lifetime value
  lifetime time 12 hour;#phase 1 lifetime
  mode_cfg on;          #gather network information through ISAKMP
  generate_policy on;   #generate ipsec policy from initiator SA payload
  nat_traversal on;     #enable use of NAT-Traversal extension
  dpd_delay 3600;       #enable dead peer detection and set time at 3600 secs

  proposal {                  #phase 1 proposal
    encryption_algorithm aes; #phase 1 encryption algorithm
    hash_algorithm sha1;      #phase 1 hash algorithm
    authentication_method xauth_psk_server; #use xauth pre-shared key method
    dh_group 2;               #use diffie-hellman group 2 (modp1024)
  }
}

# specific mode configuration
mode_cfg {
  auth_source system;         #user auth source (system=Unix user)
  group_source system;        #group validation source (system=Unix groups)
  conf_source local;          #user local pool information below
  network4 10.222.1.50;       #base/first address in VPN pool
  netmask4 255.255.255.0;     #VPN pool network mask
  pool_size 50;               #VPN pool size
  dns4 10.1.1.1;              #VPN pool DNS server
  default_domain "domain.tld";#optional VPN pool domain suffix
  banner "/etc/racoon/motd";  #optional VPN pool message of the day
}

# security association info
sainfo anonymous {                  #anonymous matches any/all SA
  encryption_algorithm aes;         #phase 2 encryption algorithm(s)
  authentication_algorithm hmac_sha1; #phase 2 authentication hash
  compression_algorithm deflate;    #phase 2 compression
  remoteid 16;                      #phase 2 remoteid to match phase 1
}



Linux Server Pre-Shared Key File


Although the /etc/racoon/psk.txt file would typically contain entries listing individual IP addresses, you can also have wildcard entries.   Naturally when travelling your MAC-OSX client is going to have a different public IP address depending on your location, and thus a wildcard pre-shared key file on the server end of things is the easiest solution.   A better solution, as mentioned above, would be to utilize a certificate rather than pre-shared key.

In order to generate a pre-shared key, I would suggest a relatively long random character string.   This is fairly easy to generate using a combination of “dd” and “base64” in the UNIX world, although other options exist.


$ dd if=/dev/urandom bs=1 count=18 2>/dev/null | base64
mylongrandomstring


Within your /etc/racoon/psk.txt pre-shared key file on the UNIX/Linux server, you should list one entry as follows:

# pre-shared key for IPSEC VPN clients
* mylongrandomstring

Note that the string “mylongrandomstring” would actually be random characters you generated from the above command.




MAC-OSX Mountain Lion:  Cisco IPSEC VPN Client

To setup your MAC-OSX IPSEC client, you need to open Network Preferences, click on the “Lock” to make changes, and then click on the small “+” at the bottom left of the dialog to ADD a new interface.  






Set the interface type to “VPN”, and VPN Type to “Cisco IPSec”, and then type in a descriptive service name.















Click on your new IPSEC VPN connection, and enter the appropriate address or domain name of your remote server, as well as your UNIX/Linux username that you will use to connect.





Next, click on the “Authentication Setttings” button and set the “Shared Secret” to the same long random string you used for the pre-shared key on the server.  Leave the “Group Name” blank, and click OK.




Testing The Configuration

If you use the "strict_address" configuration in the "listen" section of the racoon configuration, you can only test from outside your home network.   However, if we assume that your home Linux router gateway also has a second interface for "internal" network traffic, the entire listen section of the racoon.conf file can be commented out during testing to make racoon listen on all interfaces as follows.

#listen {
#  adminsock disabled;     #do not listen on the admin socket
#  isakmp 240.9.9.9 [500]; #address for ISAKMP
#  isakmp_natt 240.9.9.9 [4500]; #address for ISAKMP NAT-Traversal
#  strict_address;         #strictly bind these addresses
#}

For testing purposes, you should use either a console on your linux server, or ssh in from another machine, and then run racoon in debugging mode from the command line as root.

# service racoon stop
# /usr/sbin/racoon -F -d

The "-F" flag instructs racoon to log all output to stdout/screen.    The more "-d" flags you add to the command line, the more debugging output you should received.   After starting racoon on the command line, you should attempt to connect from your MAC-OSX system.

Assuming that your group pre-shared key matches, if you get through IPSEC key management negotiation phase 1, your MAC-OSX system should prompt you for a username and password.   This username has to be a UNIX/Linux based username that has been added to the server system.   If successful, you should see your "banner" message of the day displayed, and receive a VPN pool IP address in the 10.222.1.0/24 network.   You can then put racoon back into normal running mode, and you have successfully configured a remote access VPN.


# /usr/sbin/racoon -F -d
# CTRL-c
# service racoon start


Good luck, and please post comments/questions on your experience.