RFC 3489

STUN - Simple Traversal of User Datagram Protocol (UDP) Through Network Address Translators (NATs)

๐Ÿ“… published March 2003, from ietf

RFC 3489 ๐Ÿ’– STUN: Simple Traversal of User Datagram Protocol (UDP) Through Network Address Translators (NATs) โœจ

Okay bestie, this is the RFC that gave us STUN, which is basically how apps get through NATs without asking the NATs for permission. It's a whole vibe ๐Ÿฆ‹

Here's the title block tea โ˜•:

  • Stream: Network Working Group
  • RFC number: 3489
  • Authors: J. Rosenberg (dynamicsoft), J. Weinberger (dynamicsoft), C. Huitema (Microsoft), R. Mahy (Cisco)
  • Category: Standards Track ๐Ÿ‘‘
  • Date: March 2003
  • Obsoletes / Updates: the title block doesn't have an Obsoletes or Updates line, so there's nothing listed there ๐ŸŒธ

Status of This Memo ๐Ÿ“œ

So this doc is a standards track protocol for the whole Internet community ๐ŸŒ and it's asking everyone to talk about it and send ideas for making it better ๐Ÿ—ฃ๏ธ. If you want the official standardization state and status of this protocol, check the current edition of "Internet Official Protocol Standards" (STD 1) ๐Ÿ’…. And yes, you can share this memo as much as you want, distribution is unlimited โœจ.

Copyright (C) The Internet Society (2003). All Rights Reserved. ๐Ÿซถ

Abstract ๐ŸŒŸ

Simple Traversal of User Datagram Protocol (UDP) Through Network Address Translators (NATs) (STUN) is a lightweight protocol ๐Ÿชถ that helps apps figure out whether NATs and firewalls are sitting between them and the public Internet, and what kind of NATs they are ๐Ÿ”. It also lets apps find out which public Internet Protocol (IP) addresses the NAT gave them ๐ŸŽ€. The best part? STUN works with lots of NATs that already exist, and it doesn't need them to do anything special ๐Ÿ™Œ. So a wide variety of apps can get through the NAT infrastructure we already have. Iconic ๐Ÿ’–.

Table of Contents ๐Ÿ—‚๏ธ

   1.   Applicability Statement ...................................    3
   2.   Introduction ..............................................    3
   3.   Terminology ...............................................    4
   4.   Definitions ...............................................    5
   5.   NAT Variations ............................................    5
   6.   Overview of Operation .....................................    6
   7.   Message Overview ..........................................    8
   8.   Server Behavior ...........................................   10
        8.1   Binding Requests ....................................   10
        8.2   Shared Secret Requests ..............................   13
   9.   Client Behavior ...........................................   14
        9.1   Discovery ...........................................   15
        9.2   Obtaining a Shared Secret ...........................   15
        9.3   Formulating the Binding Request .....................   17
        9.4   Processing Binding Responses ........................   17
   10.  Use Cases .................................................   19
        10.1  Discovery Process ...................................   19
        10.2  Binding Lifetime Discovery ..........................   21
        10.3  Binding Acquisition .................................   23
   11.  Protocol Details ..........................................   24
        11.1  Message Header ......................................   25
        11.2  Message Attributes ..................................   26
              11.2.1  MAPPED-ADDRESS ..............................   27
              11.2.2  RESPONSE-ADDRESS ............................   27
              11.2.3  CHANGED-ADDRESS .............................   28
              11.2.4  CHANGE-REQUEST ..............................   28
              11.2.5  SOURCE-ADDRESS ..............................   28
              11.2.6  USERNAME ....................................   28
              11.2.7  PASSWORD ....................................   29
              11.2.8  MESSAGE-INTEGRITY ...........................   29
              11.2.9  ERROR-CODE ..................................   29
              11.2.10 UNKNOWN-ATTRIBUTES ..........................   31
              11.2.11 REFLECTED-FROM ..............................   31
   12.  Security Considerations ...................................   31
        12.1  Attacks on STUN .....................................   31
              12.1.1  Attack I: DDOS Against a Target .............   32
              12.1.2  Attack II: Silencing a Client ...............   32
              12.1.3  Attack III: Assuming the Identity of a Client   32
              12.1.4  Attack IV: Eavesdropping ....................   33
        12.2  Launching the Attacks ...............................   33
              12.2.1  Approach I: Compromise a Legitimate
                      STUN Server .................................   33
              12.2.2  Approach II: DNS Attacks ....................   34
              12.2.3  Approach III: Rogue Router or NAT ...........   34
              12.2.4  Approach IV: MITM ...........................   35
              12.2.5  Approach V: Response Injection Plus DoS .....   35
              12.2.6  Approach VI: Duplication ....................   35
        12.3  Countermeasures .....................................   36
        12.4  Residual Threats ....................................   37
   13.  IANA Considerations .......................................   38
   14.  IAB Considerations ........................................   38
        14.1  Problem Definition ..................................   38
        14.2  Exit Strategy .......................................   39
        14.3  Brittleness Introduced by STUN ......................   40
        14.4  Requirements for a Long Term Solution ...............   42
        14.5  Issues with Existing NAPT Boxes .....................   43
        14.6  In Closing ..........................................   43

   15.  Acknowledgments ...........................................   44
   16.  Normative References ......................................   44
   17.  Informative References ....................................   44
   18.  Authors' Addresses ........................................   46
   19.  Full Copyright Statement...................................   47

1. Applicability Statement ๐ŸŽฏ

Real talk, STUN is not a cure-all for NAT problems ๐Ÿ™…โ€โ™€๏ธ. It doesn't let incoming TCP connections through NAT ๐Ÿšซ. It does let incoming UDP packets through NAT, but only through some of the NAT types out there ๐Ÿงฉ. In particular, STUN can't get incoming UDP packets through symmetric NATs (defined below), and those are super common in big enterprises ๐Ÿข๐Ÿ’€.

STUN's discovery steps are built on assumptions about how NATs treat UDP. Those assumptions might stop being true later on as new NAT devices get deployed ๐Ÿ˜ฌ. STUN also doesn't work when you use it to find an address for talking to a peer who's behind the same NAT ๐Ÿ™ˆ. And it doesn't work if the STUN server isn't in a common shared address realm ๐ŸŒ€. For the full tea on STUN's limitations, see Section 14 ๐Ÿ’….

2. Introduction ๐ŸŒธ

Okay so NATs are super useful, but they come with a lot of drawbacks ๐Ÿ˜ค. The biggest one is that they break tons of existing IP apps and make it hard to ship new ones ๐Ÿ’”. There are guidelines [8] for building "NAT friendly" protocols, but honestly, a lot of protocols just can't be built that way ๐Ÿ™ƒ. The big examples are almost all peer-to-peer protocols, like multimedia communications, file sharing, and games ๐ŸŽฎ.

To fix this, people put Application Layer Gateways (ALGs) inside NATs ๐Ÿ› ๏ธ. An ALG does the application layer work a protocol needs in order to get through a NAT ๐Ÿง . Usually that means rewriting application layer messages so they contain the translated addresses instead of the ones the sender put in โœ๏ธ. ALGs have serious issues though, like scalability, reliability, and how slow it is to roll out new apps ๐Ÿข. So the Middlebox Communications (MIDCOM) protocol is being developed [9] โœจ. With MIDCOM, an application entity, like an end client or a network server such as a Session Initiation Protocol (SIP) proxy [10], can control a NAT (or firewall) to get NAT bindings and open or close pinholes ๐Ÿ•ณ๏ธ. That way NATs and apps can be split apart again, no more ALGs living inside NATs, and the limits of today's architectures get fixed ๐ŸŽ‰.

BUT. MIDCOM needs upgrades to existing NAT and firewall boxes, on top of app components ๐Ÿ˜ฉ. Those upgrades could take years, because the people who deploy NATs and firewalls aren't the same people who deploy and use apps ๐Ÿ™„. So a lot of the time, nobody has a reason to upgrade โš ๏ธ. Picture an airport Internet lounge that gives access through a NAT ๐Ÿ›ซ. A user on that NATed network wants a peer-to-peer service and can't use it, because the NAT doesn't support it โœˆ๏ธ. The lounge admins aren't the ones providing that service, so they've got zero motivation to upgrade their NAT gear with an ALG or MIDCOM ๐Ÿคทโ€โ™€๏ธ.

Another problem: MIDCOM needs the agent controlling the middleboxes to know who those middleboxes are, and to have a control relationship with them ๐Ÿ”‘. In lots of setups, that just isn't possible ๐Ÿšง. For example, plenty of cable access providers put a NAT in front of their whole access network ๐Ÿ“ก. There might also be a residential NAT that the end user bought and runs ๐Ÿ . The end user probably has no control relationship with the NAT in the cable network, and might not even know it exists ๐Ÿ‘€.

Lots of existing proprietary protocols, like the ones for online games (the games described in RFC 3027 [11]) and Voice over IP, have come up with tricks to work through NATs without changing those NATs ๐Ÿงš. This document takes some of those ideas and codifies them into an interoperable protocol that can meet the needs of lots of apps ๐Ÿ’œ.

So here's the protocol, Simple Traversal of UDP Through NAT (STUN) ๐Ÿฆ‹. It lets entities behind a NAT first find out that a NAT exists and what type it is, and then learn the address bindings the NAT allocated ๐Ÿ”. STUN needs no changes to NATs ๐Ÿ™Œ, and it works with any number of NATs stacked up between the app entity and the public Internet ๐Ÿฅž.

3. Terminology ๐Ÿ“š

Here's the key vocab, bestie ๐Ÿ’…. In this document, the key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" are to be interpreted as described in BCP 14, RFC 2119 [1], and they indicate requirement levels for compliant STUN implementations ๐ŸŽ€.

4. Definitions ๐Ÿงพ

Let's define the main characters ๐Ÿ‘‘:

STUN Client: A STUN client (also just referred to as a client) is an entity that generates STUN requests ๐Ÿ“ค. A STUN client can run on an end system, like a user's PC, or it can run in a network element, like a conferencing server ๐Ÿ–ฅ๏ธ.

STUN Server: A STUN Server (also just referred to as a server) is an entity that receives STUN requests and sends STUN responses ๐Ÿ“ฅ. STUN servers are generally attached to the public Internet ๐ŸŒ.

Part 1 of 11 done, bestie ๐Ÿซถ more parts are coming, so stay tuned ๐Ÿงšโ€โ™€๏ธ๐Ÿ’–

5. NAT Variations ๐Ÿ’…

okay so it's assumed you already know what NATs are, bestie ๐Ÿซถ apparently NAT handling of UDP is kind of all over the place between implementations. there are four treatments that show up in the wild, and they're honestly iconic in their own way ๐Ÿฆ‹

  • Full Cone: every request from the same internal IP address and port gets mapped to the same external IP address and port. And any external host can send a packet to the internal host just by sending it to that mapped external address. no notes, very open ๐ŸŒธ
  • Restricted Cone: every request from the same internal IP address and port gets mapped to the same external IP address and port too. the difference is that an external host (with IP address X) can only send a packet to the internal host if the internal host had already sent a packet to IP address X. it's giving bouncer energy ๐Ÿ’€
  • Port Restricted Cone: this one is like restricted cone, but now the port numbers get a say too ๐Ÿ™ˆ an external host can send a packet, with source IP address X and source port P, to the internal host only if the internal host had already sent a packet to IP address X and port P. very specific, very into it โœจ
  • Symmetric: all requests from the same internal IP address and port, going to one specific destination IP address and port, get mapped to the same external IP address and port. if that same host sends a packet with the same source address and port but to a different destination, it gets a different mapping. and only the external host that actually received a packet can send a UDP packet back to the internal host. main character energy but make it lonely ๐Ÿฅบ

knowing which type of NAT you're dealing with really matters ๐Ÿ”ฅ depending on what the application wants to do, it might need to take that particular behavior into account. don't skip this part, it's the whole plot ๐Ÿ’œ


6. Overview of Operation ๐Ÿงš

this section is just descriptive ๐ŸŒˆ the actual rules (the normative stuff) live in Sections 8 and 9, so don't go looking for them here ๐ŸŽ€

Here's the typical STUN setup, shown in Figure 1 โœจ

                        /-----\
                      // STUN  \\
                     |   Server  |
                      \\       //
                        \-----/


                   +--------------+             Public Internet
   ................|     NAT 2    |.......................
                   +--------------+


                   +--------------+             Private NET 2
   ................|     NAT 1    |.......................
                   +--------------+

                        /-----\
                      // STUN  \\
                     |   Client  |
                      \\       //               Private NET 1
                        \-----/

                 Figure 1: STUN Configuration

so the setup goes like this ๐Ÿ’– a STUN client sits on private network 1. that network hooks up to private network 2 through NAT 1. private network 2 then reaches the public Internet through NAT 2. and the STUN server lives out on the public Internet ๐ŸŒธ

STUN is a simple client-server protocol, so it's really just a client sending a request and a server sending back a response ๐Ÿซถ there are two kinds of requests. Binding Requests go over UDP, and Shared Secret Requests go over TLS [2] on top of TCP. the Shared Secret ones ask the server for a temporary username and password. that username and password then get used in a later Binding Request and Binding Response for authentication and message integrity ๐Ÿ”

Binding Requests are how you figure out what bindings the NATs have handed out ๐Ÿฆ‹ the client sends a Binding Request to the server over UDP. the server looks at the source IP address and port of that request and copies them into a response, which goes back to the client. there are also some parameters in the request that let the client ask for the response to be sent somewhere else, or ask the server to send the response from a different address and port ๐Ÿ‘‘ and there are attributes for message integrity and authentication too.

the trick? using STUN to figure out that a NAT is even there, and then learning and using the bindings it created ๐Ÿงš๐Ÿ’œ

the STUN client usually lives inside an application that needs a public IP address and port it can receive data on โœจ like, it might need one to get Real Time Transport Protocol (RTP) [12] traffic. when the application starts, the STUN client inside it sends a STUN Shared Secret Request to its server, gets a username and password, and then sends a Binding Request ๐Ÿ’… STUN servers can be found through DNS SRV records [3], and it's generally assumed the client has been configured with the domain it should use to find the STUN server ๐ŸŒˆ usually that's the domain of the provider of whatever service the app is using, because that provider is incentivized to run STUN servers so its customers can use the app through NAT ๐Ÿซถ a client can also figure out a STUN server's address or domain name some other way, of course. and a STUN server can even be embedded inside an end system โœจ

the STUN Binding Request is how you discover that a NAT is present, and how you find out the public IP address and port mappings the NAT made ๐Ÿ”ฅ Binding Requests go to the STUN server over UDP. when one arrives at the server, it may have passed through one or more NATs between the client and the server ๐Ÿ’€ so the source address the server sees will be the mapped address created by whichever NAT is closest to the server. the STUN server copies that source IP address and port into a STUN Binding Response and sends it back to the source IP address and port of the STUN request. for every NAT type listed above, that response will reach the STUN client ๐ŸŽ€

when the STUN client gets the Binding Response, it compares the IP address and port in the packet with the local IP address and port it was bound to when it sent the request ๐Ÿ‘€ if they don't match, the client is behind one or more NATs. with a full-cone NAT, the IP address and port in the body of the STUN response are public, so any host on the public Internet can send packets to the application that sent the STUN request ๐Ÿฆ‹ the application only has to listen on the IP address and port the STUN request was sent from. any packets a public Internet host sends to the public address and port learned through STUN will get received by the application ๐Ÿ’–

but wait, the host might not be behind a full-cone NAT ๐Ÿ˜ญ and it doesn't know yet what kind of NAT it's behind. to find out, the client uses more STUN Binding Requests. the exact procedure is flexible, but it generally goes like this. the client sends a second STUN Binding Request, this time to a different IP address, but from the same source IP address and port. if the IP address and port in that response are different from the first response, the client knows it's behind a symmetric NAT ๐ŸŒธ to check for a full-cone NAT, the client can send a STUN Binding Request with flags telling the STUN server to send the response from a different IP address and port than the one the request arrived on. in other words, if the client sent a Binding Request to IP address/port A/B from a source of X/Y, the STUN server would send the Binding Response to X/Y from IP address/port C/D. if the client gets that response, it knows it's behind a full-cone NAT ๐Ÿ™Œ

STUN also lets the client ask the server to send the Binding Response from the same IP address the request came in on, but from a different port ๐Ÿงš that's how you can tell whether the client is behind a port restricted cone NAT or just a restricted cone NAT ๐Ÿ’…

one more thing ๐Ÿซถ the configuration in Figure 1 is NOT the only possible one. the STUN server can be pretty much anywhere, even inside another client ๐ŸŒˆ the only real requirements are that the client can reach the STUN server, and that if the client is trying to get a publicly routable address, the server has to sit on the public Internet ๐Ÿ”ฅ

7. Message Overview โœจ

okay so STUN messages are TLV (type-length-value) encoded, using big endian (network ordered) binary ๐Ÿค“ Every STUN message starts with a STUN header, followed by a STUN payload ๐ŸŽ€ The payload is a series of STUN attributes, and which ones show up depends on the message type. The STUN header holds a STUN message type, a transaction ID, and a length. The message type can be Binding Request, Binding Response, Binding Error Response, Shared Secret Request, Shared Secret Response, or Shared Secret Error Response ๐Ÿ’– The transaction ID is how you match up requests and responses. The length is the total length of the STUN payload, not counting the header. This is what lets STUN run over TCP ๐Ÿฆ‹ Shared Secret Requests are always sent over TCP (indeed, using TLS over TCP) ๐Ÿ”’

Several STUN attributes are defined ๐ŸŒธ First up is MAPPED-ADDRESS, which is an IP address and port. It's always placed in the Binding Response, and it shows the source IP address and port the server saw in the Binding Request. Then there's RESPONSE-ADDRESS, which also contains an IP address and port. RESPONSE-ADDRESS can be present in the Binding Request, and it tells you where the Binding Response should go. It's optional, and when it's not present, the Binding Response goes to the source IP address and port of the Binding Request.

The third attribute is CHANGE-REQUEST, and it holds two flags that control the IP address and port used to send the response. These flags are called "change IP" and "change port" flags. CHANGE-REQUEST is only allowed in the Binding Request. The "change IP" and "change port" flags are useful for figuring out whether the client is behind a restricted cone NAT or restricted port cone NAT ๐Ÿ‘€ They tell the server to send the Binding Responses from a different source IP address and port. CHANGE-REQUEST is optional in the Binding Request.

The fourth attribute is CHANGED-ADDRESS. It shows up in Binding Responses, and it tells the client the source IP address and port that would be used if the client asked for the "change IP" and "change port" behavior ๐Ÿงš

The fifth attribute is SOURCE-ADDRESS, and it's only present in Binding Responses. It shows the source IP address and port the response was sent from. It's useful for spotting twice NAT configurations ๐Ÿ™ˆ

The sixth attribute is USERNAME. It's present in a Shared Secret Response, which gives the client a temporary username and password (the password is encoded in the PASSWORD attribute). USERNAME is also present in Binding Requests, where it acts as an index to the shared secret used for the integrity protection of the Binding Request. The seventh attribute, PASSWORD, is only found in Shared Secret Response messages. The eighth attribute is MESSAGE-INTEGRITY, which contains a message integrity check over the Binding Request or Binding Response ๐Ÿ”

The ninth attribute is ERROR-CODE. It's present in the Binding Error Response and Shared Secret Error Response, and it tells you what error has occurred ๐Ÿ˜ญ The tenth attribute is UNKNOWN-ATTRIBUTES, which is present in either the Binding Error Response or Shared Secret Error Response. It lists the mandatory attributes from the request that were unknown ๐Ÿ’€ The eleventh attribute is REFLECTED-FROM, which is present in Binding Responses. It gives the IP address and port of the sender of a Binding Request, used for traceability purposes to prevent certain denial-of-service attacks ๐Ÿ›ก๏ธ


8. Server Behavior ๐Ÿ’…

The server behavior depends on whether the request is a Binding Request or a Shared Secret Request ๐Ÿ‘‘

8.1. Binding Requests ๐ŸŽ€

A STUN server MUST be prepared to receive Binding Requests on four address/port combinations - (A1, P1), (A2, P1), (A1, P2), and (A2, P2). (A1, P1) is the primary address and port, and these are the ones obtained through the client discovery procedures below ๐Ÿงš Typically, P1 will be port 3478, the default STUN port. A2 and P2 are arbitrary. A2 and P2 are advertised by the server through the CHANGED-ADDRESS attribute, as described below.

It is RECOMMENDED that the server check the Binding Request for a MESSAGE-INTEGRITY attribute. If it's not present, and the server requires integrity checks on the request, it generates a Binding Error Response with an ERROR-CODE attribute with response code 401. If the MESSAGE-INTEGRITY attribute was present, the server computes the HMAC over the request as described in Section 11.2.8. The key to use depends on the shared secret mechanism. If the STUN Shared Secret Request was used, the key MUST be the one associated with the USERNAME attribute present in the request. If the USERNAME attribute was not present, the server MUST generate a Binding Error Response. The Binding Error Response MUST include an ERROR-CODE attribute with response code 432. If the USERNAME is present, but the server doesn't remember the shared secret for that USERNAME (because it timed out, for example), the server MUST generate a Binding Error Response. The Binding Error Response MUST include an ERROR-CODE attribute with response code 430. If the server does know the shared secret, but the computed HMAC differs from the one in the request, the server MUST generate a Binding Error Response with an ERROR-CODE attribute with response code 431. The Binding Error Response is sent to the IP address and port the Binding Request came from, and sent from the IP address and port the Binding Request was sent to. ๐Ÿ”

Assuming the message integrity check passed, processing continues. The server MUST check for any attributes in the request with values less than or equal to 0x7fff which it does not understand. If it encounters any, the server MUST generate a Binding Error Response, and it MUST include an ERROR-CODE attribute with a 420 response code.

That response MUST contain an UNKNOWN-ATTRIBUTES attribute listing the attributes with values less than or equal to 0x7fff which were not understood. The Binding Error Response is sent to the IP address and port the Binding Request came from, and sent from the IP address and port the Binding Request was sent to.

Assuming the request was correctly formed, the server MUST generate a single Binding Response. The Binding Response MUST contain the same transaction ID contained in the Binding Request. The length in the message header MUST contain the total length of the message in bytes, excluding the header. The Binding Response MUST have a message type of "Binding Response".

The server MUST add a MAPPED-ADDRESS attribute to the Binding Response. The IP address component of this attribute MUST be set to the source IP address observed in the Binding Request. The port component of this attribute MUST be set to the source port observed in the Binding Request. ๐Ÿ“

If the RESPONSE-ADDRESS attribute was absent from the Binding Request, the destination address and port of the Binding Response MUST be the same as the source address and port of the Binding Request. Otherwise, the destination address and port of the Binding Response MUST be the value of the IP address and port in the RESPONSE-ADDRESS attribute.

The source address and port of the Binding Response depend on the value of the CHANGE-REQUEST attribute and on the address and port the Binding Request was received on, and they're summarized in Table 1 ๐Ÿ’–

Let Da represent the destination IP address of the Binding Request (which will be either A1 or A2), and Dp represent the destination port of the Binding Request (which will be either P1 or P2). Let Ca represent the other address, so that if Da is A1, Ca is A2. If Da is A2, Ca is A1. Similarly, let Cp represent the other port, so that if Dp is P1, Cp is P2. If Dp is P2, Cp is P1.

If the "change port" flag was set in the CHANGE-REQUEST attribute of the Binding Request, and the "change IP" flag was not set, the source IP address of the Binding Response MUST be Da and the source port of the Binding Response MUST be Cp. If the "change IP" flag was set in the Binding Request, and the "change port" flag was not set, the source IP address of the Binding Response MUST be Ca and the source port of the Binding Response MUST be Dp. When both flags are set, the source IP address of the Binding Response MUST be Ca and the source port of the Binding Response MUST be Cp. If neither flag is set, or if the CHANGE-REQUEST attribute is absent entirely, the source IP address of the Binding Response MUST be Da and the source port of the Binding Response MUST be Dp.

   Flags          Source Address  Source Port   CHANGED-ADDRESS
   none           Da              Dp            Ca:Cp
   Change IP      Ca              Dp            Ca:Cp
   Change port    Da              Cp            Ca:Cp
   Change IP and
     Change port  Ca              Cp            Ca:Cp

Table 1: Impact of Flags on Packet Source and CHANGED-ADDRESS ๐Ÿ“Š

The server MUST add a SOURCE-ADDRESS attribute to the Binding Response, containing the source address and port used to send the Binding Response.

The server MUST add a CHANGED-ADDRESS attribute to the Binding Response. This contains the source IP address and port that would be used if the client had set the "change IP" and "change port" flags in the Binding Request. As summarized in Table 1, these are Ca and Cp, respectively, regardless of the value of the CHANGE-REQUEST flags.

If the Binding Request contained both the USERNAME and MESSAGE-INTEGRITY attributes, the server MUST add a MESSAGE-INTEGRITY attribute to the Binding Response. The attribute contains an HMAC [13] over the response, as described in Section 11.2.8. The key to use depends on the shared secret mechanism. If the STUN Shared Secret Request was used, the key MUST be the one associated with the USERNAME attribute present in the Binding Request. ๐Ÿ”

If the Binding Request contained a RESPONSE-ADDRESS attribute, the server MUST add a REFLECTED-FROM attribute to the response. If the Binding Request was authenticated using a username obtained from a Shared Secret Request, the REFLECTED-FROM attribute MUST contain the source IP address and port where that Shared Secret Request came from. If the username present in the request was not allocated using a Shared Secret Request, the REFLECTED-FROM attribute MUST contain the source address and port of the entity which obtained the username, as best can be verified with the mechanism used to allocate the username. If the username was not present in the request, and the server was willing to process the request, the REFLECTED-FROM attribute SHOULD contain the source IP address and port where the request came from. ๐Ÿชž

The server SHOULD NOT retransmit the response. Reliability is achieved by having the client periodically resend the request, each of which triggers a response from the server ๐Ÿ”

8.2 Shared Secret Requests โœจ

Shared Secret Requests are always received on TLS connections ๐Ÿ”. When the server gets a request from the client to set up a TLS connection, it MUST proceed with TLS, and SHOULD present a site certificate. The ciphersuite TLS_RSA_WITH_AES_128_CBC_SHA [4] SHOULD be used. Client TLS authentication MUST NOT be done, bestie, because the server isn't handing out any resources to clients, and the computational burden can be a source of attacks ๐Ÿ’€.

If the server gets a Shared Secret Request, it MUST verify that the request arrived on a TLS connection ๐Ÿ›ก๏ธ. If it didn't come in over TLS, it MUST generate a Shared Secret Error Response and MUST include an ERROR-CODE attribute with a 433 response code. Where the error goes depends on the transport the request came in on. For TCP, the Shared Secret Error Response goes back over the same connection the request arrived on. For UDP, it goes to the source IP address and port that the request came from.

The server MUST check for any attributes in the request with values less than or equal to 0x7fff that it doesn't understand ๐Ÿ”. If it finds any, the server MUST generate a Shared Secret Error Response and MUST include an ERROR-CODE attribute with a 420 response code. That response MUST contain an UNKNOWN-ATTRIBUTES attribute listing the attributes with values less than or equal to 0x7fff that weren't understood. The Shared Secret Error Response is sent over the TLS connection.

All Shared Secret Error Responses MUST contain the same transaction ID that was in the Shared Secret Request ๐ŸŽ€. The length in the message header MUST contain the total length of the message in bytes, excluding the header. The Shared Secret Error Response MUST have a message type of "Shared Secret Error Response" (0x0112).

Assuming the request was properly constructed, the server creates a Shared Secret Response โœจ. The Shared Secret Response MUST contain the same transaction ID that was in the Shared Secret Request. The length in the message header MUST contain the total length of the message in bytes, excluding the header. The Shared Secret Response MUST have a message type of "Shared Secret Response". It MUST contain a USERNAME attribute and a PASSWORD attribute. The USERNAME works as an index to the password, which lives in the PASSWORD attribute.

The server can use any mechanism it likes to generate the username ๐Ÿงš. However, the username MUST be valid for a period of at least 10 minutes. Valid here means the server can compute the password for that username. There MUST be a single password for each username, so the server can't come back 10 minutes later and assign a different password to the same username ๐Ÿ™ˆ. The server MUST hand out a different username for each distinct Shared Secret Request, and "distinct" in this case means a different transaction ID. It is RECOMMENDED that the server explicitly invalidate the username after ten minutes. It MUST invalidate the username after 30 minutes.

The PASSWORD contains the password bound to that username. The password MUST have at least 128 bits. The likelihood that the server assigns the same password to two different usernames MUST be vanishingly small, and the passwords MUST be unguessable ๐Ÿ”’. In other words, they MUST be a cryptographically random function of the username.

These requirements can still be met with a stateless server, by cleverly computing the USERNAME and PASSWORD ๐Ÿง . One approach is to construct the USERNAME like this:

USERNAME = <prefix,rounded-time,clientIP,hmac>

Here, prefix is some random text string (different for each Shared Secret Request). rounded-time is the current time modulo 20 minutes. clientIP is the source IP address the Shared Secret Request came from. hmac is an HMAC [13] over the prefix, rounded-time, and client IP, using a server private key.

The password is then computed as:

password = <hmac(USERNAME,anotherprivatekey)>

With this setup, the username itself, which will show up in the Binding Request, contains the source IP address the Shared Secret Request came from ๐Ÿ‘€. That lets the server meet the requirements in Section 8.1 for constructing the REFLECTED-FROM attribute. The server can check that the username wasn't tampered with, using the hmac that's present in the username.

The Shared Secret Response is sent over the same TLS connection the request was received on. The server SHOULD keep the connection open, and let the client be the one to close it ๐ŸŒธ.


9. Client Behavior ๐Ÿ’…

The client's job is pretty straightforward, honestly ๐Ÿซถ. It has to discover the STUN server, obtain a shared secret, formulate the Binding Request, handle request reliability, and process the Binding Responses.

9.1 Discovery ๐Ÿ”Ž

Generally, the client gets configured with a domain name belonging to the provider of the STUN servers. That domain name gets resolved to an IP address and port using the SRV procedures specified in RFC 2782 [3].

Specifically, the service name is "stun". The protocol is "udp" for sending Binding Requests, or "tcp" for sending Shared Secret Requests. The RFC 2782 procedures get followed to figure out which server to contact. RFC 2782 spells out how a set of SRV records gets sorted and then tried ๐Ÿ“‹. But it only says the client should "try to connect to the (protocol, address, service)", without any details on what happens when that fails ๐Ÿ˜ค. So those details are described here, for STUN.

For STUN requests, failure happens if there's a transport failure of some sort (usually a fatal ICMP error in UDP or a connection failure in TCP). Failure also happens if the transaction times out โฐ. That timeout kicks in 9.5 seconds after the first request is sent, for both Shared Secret Requests and Binding Requests. See Section 9.3 for the transaction timeouts for Binding Requests. If a failure happens, the client SHOULD create a new request that's identical to the previous one, but with a different transaction ID and a MESSAGE INTEGRITY attribute (the HMAC changes because the transaction ID changed) ๐Ÿ”. That request then gets sent to the next element in the list, as specified by RFC 2782.

The default port for STUN requests is 3478, for both TCP and UDP ๐Ÿ“. Administrators SHOULD use this port in their SRV records, but MAY use others.

If no SRV records are found, the client does an A record lookup of the domain name. The result is a list of IP addresses, and each one can be contacted at the default port.

This would allow a firewall admin to open the STUN port, so hosts within the enterprise could access new applications. Whether they will or won't do this is a good question ๐Ÿค”.

9.2 Obtaining a Shared Secret ๐Ÿ—๏ธ

As discussed in Section 12, there are several attacks possible on STUN systems ๐Ÿ˜ฌ. Many of them get prevented through integrity of requests and responses. To provide that integrity, STUN uses a shared secret between client and server, which works as the keying material for an HMAC used in both the Binding Request and the Binding Response. STUN allows the shared secret to be obtained in any way (Kerberos [14], for example). However, it MUST have at least 128 bits of randomness. To make sure everyone interoperates, this specification describes a TLS-based mechanism. This mechanism, covered in this section, MUST be implemented by clients and servers ๐Ÿซถ.

First, the client figures out the IP address and port it will open a TCP connection to. That's done using the discovery procedures in Section 9.1. The client opens the connection to that address and port, and immediately starts TLS negotiation [2]. The client MUST verify the identity of the server. To do that, it follows the identification procedures defined in Section 3.1 of RFC 2818 [5]. Those procedures assume the client is dereferencing a URI. For this specification, the client treats the domain name or IP address used in Section 9.1 as the host portion of the URI that's been dereferenced ๐Ÿงฉ.

Once the connection is open, the client sends a Shared Secret Request. This request has no attributes, just the header โœจ. The transaction ID in the header MUST meet the requirements for the transaction ID in a Binding Request, described in Section 9.3 below. The server generates a response, which can be either a Shared Secret Response or a Shared Secret Error Response.

If the response was a Shared Secret Error Response, the client checks the response code in the ERROR-CODE attribute. Interpreting those response codes is identical to the processing in Section 9.4 for the Binding Error Response ๐Ÿ“–.

If the client gets a Shared Secret Response with an attribute whose type is greater than 0x7fff, that attribute MUST be ignored. If the client gets a Shared Secret Response with an attribute whose type is less than or equal to 0x7fff, the response is ignored ๐Ÿšซ.

If the response was a Shared Secret Response, it'll contain a short-lived username and password, encoded in the USERNAME and PASSWORD attributes, respectively ๐Ÿ’œ.

The client MAY generate multiple Shared Secret Requests on the connection, and it MAY do so before receiving Shared Secret Responses to earlier Shared Secret Requests ๐Ÿ™Œ. The client SHOULD close the connection as soon as it's finished obtaining usernames and passwords ๐Ÿ‘‹.

Section 9.3 describes how these passwords get used to provide integrity protection over Binding Requests, and Section 8.1 describes how they're used in Binding Responses ๐Ÿฆ‹.

9.3. Formulating the Binding Request โœจ

Okay bestie, a Binding Request from the client has to follow the syntax rules in Section 11 ๐Ÿ’…. Any two requests that aren't bit-wise identical, and aren't going to the same server from the same IP address and port, MUST carry different transaction IDs ๐ŸŽ€. The transaction ID MUST be uniformly and randomly distributed between 0 and 2**128 - 1 ๐ŸŽฒ. That massive range is needed because the transaction ID acts as a kind of randomization, which helps stop replays of old signed responses from the server ๐Ÿ”’. The message type of the request MUST be Binding Request ๐Ÿ’–.

The RESPONSE-ADDRESS attribute is optional in a Binding Request ๐Ÿฆ‹. The client uses it if it wants the response sent to a different IP address and port than the ones the request came from. This is handy for figuring out whether the client is behind a firewall, and for apps that split their control and data parts ๐Ÿงš. See Section 10.3 for more details. The CHANGE-REQUEST attribute is optional too, and whether it shows up depends on what the app is trying to pull off โœจ. See Section 10 for some example uses.

The client SHOULD add a MESSAGE-INTEGRITY and a USERNAME attribute to the Binding Request ๐Ÿ”. The MESSAGE-INTEGRITY attribute contains an HMAC [13]. The value of the username, and the key used in MESSAGE-INTEGRITY, depend on the shared secret mechanism ๐ŸŒธ. If the STUN Shared Secret Request was used, the USERNAME MUST be a valid username obtained from a Shared Secret Response within the last nine minutes โฐ. The shared secret for the HMAC is the value of the PASSWORD attribute from that same Shared Secret Response ๐Ÿ—๏ธ.

Once it's all formulated, the client sends the Binding Request ๐Ÿš€. Reliability comes from client retransmissions. Clients SHOULD retransmit the request starting with a 100ms interval, doubling every retransmit until the interval hits 1.6s ๐Ÿ“ˆ. Retransmissions keep going at 1.6s intervals until a response arrives, or a total of 9 requests have been sent ๐Ÿ”. If no response shows up 1.6 seconds after the last request was sent, the client SHOULD consider the transaction failed ๐Ÿ’€. So the requests go out at 0ms, 100ms, 300ms, 700ms, 1500ms, 3100ms, 4700ms, 6300ms, and 7900ms. At 9500ms, if there's still no response, the client considers the transaction failed ๐Ÿ™ˆ.

9.4. Processing Binding Responses ๐ŸŒˆ

The response can be either a Binding Response or a Binding Error Response ๐Ÿ’Œ. Binding Error Responses always come back to the source address and port the request was sent from. A Binding Response will arrive on the address and port placed in the RESPONSE-ADDRESS attribute of the request. If there wasn't one, Binding Responses come back to the source address and port the request was sent from ๐Ÿ“ฌ.

If the response is a Binding Error Response, the client checks the response code in the ERROR-CODE attribute ๐Ÿšจ. For a 400 response code, the client SHOULD display the reason phrase to the user ๐Ÿ™‹. For a 420 response code, the client SHOULD retry the request, this time leaving out any attributes listed in the UNKNOWN-ATTRIBUTES attribute of the response ๐Ÿงน. For a 430 response code, the client SHOULD obtain a new shared secret and retry the Binding Request with a new transaction ๐Ÿ”‘. For 401 and 432 response codes, if the client left out the USERNAME or MESSAGE-INTEGRITY attribute, as the error indicates, it SHOULD try again with those attributes included ๐ŸŽ€. For a 431 response code, the client SHOULD alert the user, and MAY try the request again after getting a new username and password ๐Ÿšจ. For a 500 response code, the client MAY wait several seconds and then retry the request ๐Ÿ•ฐ๏ธ. For a 600 response code, the client MUST NOT retry the request, and SHOULD display the reason phrase to the user ๐Ÿ›‘. Unknown attributes between 400 and 499 are treated like a 400, unknown attributes between 500 and 599 are treated like a 500, and unknown attributes between 600 and 699 are treated like a 600 ๐Ÿงฉ. Any response between 100 and 399 MUST result in the cessation of request retransmissions, but otherwise gets discarded ๐Ÿ›‘.

If a client gets a response with an attribute whose type is greater than 0x7fff, that attribute MUST be ignored ๐Ÿ™ˆ. If the client gets a response with an attribute whose type is less than or equal to 0x7fff, request retransmissions MUST cease, but the entire response is otherwise ignored ๐Ÿซถ.

If the response is a Binding Response, the client SHOULD check it for a MESSAGE-INTEGRITY attribute ๐Ÿ”. If it isn't there, and the client put a MESSAGE-INTEGRITY attribute into the request, the client MUST discard the response ๐Ÿ—‘๏ธ. If it is there, the client computes the HMAC over the response as described in Section 11.2.8 ๐Ÿงฎ. The key depends on the shared secret mechanism. If the STUN Shared Secret Request was used, the key MUST be the same one used to compute the MESSAGE-INTEGRITY attribute in the request ๐Ÿ”. If the computed HMAC doesn't match the one in the response, the client MUST discard the response and SHOULD alert the user about a possible attack ๐Ÿ˜ฑ. If the computed HMAC matches the one from the response, processing continues โœ….

Getting a response (either a Binding Error Response or a Binding Response) to a Binding Request stops retransmissions of that request ๐Ÿ›‘. But clients MUST continue to listen for responses to a Binding Request for 10 seconds after the first response ๐Ÿ‘‚. If it gets any responses in that window with different message types (like a Binding Response and a Binding Error Response) or different MAPPED-ADDRESS values, that's a sign of a possible attack ๐Ÿ•ต๏ธโ€โ™€๏ธ. The client MUST NOT use the MAPPED-ADDRESS from any of the responses it received, whether the first one or the extra ones, and SHOULD alert the user ๐Ÿšซ.

Also, if a client gets more than twice as many Binding Responses as the number of Binding Requests it sent, it MUST NOT use the MAPPED-ADDRESS from any of those responses, and SHOULD alert the user about a potential attack ๐Ÿ“ข.

If the Binding Response is authenticated, and the MAPPED-ADDRESS wasn't discarded because of a potential attack, the CLIENT MAY use the MAPPED-ADDRESS and SOURCE-ADDRESS attributes ๐Ÿฅณ.

10. Use Cases ๐ŸŽฌ

The rules in Sections 8 and 9 explain exactly how a client and server interact to send requests and get responses ๐Ÿค. But they don't dictate how STUN gets used to accomplish useful tasks. That's up to the client ๐Ÿ‘‘. Here, we share some useful scenarios for applying STUN โœจ.

10.1. Discovery Process ๐Ÿ”Ž

In this scenario, a user is running a multimedia app that needs to figure out which of the following situations applies to it ๐ŸŽฅ:

  • On the open Internet
  • Firewall that blocks UDP
  • Firewall that allows UDP out, and responses have to come back to the source of the request (like a symmetric NAT, but no translation. We call this a symmetric UDP Firewall) ๐Ÿงฑ
  • Full-cone NAT
  • Symmetric NAT
  • Restricted cone or restricted port cone NAT

Which of the six scenarios applies can be determined through the flow chart described in Figure 2 ๐Ÿ“Š. The chart only refers to the sequence of Binding Requests. Shared Secret Requests will, of course, be needed to authenticate each Binding Request in the sequence ๐Ÿ”‘.

The flow uses three tests ๐Ÿงช. In test I, the client sends a STUN Binding Request to a server, with no flags set in the CHANGE-REQUEST attribute, and without the RESPONSE-ADDRESS attribute. This makes the server send the response back to the address and port the request came from ๐Ÿ“ฎ. In test II, the client sends a Binding Request with both the "change IP" and "change port" flags from the CHANGE-REQUEST attribute set ๐Ÿ”„. In test III, the client sends a Binding Request with only the "change port" flag set ๐Ÿ”€.

The client begins by starting test I. If this test gets no response, the client knows right away that it can't do UDP connectivity ๐Ÿ’”. If the test produces a response, the client looks at the MAPPED-ADDRESS attribute. If this address and port match the local IP address and port of the socket used to send the request, the client knows it isn't natted ๐ŸŒŸ. Then it runs test II.

If a response comes back, the client knows it has open access to the Internet (or, at least, it's behind a firewall that acts like a full-cone NAT, but without the translation) ๐ŸŒ. If no response comes back, the client knows it's behind a symmetric UDP firewall ๐Ÿงฑ.

If the IP address and port of the socket didn't match the MAPPED-ADDRESS attribute in the response to test I, the client knows it's behind a NAT ๐Ÿ•ธ๏ธ. It runs test II. If a response comes back, the client knows it's behind a full-cone NAT ๐Ÿฆ‹. If no response comes back, it runs test I again, but this time sends it to the address and port from the CHANGED-ADDRESS attribute in the response to the first test I ๐Ÿ”. If the IP address and port in the MAPPED-ADDRESS attribute aren't the same as the ones from the first test I, the client knows it's behind a symmetric NAT ๐ŸŒ€. If the address and port are the same, the client is behind either a restricted or a port restricted NAT. To figure out which one, the client starts test III. If a response comes back, it's behind a restricted NAT. If no response comes back, it's behind a port restricted NAT ๐Ÿ”.

This procedure gives a lot of info about the operating condition of the client app ๐Ÿ“š. If there are multiple NATs between the client and the Internet, the type discovered will be the type of the most restrictive NAT between the client and the Internet ๐Ÿšง. From most to least restrictive, the NAT types are: symmetric, port restricted cone, restricted cone, and full cone ๐Ÿ’œ.

Usually, a client will redo this discovery process periodically to catch changes, or to look for inconsistent results ๐Ÿ”„. It's important to note that when discovery is redone, it should not generally be done from the same local address and port used in the previous discovery process ๐Ÿ“Œ. If the same local address and port get reused, bindings from the previous test might still exist, and those will invalidate the test results ๐Ÿ˜ต. Using a different local address and port for later tests fixes this. Another option is to wait long enough to be confident the old bindings have expired (half an hour should more than suffice) โณ.

10.2 Binding Lifetime Discovery ๐Ÿ’–

okay so STUN can also be used to figure out how long the bindings the NAT creates actually last ๐Ÿฆ‹ this matters because in lots of cases the client has to refresh the binding, either with a fresh STUN request or with an application packet, so the app can keep using it. once you know the lifetime, you know how often to refresh ๐Ÿ’…

                    +--------+
                    |  Test  |
                    |   I    |
                    +--------+
                         |
                         |
                         V
                        /\              /\
                     N /  \ Y          /  \ Y             +--------+
      UDP     <-------/Resp\--------->/ IP \------------->|  Test  |
      Blocked         \ ?  /          \Same/              |   II   |
                       \  /            \? /               +--------+
                        \/              \/                    |
                                         | N                  |
                                         |                    V
                                         V                    /\
                                     +--------+  Sym.      N /  \
                                     |  Test  |  UDP    <---/Resp\
                                     |   II   |  Firewall   \ ?  /
                                     +--------+              \  /
                                         |                    \/
                                         V                     |Y
              /\                         /\                    |
   Symmetric  N  /  \       +--------+   N  /  \                   V
      NAT  <--- / IP \<-----|  Test  |<--- /Resp\               Open
                \Same/      |   I    |     \ ?  /               Internet
                 \? /       +--------+      \  /
                  \/                         \/
                  |                           |Y
                  |                           |
                  |                           V
                  |                           Full
                  |                           Cone
                  V              /\
              +--------+        /  \ Y
              |  Test  |------>/Resp\---->Restricted
              |   III  |       \ ?  /
              +--------+        \  /
                                 \/
                                  |N
                                  |       Port
                                  +------>Restricted

Figure 2: Flow for type discovery process

okay so here's the process ๐ŸŽ€ the client first sends a Binding Request to the server from a particular socket, X. this creates a binding in the NAT. the response has a MAPPED-ADDRESS attribute, which gives the public address and port on the NAT. we call those Pa and Pp, respectively. then the client starts a timer with a value of T seconds. when that timer fires, the client sends another Binding Request to the same destination address and port, but this time from a different socket, Y. this one carries a RESPONSE-ADDRESS attribute set to (Pa,Pp). that creates a new binding on the NAT, and it makes the STUN server send a Binding Response that would match the old binding, if the old binding still exists ๐Ÿงš

so now the results ๐Ÿ‘€ if the client gets the Binding Response on socket X, the old binding hasn't expired yet. if it gets the Binding Response on socket Y (which is possible if the old binding expired and the NAT gave the same public address and port to the new binding), or it gets no response at all, then the binding has expired ๐Ÿ˜ญ

to find the actual lifetime, the client does a binary search through T. eventually it lands on the value where no response comes back for any timer greater than T, but a response does come back for any timer less than T ๐Ÿ’œ

this whole discovery process takes quite a bit of time, so it's usually something that runs in the background on a device once it boots ๐ŸŒธ

also, the results might not be consistent every time it runs ๐Ÿ™ˆ for example, if the NAT reboots or gets reset for some reason, the process might find a lifetime that is shorter than the real one. because of that, implementations are encouraged to run the test numerous times and be ready for inconsistent results ๐Ÿ“


10.3 Binding Acquisition ๐ŸŽ€

let's go back to the VoIP phone ๐Ÿ“ž it ran the discovery process when it started up to learn about its environment. now it wants to make a call, and as part of discovery it figured out it's behind a full-cone NAT ๐Ÿ”ฅ

here's the twist: this phone has two logically separate components. there's a control component that handles signaling, and a media component that handles the audio, video, and RTP [12]. both of them are behind the same NAT. since they're separated like that, we want to keep the communication between them as small as possible ๐Ÿ’… they may not even be running on the same host, honestly iconic ๐Ÿ‘‘

so to make a voice call, the phone needs an IP address and port it can put in the call setup message as the destination for receiving audio ๐Ÿฆ‹

here's how it gets that address. the control component sends a Shared Secret Request to the server and gets a shared secret. then it sends a Binding Request to the server. no CHANGE-REQUEST attribute is in that Binding Request, and no RESPONSE-ADDRESS attribute either. the Binding Response has a mapped address in it. the control component then builds a second Binding Request. this one carries a RESPONSE-ADDRESS, set to the mapped address from the previous Binding Response. that request gets passed to the media component, along with the IP address and port of the STUN server. the media component sends the Binding Request. it goes to the STUN server, and the STUN server sends the Binding Response back to the control component. the control component gets it and now knows an IP address and port that will route back to the media component that sent the request โœจ

the client can receive media from anywhere on this mapped address ๐Ÿงš

with silence suppression, there can be stretches where the client gets no media at all ๐Ÿ˜ณ in that case the UDP bindings could time out (UDP bindings in NATs tend to be short, and 30 seconds is common). to avoid that, the application can periodically retransmit the query to keep the binding fresh ๐Ÿซถ

ngl this next bit is a little messy ๐Ÿ™ˆ both participants in the multimedia session might be behind the same NAT. if so, both of them repeat the procedure above and both end up with public address bindings. when one sends media to the other, the media goes out to the NAT and then turns right back around to come back into the enterprise, where it gets translated to the recipient's private address. this isn't especially efficient, and unfortunately it doesn't work with many commercial NATs. in those cases, the clients may need to retry with private addresses instead ๐Ÿ˜ญ


11. Protocol Details ๐ŸŒˆ

this section is where we get into the detailed encoding of a STUN message ๐Ÿค“

STUN is a request-response protocol. clients send a request, and the server sends back a response. there are two requests: Binding Request and Shared Secret Request. the response to a Binding Request can be either the Binding Response or the Binding Error Response. the response to a Shared Secret Request can be either a Shared Secret Response or a Shared Secret Error Response ๐Ÿ’œ

STUN messages use binary fields. all integer fields are carried in network byte order, meaning the most significant byte (octet) comes first. this byte order is commonly known as big-endian ๐Ÿง  the transmission order is described in detail in Appendix B of RFC 791 [6]. unless otherwise noted, numeric constants are in decimal (base 10) ๐Ÿ”ข

11.1 Message Header ๐ŸŽ€

every STUN message starts with a 20 byte header ๐Ÿ“ฆ

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|      STUN Message Type        |         Message Length        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                         Transaction ID
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                                                                |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

the Message Types can be any of these values ๐Ÿฆ‹

   0x0001  :  Binding Request
   0x0101  :  Binding Response
   0x0111  :  Binding Error Response
   0x0002  :  Shared Secret Request
   0x0102  :  Shared Secret Response
   0x0112  :  Shared Secret Error Response

the message length is the number of bytes in the message, not counting the 20 byte header ๐Ÿ“

the transaction ID is a 128 bit identifier ๐Ÿชช it also acts as salt to randomize the request and the response, and all responses carry the same identifier as the request they correspond to ๐Ÿ’–

11.2 Message Attributes โœจ

okay bestie, so after the header come 0 or more attributes ๐Ÿ’… Each one is TLV encoded (type, length, value), with a 16 bit type, a 16 bit length, and a variable-length value ๐ŸŽ€

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |         Type                  |            Length             |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                             Value                             ....
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

here are the types that are defined ๐Ÿฆ‹

0x0001: MAPPED-ADDRESS
0x0002: RESPONSE-ADDRESS
0x0003: CHANGE-REQUEST
0x0004: SOURCE-ADDRESS
0x0005: CHANGED-ADDRESS
0x0006: USERNAME
0x0007: PASSWORD
0x0008: MESSAGE-INTEGRITY
0x0009: ERROR-CODE
0x000a: UNKNOWN-ATTRIBUTES
0x000b: REFLECTED-FROM

so the attribute space is split into optional and mandatory ones ๐Ÿงš This is so future revisions can add new attributes if they need to ๐ŸŒˆ Attributes with values greater than 0x7fff are optional, which means a client or server can still process the message even if it doesn't understand that attribute โœจ Attributes with values less than or equal to 0x7fff are mandatory, so if you don't understand one of those, you can't process the message at all ๐Ÿ’€

the big rules: MESSAGE-INTEGRITY MUST be the last attribute within a message. And if you see a known attribute that isn't supposed to be there (like MAPPED-ADDRESS in a request, for example), it MUST be ignored ๐Ÿ™ˆ no drama, just skip it ๐Ÿ’–

Table 2 tells you which attributes show up in which messages ๐Ÿ“ An M means mandatory, O means optional, C means conditional (depends on something else in the message), and N/A means the attribute doesn't apply to that message type ๐Ÿ’œ

                                     Binding  Shared  Shared  Shared
                   Binding  Binding  Error    Secret  Secret  Secret
   Att.            Req.     Resp.    Resp.    Req.    Resp.   Error
                                                              Resp.
   _____________________________________________________________________
   MAPPED-ADDRESS      N/A      M        N/A      N/A     N/A     N/A
   RESPONSE-ADDRESS    O        N/A      N/A      N/A     N/A     N/A
   CHANGE-REQUEST      O        N/A      N/A      N/A     N/A     N/A
   SOURCE-ADDRESS      N/A      M        N/A      N/A     N/A     N/A
   CHANGED-ADDRESS     N/A      M        N/A      N/A     N/A     N/A
   USERNAME            O        N/A      N/A      N/A     M       N/A
   PASSWORD            N/A      N/A      N/A      N/A     M       N/A
   MESSAGE-INTEGRITY   O        O        N/A      N/A     N/A     N/A
   ERROR-CODE          N/A      N/A      M        N/A     N/A     M
   UNKNOWN-ATTRIBUTES  N/A      N/A      C        N/A     N/A     C
   REFLECTED-FROM      N/A      C        N/A      N/A     N/A     N/A

   Table 2: Summary of Attributes

the length is the length of the value part, counted as an unsigned integer number of bytes ๐Ÿ”ฅ

11.2.1 MAPPED-ADDRESS

the MAPPED-ADDRESS attribute tells you the mapped IP address and port ๐Ÿฆ‹ It's an 8 bit address family, then a 16 bit port, then a fixed-length value holding the IP address ๐ŸŒธ

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |x x x x x x x x|    Family     |           Port                |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                             Address                           |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

the port is in network byte order ๐ŸŒˆ The address family is always 0x01, which means IPv4 ๐Ÿ’… The first 8 bits are ignored, just there to line stuff up on natural boundaries ๐Ÿงš And the IPv4 address is 32 bits ๐Ÿ’œ

11.2.2 RESPONSE-ADDRESS

the RESPONSE-ADDRESS attribute says where the response to a Binding Request should get sent ๐ŸŽ€ Its syntax is exactly the same as MAPPED-ADDRESS ๐Ÿซถ

11.2.3 CHANGED-ADDRESS

the CHANGED-ADDRESS attribute gives the IP address and port that responses would have come from if the "change IP" and "change port" flags had been set in the CHANGE-REQUEST attribute of the Binding Request ๐Ÿ‘‘ It's always there in a Binding Response, no matter what the flags were set to โœจ Syntax is identical to MAPPED-ADDRESS ๐ŸŒธ

11.2.4 CHANGE-REQUEST

the CHANGE-REQUEST attribute is how the client asks the server to use a different address and/or port when it sends the response ๐Ÿฆ‹ It's 32 bits long, but only two bits (A and B) actually do anything ๐Ÿ™ˆ

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |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 A B 0|
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

so the flags mean:

  • A is the "change IP" flag ๐ŸŒˆ If it's true, it's asking the server to send the Binding Response from a different IP address than the one the Binding Request came in on.
  • B is the "change port" flag ๐Ÿ’– If it's true, it's asking the server to send the Binding Response from a different port than the one the Binding Request came in on.

11.2.5 SOURCE-ADDRESS

the SOURCE-ADDRESS attribute shows up in Binding Responses ๐Ÿ“ It tells you the source IP address and port the server is sending the response from ๐Ÿซถ Syntax is the same as MAPPED-ADDRESS โœจ

11.2.6 USERNAME

the USERNAME attribute is all about message integrity ๐Ÿ” It's how you identify the shared secret used in the integrity check ๐ŸŽ€ USERNAME is always in a Shared Secret Response, alongside the PASSWORD ๐Ÿ’… It's optional in a Binding Request when message integrity is being used ๐Ÿฆ‹

the value is a variable-length opaque value, and its length MUST be a multiple of 4 (in bytes) so the attributes stay aligned on word boundaries ๐ŸŒธ

11.2.7 PASSWORD

the PASSWORD attribute is used in Shared Secret Responses ๐Ÿ‘‘ It's always there in a Shared Secret Response, together with the USERNAME ๐Ÿ’œ

the value is a variable-length value that gets used as the shared secret ๐Ÿ”ฅ Its length MUST be a multiple of 4 (in bytes) for the same word-boundary alignment reason ๐Ÿงš

11.2.8 MESSAGE-INTEGRITY

okay this one is giving security ๐Ÿ˜ญ MESSAGE-INTEGRITY holds an HMAC-SHA1 [13] of the STUN message ๐Ÿ” It can show up in Binding Requests or Binding Responses ๐ŸŒˆ Since it's built on SHA1, the HMAC is 20 bytes ๐Ÿซถ The input to the HMAC is the STUN message, header included, all the way up to and including the attribute right before MESSAGE-INTEGRITY ๐Ÿ’– That text then gets padded with zeroes until it's a multiple of 64 bytes โœจ Which is exactly why MESSAGE-INTEGRITY MUST be the last attribute in any STUN message ๐Ÿ™ˆ The key used as input to the HMAC depends on the context ๐Ÿฆ‹

11.2.9 ERROR-CODE

the ERROR-CODE attribute is in the Binding Error Response and the Shared Secret Error Response ๐Ÿ’… It's a numeric value from 100 to 699, plus a textual reason phrase in UTF-8 ๐ŸŽ€ The codes are consistent with SIP [10] and HTTP [15] in both assignments and semantics ๐ŸŒธ The reason phrase is for user consumption and can say anything that fits the response code ๐Ÿ’œ The length of the reason phrase MUST be a multiple of 4 (in bytes), and if it's not, you can pad it out by adding spaces to the end ๐Ÿงš There are recommended reason phrases for the defined response codes listed below ๐Ÿ‘‘

to make processing easier, the class of the error code (the hundreds digit) is encoded separately from the rest of the code ๐Ÿ”ฅ

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                   0                     |Class|     Number    |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |      Reason Phrase (variable)                                ..
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

the class is the hundreds digit of the response code, and it MUST be between 1 and 6 ๐ŸŒˆ The number is the response code modulo 100, and it MUST be between 0 and 99 ๐Ÿ’–

these are the response codes defined right now, with their recommended reason phrases in brackets ๐Ÿ“

  • 400 (Bad Request): The request was malformed. The client should not retry the request without modification from the previous attempt. ๐Ÿ™…โ€โ™€๏ธ
  • 401 (Unauthorized): The Binding Request did not contain a MESSAGE-INTEGRITY attribute. ๐Ÿ”
  • 420 (Unknown Attribute): The server did not understand a mandatory attribute in the request. ๐Ÿง
  • 430 (Stale Credentials): The Binding Request did contain a MESSAGE-INTEGRITY attribute, but it used a shared secret that has expired. The client should obtain a new shared secret and try again. ๐Ÿ”„
  • 431 (Integrity Check Failure): The Binding Request contained a MESSAGE-INTEGRITY attribute, but the HMAC failed verification. This could be a sign of a potential attack, or client implementation error. ๐Ÿšจ ngl this one is kinda scary ๐Ÿ˜ญ
  • 432 (Missing Username): The Binding Request contained a MESSAGE-INTEGRITY attribute, but not a USERNAME attribute. Both must be present for integrity checks. ๐Ÿซฃ
  • 433 (Use TLS): The Shared Secret request has to be sent over TLS, but was not received over TLS. ๐Ÿ”’
  • 500 (Server Error): The server has suffered a temporary error. The client should try again. ๐Ÿซ 
  • 600 (Global Failure:) The server is refusing to fulfill the request. The client should not retry. ๐Ÿ›‘

11.2.10 UNKNOWN-ATTRIBUTES

the UNKNOWN-ATTRIBUTES attribute only shows up in a Binding Error Response or Shared Secret Error Response, and only when the ERROR-CODE attribute says 420 ๐Ÿง

it holds a list of 16 bit values, and each one is an attribute type the server didn't understand ๐Ÿฆ‹ If the number of unknown attributes is odd, one of them MUST be repeated in the list, so the total length of the list is a multiple of 4 bytes ๐ŸŒธ

    0                   1                   2                   3
      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |      Attribute 1 Type           |     Attribute 2 Type        |
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |      Attribute 3 Type           |     Attribute 4 Type    ...
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

11.2.11 REFLECTED-FROM โœจ

okay so the REFLECTED-FROM attribute is only ever in Binding Responses, and only when the Binding Request had a RESPONSE-ADDRESS attribute ๐ŸŽ€ it tells you the identity (aka the IP address) of where the request came from ๐Ÿ’… the whole point is traceability, so a STUN server can't be used as a reflector for denial-of-service attacks ๐Ÿซถ

its syntax is identical to MAPPED-ADDRESS ๐Ÿฆ‹

12. Security Considerations ๐Ÿ”ฅ

12.1. Attacks on STUN ๐Ÿ˜ญ

generally speaking, attacks on STUN fall into two buckets: denial of service and eavesdropping ๐Ÿ™ˆ the DoS stuff can target a STUN server itself, or other stuff that's using the STUN protocol ๐Ÿ’€

STUN servers create state through the Shared Secret Request mechanism ๐ŸŒธ so to avoid getting swamped with traffic, a STUN server SHOULD limit how many simultaneous TLS connections it holds open, by dropping an existing connection when a new one shows up (an LRU policy is one example ๐Ÿ’–) similarly, it SHOULD limit the number of shared secrets it stores, in case the server is the one storing them ๐Ÿงš

the attacks that are most interesting are the ones where the STUN server and client get used to launch DoS attacks on other entities, including the client itself ๐Ÿ‘‘

a lot of these attacks need the attacker to produce a response to a legit STUN request, so they can give the client a faked MAPPED-ADDRESS ๐Ÿ“ the attacks that can be pulled off with that trick are:

12.1.1. Attack I: DDOS Against a Target ๐ŸŒˆ

so here the attacker hands a bunch of clients the same faked MAPPED-ADDRESS, pointing at the intended target ๐Ÿ˜ˆ every STUN client now thinks its address is the target's address ๐Ÿ’… they hand that address out to receive traffic on it (like in SIP or H.323 messages), but all that traffic ends up piling onto the target ๐Ÿ’ฅ this can be a huge amplification, especially with clients using STUN for multimedia apps ๐Ÿ”ฅ

12.1.2. Attack II: Silencing a Client ๐Ÿ™ˆ

in this one the attacker wants to stop a client from getting services that STUN enables (like a client using STUN for SIP-based multimedia) ๐ŸŽ€ so they give that client a faked MAPPED-ADDRESS that is an IP address routing to nowhere ๐Ÿ•ณ๏ธ the client then never receives the packets it's expecting once it hands that MAPPED-ADDRESS out ๐Ÿ˜ญ

honestly this one isn't very exciting for the attacker ๐Ÿฅฑ it only hits a single client, which usually isn't the actual target ๐Ÿ’… plus, anyone who can pull this off could also just deny service to the client another way, like stopping it from getting any response from the STUN server, or even from a DHCP server ๐Ÿซ 

12.1.3. Attack III: Assuming the Identity of a Client ๐Ÿฆ‹

this is basically attack II, but the faked MAPPED-ADDRESS points at the attacker themself ๐Ÿ‘€ that lets the attacker receive traffic meant for the client ๐Ÿ˜ฑ

12.1.4. Attack IV: Eavesdropping ๐Ÿ‘‚

here the attacker forces the client to use a MAPPED-ADDRESS that routes to the attacker ๐Ÿ•ต๏ธโ€โ™€๏ธ then the attacker forwards any packets it gets to the client ๐Ÿ“ฆ this lets the attacker see all packets sent to the client ๐Ÿ‘€ BUT, to launch it, the attacker has to already be able to observe packets going from the client to the STUN server ๐Ÿ™ƒ in most cases (like when it's launched from an access network), that means the attacker could already see packets sent to the client anyway ๐Ÿคทโ€โ™€๏ธ so this attack is only really useful for watching traffic from attackers on the path between the client and the STUN server, not generally on the path of packets routed toward the client ๐Ÿ›ค๏ธ

12.2. Launching the Attacks ๐Ÿš€

okay this part is important bestie โš ๏ธ injecting responses with fake MAPPED-ADDRESSes (which all those attacks depend on) requires the attacker to be able to eavesdrop on requests sent from the client to the server, or to act as a MITM for them ๐Ÿ‘€ that's because STUN requests carry a transaction identifier picked by the client, which is random with 128 bits of entropy ๐ŸŽฒ the server echoes this value in the response, and the client ignores any response without a matching transaction ID ๐Ÿ™…โ€โ™€๏ธ so for an attacker's fake response to get accepted, it needs to know the transaction ID from the request ๐Ÿ”‘ the huge amount of randomness, combined with needing to know when the client sends a request, rules out guessing the transaction ID ๐Ÿšซ

since all of the above attacks rely on this one primitive (injecting a response with a faked MAPPED-ADDRESS), stopping the attacks means stopping this one operation ๐Ÿ›‘ to do that, we need to think about the different ways it can happen ๐Ÿง  there are several:

12.2.1. Approach I: Compromise a Legitimate STUN Server ๐Ÿ˜ˆ

here the attacker compromises a legit STUN server with a virus or Trojan horse ๐Ÿฆ  presumably that lets them take over the server and control what kind of responses it generates ๐ŸŽญ

compromising a STUN server can also reveal open ports ๐Ÿšช knowing about an open port opens the door to DoS attacks on those ports (or DDoS attacks if the NAT being traversed is a full cone NAT) ๐Ÿ’ฅ finding open ports is already pretty trivial with port probing, so this isn't a major threat ๐Ÿ˜Œ

12.2.2. Approach II: DNS Attacks ๐ŸŒ

STUN servers are discovered using DNS SRV records ๐Ÿ“‡ if an attacker can compromise DNS, it can inject fake records that map a domain name to the IP address of a STUN server run by the attacker ๐Ÿ˜ต that lets them inject fake responses to launch any of the attacks above ๐ŸŽฏ

12.2.3. Approach III: Rogue Router or NAT ๐Ÿ› ๏ธ

instead of compromising the STUN server, an attacker can make a STUN server generate responses with the wrong MAPPED-ADDRESS by compromising a router or NAT on the path from the client to the STUN server ๐ŸงŒ when the STUN request passes through the rogue router or NAT, it rewrites the packet's source address to be the desired MAPPED-ADDRESS ๐ŸŽญ but this address can't be arbitrary ๐Ÿ™…โ€โ™€๏ธ if the attacker is on the public Internet (so no NATs between it and the STUN server) and doesn't modify the STUN request, the address has to be one where packets sent from the STUN server to it would route through the compromised router ๐Ÿ›ฃ๏ธ that's because the STUN server sends responses back to the request's source address ๐Ÿ“ฌ with a modified source address, the only way the responses reach the client is if the compromised router directs them there ๐Ÿชค

if the attacker is on the public Internet but CAN modify the STUN request, they can insert a RESPONSE-ADDRESS attribute containing the actual source address of the request ๐ŸŽ€ that makes the server send the response to the client, no matter what source address the STUN server sees ๐Ÿ‘€ so the attacker can forge an arbitrary source address when it forwards the STUN request ๐Ÿฆนโ€โ™€๏ธ

if the attacker is on a private network (so there are NATs between it and the STUN server), it can't force the server to generate arbitrary MAPPED-ADDRESSes ๐Ÿ™…โ€โ™€๏ธ it can only make the STUN server generate MAPPED-ADDRESSes that route to the private network ๐Ÿ  that's because the NAT between the attacker and the server rewrites the request's source address, mapping it to a public address that routes to the private network ๐Ÿ—บ๏ธ so the attacker can only fake mapped addresses that route to the private network ๐Ÿ˜ค BUT, a low quality NAT might map an allocated public address to another public address (instead of an internal private address), in which case the attacker could forge the source address in a STUN request to be an arbitrary public address ๐Ÿ˜ฌ this kind of NAT behaviour does appear to be rare ๐Ÿ™

12.2.4. Approach IV: MITM ๐Ÿ•ธ๏ธ

as an alternative to approach III, if the attacker can put an element on the path from the client to the server, that element can act as a man-in-the-middle ๐Ÿฅท it can intercept a STUN request and generate a STUN response directly with any value it wants for the MAPPED-ADDRESS field ๐ŸŽจ or it can forward the STUN request to the server (after maybe modifying it), receive the response, and forward it to the client ๐Ÿ“จ when forwarding the request and response, this attack is subject to the same limitations on the MAPPED-ADDRESS described in Section 12.2.3 ๐Ÿ“Œ

12.2.5. Approach V: Response Injection Plus DoS ๐Ÿ’ฃ

in this approach, the attacker doesn't need to be a MITM (like in approaches III and IV) ๐Ÿ™Œ it only needs to be able to eavesdrop on a network segment that carries STUN requests ๐Ÿ‘‚ that's easy on multiple access networks like ethernet or unprotected 802.11 ๐Ÿ“ถ to inject the fake response, the attacker listens on the network for a STUN request ๐Ÿ‘€ when it sees one, it simultaneously launches a DoS attack on the STUN server AND generates its own STUN response with the desired MAPPED-ADDRESS value ๐ŸŽฏ the attacker's response reaches the client, and the DoS attack on the server is aimed at stopping the legit response from the server from reaching the client ๐Ÿšซ arguably, the attacker can skip the DoS on the server as long as the faked response beats the real one back to the client, and the client uses the first response and ignores the second (even though it's different) ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ

12.2.6 Approach VI: Duplication โœจ

okay so this one is giving copycat energy ๐Ÿ™ˆ It's similar to Approach V. The attacker listens on the network for a STUN request, and when it spots one, it makes its own STUN request to the server. This copy is identical to the one it saw, except the source IP address is spoofed to be the address the attacker wants placed in the MAPPED-ADDRESS of the STUN response. The attacker can even send a whole flood of these ๐Ÿ’€

So the STUN server gets the one real request plus a flood of duplicate fake ones, and it sends a response to every single one ๐Ÿ˜ญ If the flood is big enough to clog up routers or other equipment, there's a decent chance the one real response gets lost (along with plenty of the fake ones). The net result? The STUN client only ends up receiving the faked responses. And they're all identical, all carrying the MAPPED-ADDRESS the attacker wanted the client to use. Iconic for the attacker, not so iconic for us ๐Ÿฅ€

The flood isn't even needed. Only one faked request has to go out, as long as the faked response beats the real response back to the client, and the client uses the first response and ignores the second (even though it's different). Main character energy for whoever sends the fake first ๐Ÿ‘‘

Now, here's the thing ๐Ÿง In this approach, knocking out the STUN server or the IP network with a DoS attack so the valid response can't be sent or received is kinda problematic. The attacker needs the STUN server to be available to handle its own request. Because the client keeps retransmitting its request periodically, that leaves a super tiny window of opportunity. The attacker has to start the DoS attack right after the client's actual request, so the correct response gets discarded, then stop the DoS attack so it can send its own request, all before the client's next retransmission. The retransmits are spaced pretty closely (100ms to a few seconds), so this is very difficult to pull off ๐Ÿ’…

Besides DoS attacks, there may be other ways to stop the client's actual request from reaching the server. Layer 2 manipulations, for example, might be able to accomplish it.

Fortunately, Approach IV is subject to the same limitations documented in Section 12.2.3, which limit the range of MAPPED-ADDRESSes the attacker can cause the STUN server to generate. Phew ๐Ÿซถ


12.3 Countermeasures ๐Ÿ›ก๏ธ

STUN provides mechanisms to counter the approaches described above, and additional, non-STUN techniques can be used as well.

First off, it is RECOMMENDED that networks with STUN clients implement ingress source filtering (RFC 2827 [7]). This is particularly important for the NATs themselves. As Section 12.2.3 explains, NATs which do not perform this check can be used as "reflectors" in DDoS attacks. Most NATs do perform this check as a default mode of operation. We strongly advise people that purchase NATs to ensure that this capability is present and enabled ๐Ÿšจ

Secondly, it is RECOMMENDED that STUN servers be run on hosts dedicated to STUN, with all UDP and TCP ports disabled except for the STUN ports. This is to prevent viruses and Trojan horses from infecting STUN servers, in order to prevent their compromise. This helps mitigate Approach I (Section 12.2.1). Locked-down servers, locked-down vibes ๐Ÿ”’๐ŸŒธ

Thirdly, to prevent the DNS attack of Section 12.2.2, Section 9.2 recommends that the client verify the credentials provided by the server with the name used in the DNS lookup. Checking the ID before trusting the name ๐Ÿชชโœจ

Finally, all of the attacks above rely on the client taking the mapped address it learned from STUN, and using it in application layer protocols. If encryption and message integrity are provided within those protocols, the eavesdropping and identity assumption attacks can be prevented. As such, applications that make use of STUN addresses in application protocols SHOULD use integrity and encryption, even if a SHOULD level strength is not specified for that protocol. For example, multimedia applications using STUN addresses to receive RTP traffic would use secure RTP [16]. Encrypt your whole life, bestie ๐Ÿ”๐Ÿ’œ

The above three techniques are non-STUN mechanisms. STUN itself provides several countermeasures.

Approaches IV (Section 12.2.4), when generating the response locally, and V (Section 12.2.5) require an attacker to generate a faked response. This attack is prevented using the message integrity mechanism provided in STUN, described in Section 8.1. Integrity checks catch the fakes ๐Ÿฆ‹

Approaches III (Section 12.2.3) IV (Section 12.2.4), when using the relaying technique, and VI (12.2.6), however, are not preventable through server signatures. Both approaches are most potent when the attacker can modify the request, inserting a RESPONSE-ADDRESS that routes to the client. Fortunately, such modifications are preventable using the message integrity techniques described in Section 9.3. However, these three approaches are still functional when the attacker modifies nothing but the source address of the STUN request. Sadly, this is the one thing that cannot be protected through cryptographic means, as this is the change that STUN itself is seeking to detect and report. It is therefore an inherent weakness in NAT, and not fixable in STUN ๐Ÿ˜” To help mitigate these attacks, Section 9.4 provides several heuristics for the client to follow. The client looks for inconsistent or extra responses, both of which are signs of the attacks described above. However, these heuristics are just that - heuristics, and cannot be guaranteed to prevent attacks. The heuristics appear to prevent the attacks as we know how to launch them today. Implementors should stay posted for information on new heuristics that might be required in the future. Such information will be distributed on the IETF MIDCOM mailing list, midcom@ietf.org. Keep your eyes on that list, babe ๐Ÿ‘€


12.4 Residual Threats โš ๏ธ

None of the countermeasures listed above can prevent the attacks described in Section 12.2.3 if the attacker is in the appropriate network paths. Specifically, consider the case in which the attacker wishes to convince client C that it has address V. The attacker needs to have a network element on the path between A and the server (in order to modify the request) and on the path between the server and V so that it can forward the response to C. Furthermore, if there is a NAT between the attacker and the server, V must also be behind the same NAT. In such a situation, the attacker can either gain access to all the application-layer traffic or mount the DDOS attack described in Section 12.1.1. Note that any host which exists in the correct topological relationship can be DDOSed. It need not be using STUN. Scary but true ๐Ÿฅบ


13. IANA Considerations ๐Ÿ“‹

STUN cannot be extended. Changes to the protocol are made through a standards track revision of this specification. As a result, no IANA registries are needed. Any future extensions will establish any needed registries. No registry drama here, just vibes ๐ŸŒˆ


14. IAB Considerations ๐ŸŽ€

The IAB has studied the problem of "Unilateral Self Address Fixing", which is the general process by which a client attempts to determine its address in another realm on the other side of a NAT through a collaborative protocol reflection mechanism (RFC 3424 [17]). STUN is an example of a protocol that performs this type of function. The IAB has mandated that any protocols developed for this purpose document a specific set of considerations. This section meets those requirements. Checklist complete โœ…

14.1 Problem Definition ๐ŸŽฏ

From RFC 3424 [17], any UNSAF proposal must provide:

"Precise definition of a specific, limited-scope problem that is to be solved with the UNSAF proposal. A short term fix should not be generalized to solve other problems; this is why "short term fixes usually aren't"."

The specific problems being solved by STUN are:

  • Provide a means for a client to detect the presence of one or more NATs between it and a server run by a service provider on the public Internet. The purpose of such detection is to determine additional steps that might be necessary in order to receive service from that particular provider.
  • Provide a means for a client to detect the presence of one or more NATs between it and another client, where the second client is reachable from the first, but it is not known whether the second client resides on the public Internet.
  • Provide a means for a client to obtain an address on the public Internet from a non-symmetric NAT, for the express purpose of receiving incoming UDP traffic from another host, targeted to that address.

STUN does not address TCP, either incoming or outgoing, and does not address outgoing UDP communications. So, scope check: STUN is laser-focused ๐Ÿ”ฆ

14.2 Exit Strategy ๐Ÿšช

From [17], any UNSAF proposal must provide:

"Description of an exit strategy/transition plan. The better short term fixes are the ones that will naturally see less and less use as the appropriate technology is deployed."

STUN comes with its own built in exit strategy. This strategy is the detection operation that is performed as a precursor to the actual UNSAF address-fixing operation. This discovery operation, documented in Section 10.1, attempts to discover the existence of, and type of, any NATS between the client and the service provider network. Whilst the detection of the specific type of NAT may be brittle, the discovery of the existence of NAT is itself quite robust. As NATs are phased out through the deployment of IPv6, the discovery operation will return immediately with the result that there is no NAT, and no further operations are required. Indeed, the discovery operation itself can be used to help motivate deployment of IPv6; if a user detects a NAT between themselves and the public Internet, they can call up their access provider and complain about it. Honestly iconic, the user is empowered ๐Ÿ“ž๐Ÿ’…

STUN can also help facilitate the introduction of midcom. As midcom-capable NATs are deployed, applications will, instead of using STUN (which also resides at the application layer), first allocate an address binding using midcom. However, it is a well-known limitation of midcom that it only works when the agent knows the middleboxes through which its traffic will flow. Once bindings have been allocated from those middleboxes, a STUN detection procedure can validate that there are no additional middleboxes on the path from the public Internet to the client. If this is the case, the application can continue operation using the address bindings allocated from midcom. If it is not the case, STUN provides a mechanism for self-address fixing through the remaining midcom-unaware middleboxes. Thus, STUN provides a way to help transition to full midcom-aware networks. A glow-up with a clear path ๐Ÿฆ‹๐ŸŒˆ

14.3. Brittleness Introduced by STUN โœจ

Okay so [17] says any UNSAF proposal must provide a discussion of specific issues that might make systems more "brittle". Like, approaches that use data at multiple network layers create more dependencies, make debugging harder, and make it harder to transition. Makes total sense ๐Ÿง 

STUN is lowkey brittle in a bunch of ways, bestie ๐Ÿ˜ญ

  • The discovery process assumes a certain classification of devices based on how they treat UDP. There could be other kinds of NATs out there that don't fit into one of these molds, so future NATs may not be properly detected by STUN. STUN clients (but not servers) would need to change to accommodate that. ๐Ÿ™ˆ
  • The binding acquisition usage of STUN doesn't work for all NAT types. It will work for any application with full cone NATs only. For restricted cone and port restricted cone NATs, it works for some applications, depending on the application, and application specific processing will generally be needed. For symmetric NATs, binding acquisition won't yield a usable address. That super tight dependency on the specific NAT type is what makes the protocol brittle ๐Ÿ’€
  • STUN assumes the server lives on the public Internet. If the server is in another private address realm, the user may or may not be able to use its discovered address to talk to other users, and there's no way to detect that situation ๐Ÿซ 
  • The bindings allocated from the NAT need to be continuously refreshed. Since binding timeouts are very implementation specific, the refresh interval can't easily be determined. When a binding isn't being actively used to receive traffic but is just sitting there waiting for an incoming message, the refreshing needlessly eats up network bandwidth ๐Ÿ“
  • Using the STUN server as an extra network element adds another point of potential security attack. STUN's security measures prevent most of these attacks, but not all of them ๐Ÿ”’
  • Using the STUN server as an extra network element also adds another point of failure. If the client can't locate a STUN server, or if the server is unavailable because of a failure, the application can't function ๐Ÿ˜ฉ
  • Using STUN to discover address bindings increases latency for applications. For example, a Voice over IP application will see call setup delays go up by at least one RTT to the STUN server ๐Ÿ“ž
  • Discovering binding lifetimes is prone to error. It assumes that the same lifetime exists for all bindings, which may not be true if the NAT uses dynamic binding lifetimes to handle overload, or if the NAT itself reboots during the discovery process ๐ŸŒ€
  • STUN also puts some restrictions on the network topologies it needs for proper operation. If client A gets an address from STUN server X and sends it to client B, B may not be able to send to A using that IP address. The address won't work if any of the following is true:
    • The STUN server is not in an address realm that is a common ancestor (topologically) of both clients A and B. For example, picture clients A and B, both with residential NAT devices. Both devices connect them to their cable operators, but the clients have different providers, and each provider has a NAT in front of its entire network connecting it to the public Internet. If the STUN server A uses is in A's cable operator's network, the address it gives A won't be usable by B. The STUN server must be in the network that's a common ancestor to both, which in this case is the public Internet ๐ŸŒ
    • The STUN server is in an address realm that is a common ancestor to both clients, but both clients are behind the same NAT connecting to that address realm. For example, if the two clients in the previous example had the same cable operator, and that cable operator had a single NAT connecting its network to the public Internet with the STUN server on the public Internet, the address A gets still wouldn't be usable by B. That's because some NATs won't accept an internal packet sent to a public IP address that gets mapped back to an internal address. To handle this, additional protocol mechanisms or configuration parameters need to be introduced that detect this case ๐Ÿ‘€
  • Most significantly, STUN brings in security threats that can't be eliminated. This specification describes heuristics that can help mitigate the problem, but it's provably unsolvable given what STUN is trying to accomplish. These security problems are described fully in Section 12. ๐Ÿšจ

14.4. Requirements for a Long Term Solution ๐Ÿ’œ

Okay, so [17] also says any UNSAF proposal must provide the identification of requirements for longer term, sound technical solutions, contributing to the process of finding the right longer term solution.

Our experience with STUN led to the following requirements for a long term solution to the NAT problem:

Requests for bindings and control of other resources in a NAT need to be explicit. Much of the brittleness in STUN comes from it guessing at the parameters of the NAT, instead of telling the NAT which parameters to use. ๐ŸŽฏ

Control needs to be "in-band". There are way too many scenarios where the client won't know where the middleboxes are ahead of time. Instead, control of those boxes needs to happen in-band, traveling along the same path the data itself will travel. That guarantees the right set of middleboxes gets controlled. This is only true for first-party controls, though. Third-party controls are best handled using the midcom framework. ๐Ÿ›ค๏ธ

Control needs to be limited. Users need to communicate through NATs that are outside their administrative control. For providers to be willing to deploy NATs that users in different domains can control, the scope of those controls needs to be extremely limited. Typically, that means allocating a binding to reach the address where the control packets are coming from. ๐Ÿงฑ

Simplicity is paramount. The control protocol needs to be implemented in very simple clients, and the servers need to support extremely high loads. The protocol also needs to be extremely robust, since it's the precursor to a host of application protocols. So simplicity is key, bestie ๐Ÿ‘‘

14.5. Issues with Existing NAPT Boxes ๐Ÿงƒ

From [17], any UNSAF proposal must provide a discussion of the impact of the noted practical issues with existing, deployed NA[P]Ts, along with experience reports.

Several practical issues with STUN are about future proofing, meaning the protocol breaks when new NAT types get deployed. Luckily that's not a problem right now, since most deployed NATs are the types STUN assumes. STUN's main use so far is in VoIP, where it helps allocate addresses for receiving RTP [12] traffic. In that application, the periodic keepalives come from the RTP traffic itself. Still, a few practical problems show up for RTP. First, RTP assumes RTCP traffic is on a port one higher than the RTP traffic. That pairing can't be guaranteed through NATs that aren't directly controllable, so RTCP traffic may not be received properly. Protocol extensions to SDP have been proposed to fix this by letting the client signal a different port for RTCP [18]. Even so, there will be interoperability problems for some time. ๐Ÿ“‰

For VoIP, silence suppression can cause a gap in RTP packet transmission. That could mean losing a binding in the middle of a call, if the silence period is longer than the binding timeout. Sending occasional silence packets to keep the binding alive can help, but it adds brittleness. Proper operation then depends on the silence suppression algorithm in use, whether a comfort noise codec is used, the duration of the silence period, and the binding lifetime in the NAT. Lots of moving parts, periodt ๐ŸŽข

14.6. In Closing ๐ŸŒธ

The problems with STUN aren't design flaws in STUN itself. They come from the lack of standardized behaviors and controls in NATs. That lack of standardization has led to a proliferation of devices whose behavior is highly unpredictable, extremely variable, and uncontrollable. STUN does the best it can in such a hostile environment. Ultimately, the fix is to make the environment less hostile and to introduce controls and standardized behaviors into NATs. Until that happens, though, STUN is a good short term solution given the terrible conditions it's forced to operate under ๐Ÿซถ

15. Acknowledgments ๐ŸŽ€

The authors would like to thank Cedric Aoun, Pete Cordell, Cullen Jennings, Bob Penfield and Chris Sullivan for their comments, and Baruch Sterman and Alan Hawrylyshen for initial implementations. Thanks for Leslie Daigle, Allison Mankin, Eric Rescorla, and Henning Schulzrinne for IESG and IAB input on this work. ๐Ÿ’–

16. Normative References ๐Ÿ“š

[1] Bradner, S., "Key words for use in RFCs to indicate requirement levels", BCP 14, RFC 2119, March 1997.

[2] Dierks, T. and C. Allen, "The TLS protocol Version 1.0", RFC 2246, January 1999.

[3] Gulbrandsen, A., Vixie, P. and L. Esibov, "A DNS RR for specifying the location of services (DNS SRV)", RFC 2782, February 2000.

[4] Chown, P., "Advanced Encryption Standard (AES) Ciphersuites for Transport Layer Security (TLS)", RFC 3268, June 2002.

[5] Rescorla, E., "HTTP over TLS", RFC 2818, May 2000.

[6] Postel, J., "Internet Protocol", STD 5, RFC 791, September 1981.

[7] Ferguson, P. and D. Senie, "Network Ingress Filtering: Defeating Denial of Service Attacks which employ IP Source Address Spoofing", BCP 38, RFC 2827, May 2000. ๐Ÿฆ‹

17. Informative References โœจ

Okay bestie, these are the receipts ๐Ÿงพ the extra reading that backs up the whole doc. Not strictly required, but lowkey essential ๐Ÿ’…

  • [8] Senie, D., "Network Address Translator (NAT)-Friendly Application Design Guidelines", RFC 3235, January 2002.
  • [9] Srisuresh, P., Kuthan, J., Rosenberg, J., Molitor, A. and A. Rayhan, "Middlebox Communication Architecture and Framework", RFC 3303, August 2002.
  • [10] Rosenberg, J., Schulzrinne, H., Camarillo, G., Johnston, A., Peterson, J., Sparks, R., Handley, M. and E. Schooler, "SIP: Session Initiation Protocol", RFC 3261, June 2002.
  • [11] Holdrege, M. and P. Srisuresh, "Protocol Complications with the IP Network Address Translator", RFC 3027, January 2001.
  • [12] Schulzrinne, H., Casner, S., Frederick, R. and V. Jacobson, "RTP: A Transport Protocol for Real-Time Applications", RFC 1889, January 1996.
  • [13] Krawczyk, H., Bellare, M. and R. Canetti, "HMAC: Keyed-Hashing for Message Authentication", RFC 2104, February 1997.
  • [14] Kohl, J. and C. Neuman, "The kerberos Network Authentication Service (V5)", RFC 1510, September 1993.
  • [15] Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P. and T. Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", RFC 2616, June 1999.
  • [16] Baugher M., et al., "The secure real-time transport protocol", Work in Progress.
  • [17] Daigle, L., Editor, "IAB Considerations for UNilateral Self-Address Fixing (UNSAF) Across Network Address Translation", RFC 3424, November 2002.
  • [18] Huitema, C., "RTCP attribute in SDP", Work in Progress.

18. Authors' Addresses ๐Ÿฆ‹

Meet the squad who wrote this thing ๐Ÿซถ

Jonathan Rosenberg
dynamicsoft
72 Eagle Rock Avenue
First Floor
East Hanover, NJ 07936

EMail: jdrosen@dynamicsoft.com


Joel Weinberger
dynamicsoft
72 Eagle Rock Avenue
First Floor
East Hanover, NJ 07936

EMail: jweinberger@dynamicsoft.com


Christian Huitema
Microsoft Corporation
One Microsoft Way
Redmond, WA 98052-6399

EMail: huitema@microsoft.com


Rohan Mahy
Cisco Systems
101 Cooper St
Santa Cruz, CA 95060

EMail: rohan@cisco.com

Copyright (C) The Internet Society (2003). All Rights Reserved.

Okay, the legal bit, but make it cute ๐ŸŽ€ You're allowed to copy this document and hand it out to people, and you can write derivative works that comment on or explain it, or help people implement it. You can prepare, copy, publish and distribute those in whole or in part, with no restrictions of any kind, as long as the copyright notice and this paragraph show up on every copy and every derivative work.

BUT the document itself can't be modified in any way. That includes removing the copyright notice or the references to the Internet Society or other Internet organizations. The only exceptions are developing Internet standards, where the copyright procedures in the Internet Standards process must be followed, or translating it into languages other than English.

These permissions are perpetual and won't be revoked by the Internet Society or its successors or assigns. โœจ

This document and the information in it is provided on an "AS IS" basis, and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. ๐Ÿ’€

Acknowledgement ๐Ÿซถ

Funding for the RFC Editor function is currently provided by the Internet Society. ๐Ÿ’–

๐Ÿ“ฆ where this page comes from