8

Click here to load reader

An Encrypted Payload Protocol and Target-Side … Encrypted Payload Protocol and Target-Side Scripting Engine ... server-side logic, ... is a client-side penetration test against a

Embed Size (px)

Citation preview

Page 1: An Encrypted Payload Protocol and Target-Side … Encrypted Payload Protocol and Target-Side Scripting Engine ... server-side logic, ... is a client-side penetration test against a

An Encrypted Payload Protocol and Target-Side Scripting Engine

Dino A. Dai [email protected]

AbstractModern exploit payloads in commercial and open-sourcepenetration testing frameworks have grown much moreadvanced than the traditional shellcode they replaced.These payloads permit interactive access without launch-ing a shell, network proxying, and many other rich fea-tures. Available payload frameworks have several lim-itations, however. They make little use of encryption tosecure delivery and communications, especially in earlierstage payloads. In addition, their richer features requirea constant network connection to the penetration tester,making them unsuitable against mobile clients, such aslaptops, PDAs, and smart phones.

This work introduces a first-stage exploit payload thatis able to securely establish an encrypted channel usingElGamal key agreement and the RC4 stream cipher. Thekey agreement implementation requires only modularexponentiation and RC4 also lends itself to an implemen-tation requiring a very small amount of executable code.This secure channel is used to send further executablecode and deliver a fully-featured interpreter to executemission logic written in the high-level Lua scripting lan-guage. This scripting environment permits secure codedelivery as well as disconnected operation and executionof penetration testing mission logic.

1 Introduction

Although much work has gone into detecting, mitigat-ing, and preventing their exploitation, remote code ex-ecution vulnerabilities remain one of the most preva-lent and serious vulnerability classes in software today.While reported remote code execution vulnerabilities incommon server software have gotten more rare, they arestill highly prevalent in web browsers, office suites, me-dia players, anti-virus suites, and other local applicationsoftware.

Remote code execution vulnerabilities are exploitedby injecting a small amount of executable machine code

into the remote process and then triggering the vulnera-bility (the injection vector) in order to cause the remoteprocess to execute the injected code (the payload). Tra-ditionally, these payloads have been written in processor-specific assembly language, assembled, and extracted byhand into reusable machine code components. Thesepayloads were typically small and executed an operatingsystem shell, causing them to be commonly referred toas shellcode. Common shellcode variants included func-tionality such as restoring dropped privileges, breakingout of chroot environments, and attaching the shell toan inbound or outbound network connection. This styleof payload construction was both labor and skill inten-sive.

With the growth of commercial penetration testingservices and especially commercial penetration test-ing products, exploit payloads have gotten considerablymore capable and complex. These payloads have facil-itated the construction of products that help less experi-enced penetration testers better demonstrate the risk pre-sented by exploitable security vulnerabilities. In addi-tion, the increased prevalence of layered host securitydefenses require that payloads be more robust and ca-pable of more complex logic. The Unix chroot sys-tem call is typically used to run a network service in arestricted file system environment. Extensions includ-ing FreeBSD’s jail [1] extend this model to assigna dedicated IP address to a jail. More recent devel-opments include the Windows Integrity Mechanism inWindows Vista. The Windows Integrity Mechanism isa Biba Integrity Model[2] Mandatory Access Controlsecurity system used to implement Internet Explorer’s“Protected Mode” and User Account Control (UAC).Protected Mode Internet Explorer runs as a low-integrityprocess that prevents it from writing to anywhere exceptdesigned places on the file system or in the registry, re-gardless of the discretionary access control list on theobjects. Escalating privileges in these restricted permis-sion environments, pivoting through networked hosts, or

Page 2: An Encrypted Payload Protocol and Target-Side … Encrypted Payload Protocol and Target-Side Scripting Engine ... server-side logic, ... is a client-side penetration test against a

achieving mission objectives from these restricted execu-tion environments requires complex payload logic.

This work addresses two shortcomings of the exist-ing exploit payloads found in commercial and open-source penetration testing tools. The first is a lack of se-cure payload delivery and communication mechanisms.Most available systems offer partial solutions to this atthe present time by either only supporting encryption inlater-stage executable agents or by only supporting sim-ple XOR-based traffic encoding. The second area thatthis work addresses is the applicability of existing pay-loads against mobile clients. Most of the existing frame-works require a constant network connection to the com-promised target in order to carry out mission objectives.This paper introduces a target-side scripting environmentin order to push mission-objective logic onto the target.The secure channel established by the earlier stage pay-load ensures that mission objective logic is not compro-mised in transit to the target.

This paper is organized as follows. First, a summaryof existing advanced payload techniques and frameworksis presented in the next section. Afterwards, EncryptedPayload Protocol describes a system for cryptographi-cally securing exploit payload delivery and communica-tion. The final stage of this payload system, a lightweightand powerful remotely scripted agent is introduced in thesection titled Target-Side Scripting. Finally, the paperconcludes with some discussion of the security and util-ity of the described payload system.

2 Related Work

As mentioned above, the development of commercialpenetration testing applications and layered host securitydefenses have significantly increased the complexity ofexploit payloads. This section describes the exploit pay-load systems found in the major available commercialand open-source penetration testing frameworks.

Syscall proxying[3] is a simple and flexible techniquefor simulating remote execution. Syscall proxying im-plements a fat client, thin server remote procedure callprotocol based on transferring stack frames. To exe-cute a remote system call, the syscall proxy client mar-shalls the required argument register values and mem-ory buffers into a single buffer. The syscall proxy serverwrites this marshalled stack buffer directly to its stacksegment, pops the general register values from it, and ex-ecutes the system call specified. After the system callreturns, the server pushes all the general purpose regis-ters onto the stack and transfers the stack buffer back tothe client. This general mechanism requires very littleserver-side logic, but provides a great deal of flexibility,allowing the remote client to open files, make networkconnections, and even exploit other vulnerabilities on the

same or other remote systems.There are some limitations, however, with the syscall

proxy’s simple server-side logic. For example, it can-not handle the fork system call. In addition, file orsocket input and output with the read or write systemcalls requires transferring the buffer twice because allo-cating stack space requires sending unused data in themarshalled stack buffer. Similarly, a round-trip for eachsystem call can add significant latency to input/output in-tensive operations. Finally, all communication with thesyscall proxy server is performed unencrypted. This canbe a concern when a remote penetration tester is gainingaccess to sensitive hosts or files. CORE IMPACT [4], acommercial penetration testing application that employssyscall proxying, addresses these issues by also employ-ing more complex agents with richer network transportsthat perform encryption. The initial syscall proxy servercan be used to deploy a more capable remote agent, butthis requires writing an executable to the remote system’shard drive.

Immunity’s CANVAS [5], a competing penetration-testing application, uses a custom compiler-based pay-load construction system called MOSDEF [6]. TheMOSDEF compiler takes a subset of the C programminglanguage and generates highly position-independent ma-chine code suitable for dynamic injection into remoteprocesses. The remotely executed payload can make useof system functions or other locally compiled functions.Loops, conditional execution paths, and function callsare all executed inside the remote compromised processand only minimal necessary information is transferredto or from the remote process. This allows the payloadauthor to create complex payloads that can, for exam-ple, transfer an entire remote file if successful, or only asmaller error code if an error occurred.

A compiler-style approach such as MOSDEF ad-dresses many of the limitations of syscall proxying atthe expense of implementation complexity. A MOS-DEF program can create multiple processes and performa significant amount of work on the client without requir-ing network round-trips or data transfers. The low-levelflexibility of C also allows a MOSDEF program to per-form byte-level memory manipulations easily. This isan important capability as performing a heap metadataexploit typically corrupts the heap to the point of caus-ing any subsequent heap operations to crash the program.A MOSDEF program can systematically repair the heapbefore executing higher-level functions that may requireheap memory allocation. MOSDEF, however, does notencrypt the data in transit or payload code. Immunityalso provides a remote access trojan called Hydrogen thatuses RSA and Twofish to protect communications. TheHydrogen server executable contains an embedded RSAkey that is used to securely send the randomly generated

Page 3: An Encrypted Payload Protocol and Target-Side … Encrypted Payload Protocol and Target-Side Scripting Engine ... server-side logic, ... is a client-side penetration test against a

Twofish session key to the client. The Hydrogen serveris typically copied to the remote system using MOSDEFand executed [7].

An alternative approach is remote library injection.Remote library injection uses special linking and load-ing techniques to inject arbitrary shared libraries into aremote compromised process address space. The remotelibrary injection approach has been implemented for bothLinux ELF [8] and Windows DLL [9] and both imple-mentations are included in the Metasploit open-sourceexploit development framework [10]. The benefit of thisapproach is that arbitrarily complex payloads or exist-ing software can be easily re-linked and remotely exe-cuted. The existing implementations load the shared li-brary purely in memory without writing the library to theremote system’s hard drive.

The Metasploit project has implemented several pay-loads using DLL injection, including an injected VNCserver [11] for remote graphical control of the host, andthe Meterpreter [12], a dynamically extensible server-side scripted environment. The Meterpreter consists ofthe base Meterpreter library that is remotely injected intothe victim process, the interactive shell running on theattacker’s host, and custom extensions. Meterpreter ex-tensions add new functions to the Meterpreter shell thatare implemented as a combination of local scripting lan-guage code and a remotely injected library. The use ofa local scripting language (Ruby in Metasploit 3.0 andPerl in prior versions) allows payload functionality to berapidly developed and deployed on-the-fly. Meterpretercan optionally XOR-encode packets in order to evade In-trusion Detection System signatures.

In a different application but similar spirit, AdamYoung and Moti Yung have investigated many ways thatstrong cryptography can augment and prevent computerviruses [13].

3 Encrypted Payload Protocol

A professional penetration test should not expose the tar-geted client network to additional security risks in theprocess of the penetration test, even if the test is beingperformed across untrusted networks (i.e. the Internet).This includes not sufficiently protecting client data intransit to the penetration tester or using tools that open upadditional security vulnerabilities on the client’s networkduring the test. For example, an attacker on the Internetroute between a penetration tester and their client targetshould not be able to piggy-back on the penetration testin order to gain access to the client’s network. In addi-tion, the penetration tester may be employing proprietaryvulnerabilities, exploits, and techniques that should notbe compromised by an unauthorized attacker betweenthe penetration tester and the target network.

We define our attacker to be a passive traffic eaves-dropper or active traffic manipulator en route betweenthe penetration tester’s systems and the target client net-work, but not including an adversary on the client’s net-work or a honeypot target. Our penetration test scenariois a client-side penetration test against a client’s enter-prise network. Client-side penetration tests using weband e-mail based attacks are becoming more commonas Internet attackers have also been using these attacksmore and more in recent years. In addition, while Inter-net perimeter security is a relatively mature and under-stood discipline, client security is still a difficult problemfor most organizations.

An open problem with the existing exploit payloadsystems described above is cryptographically secure pay-load delivery and communication. Several of the systemsdescribed above transmit second-stage agent executablesover their first stage payload’s communication channels.While the second-stage agents employ strong cryptogra-phy to protect communications, they are sent in the clearover the unencrypted first stage payload communicationchannel. The executable agents are not polymorphic andmay easily be fingerprinted and identified by a signature-based intrusion detection system as they are transferredto the target system. Because they are easily identified,an active attacker capable of performing a man-in-the-middle attack could also modify the executables in transitto the target system. The attacker could do this to gainaccess to the compromised hosts without prior knowl-edge of the vulnerabilities or exploits used by the pen-etration tester. Even if the agent executable themselveswere made polymorphic, the custom protocols used todeliver them to the target system may still be identifiedand manipulated by an active attacker.

In a client-side penetration test, exploits are typicallydelivered as attachments to targeted e-mail messages oron web pages hosted on the penetration tester’s webserver. The attacks involve some amount of social engi-neering as the user must be convinced to open the e-mailmessage, attachment, or web page in order for the exploitto be attempted. Protecting the secrecy of these poten-tially proprietary exploits in use is a difficult problem thatthis work does not address. This work does, however,show how establishing a secure channel in the first stagepayload protects all communications beyond the deliv-ery of the exploit. This is sufficient to protect against apassive attacker. If the delivery of the exploit can be se-cured, for example, by sending exploit e-mails using Se-cure SMTP over TLS or hosting web-based exploits ona SSL web server with a certificate granted by a trustedroot certification authority, then the communications be-tween the penetration tester and target network can evenbe secured against an active attacker able to manipulatetraffic. This design provides a secure mechanism for de-

Page 4: An Encrypted Payload Protocol and Target-Side … Encrypted Payload Protocol and Target-Side Scripting Engine ... server-side logic, ... is a client-side penetration test against a

livering the later-stage exploit payloads, as well as a se-cure transport for payload and remote agent commandand control. This protects the penetration tester’s tools,mission logic, and remote target communications from apassive adversary. The polymorphic encoding of the ex-ploit and first-stage payload makes an active attack rea-sonably difficult, especially so if the exploit is deliveredover SSL.

3.1 Architecture

The payload delivery is executed in several stages in or-der to progressively establish more secure and capableexecution environments. In addition, a staged payloadsystem allows the bulk of high-level functionality to beimplemented in later stages that typically have less con-straints on their implementation. For example, the firststage payload, included in the code injection exploit, typ-ically must be implemented in hand-written assembly inorder to guarantee complete position-independent execu-tion. In addition, there may be byte value constraints onthe machine code encoding of the payload. This is typi-cally due to the fact that the payload is included with theinjection vector within a defined file format or networkprotocol. The most common example of this constraintis the inability to use the NULL byte in the payload sincethe value is also used as the ASCII string terminator. Toget around this, self-executing payload decoders are typ-ically used to convert an arbitrary machine code frag-ment into a string consisting of only “safe” byte values.More advanced encoders add polymorphism and restrictthe output byte set to printable ASCII, for example.

Our first stage payload initiates communication by ne-gotiating a shared key and establishing a secure chan-nel to the payload delivery server. The secure channel isestablished by the first stage payload in order to ham-per an active adversary desiring to identify and inter-fere with payload communications. This is done in thefirst stage because later stage communications may beeasier to identify and tamper with than the initial trans-mission of the actual code injection exploit. For exam-ple, consider that browser-based exploits may be deliv-ered over SSL and that exploit payloads typically em-ploy polymorphic self-decoders that may be difficult toidentify by signature-based network intrusion detection(IDS) and prevention (IPS) systems. In both cases, iden-tifying and intercepting the delivery of the initial exploitis difficult in principle and impossible using currentlyavailable commercial IPS technology. While technicallypossible, intercepting, decoding, and modifying a poly-morphic payload within an arbitrary exploit in transit isa very challenging task.

The secure payload delivery protocol was designed tominimize required code space for the first stage payload

Function x86 machine code bytesfp exptmod small 135fp rshd 173fp mulmod small 80fp mul comba 559s fp sub 336Total 1283

Figure 1: Cryptographic Routine Code Sizes

through the use of simple yet secure cryptographic oper-ations and algorithms. In addition, custom cryptographicroutines were chosen to maximize portability across tar-get operating systems. Our first stage payload estab-lishes the secure channel and must do so given the sizeconstraints of first stage code injection exploit payloads.The system uses ElGamal key agreement (alternativelyreferred to as Half-Certified Diffie Hellman [14]) to se-curely establish a session key with the payload serverand the RC4 stream cipher to encrypt communications.ElGamal key agreement was chosen because it requiresonly a single arbitrary-precision integer operation, mod-ular exponentiation. RC4 is also a very simple stream ci-pher, generating a keystream by swapping elements in itsinternal S-box. The use of public-key cryptography waschosen over traditional symmetric cryptography in orderto prevent a passive attacker from analyzing the initialexploit, recovering the key, and decrypting the subse-quent communications. Using public-key cryptographyto secure all communication prevents post-analysis by anadversary who has recorded all network traffic.

Both of these cryptosystems were also chosen for theirease of implementation in assembly language or low-level position-independent C. Modular exponentiation,the only mathematical operation required for ElGamalkey agreement, can be implemented compactly usingclassical methods or Montgomery exponentiation[14]for more efficiency. To estimate the code space re-quired for modular exponentiation, we modified an opensource fast fixed precision math library [15] to use somemore compact algorithms for modular exponentiationand multiplication. The compact modular exponentia-tion function fp exptmod small uses right-to-left bi-nary exponentiation[14]. The compact modular multipli-cation function fp mulmod small uses repeated sub-tractions rather than division for the modular reductionstep. The total size of the code required to implementmodular exponentiation is around 1200 bytes. The ex-act code sizes of the necessary routines are listed in table3.1.

The RC4 stream cipher, using a single S-box, maybe implemented very compactly. Most stream ciphersare optimized for hardware implementation, but RC4

Page 5: An Encrypted Payload Protocol and Target-Side … Encrypted Payload Protocol and Target-Side Scripting Engine ... server-side logic, ... is a client-side penetration test against a

requires the least number of operations on a general-purpose processor. Additional space required for the useof these cryptographic algorithms is dedicated to the sizeof the ElGamal public key, roughly twice the bit lengthof the prime modulus p. Using an elliptic curve cryp-tography equivalent of ElGamal key agreement wouldsave space for the key at the expense of increased im-plementation complexity and may actually require morecode space. Elliptic-curve cryptography is typically usedon devices with low processor power and little memoryso the increase in code space in return for smaller keysand thus less computationally intensive operations is areasonable trade-off. The target systems in our case areassumed to be modern computers with processor powerand memory sufficient for basic cryptographic opera-tions. The total payload size, including basic socket net-working, ElGamal key agreement, keys, and RC4 rou-tines is estimated to be under two kilobytes, assuming astraightforward x86 assembly language implementationand 1024-bit ElGamal.

The second stage is downloaded over the secure chan-nel created by the first stage and is executed in-placewithin the vulnerable process’ address space. The sec-ond stage executes free of code space constraints, butmay be executing in a damaged address space. This im-pediment is overcome by downloading and executing aremote agent executable, described in the next section.Each stage of the payload is described in more detail inthe following sections below.

3.2 Stage 1

The Stage 1 payload is the machine code componentincluded in the exploit delivered to the target’s webbrowser or local application. Many injection vectorshave limited space available for payload code, so the pri-mary purpose of the Stage 1 payload is to establish com-munication with a server controlled by the penetrationtester in order to download a subsequent stage payloadthat is free of code size constraints. The payload maybe wrapped in a polymorphic decoder in order to evadeintrusion detection and eliminate interpreted byte valuesfrom the exploit buffer.

The payload includes an ElGamal public key for thepayload server (generator g, prime modulus p, publicvalue x = ga mod p, where a is the secret expo-nent). The payload proceeds to complete the ElGamalkey agreement protocol and compute a session key foruse in communicating with the payload delivery server.The payload generates a random number b using anoperating-system provided secure random facility. OnWindows, RtlGenRandom from ADVAPI32.DLL canbe used to easily generate secure random bytes. Sim-ilarly, on Linux or other Unix-like operating systems

DecodePayload()b = Random() mod py = gˆb mod pk = xˆb mod pconn = Connect(server)Send(socket, y)iv = Read(conn)RC4Initialize(iv, k)While(KeepGoing == True)

length = Read(conn)If length == 0

Then KeepGoing = FalseBreak

EndRC4Decrypt(k, length)code = ReadBytes(conn, length)RC4Decrypt(k, code)result = Execute(code)Send(conn, result)

End

Figure 2: Stage 1 Payload Pseudocode

/dev/urandom can be read for secure random bytes.The payload then computes y = gb mod p using thegenerator g and prime modulus p from the server’s pub-lic key. The payload also computes the session keyk = xb = (ga)b = gab. Since g is a generator over Z∗

p

and b is cryptographically random, the computed sessionkey will have sufficient entropy. The payload proceedsto send y to the payload server and further communica-tion is encrypted using the session key k and the RC4stream cipher. The initial 256 bytes of RC4 keystreamare discarded[16] and separate RC4 keystreams are usedfor traffic in each direction in order to address weak-nesses in RC4. In addition, a random initialization vectoris used for each stream to prevent keystream reuse.

Finally, the Stage 1 payload enters a loop repeatedlydownloading, decrypting, and executing code from thepayload server.

3.3 Stage 2

The Stage 2 payload, executing as position independentmachine code fragments within the vulnerable process’address space, is free of the code space constraints ofthe Stage 1 payload, but there may still be other exe-cution environment constraints. For example, the ex-ploit may have corrupted the heap metadata and subse-quent heap operations may cause the process to crash.In these cases, the Stage 2 payload have to repair theheap before attempting to execute more complex op-erations that require explicit or implicit heap alloca-

Page 6: An Encrypted Payload Protocol and Target-Side … Encrypted Payload Protocol and Target-Side Scripting Engine ... server-side logic, ... is a client-side penetration test against a

RepairHeap()conn = Connect(server)iv = Read(conn)RC4Initialize(iv, k)f = OpenFileForWriting(AGENT)While(KeepGoing == True)

length = Read(conn)If (length == 0)

Then KeepGoing = FalseBreak

EndRC4Decrypt(k, length)buffer = ReadBytes(conn, length)RC4Decrypt(k, buffer)WriteToFile(f, buffer)

EndExecute(AGENT)

Figure 3: Stage 2 Payload Pseudocode

tion. Under Windows XP and later Windows operat-ing systems, the default heap can be quickly switched tothe low-fragmentation heap using HeapSetInformation(),thus abandoning the use of a potentially corrupted stan-dard default heap.

In order to fully escape execution and implementationconstraints, the Stage 2 payload proceeds to downloadand execute a binary executable from the payload server.In the current design, this executable is a specially-builtinterpreter for the Lua programming language, describedin the next section.

3.4 Limitations

As described above, the payload delivery protocol is notperfectly secure against an active attacker. Many of thedesign decisions were taken in order to hamper an ac-tive attacker, but preventing an active attack is not fea-sible when the delivery of the exploit is not secure. Forinstance, an active adversary could modify the first stagepayload to insert its own public key in the payload or pre-vent the generation or use of true random numbers. Theonly defense against this is the use of polymorphic self-decoders that make identification of the attack more diffi-cult. Alternatively, the penetration tester could host theirexploits on a secure web server with a certificate from atrusted root certification authority. This would secure thedelivery of the first-stage payload against modificationby an active attacker. However, later communication issubject to known-plaintext attacks. The described use ofRC4 does not guarantee integrity of the stream. An ac-tive attacker with knowledge of the plaintext can choosebytes in the decrypted stream. As described in the threat

model above, the system is not truly secure against anactive attacker, but takes reasonable effort to make an ac-tive attack difficult.

4 Target-Side Scripting

While the common targets of code execution exploitshave shifted from servers to client desktops and lap-tops, most available exploit payloads in commercial andopen-source penetration testing tools assume the targetremains at a fixed network location. This may not be thecase in many modern penetration tests. For example, theeasiest way into a network may be through compromis-ing a mobile laptop when it is associated to a “hot spot”wireless network. Existing penetration testing frame-works require that the target be continually reachable bythe penetration tester in order to maintain command andcontrol. An exploit payload that supports disconnectedoperation would allow the penetration tester to take ad-vantage of the target’s mobility in order to gain access toeach network that the client connects to.

Several of the existing exploit payload systems offerdynamic scripting support. All of this support, however,is for attacker-side script execution. The execution ofthese scripts require a constant network connection tothe penetration tester’s machine. This may be infeasiblewhen targeting mobile clients such as wireless laptops.In addition, attacker-side logic may require an infeasibleamount of input/output to the target. For example, con-sider a payload with file searching logic. With attacker-side logic, this would require a large amount of uninter-esting data to be downloaded to the attacker. Pushing thelogic onto the target allows the searching to be performedwhere the files are local. While attacker-side scripts pro-tect the payload logic, the cryptographic payload deliv-ery system described above adequately protects transportof target-side payload logic to the target. The scriptingengine could implement a similar cryptographic proto-col or use an available SSL implementation to downloadscripts from the penetration tester.

The Lua programming language [17] was chosen asthe target-side scripting language. Lua has many bene-fits for this type of application. Its interpreter is small(roughly 200k), very portable by virtue of a pure ANSIC implementation, and the Lua language is quite flexi-ble and powerful. Lua has been historically popular as ascripting and extensibility language for games, howeverrecently many open source security tools have begun touse it as well (Wireshark [18], NMAP [19], and Snort[20]).

The specific Lua interpreter chosen for the target-side scripting environment includes the C/Invoke [21] li-brary, the LuaSocket [22] library, and the custom crypto-graphic routines used in the previously described secure

Page 7: An Encrypted Payload Protocol and Target-Side … Encrypted Payload Protocol and Target-Side Scripting Engine ... server-side logic, ... is a client-side penetration test against a

U32 = clibrary.new("user32.dll","stdcall")

MessageBox = U32:get_function(Cint,"MessageBoxA", Cptr, Cstring,Cstring, Cint32)

MessageBox(0, "Hello World", "Lua", 0)

Figure 4: Lua C/Invoke Win32 API Example

payloads. This C/Invoke library allows purely scriptedcode to load and call into arbitrary dynamic library func-tions. C/Invoke supports marshaling basic types (ma-chine types and strings), structures, and even supportscallback functions written in Lua. For these reasons, itwas chosen as an ideal dynamic interface to the systemAPIs. As an example, the Lua programmer would use thecode in figure 4 to load the Win32 MessageBox() func-tion and call it.

The LuaSocket library provides interfaces for TCPand UDP sockets as well as higher level protocols likeHTTP, SMTP, and FTP. Combined with the included El-Gamal key agreement and RC4 encryption routines, Lu-aSocket’s network access can be used to establish secureconnections back to the penetration tester for further in-structions and to send back encrypted results. At present,the cryptographic support is limited to key agreementand symmetric encryption. This is enough, however, toprotect the communication against eavesdropping.

The flexibility offered by the Lua scripting environ-ment with full system library access allows the payloadauthor to rapidly develop and deploy arbitrarily complexpayloads. In addition, their implementation as purelytextual scripting code allows them to be easily encrypted,signed, downloaded, and stored. Further work will buildupon the customized Lua interpreter to build richer cryp-tographic capabilities.

In the section that follows, we describe several pay-loads that are difficult or impossible to implement withexisting penetration testing tools but straightforwardwith a target-side scripting payload such as the one de-scribed. These payloads may also be implemented asfree-standing executables, but there are several benefitsto implementing them in a target-side payload scriptingenvironment. As scripts, they are more transient than ex-ecutables. For example, script code is easier to down-load and execute on-the-fly whereas an executable mustbe saved to disk first. This facilitates cleaning up targetsystems after the penetration testing engagement termi-nates. The target-side agent could even be configured toautomatically remove itself and any downloaded scriptsand data at a certain time coinciding with the end of thepenetration test.

4.1 Example Payloads

Building rich logic into target-side scripts allows rapiddevelopment of payloads that are better suited for client-side penetration tests. These payloads may take advan-tage of the fact that they may execute without a perma-nent network connection to the penetration tester. Thisis useful when attacking mobile clients such as laptopson wireless “hot spot” networks. For example, it maybe easiest to compromise an internal network by com-promising a laptop with access to that network when thelaptop is associated to a “hot spot” wireless network in acoffee shop, airport, or hotel.

An ideal payload for a mobile client would connectback to the penetration tester from whatever network theclient was connected to. The payload could monitor thestate of the network interfaces, and whenever a networkinterface became active, it would “phone home” to aserver on the Internet. The payload could be configuredto automatically terminate at a certain date, coincidingwith the end of the penetration testing engagement.

A second payload style that takes advantage of thetarget-side logic is the “file searcher” payload. This pay-load would search local documents and files on the targetsystems’ hard drives for key words or patterns. Matchingfiles would be collected, encrypted, and sent to the pen-etration tester for analysis. Performing the file searchingon the target prevents excessive amounts of file data frombeing sent across the network.

Finally, remote target-side payloads could scan theremote network for other vulnerabilities or automati-cally gain access to other remote systems. For exam-ple, a long running password brute force may be unrea-sonable to launch when the penetration tester must becontinually connected to the target system. If the pro-cess were run autonomously on a compromised system,the attack could proceed disconnected and report resultsasynchronously. A similar model would be beneficialfor other long-running attacks such as network sniffingand hosting web exploits on the target network. Hostingweb exploits on the target’s internal network typicallygrants the attacker some level of privilege escalation asthe exploits are placed within Internet Explorer’s LocalIntranet security zone thus gaining additional privilegesover an Internet-based web attack.

5 Conclusion

The payload described above established an encryptedchannel that is secure against passive eavesdropping dur-ing or after the attack. It is not, however, perfectly se-cure against a malicious user able to perform a man-in-the-middle attack because the public key of the payloaddelivery server is included in the exploit. However, an

Page 8: An Encrypted Payload Protocol and Target-Side … Encrypted Payload Protocol and Target-Side Scripting Engine ... server-side logic, ... is a client-side penetration test against a

attacker taking advantage of this must be able to activelyidentify and intercept the exploit as it is being deliveredto the target. This is somewhat unlikely as it requiresan exact signature for the specific exploit being used ora means to identify, simulate, and replace polymorphicself-decoding executable code.

Assuming that the exploit delivery has not been tam-pered with, the delivery and communication of the target-side scripting system is secure against both eavesdrop-ping and man-in-the-middle attacks. An active attackerwith knowledge of the plaintext may, however, modifythose bytes within the RC4 encrypted streams. The de-livered executable does nothing to protect itself againstrecovery from the target filesystem. This is typically notan issue in professional penetration testing and intention-ally makes the payload unsuitable for illicit activities.The mission-logic encapsulated in Lua script, however,is never written to disk and is secure against eavesdrop-ping and filesystem recovery.

Future work will enrich the capabilities of the systemto perform in-memory Lua interpreter injection and im-plement richer cryptographic support within the Lua in-terpreter. In addition, research into secure asynchronouscommand and control protocols would provide an idealremote management system for deployed payloads. Theauthor believes that penetration-testing techniques andtools must grow to resemble the Internet attacker tech-nology used in drive-by downloads, botnets, and e-mailattacks in order to better evaluate an organization’s de-fenses against these threats.

References

[1] P.-H. Kamp and R. N. M. Watson, “Jails: Confin-ing the omnipotent root,” in Proceedings of the 2ndInternational SANE Conference, 2000.

[2] K. J. Biba, “Integrity considerations for securecomputer systems,” Tech. Rep. MTR-3153, TheMitre Corporation, April 1977.

[3] M. Caceres, “Syscall proxying - simulating re-mote execution.” CORE Security Technical Report,2002.

[4] CORE Security Technologies, “Impact.”http://www.coresecurity.com/products/coreimpact/.

[5] Immunity Security, “Canvas.”http://www.immunitysec.com/products-canvas.shtml.

[6] D. Aitel, “Mosdef,” in BlackHat Briefings Federal,2003.

[7] D. Aitel. personal communication, July 2007.

[8] A. E. Cuttergo, “The joys of impurity.”http://archives.neohapsis.com/archives/vuln-dev/2003-q4/0006.html, October 2003.

[9] M. Miller and J. Turkulainen,“Remote library injection.”http://www.nologin.net/Downloads/Papers/remote-library-injection.pdf.

[10] Metasploit Project, “Metasploit framework.”http://www.metasploit.org.

[11] AT&T Laboratories Cambridge, “Virtual networkcomputing.” http://www.cl.cam.ac.uk/research/dtg/attarchive/vnc/.

[12] M. Miller, “Metasploit’s meterpreter.”http://www.nologin.org/Downloads/Papers/ meter-preter.pdf, December 2004.

[13] A. Young and M. Yung, Malicious Cryptography:Exposing Cryptovirology. Wiley, 2004.

[14] S. A. V. Alfred J. Menezes, Paul C. van Oorschot,Handbook of Applied Cryptography. CRC, 1996.

[15] T. S. Denis, “Tomsfastmath.” http://libtom.org.

[16] S. Fluhrer, I. Mantin, and A. Shamir, “Weaknessesin the key scheduling algorithm of RC4,” EighthAnnual Workshop on Selected Areas in Cryptogra-phy, August 2001.

[17] L. H. d. F. Roberto Lerusalimschy, Walde-mar Celes, “The programming language lua.”http://www.lua.org.

[18] G. Combs, “Wireshark network analyzer.”http://www.wireshark.org.

[19] Fyodor, “Nmap security scanner.”http://www.insecure.org/nmap/.

[20] M. Roesch, “Snort network intrusion detection sys-tem.” http://www.snort.org.

[21] W. Weisser, “C/invoke.”http://www.nongnu.org/cinvoke/.

[22] D. Nehab, “Luasocket: Networksupport for the lua language.”http://www.cs.princeton.edu/ diego/professional/luasocket/.