1 /*
2  *  Copyright 2017 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "pc/ice_server_parsing.h"
12 
13 #include <stddef.h>
14 
15 #include <algorithm>
16 #include <cctype>  // For std::isdigit.
17 #include <memory>
18 #include <string>
19 
20 #include "p2p/base/port_interface.h"
21 #include "rtc_base/arraysize.h"
22 #include "rtc_base/checks.h"
23 #include "rtc_base/ip_address.h"
24 #include "rtc_base/logging.h"
25 #include "rtc_base/socket_address.h"
26 #include "rtc_base/string_encode.h"
27 
28 namespace webrtc {
29 
30 // Number of tokens must be preset when TURN uri has transport param.
31 static const size_t kTurnTransportTokensNum = 2;
32 // The default stun port.
33 static const int kDefaultStunPort = 3478;
34 static const int kDefaultStunTlsPort = 5349;
35 static const char kTransport[] = "transport";
36 
37 // Allowed characters in hostname per RFC 3986 Appendix A "reg-name"
38 static const char kRegNameCharacters[] =
39     "abcdefghijklmnopqrstuvwxyz"
40     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
41     "0123456789"
42     "-._~"          // unreserved
43     "%"             // pct-encoded
44     "!$&'()*+,;=";  // sub-delims
45 
46 // NOTE: Must be in the same order as the ServiceType enum.
47 static const char* kValidIceServiceTypes[] = {"stun", "stuns", "turn", "turns"};
48 
49 // NOTE: A loop below assumes that the first value of this enum is 0 and all
50 // other values are incremental.
51 enum ServiceType {
52   STUN = 0,  // Indicates a STUN server.
53   STUNS,     // Indicates a STUN server used with a TLS session.
54   TURN,      // Indicates a TURN server
55   TURNS,     // Indicates a TURN server used with a TLS session.
56   INVALID,   // Unknown.
57 };
58 static_assert(INVALID == arraysize(kValidIceServiceTypes),
59               "kValidIceServiceTypes must have as many strings as ServiceType "
60               "has values.");
61 
62 // |in_str| should follow of RFC 7064/7065 syntax, but with an optional
63 // "?transport=" already stripped. I.e.,
64 // stunURI       = scheme ":" host [ ":" port ]
65 // scheme        = "stun" / "stuns" / "turn" / "turns"
66 // host          = IP-literal / IPv4address / reg-name
67 // port          = *DIGIT
GetServiceTypeAndHostnameFromUri(const std::string & in_str,ServiceType * service_type,std::string * hostname)68 static bool GetServiceTypeAndHostnameFromUri(const std::string& in_str,
69                                              ServiceType* service_type,
70                                              std::string* hostname) {
71   const std::string::size_type colonpos = in_str.find(':');
72   if (colonpos == std::string::npos) {
73     RTC_LOG(LS_WARNING) << "Missing ':' in ICE URI: " << in_str;
74     return false;
75   }
76   if ((colonpos + 1) == in_str.length()) {
77     RTC_LOG(LS_WARNING) << "Empty hostname in ICE URI: " << in_str;
78     return false;
79   }
80   *service_type = INVALID;
81   for (size_t i = 0; i < arraysize(kValidIceServiceTypes); ++i) {
82     if (in_str.compare(0, colonpos, kValidIceServiceTypes[i]) == 0) {
83       *service_type = static_cast<ServiceType>(i);
84       break;
85     }
86   }
87   if (*service_type == INVALID) {
88     return false;
89   }
90   *hostname = in_str.substr(colonpos + 1, std::string::npos);
91   return true;
92 }
93 
ParsePort(const std::string & in_str,int * port)94 static bool ParsePort(const std::string& in_str, int* port) {
95   // Make sure port only contains digits. FromString doesn't check this.
96   for (const char& c : in_str) {
97     if (!std::isdigit(c)) {
98       return false;
99     }
100   }
101   return rtc::FromString(in_str, port);
102 }
103 
104 // This method parses IPv6 and IPv4 literal strings, along with hostnames in
105 // standard hostname:port format.
106 // Consider following formats as correct.
107 // |hostname:port|, |[IPV6 address]:port|, |IPv4 address|:port,
108 // |hostname|, |[IPv6 address]|, |IPv4 address|.
ParseHostnameAndPortFromString(const std::string & in_str,std::string * host,int * port)109 static bool ParseHostnameAndPortFromString(const std::string& in_str,
110                                            std::string* host,
111                                            int* port) {
112   RTC_DCHECK(host->empty());
113   if (in_str.at(0) == '[') {
114     // IP_literal syntax
115     std::string::size_type closebracket = in_str.rfind(']');
116     if (closebracket != std::string::npos) {
117       std::string::size_type colonpos = in_str.find(':', closebracket);
118       if (std::string::npos != colonpos) {
119         if (!ParsePort(in_str.substr(closebracket + 2, std::string::npos),
120                        port)) {
121           return false;
122         }
123       }
124       *host = in_str.substr(1, closebracket - 1);
125     } else {
126       return false;
127     }
128   } else {
129     // IPv4address or reg-name syntax
130     std::string::size_type colonpos = in_str.find(':');
131     if (std::string::npos != colonpos) {
132       if (!ParsePort(in_str.substr(colonpos + 1, std::string::npos), port)) {
133         return false;
134       }
135       *host = in_str.substr(0, colonpos);
136     } else {
137       *host = in_str;
138     }
139     // RFC 3986 section 3.2.2 and Appendix A - "reg-name" syntax
140     if (host->find_first_not_of(kRegNameCharacters) != std::string::npos) {
141       return false;
142     }
143   }
144   return !host->empty();
145 }
146 
147 // Adds a STUN or TURN server to the appropriate list,
148 // by parsing |url| and using the username/password in |server|.
ParseIceServerUrl(const PeerConnectionInterface::IceServer & server,const std::string & url,cricket::ServerAddresses * stun_servers,std::vector<cricket::RelayServerConfig> * turn_servers)149 static RTCErrorType ParseIceServerUrl(
150     const PeerConnectionInterface::IceServer& server,
151     const std::string& url,
152     cricket::ServerAddresses* stun_servers,
153     std::vector<cricket::RelayServerConfig>* turn_servers) {
154   // RFC 7064
155   // stunURI       = scheme ":" host [ ":" port ]
156   // scheme        = "stun" / "stuns"
157 
158   // RFC 7065
159   // turnURI       = scheme ":" host [ ":" port ]
160   //                 [ "?transport=" transport ]
161   // scheme        = "turn" / "turns"
162   // transport     = "udp" / "tcp" / transport-ext
163   // transport-ext = 1*unreserved
164 
165   // RFC 3986
166   // host     = IP-literal / IPv4address / reg-name
167   // port     = *DIGIT
168 
169   RTC_DCHECK(stun_servers != nullptr);
170   RTC_DCHECK(turn_servers != nullptr);
171   std::vector<std::string> tokens;
172   cricket::ProtocolType turn_transport_type = cricket::PROTO_UDP;
173   RTC_DCHECK(!url.empty());
174   rtc::tokenize_with_empty_tokens(url, '?', &tokens);
175   std::string uri_without_transport = tokens[0];
176   // Let's look into transport= param, if it exists.
177   if (tokens.size() == kTurnTransportTokensNum) {  // ?transport= is present.
178     std::string uri_transport_param = tokens[1];
179     rtc::tokenize_with_empty_tokens(uri_transport_param, '=', &tokens);
180     if (tokens[0] != kTransport) {
181       RTC_LOG(LS_WARNING) << "Invalid transport parameter key.";
182       return RTCErrorType::SYNTAX_ERROR;
183     }
184     if (tokens.size() < 2) {
185       RTC_LOG(LS_WARNING) << "Transport parameter missing value.";
186       return RTCErrorType::SYNTAX_ERROR;
187     }
188     if (!cricket::StringToProto(tokens[1].c_str(), &turn_transport_type) ||
189         (turn_transport_type != cricket::PROTO_UDP &&
190          turn_transport_type != cricket::PROTO_TCP)) {
191       RTC_LOG(LS_WARNING) << "Transport parameter should always be udp or tcp.";
192       return RTCErrorType::SYNTAX_ERROR;
193     }
194   }
195 
196   std::string hoststring;
197   ServiceType service_type;
198   if (!GetServiceTypeAndHostnameFromUri(uri_without_transport, &service_type,
199                                         &hoststring)) {
200     RTC_LOG(LS_WARNING) << "Invalid transport parameter in ICE URI: " << url;
201     return RTCErrorType::SYNTAX_ERROR;
202   }
203 
204   // GetServiceTypeAndHostnameFromUri should never give an empty hoststring
205   RTC_DCHECK(!hoststring.empty());
206 
207   int port = kDefaultStunPort;
208   if (service_type == TURNS) {
209     port = kDefaultStunTlsPort;
210     turn_transport_type = cricket::PROTO_TLS;
211   }
212 
213   if (hoststring.find('@') != std::string::npos) {
214     RTC_LOG(WARNING) << "Invalid url: " << uri_without_transport;
215     RTC_LOG(WARNING)
216         << "Note that user-info@ in turn:-urls is long-deprecated.";
217     return RTCErrorType::SYNTAX_ERROR;
218   }
219   std::string address;
220   if (!ParseHostnameAndPortFromString(hoststring, &address, &port)) {
221     RTC_LOG(WARNING) << "Invalid hostname format: " << uri_without_transport;
222     return RTCErrorType::SYNTAX_ERROR;
223   }
224 
225   if (port <= 0 || port > 0xffff) {
226     RTC_LOG(WARNING) << "Invalid port: " << port;
227     return RTCErrorType::SYNTAX_ERROR;
228   }
229 
230   switch (service_type) {
231     case STUN:
232     case STUNS:
233       stun_servers->insert(rtc::SocketAddress(address, port));
234       break;
235     case TURN:
236     case TURNS: {
237       if (server.username.empty() || server.password.empty()) {
238         // The WebRTC spec requires throwing an InvalidAccessError when username
239         // or credential are ommitted; this is the native equivalent.
240         RTC_LOG(LS_ERROR) << "TURN server with empty username or password";
241         return RTCErrorType::INVALID_PARAMETER;
242       }
243       // If the hostname field is not empty, then the server address must be
244       // the resolved IP for that host, the hostname is needed later for TLS
245       // handshake (SNI and Certificate verification).
246       const std::string& hostname =
247           server.hostname.empty() ? address : server.hostname;
248       rtc::SocketAddress socket_address(hostname, port);
249       if (!server.hostname.empty()) {
250         rtc::IPAddress ip;
251         if (!IPFromString(address, &ip)) {
252           // When hostname is set, the server address must be a
253           // resolved ip address.
254           RTC_LOG(LS_ERROR)
255               << "IceServer has hostname field set, but URI does not "
256                  "contain an IP address.";
257           return RTCErrorType::INVALID_PARAMETER;
258         }
259         socket_address.SetResolvedIP(ip);
260       }
261       cricket::RelayServerConfig config =
262           cricket::RelayServerConfig(socket_address, server.username,
263                                      server.password, turn_transport_type);
264       if (server.tls_cert_policy ==
265           PeerConnectionInterface::kTlsCertPolicyInsecureNoCheck) {
266         config.tls_cert_policy =
267             cricket::TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK;
268       }
269       config.tls_alpn_protocols = server.tls_alpn_protocols;
270       config.tls_elliptic_curves = server.tls_elliptic_curves;
271 
272       turn_servers->push_back(config);
273       break;
274     }
275     default:
276       // We shouldn't get to this point with an invalid service_type, we should
277       // have returned an error already.
278       RTC_NOTREACHED() << "Unexpected service type";
279       return RTCErrorType::INTERNAL_ERROR;
280   }
281   return RTCErrorType::NONE;
282 }
283 
ParseIceServers(const PeerConnectionInterface::IceServers & servers,cricket::ServerAddresses * stun_servers,std::vector<cricket::RelayServerConfig> * turn_servers)284 RTCErrorType ParseIceServers(
285     const PeerConnectionInterface::IceServers& servers,
286     cricket::ServerAddresses* stun_servers,
287     std::vector<cricket::RelayServerConfig>* turn_servers) {
288   for (const PeerConnectionInterface::IceServer& server : servers) {
289     if (!server.urls.empty()) {
290       for (const std::string& url : server.urls) {
291         if (url.empty()) {
292           RTC_LOG(LS_ERROR) << "Empty uri.";
293           return RTCErrorType::SYNTAX_ERROR;
294         }
295         RTCErrorType err =
296             ParseIceServerUrl(server, url, stun_servers, turn_servers);
297         if (err != RTCErrorType::NONE) {
298           return err;
299         }
300       }
301     } else if (!server.uri.empty()) {
302       // Fallback to old .uri if new .urls isn't present.
303       RTCErrorType err =
304           ParseIceServerUrl(server, server.uri, stun_servers, turn_servers);
305       if (err != RTCErrorType::NONE) {
306         return err;
307       }
308     } else {
309       RTC_LOG(LS_ERROR) << "Empty uri.";
310       return RTCErrorType::SYNTAX_ERROR;
311     }
312   }
313   // Candidates must have unique priorities, so that connectivity checks
314   // are performed in a well-defined order.
315   int priority = static_cast<int>(turn_servers->size() - 1);
316   for (cricket::RelayServerConfig& turn_server : *turn_servers) {
317     // First in the list gets highest priority.
318     turn_server.priority = priority--;
319   }
320   return RTCErrorType::NONE;
321 }
322 
323 }  // namespace webrtc
324