Wednesday, October 27, 2010

Wireless Reconnaissance in Practice

Kismet (stable, devel and newcore) 
Locate / Identify AP(s)
-BSSID, ESSID, Channel and Encryption
-GPS data
Locate / Identify Client(s)
-MAC Address
-Manufacturers
Perform Spectrum analysis
Drones / open-source WIPS

Aircrack-ng – Cracking WEP and WPA
-Suite of tools for wireless testing
-Mostly thought for wireless cracking
-Can also be used for wireless recon
-IE Airodump-ng

Netstumbler
-All for the Win32 geeks.

Types Reconnaissance Data
Kismet-(stable|devel) – Txt, CSV, XML, GPS and pcap
Kismet-newcore – Txt, NetXML, GPS and pcap
Aircrack-ng – CSV, pcap, XML

Wireless Recon Visualization Tools
-Gpsmap (ancient)
-Pykismet
-Kismet-earth
-kisgearth

Limitations of Visualization Tools
-None work with Kismet-newcore
-None work with Aircrack-ng
-Flexible representation of specific information (total flexibility in the generated graphs).

Tuesday, October 12, 2010

Analyzing Malware Through MS-Office Documents

Key Highlights
-MS Office commonly exploited since 2006
-Existing exploits in the wild exploit unexceptional the older OLESS file format.
-Currently no known bugs in the newer XML based MS Office format.

Some MS Office exploits since 2006
-CVE-2006-0009 Powerpoint MS06-012 (March 2006)
-CVE-2006-0022 Powerpoint MS06-028 (June 2006)
-CVE-2006-2492 Word MS06-027 (June 2006)
-CVE-2006-3434 Powerpoint MS06-062 (October 2006)
-CVE-2006-3590 Powerpoint MS06-048 (August 2006)
-CVE-2006-4534 Word MS06-060 (October 2006)
-CVE-2006-4694 Powerpoint MS06-058 (October 2006)
-CVE-2006-5994 Word MS07-014 (February 2007)
-CVE-2006-6456 Word MS07-014 (February 2007)
-CVE-2007-0515 Word MS07-014 (February 2007)
-CVE-2007-0671 Excel MS07-015 (February 2007)
-CVE-2007-0870 Word MS07-024 (May 2007)
-CVE-2008-0081 Excel MS08-014 (March 2008)
-CVE-2008-4841 Word MS09-010 (April 2009)
-CVE-2009-0238 Excel MS09-009 (April 2009)
-CVE-2009-0556 Powerpoint MS09-017 (May 2009)

Generic OLESS Format
-OLESS Header
-FAT FS: SectorNumbers, OLESS directory entries
-Data is divided into directories (storages) and files (streams)
-Depending on the application streams may contain: Macros, Graphics, Tables, Sounds, Animations, etc.
-Parsing can be done using the Win32 COM API: StgOpenStorage(), IStoragemethods, IStreammethods.

Malicious Document Structure

Typical MS-Office Shellcode Behavior

When a bug in a MS Office application gets triggered:
-Shellcode executes
-Finds itself by open file handles enumeration and file size checking
-SetFilePointerto encrypted PE-File(s), decrypt, drop and execute
-Drop harmless embedded MS Office document and start to look innocent

More information:
-Not much public information about MS-Office malware analysis available
-Microsoft Office Binary File Format Specification (since Feb. 2008)
-Bruce Dang's talk "Methods for Understanding Targeted Attacks with Office Documents".

Available Tools For Analysis
-DFView (old school Microsoft OLE structure viewer)
-Officecat (signature based CLI utility)
-FlexHexEditor (OLE compound viewer)
-OffVis (office binary file format visualization tool)
-OfficeMalScanner (forensic tool for analysts to find malicious traces in MS Office documents)

Wednesday, August 25, 2010

Analyzing Side Channel Attacks on Embedded Systems

General embedded systems based on micro-controller and complex processors:
-USB sticks
-Car locks
-Remote access tokens
-Mobile devices
-Game consoles
-Multi-media chipsets for pay-TV

Think of Security:
-What is the threat from side channel analysis to embedded systems?
-How does it compare with attacks on smart cards?
-What are the future developments?

Attacking Side Channels
-Time
-Power consumption
-Electro-Magnetic radiation
-Light
-Sound

Power/EM traces
-Signal leakage from busses, registers, ALUs, etc.

Statistical data detection
-Where is data processed in presence of noise?
-Collect many traces with different data (n > 1000)
-Assume data values are:
    known (e.g. algorithm input or output)
    uniformly random (typical for crypto)
-We focus on one bit of one variable in the process


Differential trace
-Input: n traces with known variable (e.g. input or output)
-Output: 1 trace with indication where bit causes trace differences

Purpose of Side Channel Attacks on Embedded Systems
-Retrieve secrets (Key, PIN, Unlock code)
-Reverse engineer (Program flow, Crypto protocol, Algorithm)

Why Side Channel Attacks are interesting? If side channel threats depends on:
-Physical access?
-Access time window?
-Interfacing and control?
-Exploitation equipment $?

A device becomes interesting when:
-It contains a secret
-It contains a feature that can be unlocked
-Logical or physical access to internals is hard

Typical Side Channel Attack Example



Typical Prerequisites
-Access to side channel
-Access to input or output data
-Minimize noise in side channel
-Time measurement of operation (trigger)
-Link data to operation

Processor comparison with Smart Card
 
Acquisition comparison with Smart Card


Test vs. Attack
-An attacker needs to turn a vulnerability into an exploit
-A tester needs to gain insight in attacker cost efficiently
-How to create the optimal environment to discover a vulnerability?

General aspects of testing
-Controlling the crypto
-Linking data with measurements
-Efficiency of acquisition
-Increased speed versus increased complexity

Timing analysis
-Peripheral outputs assist (example XBOX 360)
-Exploiting runtime access (cache)
-Increasing accuracy with EM and power
-Timing is a risk in many software implementations: both crypto and comparisons

XBOX 360 with Backdoor

 -XBOX 360 has a secure boot chain
-First boot loader security implemented with a HMAC-SHA1
-Hash secret key + boot loader with SHA1
-Compare 16 bytes result with stored 16 bytes
-Comparison is per byte -> timing attack
-Implementation in this infectus board:
    It can modify stored HMAC-SHA1 value in NAND flash
    Observes timing of diagnostic POST byte on PCB
    Reset CPU with nTRST
-Brute forcing 16*128 = 2048 values on average takes about 2 hrs

Power analysis
-Tapping power or supplying it
-Reaching rails
-Identifying the correct supply rail
-Disabling power domains
-Disabling peripherals
-All require more detailed knowledge on target

EM (Electro Magnetic) Analysis
-EM signal adds dimension
-How to locate?
-When can EM be better?
-EMA is an active research topic
-EM seems to add most when target operation is small relative to overall chip

Threat and Impact
-Few countermeasures
-Significant leakage
-Fast acquisition
-Required level of control
-Attacks needed to achieve control
-High noise level, increased acquisition times

Countermeasures
Hardware
-Random Interrupts
-Data / Key masking
-Shielding
-Balancing

Software
-Randomizing flow
-Blinding / Masking
-Algorithm
-Protocol design

Monday, August 9, 2010

Scanning SS7 Networks and Telecom Backbones

Historic View
-Phreaking is a term for the action of making a telephone system do something that it normally should not allow.
-Telecommunications security problems started in the 1960’s when the hackers of the time started to discover ways to abuse the telephone company.
-Discovery and exploration of features of telecommunications systems.
-Controlling Network Elements (NE) in a way that was not planned by its designers.
-Abusing weaknesses of protocols, systems and applications in telephone networks.

Fraud Implanted by
-Blue Box
-Internal Fraud

Reliability
-US: 911, Europe: 112
-How much lost revenue is one minute of downtime?

Today's View
-SIP account hacking, remind the "Calling Cards" fraud?
-VoIP GW hacking, remind the "PBX hacking"?
-Signaling hacking directly on SS7 – SIGTRAN level

SS7 Attacks Scenarios
-Theft of service, interception of calling cards numbers, privacy concerns
-Introduce harmful packets into the national and global SS7 networks
-Get control of call processing, get control of accounting reports
-Obtain credit card numbers, non-listed numbers, etc.
-Messages can be read, altered, injected or deleted
-Denial of service, security triplet replay to compromise authentication
-Annoyance calls, free calls, disruption of emergency services
-Capture of gateways, rerouting of call traffic
-Disruption of service to large parts of the network
-Call processing exposed through Signaling Control Protocol
-Announcement service exposed to IP through RTP
-Disclosure of bearer channel traffic

Telecom Backbone



Discovering The Backbone
Deregulation
-Europe / US: CLEC vs ILEC

New services and new business partners
-Premium numbers, SMS providers, etc.

Push toward an “All IP” infrastructure
-Management network
-Cost
-SIGTRAN (SS7 over IP)

SS7 & SIGTRAN
-Core
-Formerly, the walled garden

VoIP
-Edge
-Hard to make it reliable (QoS, SBCs)

SS7 and IP
-There is also exponential growth in the use of interconnection between the telecommunication networks and the Internet, for example with VoIP protocols (e.g. SIP, SCTP, M3UA, etc.)
-The IT community now has many protocol converters for conversion of SS7 data to IP, primarily for the transportation of voice and data over the IP networks. In addition new services such  as those based on IN will lead to a growing use of the SS7 network for general data transfers.
-There have been a number of incidents from accidental action on SS7, which have damaged a  network. To date, there have been very few deliberate actions. Far from VoIP here. 

Attacking SIGTRAN with SCTPscan (http://sctp.tstf.net/)
Where implementation diverge from RFCs
-RFC says "hosts should never answer to INIT packets on non-existings ports".
-Syn scanning is slow when no RST

Below the IDS
-How many firewall logs dropped SCTP packets?
-How many IDS(s) watch for SCTP socket evil content?
-Example: Dshield.org - Real life distributed IDS, Hundreds of thousands of IP scanned, nor detected neither reported as scanner.

INIT vs SHUTDOWN_ACK Packet Scanning
From RFC 2960
-8.4 Handle "Out of the blue" Packets
-An SCTP packet is called an "out of the blue" (OOTB) packet if it is correctly formed, i.e., passed the  receiver's Adler-32 / CRC-32 check (see Section 6.8), but the receiver is not able to identify the association to which this packet belongs.
-The receiver of an OOTB packet MUST do the following:
"If the packet contains a SHUTDOWN ACK chunk, the receiver should respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE."

-New way to elicit answers even if not answering ABORTs to INITs targeted at not-opened port.

SCTP ports (-sS) Stealth Scanning
root@bt:~/sctp# ./sctpscan-v11 --scan --autoportscan -r
203.151.1
Netscanning with Crc32 checksumed packet
203.151.1.4 SCTP present on port 2905
203.151.1.4 SCTP present on port 7102
203.151.1.4 SCTP present on port 7103
203.151.1.4 SCTP present on port 7105
203.151.1.4 SCTP present on port 7551
203.151.1.4 SCTP present on port 7701
203.151.1.4 SCTP present on port 7800
203.151.1.4 SCTP present on port 8001
203.151.1.4 SCTP present on port 2905
root@bt:~/sctp#

SCTP Stack Fingerprinting
-SCTP stack reliability
-Robustness testing (stress testing)
-QA of a few stacks
-Fuzzing built-in SCTPscan
-Discrepancies in SCTP answer packets
-Different stack behaviours
-Much more states than TCP=opportunities
-Cookie randomness

Credits: Philippe Langlois, P1 Security (p1security.com)

Monday, August 2, 2010

Using DAVIX For Security Visualization (revised)

Information visualization
-Visualize large collections of abstract data

Scientific visualization
-Representation of data with geometric structure



Visualization Concept
-Analyzing floods of data in tabular or textual form is tedious
-Humans must sequentially scan such data
-Visualization exploits the human's visual perceptive capabilities and parallel processing Size, Shape, Distance, and Color
-Easy to spot patterns and irregularities

Data types supported
-Ordinal
Has a sequence e.g. day of week
-Nominal
Has no sequence e.g. types of fishes
-Quantitative
Can be measured e.g. length, time, weight, temperature, speed

Visualization Effectiveness
-Each data type has its most effective way of visualization


Information Visualization Process



DAVIX Linux Distribution (http://davix.secviz.org/)
-Provide the audience with a workable and integrated tools set
-Enable them to immediately start with security visualization
-Motivate them to contribute to the security visualization community

Tools Available
Capture
-Network Tools (Argus, Snort, Wireshark)
-Logging (syslog-ng)
-Fetching Data (wget, ftp, scp)

Processing
-Shell Tools (awk, grep, sed)
-Visualization Preprocessing (AfterGlow, LGL)
-Extraction (Chaosreader)
-Data Enrichment (geoiplookup, whois, gwhois)

Visualization
-Network Traffic (EtherApe, InetVis, tnv)
-Generic (AfterGlow, Cytoscape, Graphviz, LGL Viewer, Mondrian, R Project, Treemap)

Interface Transport
-Each visualization tool has its own file format interfaces
-Data must be converted to match the import interfaces
-These adapters are mostly self-written snippets of code

Important Note:
All the images presented in this post are intellectual property of the copyright owner (www.secviz.org)

Tuesday, June 22, 2010

Defending BGP MITM (Man-In-The-Middle) Attacks

Every organization owes its Internet connectivity to one protocol: BGP4. There are no alternatives. BGP4 has longstanding vulnerabilities that cannot be fixed, and can only be monitored carefully.

Two key points:
1. Everyone who connects to the Internet is currently exposed to various routing risks: downtime, hijacking and now even wholesale traffic interception.
2. Very few people understand these risks, so they are not being measured or managed appropriately.

Basics of routing and the inherent threats:
-Prefixes
-ASNs
-Routing updates
-Route attributes
-Vulnerabilities & typical historical attacks

Internet Routing – Prefixes
-Internet routing is orchestrated via blocks of IP addresses.
-A network prefix is a block of contiguous IP addresses.
-IP addresses in the same prefix are routed in the same way.

Internet Routing – ASNs
Global Internet routing relies on the Border Gateway Protocol. Each organization participating in BGP is assigned:
-A unique Autonomous System Number or ASN (integer)
-One or more prefixes (range of IP addresses)
-All routing decisions are local

BGP Update Messages
-An UPDATE message announces a new route or withdraws a previously announced route. UPDATE = prefix + route attributes
-Adjacent routers chatter constantly with each other as routes come and go. Globally, Renesys observes 45,000+ updates per minute when things are quiet!

BGP Attributes
Routing announcements have attributes and many possibilities but the (hopefully valid) "AS" path to the announced prefix is always present.

Routing Vulnerabilities
1. No single authoritative source of who should be doing what.
-If there were, you could filter out the errors / hijacks.
-As a result, filtering by ISPs is not common or easy.

2. All of Internet routing is based on trust.
-Anyone can announce any IP space they want.
-Anyone can prepend any ASN to any path that they want.

3. No mechanism in place to handle ASNs who go rogue. There are no Internet police!

Two typical types of hijacks:

No operational impact
-Hijack unused (but maybe assigned) IP space
-Potentially harms the reputation of the owner
-But does not disrupt any legitimate traffic on the Internet
-DoD owns but does not announce 7.0.0.0/8, 11.0.0.0/8, 30.0.0.0/8 and others. These networks
are “free for the taking” without any impact on DoD. Every announcement in this space is a hijack.

Obvious operational impact
-Hijack currently used IP space
-Legitimate traffic diverted to the hijacker
-Victim can be effectively taken off the Internet
-Very disruptive and very obvious
-YouTube owns 208.65.152.0/22 (Feb 2008)
This contains the more-specific 208.65.153.0/24
The above /24 used to contain all of YouTube’s
DNS Servers (have since moved)
Web Servers (have since added additional IP space)
YouTube announced only the /22
-Pakistan Telecom announces the /24
In BGP, most specific route to an IP address wins!
Pakistan Telecom gets all traffic intended for YouTube
YouTube is globally unreachable for 2 hours


Both types of hijack allow an attacker to attract all traffic bound for the hijacked space.

Final Evaluation
-Hijacking has been going on for over 10 years!
-No incremental or comprehensive solutions
-Solutions lack economic drivers
-Doesn’t happen daily and universally
-Avoiding negative publicity is not necessarily compelling
-Impact poorly understood by management
-Miscreants are actively hijacking now
-To send spam from “clean” IP blocks
-To cover their other nefarious activities
-What good are your firewall/IDS logs now?
-Need historical global routing data to identify hijackers

Man-In-The-Middle Attack
-Review the MITM exploit presented at DEFCON 16 (August 10, 2008)
-AS path attribute
-AS loop prevention
-MITM attack technique
-Obscuring the MITM attack with TTL adjustment



How can the victim observe this?
-Victim’s routes and those of at least one provider will look normal
-Traceroute from a public looking glass to the victim’s IPs will show the hijacker
(assuming the looking glass hasn’t been blinded to the attack).
-Traceroute depends on incrementally increasing TTLs
-Hijacker can hide his presence by silently increasing TTLs for packets intended for the victim
-Hides hijacker’s routers
-Hides hijacker’s outbound routes to victim

Detecting the Attack
-Is this generally visible?
-Attacker profile
-Difficulties with detection
-You know the correct routing policies (easy)
-Generally limited to networks under your control
-Review of available alarm services
-Can you attack the alarm services?
-You don’t know the routing policies (hard)
-A proposed global detection technique

Difficulties in observing the MITM attack
-Most Internet routers will see and prefer the hijacked routes. Won’t be obvious among their
270,000+ routes.
-Traceroutes won’t show the hijacking (with TTL adjustments). Independent of source location.
-Latency to the victim will increase. Could be slight if the hijacker isn’t far from the victim.
-Route alarming services might see this if AS loop detection is disabled.

Two simple questions:
Can I detect MITM for my network?
-Easy: Routing policy is presumably known or at least knowable.

Can I detect MITM for the Internet at large?
-Much harder: Routing policies are not known and probably unknowable for all 270,000+ prefixes

Monday, May 31, 2010

Breaking Into SharePoint Portal

Windows SharePoint Services (WSS)
- Base technology
- Free (with Windows Server)
- Consists of an ASP.NET web site and ISAPI filter

Microsoft Office SharePoint Server (MOSS)
- Built on top of WSS
- Not free
- Supports collaboration on MS Office documents

Security Aware?
- Gartner predicts SharePoint will replace network file shares
- Default security model: all site users have read access to all documents
- Big target – single repository for sensitive corporate data – salaries, phone numbers, customer lists,  passwords, strategic plans, etc.

Hacking the SharePoint ISAPI Registry
A potential EoP, but not interesting:
- Requires Terminal Services to be enabled with “NT4 compat mode”
- In that scenario, several Windows components have the same bug
- See “Web Server Extensions”, referenced in HKLM
- Check out usage of “Terminal Server User” SID throughout Windows

Hacking SharePoint with Google
- Thousands of public, internet-facing SharePoint sites have been created
- Use Google to identify configuration mistakes
- More info: http://tinyurl.com/4dccn9

Hacking SharePoint with NMap
- SharePoint servers have a distinctive network port signature
- Depends on firewall config, of course
- More info: http://tinyurl.com/3oykwp

Hacking SharePoint with RegEx
SharePoint RegEx Search
- http://www.codeplex.com/MossRegExSearch
- See blog post – http://tinyurl.com/4s49p3
- Avoid limitations of built-in SharePoint search (i.e., SQL ‘LIKE’ and ‘CONTAINS’ keywords)
- Instead, harness the power of regular expressions!
- Search for: strong passwords, credit card info, phone numbers, SSNs, etc.

Friday, April 30, 2010

Defeating OS Fingerprinting Using IpMorph

IpMorph is an Open Source project used to disguise OS-detection process performed using various techniques, such as, banner grabbing, ICMP replies, ISN profile, TCP headers, timeouts and other similar trends. These techniques are usually available in number of tools like Nmap, Xprobe2, SinFP, Ring2, p0f, Ettercap, etc.

Active Stack Fingerprinting











Passive Stack Fingerprinting












How IpMorph Works













Spoofing States
Filtering
– Stealth patch : Unmaintained as of 2002, GNU/Linux kernel 2.2-2.4
– Blackhole : FreeBSD, kernel options
– IPlog : Unmaintained as of 2001, *BSD
– Packet filter : OpenBSD
Host TCP/IP stack tweaking
– Ip Personality
– Fingerprint opt
– Fingerprint scrubber
– OSfuscate
Host TCP/IP stack replacement (proxy behaviour)
– Honeyd
– Packet purgatory / Morph
Integrated Tools
–IpMorph (Core)
–IpMorph Controller
–IpMorph Personality Manager
–IpView (IpMorph GUI)
Portability
–GNU/Linux
–BSD, Mac OS

IpMorph General Architecture

Sunday, April 18, 2010

Insights of the CyberCrime World

Malware Trends
-High complexity of technology introduces higher number of fault (Hardware, Software)
-Proof of Concept, Exploit Codes, Vulnerabilities (Finding exploits in order to misuse them, making money!)
-Today's Malware (Organized in botnets, uses human vulnerabilities)
-Botnets (Money making operation by selling stolen credentials, renting out botnet services like DDoS, Adware installations, etc)
 
Anti-Malware Solutions
The decision about the detection of malware (adware, spyware, trojan, etc) can be troublesome. It can be difficult to give a reason why any software is malicious, unwanted or not useful. However, implementing detection mechanism can be rather easy but there is an exception to this rule. Additionally, there is always a need for the cooperation between AV companies to avoid ambiguous decisions. This can be established by introducing standards and best practices such as AVPD, ASC, AMTSO, etc.

Detection vs Decision in Terms of Malware
Malware Distribution Channels
Trojan or Normal Application?
Trojan
-Uncompromising infection
-Make use of exploits
-Unattended, unsolicited installation
-Perform stealth activities
-Invasiveness
-Impact on system stability, security and integrity
-Obfuscated data
-Detection evasion mechanism

Normal Application
-The application itself isn't causing any harm
-EULA, the installation take place with user's consent
-The vendors disclaim involvement with the distribution channels

Vendors doesn't want their application to be detected
 
 
Final Outlook of the Malware
Legal and Problematic Issues
-Applications developed by well-established companies roll out with different affiliate distribution
model. Now, typically with botnet era?
-Mutual customers: those who want to use software and be protected at the same time.
-Other customers: those who never agree to install anything without their trustful consent.
-Uncontrolled open affiliate distribution model is unfeasible.
-Direct sponsorship for cybercrime activities.
-Once detected, these criminal groups are ready to fight even for the price of lawsuit.

Over the Past 4-years (according to Eset AV Press)
-20+ cases where the legal department has been involved
-Over 1150 hours and 530 employee interactions
-2006: 16 hours/month, 6 total interactions
-2009: 46 hours/month, 21 total interactions

Thursday, April 1, 2010

Dissecting Malicious Office Documents

In the past, malware was only appearing as an executable file but this threat has changed its landscape to skew through the application data files which includes, pdf, doc, xls, etc. In order to combat this threat, MalOffice has introduced a combination of both "static" and "dynamic" analysis techniques to inspect the application data files. The static analysis uses general and filetype-dependable scanning while the dynamic analysis uses the approach of CWSandbox and other test analysis techniques.

Static Analyzers
General:
-AV Scanner
-PE-Detector

Specialized:
-Detect embedded javascript in PDF document
-Heuristics for malicious javascript
-Detect shellcode in Office documents

PDFScanner
Specialized scanner for PDF files
-Decompose PDF stream into objects (pdftoolkit)
-Detect javascript objects
-Use heuristics to detect malicious javascript
-Extract Variable names
-Find code obfuscation
-Usage of known vulnerable functions

OfficeMalScanner
Specialized scanner for MS Word files
-Uses OfficeMalScanner, by Frank Boldewin (http://www.reconstructer.org)
-Forensic tool for Office documents
-Scans for shellcode pattern
-Dumps OLE structures and VB-macros
-Generates a malicious index value
Limitations
Static analyis can be circumvented by attacker
-different kinds of obfuscation are possible
-general drawbacks of static malware analysis
-exploit might trigger only on certain events
-Exploit might require specific version

Dynamic Analyzers

CWSandbox
-Tool for automated behavior analysis
-PE-executables or arbitrary data files
-Creates XML analysis report: operations executed by the monitored processes
-Filesystem, registry, network, user management,services, protected storage, etc
-Each file type has associated host application e.g. Acrobat Reader, Foxit Reader, MS Word, etc
-Some exploits only trigger in specific app versions e.g. Acrobat Reader 8.0, 8.1.0, 8.1.1, 9.0
-Task: decide from analysis report, if executed data file is malicious based on "Policies"
-consist of white and blacklisted operations
-created in a semi-automated way
-One policy per host application version
-What operations are usually perfomed when running this application with a (benign) data file?

Static Analysis Result (suspicious points)

Dynamic Analysis Result (malicious points)

Other Tools
SPARSE - focus only on Word documents
OfficeCat - static scanner for office documents
OfficeMalScanner - MS office forensic tool
Wepawet - powerful tool to analyze PDF and Flash files

Tuesday, March 23, 2010

Reverse Engineering Through Inline Hooking

Reverse Engineering techniques are generally divided into two broad categories:
1. Static Analysis
2. Dynamic Analysis

Static Analysis
-Techniques which do not involve running the code
-Disassembly, file structure analysis, strings, etc.

Dynamic Analysis
-Techniques which involve running the code
-Behavioral analysis

Approaches to Dynamic analysis involve:
-Network Monitoring
      Isolated Physical Networks
      Virtual Networks
-Hardware Emulation
      Norman Sandbox, etc.
-Kernel-Level Monitoring (SSDT hooks)
      Sysinternal Process Monitor
-Debuggers

Kernel-Level Monitoring


Advantages
      Captures every system call
      Can’t be avoided from userland
Disadvantages
      Only captures functions implemented as system calls
      Not every important function call in the Win32 API is implemented as a system call
      Tools don’t differentiate between process housekeeping and calls from usercode
      Calls to internal DLL’s cannot be observed

Process Monitoring via Debugging
Advantages
      Debugger can trap any function call, not just system calls
      Trapped calls are more likely to be highly relevant to the program’s operation
Disadvantages
      Have to act as a debugger
      Susceptible to countless anti-debugging techniques

Inline Hooks
Advantages
      Can trap any function call, not just system calls
      Trapped calls are more likely to be highly relevant to the program’s operation
      Not operating as a debugger
      No device driver required
Disadvantages
      Hard to implement
Implementing Inline Hooks
1. Find a function of interest
2. Disassemble the beginning of the function
3. If possible, overwrite the beginning bytes of the function with a jump or call instruction
4. Implement a handler for the hooked function

What to do with hooked functions?
Observe and Report
      Collect data about the current function call by gathering data from stack and report to console
      Execute any instructions overwritten from the hook
      Jump back to the next instruction in the hooked function
Intercept and Emulate
      Perform a specified action instead of calling the intended function

Running your own Sandbox
-Trap gethostbyname() to always return a fixed IP address.
-A pseudo-handle interface to allow fake reads and writes to files and netwok sockets. Trap connect() to connection to a pseudo-socket. CreateFile(), ReadFile(), WriteFile(), etc.

API Thief Tool (by mandiant.com)
-Launches target process in a suspended state
-Injects a DLL into the process.
-The Injected DLL hooks all Win32 API functions before the target process is resumed
-API Call monitoring can be used simply with a process monitor-style console
-Embedded python can be used to write custom handlers for specific hooked functions

Saturday, February 27, 2010

Network Intrusion: The Advanced IPS Evasion Techniques

As most of you may know that the Intrusion Prevention Systems (IPS) should protect vulnerable hosts from remote exploits. However, there are occassions where exploits can apply multiple evasion methods to bypass these detection mechanisms and break into the system. There are many hacking tools which apply multiple IDS/IPS evasion techniques but these tools are more exploit oriented rather than evasion oriented.

Known Evasion Techniques

-IP Fragmentation with manipulated fragment size and order
-IP Random Options
-TCP segmentation with manipulated segment size and order
-TCP Time Wait
-TCP Urgent Pointer
-SMB Fragmentation
-SMB Transaction Write Method
-SMB Write/Read Padding
-SMB Transaction Method fragmentation
-SMB Session Mixing
-MSRPC Multibind (bind to multiple unnecessary or non-existent context + the vulnerable context)
-MSRPC fragmentation
-MSRPC encryption
-MSRPC Alter Context
-MSRPC Object Reference
-MSRPC Endian Manipulation

Evasion Method

IPS signatures can be evaded completely if the protocol stacks do not understand the evasions and normalize the traffic over the network. For example, SMB and MSRPC signatures should not worry about fragmentation, padding, extra methods or other randomizations. More of these examples are discussed below.

IP Random Options

-Fill IP Packet with random Options
-If the target host and the IPS device disagree about the validity of the packet, the target host may see different data than the IPS.

TCP Time Wait

-Open and close a TCP connection. Open a new TCP-connection to the same service using the same TCP-source port. According the TCP RFC, the TCP client MUST wait "TIME-Wait Delay" amount of seconds before reusing a port.

-If the attacker uses his own TCP/IP Stack, he can open and close a TCP-connection and immediately open a new TCP connection using the same source port.

TCP Urgent Pointer

-Insert one byte into a TCP-stream.
-TCP-Server chooses whether to use or discard the added byte.
-An IPS device inspection can be evaded by clever use of the urgent pointer.
-Example: TCP Stream: GETP / (P is urgent data)
IPS looks: GETP /
Apache looks: GET /

SMB Session Mixing

It is possible to use multiple resources over the same SMB-session within the single TCP-connection at same time. Simultaneously read and write into multiple files.

SMB Write/Read Padding

-The write and read commands have an offset pointer that can be used for padding.
-All data after the SMB header till the pointed byte should be discarded.

MSRPC Alter Context

The client may change the current context using the Alter Context Method. All subsequent requests then go to the new context.
Example: The client binds to non vulnerable context and then changes into a vulnerable context and sends the exploit.

MSRPC Object Reference

Adding an Object Reference (UUID) to an MSRPC Request Header enlarges the header by 16 bytes, and thus moves the MSRPC payload 16 bytes forward.


IPS Evasion Tool - Predator (IPForge)

-Evasions for attack "CVE-2008-4250"

-IP fragmentation, --ip_frag:
8byte: Fragment IP payload into 8 byte fragments
16byte: Fragment IP payload into 16 byte fragments
24byte Fragment IP payload into 24 byte fragments
256byte Fragment IP payload into 256 byte fragments
random_order: Send fragments in a random order
out_of_order: Send one fragment out of order
fwd_overwrite Perform forward overwriting with fragments
last_first Send last fragment first
one_duplicate Send one duplicate fragment

-IP evasion, --ip_evasion:
random_options: Send random IP options

-TCP fragmentation, --tcp_frag:
1byte Fragment TCP payload into 1 byte segments

-TCP evasion, --tcp_evasion:
time_wait Open a decoy connection and attack from same ip:port while in time-wait
urgent_ptr Insert meaningless data into 1 byte urgent segments

-SMB fragmentation, --smb_frag:
16byte Fragment SMB payload into 16 byte fragments
256byte Fragment SMB payload into 256 byte fragments

-SMB evasion, --smb_evasion:
andx_connect Negotiate SMB session and connect to a tree connect an AndX message
decoy_trees Open decoy SMB tree connects in the same TCP stream as the attack
read_offset Use random offsets in SMB read operations
pad_write_random Pad SMB write commands with a random sized block of random data
pad_write_static Pad SMB write commands with a static sized block of random data
random_write_method Use a random SMB write method ( TRANSACT / WRITE )
write_offset Use random offsets in SMB write operation

-MSRPC fragmentation, --msrpc_
frag: 16byte Fragment MSRPC payload into 16 byte fragments
256byte Fragment MSRPC payload into 256 byte fragments

-MSRPC evasion, --msrpc_evasion:
big_endian Communicate in big endian format
random_object: Add a random object reference to MSRPC requests
alter_context: Bind to a random context and then alter to the correct ip

Friday, February 19, 2010

Analyzing Malware Using Advanced Inspection Procedures

Why you want to analyze the malware? What could be the possible reasons?

-Better understanding of threats to protect network
-To write software that detects malware (anti-virus vendor)
-Admiration of new techniques
-Financial Gain (malware writer)
-Political agenda
-Used to be for the challenge and pranks

Characteristics of the good Malware Analyst

-Meticulous data collection
-Thinks outside the box
-Logical processes interaction
-Tenacious
-Good understanding of systems/network
-Reverse engineering skills

Attack Vectors

-Via portable devices
-Downloads from FTP or BBS
-Exploitation of remote services, worms
-System is only as strong as its weakest link

Human Factors

-In the past, humans not involved in the attack cycle
-Attackers searched for network or systems level vulnerabilities
-Automatic exploitation and spread
-In the present, exploit human (Spam email, compromise a legitimate site, advertising attacks)

Attacking through Social Networks

-All social networks have their history (Flickr, Facebook, Twitter, Myspace, Orkut)
-File sharing (Torrents, warez stuff, p2p)
-Massive information sharing networks
-Rich media content (web 2.0)

Attack Lifecycle

-Initial payload is small
-Initial checks (Mutex, OS Version, Keyboard, location)
-Payload is downloaded
-Contacts command and control server for tasks
-May fall back to secondary C&C
-Dynamically generate rendezvous point

Basic Obfuscation Techniques

-Polymorphism and Packers (UPX, Armadillo or custom packers)
-Simple Debugger checks
-Jumping into data/ middle of instructions
-Encoding strings/values
-Manipulating imports
-Corrupting PE Header
-Overlapping Section Header
-Junk code
-SEH (exception handler patches memory)

Advanced Obfuscation Techniques

-Metamorphic nature
-Custom virtual machines (Polymorphic instruction sets)
-Encryption
-Instruction Timing (Model Specific Register (MSR), RDTSC instruction)
-Debugging register tricks
-Breakpoint detection
-VMWare detection

Malware Lab

-Virtualization Platform (VMware, Xensource, Qemu)
-Must not be on any network but its own
-Dynamic Internet Connection

Virtualization Techniques

-Serial Debugging
-Copy on Write
-Memory Image
-Fast reversion of images

Logging Activities

-Needed to store data from automatic and manual analysis.
-Malware analysis is far more useful with a corpus to compare against.
-The more data we have on characteristics, the more we are able to do a determination of whether it is malware.
-Reverse engineering is expensive in terms of man-power to do.
-Identify characteristics and understand malware to allocate reverse engineering where it is worthwhile to.
-Store actual malware sample
-Store network traces
-Store static forensics information

Obtaining Malware

-Be an anti-virus or anti-malware software vendor
-Join an existing antimalware intelligence groups (Honeynet Project, Sandnet)
-Build your own honeynet
-Beg, borrow or steal

Advanced Tools

-Debuggers (WinDBG, IDA, Ollydbg)
-Tracers (regmon, filemon, detours, apimonitor, strace)
-Unpackers (PEiD)
For more information: Practical Toolkit for Reverse Engineering

Conclusions

-Simple tracing/monitoring can give lots of information
-Static analysis of Malware can also yield many clues
-Storing all bits of data and characteristics in a database can yield large dividends
-Trend is toward decentralized botnets (p2p)
-New coordination efforts in botnet takedowns

Sunday, February 7, 2010

Social Engineering: A science behind major Corporate Attacks

All social engineering techniques are usually based on specific attributes of human decision-making known as cognitive biases. These biases, sometimes called "bugs in the human hardware," which can be exploited in various combinations to create attack techniques. Source: "Wikipedia".

Social Engineering misdirection takes advantage of the limits of the human mind in order to give the wrong picture and memory. The mind can concentrate on only one thing at a time. The magician uses this to manipulate the "victim's" idea of how the world is supposed to be.

Common Risks From Social Engineering
–Direct users to malware attack
–Trick users into executing malware
–Persuade users into handing the information (data leakage)

Past Recaps:
Nigeria 419 scams, since 1980s
Phishing at AOL users
-AOL's chat rooms have been awash in password-stealing since at least 1994.
-In one three-month period in 1996, AOL cancelled 370,000 accounts for "creditcard fraud, hacking, etc "Washington post".

Other Email Scams Since 90s
Changes In The Social Engineering Attacks

Internet Statistics (1990-2008)
-Online presence1,463,632,361 –Internet users worldwide (June 2008).
-1.3 billion–email users worldwide. 210 billion emails sent per day (2008).
-Web Sites: 186,727,854–in December 2008. 31.5 million added during 2008.

Targeting Users for your Attack?
Using Popular Search Terms
Using celebrities popularity
Cyber attackers use Terrorist tactics
Terrorist cells are increasingly looking at less well-protected "soft" targets where Westerners can be found, such as social and retailvenues, tourist sites and transport networks (rail, road and airports), as illustrated by the attacks in Bali in October 2002,Madrid in March 2004 and Egypt in July 2005.

Business Strategies?

77% of employees have a Facebook account.
2/3rd access during working hours for average 15mins per day.
87% couldn’t define a clear business reason.
1 in 33 built and manage their entire profile at work.
1.47% total lost productivity across entire employee population.

Common issues with social networking

Who are you really communicating with?
–Has their account been compromised?
–Has the provider of the tool/service been compromised?
–Has the content been tampered?
–Does it have an abbreviated URL?

Stopping users getting to the compromised sites
–Content filtering: Needs real time intelligence.

Ensuring users don’t self infect
–Anti-malware solution
–Control what users can execute: User Access Control (Microsoft), Whitelistingtools (apple model - Digitally signed applications, 3rd party whitelisting tools) -Behavioural controls (IPS, FW, etc): Harden OS, Control what can be installed, used, interacted with other resources.
-Data leakage: Education, Data Loss Prevention controls (DRM).

Digital Reputation - Risk Management
Monitoring and controlling Social Networking Usage
-56% of employers admit to monitoring employees to see if accessing on-line social networking sites, amongst others things.
-38% block employees from accessing such websites.
-1/3rd of employers have adopted policies limiting or prohibiting use of such sites during work time.
-6% have terminated employees for utilizing online social networking sites during work.

Wednesday, January 27, 2010

CyberWar, CyberTerror and CyberCrime

During the past few years, these terms have refined and brought enormous attention in the media. However, the actual definitions remain same but keep blending with the growing threats.

As mentioned in Wikipedia:

CyberWar - Also known as "Cyber Warfare", is the use of computers and the Internet in conducting warfare in cyberspace.

CyberTerror - Cyberterrorism is a controversial term. The premeditated use of disruptive activities, or the threat thereof, against computers and/or networks, with the intention to cause harm or further social, ideological, religious, political or similar objectives Or to intimidate any person in furtherance of such objectives.

CyberCrime - Computer crime encompass a broad range of potentially illegal activities. This involves, crimes that target computer networks or devices directly or crimes facilitated by computer networks or devices, the primary target of which is independent of the computer network or device.

Now, I am going to point some of the key facts and their associated conflicts in dimension with cyber warfare.

-Distributed attacks, high anonymity.
-Possibility to use the same enemy’s infrastructures.
-Low cost of technology implementation and R&D.
-Wide range of critical infrastructures to be attacked.
-Possibility to carry out unconventional activities.
-Direct contact with the enemy’s command and control center at the highest ranks.

Evaluation#1:
In the traditional wars, to fight a country it requires a huge amount of resources (weapons, ammunition, etc). While, in asymmetric Internet based conflicts, to fight a country it can take just a few or just one motivated skilled hacker.

Cyber Politics (Historical track-record)
2001 Pakistan vs West
2002 USA vs China
2004 South America vs USA
2007 Arab countries vs Denmark
2007 Russia vs Estonia
2008 Russia vs Georgia

Cyber Industrial and Private Espionage
2001 Pakistan vs India
2005 China vs EU (political)
2005 China vs Italy (industrial)
2006 Russia vs USA (militar)
2008 China vs rest of the world
2009 China vs USA (preemptive war?)


Evaluation#2:
-The tactical systems were downloading nothing most of the time and when they were downloading they downloaded irrealistic data.
-The system was so slow in distributing the intelligence that we knew about the enemy presence only when it was in front of us and shooting.
-Too much of intelligence = No intelligence!

Lessons Never Learned
-Germany (Parliament law against security/hacking tools).
-France (Sarkozy doctrine).
-Italy (Pisanu decree).
-Sweden (The Pirate Bay case).
-All other countries (Blindness towards multi-layered threats and blindness towards excessive data retention).

Lessons Learned
-Use proprietary software and hardware when possible. And when it is not possible, use at least well reviewed open sourced software.
-Excessive data retention causes more troubles than benefits. There is a hidden danger from the social point of view as once adopted and enforced a data retentive policy, it will take a revolution to take it down (remember the London airport case?).




Durante los últimos años, estos términos han estado referidos y llamando la atención de los medios. Sin embargo, las definiciones actuales siguen siendo iguales, y se mantienen con las crecientes amenazas.

Según Wikipedia:

CyberWar (Ciber-Guerra): También conocido como "Cyber Warfare", es el uso de las computadoras y el internet para realizar la guerra en el ciberespacio.

CyberTerror – Cyberterrorism: el ciberterrorismo o terrorismo electrónico es el uso de medios de tecnologías de información, comunicación, informática, electrónica o similar con el propósito de generar terror o miedo generalizado en una población, clase dirigente o gobierno, causando con ello una violencia a la libre voluntad de las personas. Los fines pueden ser económicos, políticos o religiosos principalmente.

CyberCrime (CiberCrimen): El delito informático abarca una amplia gama de actividades potencialmente ilegales. Esto implica, los crímenes en el que las redes de computadoras, dispositivos de las mismas son el objetivo o crímenes facilitados por las redes o sus dispositivos, el objetivo principal de que es independiente de la red del ordenador o dispositivo.

Ahora, partamos del punto clave y sus conflictos asociados en dimensión con la Ciber-Guerra.


-Ataques distribuidos, con un anonimato alto.
-Posibilidad de utilizar la infraestructura del mismo enemigo.
-Bajo costo de implementación tecnológica y R&D.
-Amplia gama de infraestructuras críticas para ser atacados.
-Posibilidad de realizar actividades no convencionales.
-El contacto directo con el comando del enemigo y el centro de control en los rangos más altos.

Evaluación # 1:
En las guerras tradicionales, para luchar contra un país se requiere una enorme cantidad de recursos (armas, municiones, etc.) Si bien, en Internet basados en los conflictos asimétricos, para luchar contra un país que puede tomar sólo unos pocos o sólo un hacker experto motivado.

Ciber Politicas (Historia)
2001 Pakistan vs West
2002 USA vs China
2004 South America vs USA
2007 Arab countries vs Denmark
2007 Russia vs Estonia
2008 Russia vs Georgia

Ciber Industria y Espionage Privado
2001 Pakistan vs India
2005 China vs EU (politico)
2005 China vs Italy (industrial)
2006 Russia vs USA (militar)
2008 China vs rest of the world
2009 China vs USA (guerra preventiva?)

Evaluación # 2:
-Los sistemas tácticos se descarga nada más de las veces y cuando se descarga que los datos transferidos irrealista.
-El sistema era tan lento en la distribución de la inteligencia que sabíamos acerca de la presencia del enemigo sólo cuando estaba delante de nosotros y de tiro.
-El exceso de inteligencia = nada de inteligencia!

Lecciones no aprendidas
-Alemania (ley del Parlamento contra la seguridad / herramientas de hacking).
-Francia (doctrina de Sarkozy).
-Italia (decreto Pisanu).
-Suecia (El caso de Pirate Bay).
-Todos los otros países (ceguera ante los múltiples niveles de amenazas y la ceguera a la retención excesiva de datos).

Lecciones aprendidas
Uso de software propietario y de hardware cuando sea posible. Y cuando no es posible, al menos la revisión más actual del software de código abierto.
-Excesiva retención de datos provoca más problemas que beneficios. Hay un peligro oculto desde el punto de vista social, ya que una vez adoptado y aplicada una política de retención de datos, será necesaria una revolución para revocarla (recordemos el caso del aeropuerto de Londres?).

S.A & R.M

Monday, January 18, 2010

Cracking The Cryptographic Systems

Many reverse engineers always try to break the cryptographic protocols/applications using reverse engineering process as their primary key. The process itself is known as "Cryptanalysis". It is hard, time consuming and resource mean. A common way to break the commercial crypto system is to reverse the code and find the implementation errors. I will take two such commercial examples below:

MXI Stealth
EISST E-capsule PrivateSafe

MXI Stealth
- FIPS 142-3 level 2 certified USB Key
- AES on-chip encryption
- Authentication through password (windows application) or fingerprint (OS independent)
- Upon connection a first removable drive with a locked contents appears.
- Upon successful authentication a second drive appears.

Problem with Technology
Passwords are injected upon creation from external USB interface. A random salt is also added as a plain text through USB and stored in the EEPROM. Combined password with salt is then hashed using SHA-256 bit algorithm and stored again in EEPROM with associated user. Now upon failed password attempt there is a delay of 500ms. However, this delay also applies when a password verfication operation is done. This gap allows a maximum of 120 tries/minute. It gives an attacker enough time to break into.

- There is a library to exchange encrypted messages with the key.
– Apparently the password is encrypted and sent to the key.
– After some messages are exchanged the protected disk is activated.
- A logging function is implemented. It does not write log messages into a log file but they can be seen in the memory.
– A simple patch of the code can reactivate the log file.

- The 60 byte string are three SHA1 hashes. The current password and the previous 2 passwords.
- The "enterprise" version of the software needs this info to make sure the user does not reuse
the current and last "n" passwords.
- This information is received by the software even before the user has authenticated.


EISST E-capsule PrivateSafe

PrivateSafe is a software that creates encrypted containers.
There are 4 passwords:
1. The admin password allows managing the container.
2. The public password reveals one part of the content.
3. The private passwod gives access to the rest of the content.
4. The panic password deletes all files and gives access to an empty container.

There are 2 files:
1. The encrypted file system.
2. A control file.

Through reverse engineering we found that:
- Each block of the control file is encrypted with AES 256 CTS mode.
– The key is the SHA256 hash of the corresponding password.
– The IV is the ripemd160 hash of the password.
– The clear text of blocks 1,2 and 3 are the same. Block 0 corresponds to the admin key.

- Exchanging two blocks in the control file inverts the role of their keys. E.g, private <-> public
- Worse. E.g, Shred <-> private
- Actually, exchanging just the single ascii character that identify the blocks is enough.

Monday, January 4, 2010

El Malware y su futuro en el 2010


Según wikipedia el “Malware es un software que tiene como objetivo infiltrarse en el sistema y dañar la computadora sin el conocimiento de su dueño, con finalidades muy diversas…”
Un ejemplo de malware son los troyanos (esos programitas que parecen inofensivos pero le dan acceso remoto a una persona sin nuestro consentimiento), los virus ya conocidos por todos, etc.

Desde que la banca coloco sus sistemas al público mediante internet para darle la facilidad al usuario final, de que realice sus operaciones sin trasladarse físicamente a una sucursal, los delincuentes tuvieron que evolucionar, atacar ese campo que estaba naciendo y que no había sido tocado por ellos, el ataque más conocido por la población hoy en día es el Phishing. Pero hay una modalidad de malware que va contra el sector bancario online y es el Crimeware. El desarrollo de este tipo de software es muy lucrativo para los programadores o blackhats que se especializan en esta modalidad, este tipo de software se aprovecha de vulnerabilidades de sistemas operativos o vulnerabilidades en programas instalados para infectar al usuario.

Herramientas como: Liberty Exploit System, Neon Exploit System, Sploit25, Unique Sploits Pack, Eleonore Exploits Pack, YES Exploit System, etc., pueden ir desde 500$US hasta 3000$US. Esta cantidad de dinero por el desarrollo de malware hace que los programadores saquen provecho por la venta de estos sistemas y hasta den garantías a sus compradores sobre si su sistema es detectado por algún antivirus.

Dependiendo del tipo de malware y lo complejo que sea varia su precio, encontraran ofertas en internet de troyanos por 250$US hasta los sistemas de crimeware mencionado anteriormente. Rusia lleva la delantera y le sigue china en el desarrollo de malware. Los nuevos estudios de Mcafee Labs pronostican que en el 2010 la compañía que será más atacada por este tipo de malware va a ser Adobe y se dejara de lado a Microsoft Office, debido a que se van encontrando nuevas vulnerabilidades en sus programas lideres como Adobe Reader y Adobe Flash. Solamente con abrir un sencillo PDF realizado por estos sistemas y una versión vulnerable de Adobe Reader el usuario sin darse cuenta se descarga un malware, se infecta y ya pasa a ser una víctima más en el mundo de los ciber-delitos, lo mismo pasaría con una animación Flash.

Más allá, la Cyber-Warfare también puede ir por este rumbo y cualquier país involucrado utilizaría estos sistemas para en vez de ir contra lo monetario atacar los sistemas informáticos gubernamentales de su contraparte mediante estas botnets.
Adobe constantemente está en la corrección de estas vulnerabilidades y han desarrollado un blog para este tipo de temas, claro está que si como usuarios no ponemos de nuestra parte y no mantenemos los sistemas actualizados, no será nada útil las correcciones que se hagan a nivel de desarrollo de código hasta que instalemos los updates necesarios.

Para más info sobre adobe y su blog: http://blogs.adobe.com/psirt/