Tag Archives: ICE

WebRTC Security

Unlike most conventional  real-time systems (e.g., SIP-based soft phones) WebRTC communications  are directly controlled by a Web server over some signalling protocol which may be XMPP , websockets , socket.io , Ajax etc . This poses new  challenges such as

  • Web browser might expose a JavaScript APIs which allows  web server to place a video call itself.This may cause web pages to secretly record and stream the webcam activity from user’s computer
  • malicious calling services can record the user’s conversation and misuse
  • malicious webpages can lure users via advertising and execute auto calling services .
  • Since JavaScript calling APIs are implemented as browser built-ins , un authorized access to these can also make user’s audio and camera streams vulnerable
  • If program and APIs allow the server to instruct the browser to send arbitrary content, then they can be used to bypass firewalls or mount denial of service attacks.

WEB ATTACKERS are who induce users to visit their sites but do not control the network.NETWORK ATTACKERS are who are able to control network. When analyzing HTTP connections, we must assume that traffic is going to the attacker.

security WebRTC

The Browser Threat Model

The browser acts as a TRUSTED COMPUTING BASE (TCB) both from the user’s perspective and to some extent from the  server’s.  HTML and JavaScript (JS) provided by the web server can execute scripts on browser and generate actions and events . However browser  operates in a sandbox that isolates these scripts both from the user’s computer and from server .

 

Access to Local Resources

The users computer may have lot of private and confidential data on the disk . Browser do make it mandatory that user must explicitly select the file and consent to its upload before doing file upload and transfer transactions . However still it is not very rare that misleading text and buttons can make users click files .  

Another way of accessing local resources is through downloading malicious files to users computer which are executable and may harm users computer .

 

SOP or Same Origin Policy

SOP  forces scripts from each site to run in their own, isolated, sandboxes.  It enables webpages and scripts from the same origin server to interact with each other’s JS variables, but prevents pages from the different origins or even iframes on the same page to not exchange information.

As part of SOP scripts are allowed to make HTTP requests via the  XMLHttpRequest() API to only those server which have same ORIGIN/domain as that of the originator .

 

CORS [Cross-Origin Resource Sharing ]

CORS enables multiple web services to intercommunicate . Therefore when a script from origin A executes what would otherwise be a forbidden cross-origin request, the browser instead contacts the target server B to determine whether it is willing to allow cross-origin requests from A.  If it is so willing, the browser then allows the request.  This consent verification process is designed to safely allow cross-origin requests.

 

Websockets

Even websockets overcome SOP and establish cross origin transport channels .

Once a WebSockets connection has been established from a script to a site, the script can exchange any traffic it likes without being required to frame it as a series of HTTP request/response transactions.

WebSockets use masking technique to randomize the bits that are being transmitted , thus making it more difficult to generate traffic which resembles a given protocol , thus making it difficult for inspection from flowing traffic .

 

JSONP

Jsonp is a hack designed to bypass origin restriction through script tag injection. A JSONp enabled server passes the response in user specified function

when we use <script> tags the domain limitation is ignored ie we can load scripts from any domain .  So when we need to fetch get exchange data just pass callback parameters through scripts . For example


function mycallback(data){
// this is the callback function executed when script returns 
alert("hi"+ data);</span>
}

var script = document.createElement('script');
script.src = '//serverb.com/v1/getdata?callback=mycallback'
document.head.appendChild(script) 

 

There have been found vulnerabilities in the existing Java and Flash consent verification techniques and handshake.

The Security arising from ICE and TURN

ICE

Sender and receiver are able to share media stream after a offer answer handshake. But we already need one in order to do NAT hole-punching. Presuming the ICE server is malicious , in absence of transaction IDs by stun unknow to call scripts , it is not possible for the webpage of receiver to ascertain is the data is forged or original . Thus to prevent this the browser must generate hidden transaction Id’s and should not sharing with call scripts ,even via a diagnostic interface.

 

IP Location Privacy

As soon as the callee sends their ICE candidates, the caller learns the callee’s IP addresses.  The callee’s server reflexive address reveals a lot of information about the callee’s location.

To prevent server should suppress the start of ICE negotiation until the callee has answered.

Also user may hide their location entirely by forcing all traffic through a TURN server.

Communications Security

Goal of webrtc based call services should be to create channel which is secure  against both message recovery and message modification for all audio / video and data .

Threats from Screen Sharing

With the increasing requirement of screen sharing in web app and communication systems there is always a high threat of oversharing / exposing confidential passwords , pins , security details etc . This may either through some part of screen or some notification whihc pops up .

There is always the case when the user may believe he is sharing a window when in fact they are the entire desktop.

The attacker may request screensharing and make user open his webmail , payment settings or even net-banking accounts .

 

Long term access to camera and microphone

When user frequently uses a site he / she may want to give the site a long-term access to the camera and microphone ( indicated by ” Always allow on this site ” in chrome ). However the site may be hacked and thus initiate call on users’ computer automatically to secretly listen-in .

 

False UI shows cut off call while still being active

Unless the user checks his laptops glowing camera light LED or goes and monitors the traffic himself he would not know if there is active call in background, which according to him he had cut off . In such a case an attacker may pretend to cut a call shows red phone signs and supportive text but still keep the session and media stream active placing himself on mute .

 

During-Call Attack

Even if the calling service cannot directly access keying material ,it  can simply mount a man-in-the-middle attack on the connection. The idea is to mount a bridge capturing all the traffic.

To protect against this it is now mandatory to use https for using getusermedia and otherwise also recommended to keep webrtc comm services on https or use strict fingerprinting .
This section is derived from Security Considerations for WebRTC draft-ietf-rtcweb-security-08


 

How can I make my WebRTC solution secure?

In one of my previous posts I have mentioned about Security threats to WebRTC Solution . It includes mainly 4 ways in which WebRTC Solution Providers and Users are vulnerable . It includes

  1. Identity Management ,
  2. Browser Security ,
  3. Authentication and
  4. Media encryption.

Since I have already covered these topics here( https://altanaitelecom.wordpress.com/2014/10/03/security-for-webrtc-applications/ ) I will not repeat the same here. This post is about making WebRTC secure so that they can be used inn area which require sensitive data to be communicated and need to be secure enough to withstand and hacks and attacks.

In the recent months everyone has been trying to get into the WebRTC  space but at the same time fearing that hackers might be able to listen in on conferences, access user data, or even private networks. Although development and usage around WebRTC is so simple , the security and encryption aspects of it are in the dim light.

So does existing WebRTC model offer security ?

We know that the forces behind WebRTC standardization are WHATWG, W3C, IETF and strong internet working groups . WebRTC security was already taken into consideration when standards were being build for it . The encryption methods and technologies like DTLS and SRTP were included to safeguard users from intrusions so that the information stays protected.

WebRTC media stack has native built-in features that address security concerns. The peer-to-peer media is already encrypted for privacy . Figure below:

WebRTC media stack Solution Architecture - Google Slides (1)

WebRTC media stack

For WebRTC to transfer real time data, the data is first encrypted using the DTLS (Datagram Transport Layer Security) method. This is a protocol built into all the WebRTC supported browsers from the start (Chrome, Firefox and Opera). On a DTLS encrypted connection, eavesdropping and information tampering cannot take place.

Other than DTLS, WebRTC also encrypts video and audio data via the SRTP (Secure Real-Time Protocol) method ensuring that IP communications – your voice and video traffic – can not be heard or seen by unauthorized parties.

What is SRTP ?

The Secure Real-time Transport Protocol (or SRTP) defines a profile of RTP (Real-time Transport Protocol), intended to provide encryption, message authentication and integrity, and replay protection to the RTP data in both unicast and multicast applications.

Earlier models of VOIP communication such as SIP based calls had an option to use only RTP for communication thereby subjecting the endpoint users to lot of problem like compromising media Confidentiality  . However the WebRTC model mandates the use of SRTP hence ruling out insecurities of RTP completely. For encryption and decryption of the data flow SRTP utilizes the Advanced Encryption Standard (AES) as the default cipher.

What is DTLS ?

DTLS allows datagram-based applications to communicate in a way that is designed to prevent eavesdropping, tampering, or message forgery. The DTLS protocol is based on the stream-oriented Transport Layer Security (TLS) protocol .

Together DTLS and SRTP enables the exchange of the cryptographic parameters so that the key exchange takes place in the media plane and are multiplexed on the same ports as the media itself without the need to reveal crypto keys in the SDP.

Today the browser acts as a TRUSTED COMPUTING BASE (TCB) where the HTML and JS act inside of a sandbox that isolates them both from the user’s computer.

A script cannot access user’s webcam , microphone , location , file , desktop capture without user’s explicit consent. When the user allows access, a red dot will appear on that tab, providing a clear indication to the user, that the tab has media access.

Figure depicting browser asking for user’s consent to access Media devices for WebRTC .

Untitled drawing

Figure depicting Media Capture active on browser with red dot .

Untitled drawing (1)
we know that XMLHttpRequest() API can be used to secretly send data from one origin to other and this can be used to secretly send information without user’s knowledge . However now , SAME ORIGIN POLICY (SOP) in browser’s prevents server A from mounting attacks on server B via the user’s browser, which protects both the user (e.g., from misuse of his credentials) and the server B (e.g., from DoS attack).

 

In-spite of all this ,  the security challenges with Web Server based WebRTC service are many for example :

  1. If the both the peers have WebRTC browser then one can place a WebRTC call to callee anytime this might result in denial of service .
  2. Since the media is p2p and also can override firewalls settings through TURN server , it can result in unwanted data being send to peer .
  3. One may secretly make calls to users through website and extract information .
  4. Threat from screen sharing, for example user might mistakenly share his internet banking screen or some confidential information.
  5. Giving long-term access to the camera and microphone for certain sites is also a concern . for example : since next time you visit a site that has access to your microphone and camera , they can secretly be viewing youe webcam and microphone inputs .
  6. Clever use of User Interface to mask a ongoing call can mislead the user into believing that call has been cut while it is secretly still ongoing.
  7. Network attackers can modify an HTTP connection through my Wifi router or hotspot to inject an IFRAME (or a redirect) and then forge the response to initiate a call to himself.
  8. As WebRTC doesn’t yet have an congestion control mechanism , it can eat up a large chunk of user’s bandwidth.
  9. By visiting chrome://webrtc-internals/ in chrome browser alone , one can view the full traces of all webRTC communication happening through his browser . The traces contain all kinds of details like signalling server used , relay servers , TURN servers , peer IP , frame rates etc .

 

WebRTC Internals

Ofcourse other challenges that arrive with any other webservice based architecture are also applicable here such as :

  1. Malicious Websites which automatically execute the attacker’s scripts.
  2. User can be induced to download harmful executable files and run them.
  3. Improper use of W3C Cross-Origin Resource Sharing (CORS) to bypass SAME ORIGIN POLICY (SOP) .

Best practices to make your VOIP Solution more secure

A simple WebRTC architecture is shown in the figure below :

WebRTC media stack Solution Architecture - Google Slides (2)

By following the simple steps described below one can ensure a more secure WebRTC implementation . The same applies to healthcare and banking firms looking forth to use WebRTC as a communication solution for their portals .

1. Ensure that the signalling platform is over a secure protocol such as SIP / HTTPS / WSS .

2. User’s that can participate in a call , should be pre registered / Authenticated with a registrar service. Unauthenticated entities should be kept away from session’s reach .

WebRTC authentication certificate

WebRTC authentication certificate

2. Make sure that ICE values are masked thereby not rendering the caller/ callee’s IP and location to each other through tracing in chrome://webrtc-internals/ or packet detection in Wirehsark on user’s end.

3. Also since media is p2p , the media contents like audio video channel are between peers directly in full duplex. Thus

4. As the signalling server maintains the number of peers , it should be consistently monitored for addition of suspicious peers in a call session. If the number of peers actually present on signalling server is more that the number of peers interacting on WebRTC page then it means that someone is eavesdropping secretly and should be terminated from session access by force.

5. It is observed these days that users simply agree to all permissions request from browser without actually consciously giving consent . Therefore user’s should be made aware of API in websites which ask for undue permissions . For example permission to :

Screenshot from 2015-04-22 15:22:15

6. To protect against Man-In-The-Middle (MITM) attack the media path should be monitored regularly for no suspicious relay.

7. Third party API should be thoroughly verified before sending their data on WebRTC DataChannel.

8. Before Desktop Sharing user’s should be properly notified and advised to close any screen containing sensitive information .

 

What happens if your VOIP solution is on the verge of being compromised ?

As the media connections are p2p , even if we restart the signalling server , it will not affect the ongoing media sessions . Only the time duration ( probably 3 – 4 minutes ) it takes to restart the server , is when the users will not be able to connect to signalling server for creating new sessions .

Most browsers today like Google Chrome and Mozilla Firefox have a goof record of auto-updating themselves withing 24 hours of a vulnerability of threat occurring .

If a call is confirmed to be compromised , it should be within the power of Web Application server rendering the WebRTC capable page to cut off the call .

References :

TURN server for WebRTC – RFC5766-TURN-Server , Coturn , Xirsys

STUN (Session Traversal Utilities for NAT) and TURN (Traversal Using Relays around NAT) are protocols that can be used to provide NAT traversal for VoIP and WebRTC. These projects provide a VoIP media traffic NAT traversal server and gateway.

TURN Server is a VoIP media traffic NAT traversal server and gateway.

I come accross the question of difference between turn and stun a lot . Here I wanted to specify in very clear words that TURN is an extension of STUN .

rfc5766-turn-server

This is a VoIP gateway for inter network communication which is popular and MIT based .

platforms supported :

Any client platform is supported, including Android, iOS, Linux, OS X, Windows, and Windows Phone. This project can be successfully used on other *NIX platforms ( Aamazon EC2) too. It supports flat file or Database based user management system ( MySQL , postgress , redis ). The source code project contains ,  TURN server ,  TURN client messaging library and some sample scripts to test various modules like protocol , relay , security etc .

Protocols :

protocols between the TURN client and the TURN server – UDP, TCP, TLS, and DTLS. Relay protocol – UDP , TCP .

Authentication

The authentication mechanism is using key which is calculated over the user name, the realm, and the user password. Key for the HMAC depends on whether long-term or short-term credentials are in use. For long-term credentials, the key is 16 bytes:
key = MD5(username “:” realm “:” SASLprep(password))

Installation

Since I used my Ubuntu Software center for installing the RFC turn server 5677 .

Screenshot from 2015-03-05 15:22:30

More information is on Ubuntu Manuals : http://manpages.ubuntu.com/manpages/trusty/man1/turnserver.1.html

The content got stored inside /usr/share/rfc5766-turn-server.

Also install mysql for record keeping

sudo apt-get install mysql-server

mysql

mysql2mysql4

Intall MySQL workbench to monitor the values feed into the turn database server in MysqL. connect to MySQL instance using the following screenshot

mysql5

The database formed with mysql after successful operation is as follows . We  shall notice that the initial db is absolutely null

mysql8empty

Terminal Commands

These terminal command ( binary images ) get stored inside etc/init.d after installing

turnadmin –

Its turn relay administration tool used for generating , updating keys and passwords . For generating a key to get long term crdentaial use -k command and for aading or updateing a long -term user use the -a command. Therefore a simple command to generate a key is

format : turnadmin -k -u -r -p
examples : turnadmin -k -u turnwebrtc -r mycompany.com -p turnwebrtc

The generated key is displayed in console . For example the following screenshot shows this :

rfc5677turnkey

To fill in user with long term credentails

Format : turnadmin -a [-b | -e | -M | -N ] -u -r -p

exmaple : turnadmin -a -M “host=localhost dbname=turn user=turn password=turn” -u altanai -r mycompany.com -p 123456

Check the values reflected in MySQL workbench for long term user table . ( screenshot depicts two entries for altanai and turnwebrtc user )

turnkeylongterm

you can also check it on console using the -l command

format :turnadmin -l –mysql-userdb=””

example :  turnadmin -l –mysql-userdb=”host=127.0.0.1 dbname=turn user=turnwebrtc password=turnwebrtc connect_timeout=30″

longtermuserlcommand

or we can also check using the terminal based mySQL client

mysql> use turn;
Database changed

mysql> select * from turnusers_lt;
+------------+----------------------------------+
| name | hmackey |
+------------+----------------------------------+
| altanai | 57bdc681481c4f7626bffcde292c85e7 |
| turnwebrtc | 6066cbe0b5ee14439b2ddfc177268309 |
+------------+----------------------------------+
2 rows in set (0.00 sec)

turnserver –

Its command to handle the turnserver itself . We can use the simple turnserver command to start it without any db support using just turnserver. Screenshot for this is

turnserverstart

We can use a database like mysql to start it with db connection string

Format : turnserver –mysql-userdb=””

Example : turnserver –mysql-userdb=”host=127.0.0.1 dbname=turn user=turnwebrtc password=turnwebrtc connect_timeout=30″

turnservermysqldb

turnutils_uclient:

emulates multiple UDP,TCP,TLS or DTLS clients.

turnutils_peer:

simple stateless UDP-only “echo” server. For every incoming UDP packet, it simply echoes it back.

turnutils_stunclient:

simple STUN client example that implements RFC 5389 ( using STUN as endpoint to determine the IP address and port allocated to it , keep-alive , check connectivity etc) and RFC 5780 (experimental NAT Behavior Discovery STUN usage) .

turnutils_rfc5769check:

checks the correctness of the STUN/TURN protocol implementation. This program will perform several checks and print the result on the screen. It will exit with 0 status if everything is OK, and with (-1) if there was an error in the protocol implementation.

Specifications :

TURN specifications include :

  • RFC 5766 – base TURN specs
  • RFC 6062 – TCP relaying TURN extension
  • RFC 6156 – IPv6 extension for TURN
  • DTLS
  • Mobile ICE (MICE)

STUN specifications :

  • RFC 3489 – Simple Traversal of User Datagram Protocol (UDP) Through Network Address Translators (NATs) (STUN) to discover the presence and public IP
  • RFC 5389 – STUN serves as a tool for other protocols in NAT traversal. It can be used by an endpoint to determine the IP address and port allocated to it , keep-alive  , check connectivity etc .
  • RFC 5769 – test vectors for STUN protocol . FINGERPRINT, MESSAGE-INTEGRITY, and XOR-MAPPED-ADDRESS involving binary-logical operations (hashing, xor)
  • RFC 5780 – experimental NAT Behavior Discovery STUN usage

ICE specifications :

  • RFC 5245 – ICE
  • RFC 5768 – ICE–SIP
  • RFC 6336 – ICE–IANA Registry
  • RFC 6544 – ICE–TCP
  • RFC 5928 – TURN Resolution Mechanism

Test :

1. Test vectors from RFC 5769 to double-check that our
STUN/TURN message encoding algorithms work properly. Run the utility to check all protocols :

$ cd examples
$ ./scripts/rfc5769.sh

2. TURN functionality test (bare minimum TURN example).

If everything compiled properly, then the following programs must run
together successfully, simulating TURN network routing in local loopback
networking environment:

console 1 :

$ cd examples
$ ./scripts/basic/relay.sh

console2 :

$ cd examples
$ ./scripts/peer.sh

If the client application produces output and in approximately 22 seconds
prints the jitter, loss and round-trip-delay statistics, then everything is
fine.

Usage

iceServers:[
{ ‘url’: ‘stun: altanai@mycompany.com’},
{ ‘url’: ‘turn: altanai@mycompany.com’, ‘credential’: ‘123456’}]

Insert the above piece of code on peer connection config .

Now call from one network environment to another . For example call from a enterprise network behind a Wifi router to a public internet datacard webrtc agent . The call should connect with video flowing smoothly between the two .

tooltips

website : https://code.google.com/p/rfc5766-turn-server/

Download the executable from : http://turnserver.open-sys.org/downloads/v3.2.5.4/

you can read about setting a carrier grade TURN infrastructure on amazon EC2 here –

coturn

Project Coturn evolved from rfc5766-turn-server project with many new advanced TURN specs beyond the original RFC 5766 document.
Here the databses supported are : SQLite , MySQL , PostgreSQL , Redis , MongoDB

Protocols :

The implementation fully supports the following client-to-TURN-server protocols: UDP  , TCP  , TLS  SSL3/TLS1.0/TLS1.1/TLS1.2; ECDHE , DTLS versions 1.0 and 1.2. Supported relay protocols UDP (per RFC 5766) and TCP (per RFC 6062)

Authetication :

Supported message integrity digest algorithms:

  • HMAC-SHA1, with MD5-hashed keys (as required by STUN and TURN standards)
  • HMAC-SHA256, with SHA256-hashed keys (an extension to the STUN and TURN specs)

Supported TURN authentication mechanisms:

Installation :

Install libopenssl and libevent plus its dev or extra libraries .
OpenSSL has to be installed before libevent2 for TLS beacuse When libevent builds it checks whether OpenSSL has been already installed, and its version.

Download coturn readonly  from

svn checkout http://coturn.googlecode.com/svn/trunk/ coturn-read-only

extract the tar contents
$ tar xvfz turnserver-.tar.gz

go inside the extracted folder and run the following command to build
$ ./configure
$ make
$ make install

Adding users in the format using turnadmin
$ Sudo turnadmin -a -u -r -p

Example
$ Sudo turnadmin -a -u altanai -r myserver.com -p 123456

Start the turn Server using turnserver from inside of /etc/init.d using the start command

$ sudo /etc/init.d/coturn start

Screenshot from 2015-01-06 12-08-15

The logs are usually stored in /var/log . Screenshot of log file

tuenlog2

The default configured port is 3478.If other port is needed, change the file /etc/turnserver.conf

Usuage:

Specify the  values in Peer Connection

Format:
iceServers: [
{ ‘url’: ‘stun: @: ‘},
{ ‘url’: ‘turn: @: ‘, ‘credential’: ”}]

example:

iceServers:[
{ ‘url’: ‘stun: altanai@myserver.com’},
{ ‘url’: ‘turn: altanai@myserver.com’, ‘credential’: ‘123456’}]

Specifications:

TURN specs:

STUN specs:

  • RFC 3489 – STUN – Simple Traversal of User Datagram Protocol (UDP) Through Network Address Translators (NATs)
  • RFC 5389 – Session Traversal Utilities for NAT (STUN)
  • RFC 5769 – test vectors for STUN protocol testing
  • RFC 5780 – NAT behavior discovery support
  • RFC 7443 – Application-Layer Protocol Negotiation (ALPN) Labels for STUN and TURN

ICE :

  • RFC 5245 – ICE
  • RFC 5768 – ICE–SIP
  • RFC 6336 – ICE–IANA Registry
  • RFC 6544 – ICE–TCP
  • RFC 5928 – TURN Resolution Mechanism

website : https://code.google.com/p/coturn/

Xirsys

Xirsys is a provider for WebRTC infrastructure which included stun and turn server hosting as well .

The process of using their services includes singing up for a account and choosing whether you want a paid service capable of handling more calls simultaneously or free one handling only upto 10 concurrent turn connections .

The dashboard appears like this :

xirsys1

To receive the api one need to make a one time call to their service , the result of which contains the keys to invoke the turn services from webrtc script .


&lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js&quot;&gt;&lt;/script&gt;&lt;script&gt;// &lt;![CDATA[

$.post(&quot;https://api.xirsys.com/getIceServers&quot;, {
ident: &quot;altanai&quot;,
secret: &quot;&lt; your secret key &gt;&quot;,
domain: &quot; &lt; your doemain &gt;&quot;,
application: &quot;default&quot;,
room: &quot;default&quot;,
secure: 1
},
function(data, status) {
alert(&quot;Data: &quot; + data + &quot;n Status: &quot; + status);
console.log(&quot;Data: &quot; + data + &quot;nnStatus: &quot; + status);
});
});
&lt;/script&gt;

The resulting output should look like ( my keys are hidden with a red rectangle ofcourse )

xirsysedited

The process of adding a TURN / STUN to your webrtc script in JS is as follows :

iceServers:[
{“url”:”stun:turn2.xirsys.com”},
{“username”:”< put your API username>”,”url”:”turn:turn2.xirsys.com:443?transport=udp”,”credential”:”< put your API credentail>”},
{“username”:”< put your API username>”,”url”:”turn:turn2.xirsys.com:443?transport=tcp”,”credential”:”< put your API credentail>”}]

website : http://xirsys.com/technology/

NAT traversal using STUN and TURN

We know that WebRTC is web based real-time communications on browser-based platform using the browser’s media application programming interface (API) and adding our JavaScript & HTML5 t control the media flow .
WebRTC has enabled developers to build apps/ sites / widgets / plugins capable of delivering simultaneous voice/video/data/screen-sharing capability in a peer to peer fashion.

But something which escapes our attention is the way in which media ia traversing across the network. Ofcourse the webrtc call runs very smoothly when both the peers are on open public internet without any restrictions or firewall blocks . But the real problem begins when one of the peer is behind a Corporate/Enterprise network or using a different Internet service provider with some security restrictions . In such a case the normal ICE capability of WebRTC is not enough , what is required is a NAT traversal mechanism .

STUN and TURN server protocols handle session initiations with handshakes between peers in different network environments . In case of a firewall blocking a STUN peer-to-peer connection, the system fallback to a TURN server which provides the necessary traversing mechanism through the NAT.


Lets study from the start ie ICE . What is it and why is it used ?

ICE (Interactive Connectivity Establishment )  framework ( mandatory by WebRTC standards  ) find network interfaces and ports in Offer / Answer Model to exchange network based information with participating communication clients. ICE makes use of the Session Traversal Utilities for NAT (STUN) protocol and its extension, Traversal Using Relay NAT (TURN)

ICE is defined by RFC 5245 – Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal for Offer/Answer Protocols.

Sample WebRTC offer holding ICE candidates :

type: offer, sdp: v=0
o=- 3475901263113717000 2 IN IP4 127.0.0.1
s=-
t=0 0
a=group:BUNDLE audio video data
a=msid-semantic: WMS dZdZMFQRNtY3unof7lTZBInzcRRylLakxtvc
m=audio 9 RTP/SAVPF 111 103 104 9 0 8 106 105 13 126
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:/v5dQj/qdvKXthQ2
a=ice-pwd:CvSEjVc1z6cMnhjrLlcbIxWK
a=ice-options:google-ice
a=fingerprint:sha-256 F1:A8:2E:71:4B:4E:FF:08:0F:18:13:1C:86:7B:FE:BA:BD:67:CF:B1:7F:19:87:33:6E:10:5C:17:42:0A:6C:15
a=setup:actpass
a=mid:audio
a=sendrecv
a=rtcp-mux
a=rtpmap:111 opus/48000/2
a=fmtp:111 minptime=10
a=rtpmap:103 ISAC/16000
a=rtpmap:104 ISAC/32000
a=rtpmap:9 G722/8000
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:106 CN/32000
a=rtpmap:105 CN/16000
a=rtpmap:13 CN/8000
a=rtpmap:126 telephone-event/8000
a=maxptime:60
m=video 9 RTP/SAVPF 100 116 117 96
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:/v5dQj/qdvKXthQ2
a=ice-pwd:CvSEjVc1z6cMnhjrLlcbIxWK
a=ice-options:google-ice
a=fingerprint:sha-256 F1:A8:2E:71:4B:4E:FF:08:0F:18:13:1C:86:7B:FE:BA:BD:67:CF:B1:7F:19:87:33:6E:10:5C:17:42:0A:6C:15
a=setup:actpass
a=mid:video
a=sendrecv
a=rtcp-mux
a=rtpmap:100 VP8/90000
a=rtcp-fb:100 ccm fir
a=rtcp-fb:100 nack
a=rtcp-fb:100 nack pli
a=rtcp-fb:100 goog-remb
a=rtpmap:116 red/90000
a=rtpmap:117 ulpfec/90000
a=rtpmap:96 rtx/90000
a=fmtp:96 apt=100
m=application 9 DTLS/SCTP 5000
c=IN IP4 0.0.0.0
a=ice-ufrag:/v5dQj/qdvKXthQ2
a=ice-pwd:CvSEjVc1z6cMnhjrLlcbIxWK
a=ice-options:google-ice
a=fingerprint:sha-256 F1:A8:2E:71:4B:4E:FF:08:0F:18:13:1C:86:7B:FE:BA:BD:67:CF:B1:7F:19:87:33:6E:10:5C:17:42:0A:6C:15
a=setup:actpass
a=mid:data
a=sctpmap:5000 webrtc-datachannel 1024

Notice the ICE candidates under video and audio . Now take a look at the SDP answer

type: answer, sdp: v=0
o=- 6931590438150302967 2 IN IP4 127.0.0.1
s=-
t=0 0
a=group:BUNDLE audio video data
a=msid-semantic: WMS R98sfBPNQwC20y9HsDBt4to1hTFeP6S0UnsX
m=audio 1 RTP/SAVPF 111 103 104 0 8 106 105 13 126
c=IN IP4 0.0.0.0
a=rtcp:1 IN IP4 0.0.0.0
a=ice-ufrag:WM/FjMA1ClvNb8xm
a=ice-pwd:8yy1+7x0PoHZCSX2aOVZs2Oq
a=fingerprint:sha-256 7B:9A:A7:43:EC:17:BD:9B:49:E4:23:92:8E:48:E4:8C:9A:BE:85:D4:1D:D7:8B:0E:60:C2:AE:67:77:1D:62:70
a=setup:active
a=mid:audio
a=sendrecv
a=rtcp-mux
a=rtpmap:111 opus/48000/2
a=fmtp:111 minptime=10
a=rtpmap:103 ISAC/16000
a=rtpmap:104 ISAC/32000
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:106 CN/32000
a=rtpmap:105 CN/16000
a=rtpmap:13 CN/8000
a=rtpmap:126 telephone-event/8000
a=maxptime:60
m=video 1 RTP/SAVPF 100 116 117 96
c=IN IP4 0.0.0.0
a=rtcp:1 IN IP4 0.0.0.0
a=ice-ufrag:WM/FjMA1ClvNb8xm
a=ice-pwd:8yy1+7x0PoHZCSX2aOVZs2Oq
a=fingerprint:sha-256 7B:9A:A7:43:EC:17:BD:9B:49:E4:23:92:8E:48:E4:8C:9A:BE:85:D4:1D:D7:8B:0E:60:C2:AE:67:77:1D:62:70
a=setup:active
a=mid:video
a=sendrecv
a=rtcp-mux
a=rtpmap:100 VP8/90000
a=rtcp-fb:100 ccm fir
a=rtcp-fb:100 nack
a=rtcp-fb:100 nack pli
a=rtcp-fb:100 goog-remb
a=rtpmap:116 red/90000
a=rtpmap:117 ulpfec/90000
a=rtpmap:96 rtx/90000
a=fmtp:96 apt=100
m=application 1 DTLS/SCTP 5000
c=IN IP4 0.0.0.0
b=AS:30
a=ice-ufrag:WM/FjMA1ClvNb8xm
a=ice-pwd:8yy1+7x0PoHZCSX2aOVZs2Oq
a=fingerprint:sha-256 7B:9A:A7:43:EC:17:BD:9B:49:E4:23:92:8E:48:E4:8C:9A:BE:85:D4:1D:D7:8B:0E:60:C2:AE:67:77:1D:62:70
a=setup:active
a=mid:data
a=sctpmap:5000 webrtc-datachannel 1024

Call Flow for ICE

STUN call flow for WebRTC Offer Answer

STUN call flow for WebRTC Offer Answer


WebRTC needs SDP Offer to be send to the clientB Javascript code from clientA Javascript code . Client B uses this SDP offer to generate an SDP Answer for client A. The SDP ( as seen on chrome://webrtc-internals/ ) includes ICE candidates which punchs open ports in the firewalls.
However incase both sides are symmetric NATs the media flow gets blocked. For such a case TURN is used which tries to give a public ip and port mapped to internal ip and port so as to provide an alternative routing mechanism like a packet-mirror. It can open a DTLS connection and use it to key the SRTP-DTLS media streams, and to send DataChannels over DTLS.

In order to Understand this better consider various scenarios

1 . No Firewall present on either peer . Both connected to open public internet .

Diagrammatic representation of  this shown as follows :

WebRTC signalling and media flow on Open public network

WebRTC signalling and media flow on Open public network

In this case there is no restriction to signal or media flow and the call takes places smoothly in p2p fashion.

2.  Either one or both the peer ( could be many in case of multi conf call ) are present behind a firewall  or  restrictive connection or router configured for intranet .

In such a case the signal may pass with the use of default ICE candidates or simple ppensource google Stun server such as

iceServers:[
{ ‘url’: “stun:stun.l.google.com:19302”}]

Diagram :

WebRTC signalling when peers are behind  firewalls

WebRTC signalling when peers are behind firewalls

However the media is restricted resulting in a black / empty / no video situation for both peers  . To combat such situation a relay mechanism such as TURN is required which essentially maps public ip to private ips thus creating a alternative route for media and data to flow through .

WebRTC media flow when peers are behind NAT . Uses TURN relay mechanism

WebRTC media flow when peers are behind NAT . Uses TURN relay mechanism

Peer config should look like :

var configuration =  {
iceServers: [
{ “url’:”stun::”},
{ “url”:”turn::”}
]
};

var pc = new RTCPeerConnection(configuration);

3. When the TURN server is also behind a firewall .  The config file of the turn server need to be altered to map the public and private IP

The diagrammatic description of this is as follows :

WebRTC media flow when peers are behind NAT and TURN server is behind NAT as well . TURN config files bind a public interface to private interface address.

WebRTC media flow when peers are behind NAT and TURN server is behind NAT as well . TURN config files bind a public interface to private interface address .