Monday, July 9, 2012

Exploit Mitigation Techniques on Linux Systems

Each year we see phenomenal research works being presented in a number of security conferences and events around the world. Vendors/communities present solutions for existing issues and those on the offensive side present workarounds against these solutions. Eventually this race, between those working on either sides of the coin, helps to make our world a safer place.

Over the last decade, reliable exploitation of memory corruption bugs has become extremely difficult. This has happened, primarily, due to the introduction of various exploit mitigation techniques. In this post, we'll be looking at the current state of exploitation within the Linux environment.

The following security/mitigation techniques are commonly available on most recent distributions:
    1. ASLR
    2. NX
    3. Stack Canaries
    4. FORTIFY_SOURCE
    5. RELRO
    6. PIE
Except for ASLR, which effects system-wide configuration, all of the above techniques are user-space mitigation features that have to be enabled on a per-binary basis. Here is the sample program that we'll be using for our tests:


Let's have a detailed look at each of the above techniques:
Enables randomization of  various memory allocation segments (stack, mmap, exec, brk, and vdso). When enabled, each invocation of a binary will have its memory allocations randomized within the available virtual address space. As such, an exploit technique like Ret2libc, that requires static memory addresses of common library functions, is no longer effective.
The randomize_va_space kernel parameter defines system-wide configuration setting for ASLR. This parameter could be set to the following values: 
0 - ASLR is turned OFF 
1 - ASLR is turned ON (stack randomization)
2 - ASLR is turned ON (stack, heap, and mmap allocation randomization)
Once enabled, each invocation of a program will have different memory locations assigned to it:

 
In the above output note that all the segments of the /bin/cat process are mapped at different memory locations with each invocation. However, closer look provides an interesting observation. The first three segments that contain .text section of the binary (notice the r-x permissions) are still mapped at similar locations each time. We have enabled ASLR and it is indeed active, so why aren't the .text segments not mapped randomly? We will talk about this behavior in much detail within the PIE section.
This feature disallows code execution from marked memory pages/segments. It is also referred to as W^X (W XOR X) due to the fact that the pages marked with this feature could either be writable OR executable but not both at the same time. When enabled, a process's memory allocations, that do not contain instructions, will have only rw- permissions assigned to them by default. As such, even if an attacker successfully injects code into a writable memory region through an overflow bug, an attempt to execute code from this section would still fail.
NX is enabled through the MMU by setting bit 63 of the page directory entry. Important thing to note here is that this feature is available only on those systems that have 64bit capability or on those systems that use a PAE-enabled kernel. This is because on a regular 32bit kernel without PAE support, a page directory entry is just 32bit wide and hence there is no room to store additional meta-information about memory pages it points to. The Execshield and Grsecurity set of kernel patches could also be used to simulate this behavior when the above requirements could not be met:

-z execstack - request the linker to mark program stack as executable
-z noexecstack - request the linker to mark program stack as non-executable (recommended)
Note the permissions of the GNU_STACK section in the above output. When we request executable stack through the linker option, GCC marks the stack as executable with RWE permissions. On my test system, which is an Ubuntu 10.04 derivative with GCC version 4.4.3, the default command-line disables executable stack markings as evident in the output of first command-line. This behavior of implicitly enabling safeguards makes an application immune to stack-based execution and other such attacks even if the developer fails to include them during compilation.
Stack Canaries are a protection feature that safeguard critical program metadata information located on call stack. When enabled, a random canary value is placed on the stack, just below the saved registers from the function prologue. Before a program returns control to its parent, the saved canary value is checked. Any attempts to overwrite the saved return address on the stack will also overwrite the saved cookie and as such the above check would fail. In such cases, the __stack_chk_fail function is called, which displays a friendly "stack smashing detected" message and aborts the execution of the program.
This mitigation technique also reorders the placement of local variables on the stack. This is done to ensure that any variable, that directly influences the program control and redirects its normal flow, is placed below a buffer that accepts user-supplied input. Such a placement prevents overwriting of variables placed adjacent to buffers. To read more about other such novel ideas implemented in this protection technique, visit this link: SSP
The following options enable/disable this check:
-fstack-protector - enable checks for functions with character buffers of size 8B or higher
-fstack-protector-all - enable checks for all functions (recommended)
-fno-stack-protector - disable stack protection checks
-Wstack-protector - emit warnings for all unprotected functions (recommended)
--parm=ssp-buffer-size=<size_in_bytes> - modifies the default 8B buffer length
GCC versions 4.x include SSP techniques in their native implementations. Prior 3.x versions had this feature enabled through a patch.
There are cases when a compiler can correctly estimate the size of a destination operand used in a certain string operation. For such cases, the compiler could be requested to replace any vulnerable function calls in the program source with their equivalent safer counterparts. This would eventually make the compiled binary resilient to most overflow attempts without significantly impacting its performance:
In the above output you could see that the GCC option -D_FORIFY_SOURCE has been used to include fortifying checks. The call for function printf and gets were replaced with their safer equivalents, __printf_chk and __gets_chk respectively. This option can accept two values:
-D_FORIFY_SOURCE=1 - to enable checks against buffer overflow attacks
-D_FORIFY_SOURCE=2 - to enable checks against buffer overflow and format string attacks (recommended)
Another mitigation technique that safeguard against those exploits that require Global Offset Table (GOT) modifications. For this to work, all dynamic symbol resolutions, requested by a binary, have to be carried out before the program execution begins. Once this is done, the GOT could be marked as read-only, thus preventing any runtime modifications.
By default, when we use the GCC linker option -Wl,-z,relro, PLT (Procedure Linking Table) entries, which include references for library functions within a process's memory allocation, are marked as writable (lazy-linking). All other GOT entries apart from PLT remain read-only, providing what is know as Partial-RELRO support:
The -z,now option ensures that PLT entries are resolved immediately before execution, thus allowing the entire GOT to be marked as read-only. This ensure that Full-RELRO support is enabled for the compiled program. The summary for these options is:
-Wl,-z,relro - enables Partial RELRO support
-Wl,-z,relro,-z,now - enables Full-RELRO support (recommended)
This feature helps to load a program at a random memory location on each invocation. With ASLR enabled, the stack, heap, and mmap allocations are automatically randomized. However, like we saw earlier with the /bin/cat binary, the .text and other sections of a program are still loaded at static addresses. To make all sections of a program to load at random addresses, we need to compile it with PIE support:
The following GCC options could be used to enable PIE support as evident from the above output: -fpie -pie (recommended)
Programs compiled with this feature are marked as shared relocatable, much similar to shared object libraries used in dynamic linking. To read more, visit this link: PIE
Enabling these mitigation techniques will definitely improve the overall security posture of a system, it still does not make it bullet-proof. Some of these techniques might break compatibility with legacy applications, while others might not work as expected. Different distributions use different default configuration settings and as such you can not simply standardize. The most suitable option would be to test your application code first hand with each of these options, carefully considering the tradeoffs and using only those that provide that rare mix of security and usability.

Saturday, June 2, 2012

Vulnerable Weekends #8

Vulnerability Report #8: HP LoadRunner magentservice.exe Component Remote Code Execution Vulnerability

Vulnerable Product: Installations of HP LoadRunner prior to version 11 patch 4

CVE ID: CVE-2011-4789

CVSS v2 Score:
Access Vector: REMOTE
Access Complexity: LOW
Authentication: NONE

Confidentiality Impact: COMPLETE
Integrity Impact: COMPLETE
Availability Impact: COMPLETE
Base Score: 10

Exploitability: FUNCTIONAL
Remediation Level: OFFICIAL FIX
Report Confidence: CONFIRMED
Temporal Score: 8.3

Details:
HP LoadRunner is vulnerable to a remote code execution vulnerability due to insufficient boundary checks performed on user-supplied input received via its magentservice.exe component.

The vulnerability exists due to an implementation flaw within the affected software. The vulnerable component listens for incoming requests on TCP/23472 and it expects a size value within the first 32bits of user-supplied input. This value is used as-is, without any sanitization, for internal calculations that involve deriving the number of bytes to be copied in to a destination buffer. Due to the insufficient checks, a 32bit value of 0x00000000 could cause an error within the internal calculation logic and trigger a stack-based buffer overflow during a later copy operation. This action could allow a remote attacker to execute arbitrary code with SYSTEM privileges on the targeted system.

HP has confirmed this vulnerability and released a security patch for registered users.

Vulnerability Sources:
Bugtraq ID: 51398
HP Security Bulletin: HPSBMU02785 SSRT100526
Metasploit Module: hp_magentservice
Zero Day Initiative: ZDI-12-016

Generic Sources:
Common Vulnerabilities and Exposures (CVE)
Common Vulnerability Scoring System (CVSS)

Saturday, January 7, 2012

Vulnerable Weekends #7

Vulnerability Report #7: Iptools rcmd Denial of Service Vulnerability

Vulnerable Product: Installations of Iptools with version 0.1.4

CVE ID: NA

CVSS v2 Score:
Access Vector: NETWORK
Access Complexity: LOW
Authentication: NONE

Confidentiality Impact: NONE
Integrity Impact: NONE
Availability Impact: PARTIAL
Base Score: 5

Exploitability: PROOF-OF-CONCEPT
Remediation Level: WORKAROUND
Report Confidence: UNCORROBORATED
Temporal Score: 4.1

Details:
Iptools is a popular set of tiny TCP/IP utilities implemented as Perl scripts, that include a minimalist webserver, a remote command server on the lines of Telnet, a TFTP server/client, SNMP browser, etc. The toolset has been reported to be vulnerable to a denial of service (DoS) vulnerability, specifically within its remote command server script, rcmd.

The vulnerable utility receives user-supplied input through its listening port, TCP/23, which is then tested against a set of weak sanitization checks. This input is used as a placeholder for the EXPR parameter used by the internal chdir function which parses it as a filename reference. Since this parameter could reference a string of an unbounded length, the directory change operation could generate an untrappable exception. This flaw could make the vulnerable utility unstable, effectively terminating the Perl interpreter abnormally, leading to the DoS condition. The following code snippet depicts where the vulnerability could have been introduced within the rcmd script:

chop($curdir=`cd`);
print NS "$curdir> ";
while (<NS>) {
  print "Client request : ";
    print;
  CASE: {
      /cd / && do { $dir=$'; $dir=~s/\015\012//; print $dir if $debug;
                    chdir "$dir" || print NS "Invalid directory\015\012"  ; last CASE; };
      /^(\b)*(.:)/ && do { $drive=$2; ; print "driver:[$drive]" if $debug;
                    chdir "$drive" || print NS "Invalid drive\015\012"  ; last CASE; };


An official confirmation and software updates are currently unavailable. Users are requested to avoid using the vulnerable utility until official fixes are released. For a workaround, users could consider introducing restrictive firewall policies that prohibit unnecessary access to the vulnerable script from an unauthorized source.

Vulnerability Sources:
http://www.securityfocus.com/bid/51312/
http://iptools.sourceforge.net/iptools.html

Generic Sources:
http://cve.mitre.org
http://www.first.org/cvss/cvss-guide.html
http://nvd.nist.gov/cvss.cfm?calculator&adv&version=2

Sunday, January 1, 2012

Vulnerable Weekends #6

Introduction:
Report #6A analyzes the WPS implementation flaw that allows brute force guessing of the 8 digit PIN used to restrict wireless access to authenticated users.

Report #6B analyzes the memory corruption vulnerability in the CoCSoft Stream Down that could allow execution of arbitrary code on the targeted system.

Vulnerability Report #6A: Multiple WPS Implementations Brute Force Authentication Bypass Vulnerability

Vulnerable Product: Installations of WPS enabled wireless devices

CVE ID: CVE-2011-5053

CVSS v2 Score:
Access Vector: NETWORK
Access Complexity: MEDIUM
Authentication: NONE

Confidentiality Impact: COMPLETE
Integrity Impact: COMPLETE
Availability Impact: COMPLETE
Base Score: 9.3

Exploitability: FUNCTIONAL
Remediation Level: WORKAROUND
Report Confidence: CONFIRMED
Temporal Score: 8.4

Details:
Multiple WiFi Protected Setup (WPS) implementations were reported to contain a vulnerability that could be leveraged to bypass authentication checks and gain privileged access to the targeted wireless devices. The vulnerability has been identified within the WPS specification and it enables brute force detection of the PIN used to authenticate a remote wireless user.

The vulnerability exists because the WPS specification allows a remote attacker to guess the 8 digit PIN being used to authenticate remote wireless users. The first 4 digits of this PIN could be guessed by attempting multiple connections to the wireless AP with incorrect PIN values and analyzing the received EAP-NACK responses.

The EAP-NACK messages provide information that could be leveraged to successfully calculate the first and second halves of the 8 digit PIN being used. The number of brute force attempts to guess the PIN is also reduced because the 8th digit of this PIN is always a checksum which can be easily derived. This analysis brings the total number of brute force attempts to be 104 + 103; i.e 11,000 attempts to successfully calculate the WPS PIN for the targeted AP.

Since most vendors, except for Netgear, do not implement a lock down functionality for blocking such brute force attempts, the time complexity to successfully execute this attack is reduced significantly. On some implementation the overhead of processing such rapid surge of authentication requests leads to an internal state corruption, which could only be recovered via a device reboot. This makes it possible to launch denial of service (DoS) attacks on the targeted AP.

Vulnerability Sources:
http://www.securityfocus.com/bid/51187
http://sviehb.wordpress.com/2011/12/27/wi-fi-protected-setup-pin-brute-force-vulnerability/


Vulnerability Report #6B: CoCSoft Sream Down Insufficient Boundary Checks Buffer Overflow Vulnerability

Vulnerable Product: Installations of CoCSoft Stream Down with versions 6.8 and prior

CVE ID: CVE-2011-5052

CVSS v2 Score:
Access Vector: NETWORK
Access Complexity: LOW
Authentication: NONE

Confidentiality Impact: PARTIAL
Integrity Impact: PARTIAL
Availability Impact: PARTIAL
Base Score: 7.5

Exploitability: FUNCTIONAL
Remediation Level: UNAVAILABLE
Report Confidence: UNCORROBORATED
Temporal Score: 6.8

Details:
CoCSoft Stream Down media download application is prone to a buffer overflow vulnerability that could be leveraged to execute remote code or to cause a denial of service condition on the targeted system.

The vulnerable application fails to impose sufficient size limits on user-supplied input before copying it to a fixed length destination buffer. This implementation flaw could allow injection of arbitrary shellcode into the targeted system's memory space, leading to a memory corruption error. Later execution of this shellcode could allow the attacker to launch additional attacks on the targeted system.

CoCSoft has not yet confirmed this vulnerability. Users are advised to immediately stop using the vulnerable application.

Vulnerability Sources:
http://www.securityfocus.com/bid/51190/


Generic Sources:
http://cve.mitre.org
http://www.first.org/cvss/cvss-guide.html
http://nvd.nist.gov/cvss.cfm?calculator&adv&version=2

Saturday, December 24, 2011

Vulnerable Weekends #5

Introduction:
Report #5A analyzes the MIT Kerberos Telnet remote, privileged code execution vulnerability. This vulnerability has been identified within the MIT Kerberos based Telnet installations that are provided with FreeBSD, GNU inetutils, etc.

Report #5B analyzes the VLC TiVo file parser arbitrary code execution vulnerability.

Vulnerability Report #5A: MIT krb5-appl Telnet Client and Server encrypt_keyid() Remote Code Execution Vulnerability

Vulnerable Product: Installations of MIT krb5-appl derived telnet utilities prior to krb5-1.8

CVE ID: CVE-2011-4862

CVSS v2 Score:
Access Vector: NETWORK
Access Complexity: LOW
Authentication: NONE

Confidentiality Impact: COMPLETE
Integrity Impact: COMPLETE
Availability Impact: COMPLETE
Base Score: 10.0

Exploitability: FUNCTIONAL
Remediation Level: OFFICIAL FIX
Report Confidence: CONFIRMED
Temporal Score: 8.3

Details:
MIT krb5-appl has been reported to contain a vulnerability that could be leveraged by a remote attacker to execute arbitrary code on the targeted system.  The vulnerability has been reported in the code responsible for handling Kerberos based authentication mechanism.

The vulnerability was introduced when BSD telnet daemon and client utilities included support for cryptographic security via MIT Kerberos based authentication mechanism. This code was further included within FreeBSD and GNU inetutils making these vulnerable as well.

The vulnerability allows a pre-authentication memory corruption error that could be triggered remotely by submitting an arbitrarily long encryption key to the target system. Specifically, the vulnerability exists within the encrypt_keyid() function of the encrypt.c source file of the affected software:

static void
encrypt_keyid(struct key_info *kp, unsigned char *keyid, int len)
{
   ...
    } else if ((len != kp->keylen) || (memcmp(keyid,kp->keyid,len) != 0)) {
    /*
     * Length or contents are different
     */
    kp->keylen = len;
    memcpy(kp->keyid,keyid, len);
    if (ep->keyid)
        (void)(*ep->keyid)(dir, kp->keyid, &kp->keylen);
    ...
}

The vulnerable source file defines the following structure to keep record of the encryption state:

#define   MAXKEYLEN 64

static struct key_info {
    unsigned char keyid[MAXKEYLEN];
    int keylen;
    int dir;
    int *modep;
    Encryptions *(*getcrypt)();
} ki[2] = {
    { { 0 }, 0, DIR_ENCRYPT, &encrypt_mode, findencryption },
    { { 0 }, 0, DIR_DECRYPT, &decrypt_mode, finddecryption },
};

However, the vulnerable function fails to impose sufficient boundary restrictions on user-supplied encryption keys and copies those into keyinfo structure without honoring the MAXKEYLEN constant via a memcpy operation. This could cause a heap-based buffer overflow error, leading to the memory corruption error.

Successful exploitation could allow the attacker to leverage the memory corruption error to execute arbitrary code on the targeted system with the privileges of the affected software. Failed exploit attempts could result in a denial of service condition on the targeted system.

Vulnerability Sources:
http://www.securityfocus.com/bid/51182
http://web.mit.edu/kerberos/advisories/MITKRB5-SA-2011-008.txt
http://security.freebsd.org/advisories/FreeBSD-SA-11:08.telnetd.asc
https://bugzilla.redhat.com/show_bug.cgi?id=770325
http://osvdb.org/78020


Vulnerability Report #5B: VLC .TY (TiVo) File Parser Arbitrary Code Execution Vulnerability

Vulnerable Product: Installations of VLC Media Player with versions 0.9.0 through 1.1.12

CVE ID: NA

CVSS v2 Score:
Access Vector: NETWORK
Access Complexity: MEDIUM
Authentication: NONE

Confidentiality Impact: COMPLETE
Integrity Impact: COMPLETE
Availability Impact: COMPLETE
Base Score: 9.3

Exploitability: UNPROVEN
Remediation Level: OFFICIAL FIX
Report Confidence: CONFIRMED
Temporal Score:6.9

Details:
VLC Media Player has been reported to contain a vulnerability that could allow a remote attacker to execute arbitrary code on the targeted system. The vulnerability is introduced by the libty_plugin that helps parsing of .ty files.

struct demux_sys_t
{
...
ty_rec_hdr_t    *rec_hdrs;          /* record headers array */
int             i_cur_rec;          /* current record in this chunk */
int             i_num_recs;         /* number of recs in this chunk */
...
};

The vulnerability exists due to an implementation flaw within the get_chunk_header() function of the ty.c source file of the vulnerable plugin. The vulnerable plugin improperly handles the record headers array, rec_hdrs, corrupting heap structures in the memory.

diff --git a/modules/demux/ty.c b/modules/demux/ty.c
index e916b41..b181a6a 100644 (file)

--- a/modules/demux/ty.c
+++ b/modules/demux/ty.c
@@ -1887,6 +1887,7 @@ static int get_chunk_header(demux_t *p_demux)
     /*msg_Dbg( p_demux, "chunk has %d records", i_num_recs );*/

     free(p_sys->rec_hdrs);
+    p_sys->rec_hdrs = NULL;
     /* skip past the 4 bytes we "peeked" earlier */
     stream_Read( p_demux->s, NULL, 4 );

Successful exploitation could allow the attacker to leverage the memory corruption error further and execute arbitrary code on the targeted system within the security context of the affected software.

Vulnerability Sources:
http://www.securityfocus.com/bid/51147
http://www.videolan.org/security/sa1108.html
http://git.videolan.org/?p=vlc.git;a=blobdiff;f=modules/demux/


Generic Sources:
http://cve.mitre.org
http://www.first.org/cvss/cvss-guide.html
http://nvd.nist.gov/cvss.cfm?calculator&adv&version=2

Sunday, December 18, 2011

Vulnerable Weekends #4

Introduction:
Report #4A analyzes the Microsoft Windows True-Type fonts handling vulnerability that the W32.Duqu malware leverages to install itself on vulnerable systems. Once installed, it could then leverage its elevated privileges to execute arbitrary code.

Report #4B analyzes the Microsoft Windows DVR-MS media files processing vulnerability that could also be leveraged to execute arbitrary code on the targeted system.

Vulnerability Report #4A: Microsoft Windows Kernel-Mode Drivers True-Type Font Handling Remote Code Execution Vulnerability

Vulnerable Product: Installations of Microsoft Windows XP, Server 2003, Vista, Server 2008, and 7

CVE ID: CVE-2011-3402

CVSS v2 Score:
Access Vector: NETWORK
Access Complexity: MEDIUM
Authentication: NONE

Confidentiality Impact: COMPLETE
Integrity Impact: COMPLETE
Availability Impact: COMPLETE
Base Score:9.3

Exploitability: FUNCTIONAL
Remediation Level: OFFICIAL FIX
Report Confidence: CONFIRMED
Temporal Score:7.7

Details:
Microsoft Windows has been reported to contain a vulnerability that could be leveraged to execute arbitrary code on the targeted system. The vulnerability has been reported within the Kernel-Mode driver, Win32k.sys, that provides rendering support for True-Type fonts.

The vulnerability is due to the fact that the vulnerable font processing engine fails to perform mandatory boundary checks on user-supplied input received via crafted True-Type fonts embedded within a Microsoft Office .doc file. An attacker who could convince a remote user to open a malicious .doc file, containing the specially crafted content, could exploit this vulnerability to cause a memory corruption error within kernel space. Further, the attacker could leverage such memory corruption errors to inject arbitrary shellcode within system memory and execute it with SYSTEM privileges on the targeted system.

Public sources confirm that the W32.Duqu malware, assumed to be a variant of W32/Stuxnet-B, leverages this vulnerability to infect vulnerable systems.

The vendor, Microsoft, has released a security bulletin to confirm this vulnerability and provided official patches for its mitigation. Users are requested to keep their systems updated with the latest available patches.

Vulnerability Sources:
http://www.securityfocus.com/bid/50462
http://tools.cisco.com/security/center/viewAlert.x?alertId=24500
http://www.symantec.com/security_response/writeup.jsp?docid=2011-101814-1119-99


Vulnerability Report #4B: Microsoft Windows Media Player DVR-MS Files Processing Remote Code Execution Vulnerability

Vulnerable Product: Installations of Microsoft Windows XP, Vista, and 7

CVE ID: CVE-2011-3401

CVSS v2 Score:
Access Vector: NETWORK
Access Complexity: MEDIUM
Authentication: NONE

Confidentiality Impact: COMPLETE
Integrity Impact: COMPLETE
Availability Impact: COMPLETE
Base Score: 9.3

Exploitability: UNPROVEN
Remediation Level: OFFICIAL FIX
Report Confidence: CONFIRMED
Temporal Score: 6.9

Details:
Microsoft Windows Media Player has been reported to contain a vulnerability that could be leveraged to execute arbitrary code on the targeted system. The vulnerability exists within the encdec.dll library used by the vulnerable platforms.

The vulnerability is introduced while the affected software tries to process Microsoft Digital Video Recording (DVR-MS) media files. The affected software fails to perform sufficient security checks on user-supplied input received via such files, leading to a memory corruption error within kernel space. An attacker who could convince a targeted user to open a malicious .dvr-ms file, could exploit this vulnerability and leverage the memory corruption error to execute arbitrary code with SYSTEM privileges.

The vendor, Microsoft, has released a security bulletin to confirm this vulnerability and provided official patches for its mitigation. Users are requested to keep their systems updated with the latest available patches.

Vulnerability Sources:
http://www.securityfocus.com/bid/50957
http://secunia.com/advisories/cve_reference/CVE-2011-3401/

Generic Sources:
http://cve.mitre.org
http://www.first.org/cvss/cvss-guide.html
http://nvd.nist.gov/cvss.cfm?calculator&adv&version=2