blob: 2098330f5aad8d96ce92d126aa20da8d5090c69a [file] [log] [blame]
Patrik Höglund56d94522019-11-18 15:53:32 +01001/*
2 * Copyright 2004 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#ifndef API_TRANSPORT_STUN_H_
12#define API_TRANSPORT_STUN_H_
13
14// This file contains classes for dealing with the STUN protocol, as specified
15// in RFC 5389, and its descendants.
16
17#include <stddef.h>
18#include <stdint.h>
Harald Alvestrand07d83c82021-03-02 08:09:53 +000019
Harald Alvestrandbee64082020-11-12 11:17:41 +000020#include <functional>
Patrik Höglund56d94522019-11-18 15:53:32 +010021#include <memory>
22#include <string>
23#include <vector>
24
Harald Alvestrandbee64082020-11-12 11:17:41 +000025#include "absl/strings/string_view.h"
26#include "api/array_view.h"
Patrik Höglund56d94522019-11-18 15:53:32 +010027#include "rtc_base/byte_buffer.h"
28#include "rtc_base/ip_address.h"
29#include "rtc_base/socket_address.h"
30
31namespace cricket {
32
33// These are the types of STUN messages defined in RFC 5389.
Tommi408143d2022-06-01 15:29:31 +020034enum StunMessageType : uint16_t {
35 STUN_INVALID_MESSAGE_TYPE = 0x0000,
Patrik Höglund56d94522019-11-18 15:53:32 +010036 STUN_BINDING_REQUEST = 0x0001,
37 STUN_BINDING_INDICATION = 0x0011,
38 STUN_BINDING_RESPONSE = 0x0101,
39 STUN_BINDING_ERROR_RESPONSE = 0x0111,
Jonas Oreland63737a92019-11-21 15:12:14 +010040
Jonas Oreland9a52bd72019-12-11 11:35:48 +010041 // Method 0x80, GOOG-PING is a variant of STUN BINDING
42 // that is sent instead of a STUN BINDING if the binding
43 // was identical to the one before.
Jonas Oreland63737a92019-11-21 15:12:14 +010044 GOOG_PING_REQUEST = 0x200,
45 GOOG_PING_RESPONSE = 0x300,
46 GOOG_PING_ERROR_RESPONSE = 0x310,
Patrik Höglund56d94522019-11-18 15:53:32 +010047};
48
49// These are all known STUN attributes, defined in RFC 5389 and elsewhere.
50// Next to each is the name of the class (T is StunTAttribute) that implements
51// that type.
52// RETRANSMIT_COUNT is the number of outstanding pings without a response at
53// the time the packet is generated.
54enum StunAttributeType {
55 STUN_ATTR_MAPPED_ADDRESS = 0x0001, // Address
56 STUN_ATTR_USERNAME = 0x0006, // ByteString
57 STUN_ATTR_MESSAGE_INTEGRITY = 0x0008, // ByteString, 20 bytes
58 STUN_ATTR_ERROR_CODE = 0x0009, // ErrorCode
59 STUN_ATTR_UNKNOWN_ATTRIBUTES = 0x000a, // UInt16List
60 STUN_ATTR_REALM = 0x0014, // ByteString
61 STUN_ATTR_NONCE = 0x0015, // ByteString
62 STUN_ATTR_XOR_MAPPED_ADDRESS = 0x0020, // XorAddress
63 STUN_ATTR_SOFTWARE = 0x8022, // ByteString
64 STUN_ATTR_ALTERNATE_SERVER = 0x8023, // Address
65 STUN_ATTR_FINGERPRINT = 0x8028, // UInt32
Patrik Höglund56d94522019-11-18 15:53:32 +010066 STUN_ATTR_RETRANSMIT_COUNT = 0xFF00 // UInt32
67};
68
69// These are the types of the values associated with the attributes above.
70// This allows us to perform some basic validation when reading or adding
71// attributes. Note that these values are for our own use, and not defined in
72// RFC 5389.
73enum StunAttributeValueType {
74 STUN_VALUE_UNKNOWN = 0,
75 STUN_VALUE_ADDRESS = 1,
76 STUN_VALUE_XOR_ADDRESS = 2,
77 STUN_VALUE_UINT32 = 3,
78 STUN_VALUE_UINT64 = 4,
79 STUN_VALUE_BYTE_STRING = 5,
80 STUN_VALUE_ERROR_CODE = 6,
81 STUN_VALUE_UINT16_LIST = 7
82};
83
84// These are the types of STUN addresses defined in RFC 5389.
85enum StunAddressFamily {
86 // NB: UNDEF is not part of the STUN spec.
87 STUN_ADDRESS_UNDEF = 0,
88 STUN_ADDRESS_IPV4 = 1,
89 STUN_ADDRESS_IPV6 = 2
90};
91
92// These are the types of STUN error codes defined in RFC 5389.
93enum StunErrorCode {
94 STUN_ERROR_TRY_ALTERNATE = 300,
95 STUN_ERROR_BAD_REQUEST = 400,
96 STUN_ERROR_UNAUTHORIZED = 401,
97 STUN_ERROR_UNKNOWN_ATTRIBUTE = 420,
Patrik Höglund56d94522019-11-18 15:53:32 +010098 STUN_ERROR_STALE_NONCE = 438,
99 STUN_ERROR_SERVER_ERROR = 500,
100 STUN_ERROR_GLOBAL_FAILURE = 600
101};
102
103// Strings for the error codes above.
104extern const char STUN_ERROR_REASON_TRY_ALTERNATE_SERVER[];
105extern const char STUN_ERROR_REASON_BAD_REQUEST[];
106extern const char STUN_ERROR_REASON_UNAUTHORIZED[];
107extern const char STUN_ERROR_REASON_UNKNOWN_ATTRIBUTE[];
Patrik Höglund56d94522019-11-18 15:53:32 +0100108extern const char STUN_ERROR_REASON_STALE_NONCE[];
109extern const char STUN_ERROR_REASON_SERVER_ERROR[];
110
111// The mask used to determine whether a STUN message is a request/response etc.
112const uint32_t kStunTypeMask = 0x0110;
113
114// STUN Attribute header length.
115const size_t kStunAttributeHeaderSize = 4;
116
117// Following values correspond to RFC5389.
118const size_t kStunHeaderSize = 20;
119const size_t kStunTransactionIdOffset = 8;
120const size_t kStunTransactionIdLength = 12;
121const uint32_t kStunMagicCookie = 0x2112A442;
122constexpr size_t kStunMagicCookieLength = sizeof(kStunMagicCookie);
123
124// Following value corresponds to an earlier version of STUN from
125// RFC3489.
126const size_t kStunLegacyTransactionIdLength = 16;
127
128// STUN Message Integrity HMAC length.
129const size_t kStunMessageIntegritySize = 20;
Jonas Oreland63737a92019-11-21 15:12:14 +0100130// Size of STUN_ATTR_MESSAGE_INTEGRITY_32
131const size_t kStunMessageIntegrity32Size = 4;
Patrik Höglund56d94522019-11-18 15:53:32 +0100132
133class StunAddressAttribute;
134class StunAttribute;
135class StunByteStringAttribute;
136class StunErrorCodeAttribute;
Patrik Höglund56d94522019-11-18 15:53:32 +0100137class StunUInt16ListAttribute;
138class StunUInt32Attribute;
139class StunUInt64Attribute;
140class StunXorAddressAttribute;
141
142// Records a complete STUN/TURN message. Each message consists of a type and
143// any number of attributes. Each attribute is parsed into an instance of an
144// appropriate class (see above). The Get* methods will return instances of
145// that attribute class.
146class StunMessage {
147 public:
Tommi408143d2022-06-01 15:29:31 +0200148 // Constructs a StunMessage with an invalid type and empty, legacy length
149 // (16 bytes, RFC3489) transaction id.
Patrik Höglund56d94522019-11-18 15:53:32 +0100150 StunMessage();
Tommi408143d2022-06-01 15:29:31 +0200151
152 // Construct a `StunMessage` with a specific type and generate a new
153 // 12 byte transaction id (RFC5389).
154 explicit StunMessage(uint16_t type);
155
156 StunMessage(uint16_t type, absl::string_view transaction_id);
157
Patrik Höglund56d94522019-11-18 15:53:32 +0100158 virtual ~StunMessage();
159
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000160 // The verification status of the message. This is checked on parsing,
161 // or set by AddMessageIntegrity.
Harald Alvestrand38b3b5e2022-10-10 04:36:12 +0000162 // These values are persisted to logs. Entries should not be renumbered and
163 // numeric values should never be reused.
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000164 enum class IntegrityStatus {
Harald Alvestrand38b3b5e2022-10-10 04:36:12 +0000165 kNotSet = 0,
166 kNoIntegrity = 1, // Message-integrity attribute missing
167 kIntegrityOk = 2, // Message-integrity checked OK
168 kIntegrityBad = 3, // Message-integrity verification failed
169 kMaxValue = kIntegrityBad,
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000170 };
171
Patrik Höglund56d94522019-11-18 15:53:32 +0100172 int type() const { return type_; }
173 size_t length() const { return length_; }
174 const std::string& transaction_id() const { return transaction_id_; }
175 uint32_t reduced_transaction_id() const { return reduced_transaction_id_; }
176
177 // Returns true if the message confirms to RFC3489 rather than
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000178 // RFC5389. The main difference between the two versions of the STUN
Patrik Höglund56d94522019-11-18 15:53:32 +0100179 // protocol is the presence of the magic cookie and different length
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000180 // of transaction ID. For outgoing packets the version of the protocol
Patrik Höglund56d94522019-11-18 15:53:32 +0100181 // is determined by the lengths of the transaction ID.
182 bool IsLegacy() const;
183
Tommib5af6ee2022-06-04 09:50:22 +0200184 [[deprecated]] void SetType(int type) { type_ = static_cast<uint16_t>(type); }
Tommi408143d2022-06-01 15:29:31 +0200185 [[deprecated]] bool SetTransactionID(absl::string_view transaction_id) {
186 if (!IsValidTransactionId(transaction_id))
187 return false;
188 SetTransactionIdForTesting(transaction_id);
189 return true;
190 }
Patrik Höglund56d94522019-11-18 15:53:32 +0100191
Taylor Brandstetterfb4351b2020-03-23 16:00:31 -0700192 // Get a list of all of the attribute types in the "comprehension required"
193 // range that were not recognized.
194 std::vector<uint16_t> GetNonComprehendedAttributes() const;
195
Patrik Höglund56d94522019-11-18 15:53:32 +0100196 // Gets the desired attribute value, or NULL if no such attribute type exists.
197 const StunAddressAttribute* GetAddress(int type) const;
198 const StunUInt32Attribute* GetUInt32(int type) const;
199 const StunUInt64Attribute* GetUInt64(int type) const;
200 const StunByteStringAttribute* GetByteString(int type) const;
Jonas Oreland1721de12019-11-20 12:10:39 +0100201 const StunUInt16ListAttribute* GetUInt16List(int type) const;
Patrik Höglund56d94522019-11-18 15:53:32 +0100202
203 // Gets these specific attribute values.
204 const StunErrorCodeAttribute* GetErrorCode() const;
205 // Returns the code inside the error code attribute, if present, and
206 // STUN_ERROR_GLOBAL_FAILURE otherwise.
207 int GetErrorCodeValue() const;
208 const StunUInt16ListAttribute* GetUnknownAttributes() const;
209
210 // Takes ownership of the specified attribute and adds it to the message.
211 void AddAttribute(std::unique_ptr<StunAttribute> attr);
212
213 // Remove the last occurrence of an attribute.
214 std::unique_ptr<StunAttribute> RemoveAttribute(int type);
215
Jonas Oreland63737a92019-11-21 15:12:14 +0100216 // Remote all attributes and releases them.
217 void ClearAttributes();
218
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000219 // Validates that a STUN message has a correct MESSAGE-INTEGRITY value.
220 // This uses the buffered raw-format message stored by Read().
221 IntegrityStatus ValidateMessageIntegrity(const std::string& password);
222
223 // Returns the current integrity status of the message.
224 IntegrityStatus integrity() const { return integrity_; }
225
226 // Shortcut for checking if integrity is verified.
227 bool IntegrityOk() const {
228 return integrity_ == IntegrityStatus::kIntegrityOk;
229 }
230
231 // Returns the password attribute used to set or check the integrity.
232 // Can only be called after adding or checking the integrity.
233 std::string password() const {
234 RTC_DCHECK(integrity_ != IntegrityStatus::kNotSet);
235 return password_;
236 }
Jonas Oreland63737a92019-11-21 15:12:14 +0100237
Patrik Höglund56d94522019-11-18 15:53:32 +0100238 // Adds a MESSAGE-INTEGRITY attribute that is valid for the current message.
Tommie83500e2022-06-03 14:28:59 +0200239 bool AddMessageIntegrity(absl::string_view password);
Patrik Höglund56d94522019-11-18 15:53:32 +0100240
Jonas Oreland63737a92019-11-21 15:12:14 +0100241 // Adds a STUN_ATTR_GOOG_MESSAGE_INTEGRITY_32 attribute that is valid for the
242 // current message.
243 bool AddMessageIntegrity32(absl::string_view password);
244
Jonas Oreland253d50f2019-11-28 17:08:07 +0100245 // Verify that a buffer has stun magic cookie and one of the specified
246 // methods. Note that it does not check for the existance of FINGERPRINT.
247 static bool IsStunMethod(rtc::ArrayView<int> methods,
248 const char* data,
249 size_t size);
250
Patrik Höglund56d94522019-11-18 15:53:32 +0100251 // Verifies that a given buffer is STUN by checking for a correct FINGERPRINT.
252 static bool ValidateFingerprint(const char* data, size_t size);
253
Tommi408143d2022-06-01 15:29:31 +0200254 // Generates a new 12 byte (RFC5389) transaction id.
255 static std::string GenerateTransactionId();
256
Patrik Höglund56d94522019-11-18 15:53:32 +0100257 // Adds a FINGERPRINT attribute that is valid for the current message.
258 bool AddFingerprint();
259
260 // Parses the STUN packet in the given buffer and records it here. The
261 // return value indicates whether this was successful.
262 bool Read(rtc::ByteBufferReader* buf);
263
264 // Writes this object into a STUN packet. The return value indicates whether
265 // this was successful.
266 bool Write(rtc::ByteBufferWriter* buf) const;
267
268 // Creates an empty message. Overridable by derived classes.
269 virtual StunMessage* CreateNew() const;
270
271 // Modify the stun magic cookie used for this STUN message.
272 // This is used for testing.
Tommi408143d2022-06-01 15:29:31 +0200273 [[deprecated]] void SetStunMagicCookie(uint32_t val);
274
275 // Change the internal transaction id. Used only for testing.
276 void SetTransactionIdForTesting(absl::string_view transaction_id);
Patrik Höglund56d94522019-11-18 15:53:32 +0100277
Artem Titov0e61fdd2021-07-25 21:50:14 +0200278 // Contruct a copy of `this`.
Jonas Oreland253d50f2019-11-28 17:08:07 +0100279 std::unique_ptr<StunMessage> Clone() const;
280
Artem Titov0e61fdd2021-07-25 21:50:14 +0200281 // Check if the attributes of this StunMessage equals those of `other`
282 // for all attributes that `attribute_type_mask` return true
Jonas Oreland253d50f2019-11-28 17:08:07 +0100283 bool EqualAttributes(const StunMessage* other,
284 std::function<bool(int type)> attribute_type_mask) const;
285
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000286 // Expose raw-buffer ValidateMessageIntegrity function for testing.
287 static bool ValidateMessageIntegrityForTesting(const char* data,
288 size_t size,
289 const std::string& password) {
290 return ValidateMessageIntegrity(data, size, password);
291 }
292 // Expose raw-buffer ValidateMessageIntegrity function for testing.
293 static bool ValidateMessageIntegrity32ForTesting(
294 const char* data,
295 size_t size,
296 const std::string& password) {
297 return ValidateMessageIntegrity32(data, size, password);
298 }
299 // Validates that a STUN message in byte buffer form
300 // has a correct MESSAGE-INTEGRITY value.
301 // These functions are not recommended and will be deprecated; use
302 // ValidateMessageIntegrity(password) on the parsed form instead.
303 static bool ValidateMessageIntegrity(const char* data,
304 size_t size,
305 const std::string& password);
306 static bool ValidateMessageIntegrity32(const char* data,
307 size_t size,
308 const std::string& password);
309
Patrik Höglund56d94522019-11-18 15:53:32 +0100310 protected:
311 // Verifies that the given attribute is allowed for this message.
312 virtual StunAttributeValueType GetAttributeValueType(int type) const;
313
Jonas Oreland253d50f2019-11-28 17:08:07 +0100314 std::vector<std::unique_ptr<StunAttribute>> attrs_;
315
Patrik Höglund56d94522019-11-18 15:53:32 +0100316 private:
317 StunAttribute* CreateAttribute(int type, size_t length) /* const*/;
318 const StunAttribute* GetAttribute(int type) const;
Tommi408143d2022-06-01 15:29:31 +0200319 static bool IsValidTransactionId(absl::string_view transaction_id);
Jonas Oreland63737a92019-11-21 15:12:14 +0100320 bool AddMessageIntegrityOfType(int mi_attr_type,
321 size_t mi_attr_size,
Tommie83500e2022-06-03 14:28:59 +0200322 absl::string_view key);
Jonas Oreland63737a92019-11-21 15:12:14 +0100323 static bool ValidateMessageIntegrityOfType(int mi_attr_type,
324 size_t mi_attr_size,
325 const char* data,
326 size_t size,
327 const std::string& password);
Patrik Höglund56d94522019-11-18 15:53:32 +0100328
Tommi408143d2022-06-01 15:29:31 +0200329 uint16_t type_ = STUN_INVALID_MESSAGE_TYPE;
330 uint16_t length_ = 0;
Patrik Höglund56d94522019-11-18 15:53:32 +0100331 std::string transaction_id_;
Tommi408143d2022-06-01 15:29:31 +0200332 uint32_t reduced_transaction_id_ = 0;
333 uint32_t stun_magic_cookie_ = kStunMagicCookie;
Harald Alvestrand07d83c82021-03-02 08:09:53 +0000334 // The original buffer for messages created by Read().
335 std::string buffer_;
336 IntegrityStatus integrity_ = IntegrityStatus::kNotSet;
337 std::string password_;
Patrik Höglund56d94522019-11-18 15:53:32 +0100338};
339
340// Base class for all STUN/TURN attributes.
341class StunAttribute {
342 public:
343 virtual ~StunAttribute() {}
344
345 int type() const { return type_; }
346 size_t length() const { return length_; }
347
348 // Return the type of this attribute.
349 virtual StunAttributeValueType value_type() const = 0;
350
351 // Only XorAddressAttribute needs this so far.
352 virtual void SetOwner(StunMessage* owner) {}
353
354 // Reads the body (not the type or length) for this type of attribute from
355 // the given buffer. Return value is true if successful.
356 virtual bool Read(rtc::ByteBufferReader* buf) = 0;
357
358 // Writes the body (not the type or length) to the given buffer. Return
359 // value is true if successful.
360 virtual bool Write(rtc::ByteBufferWriter* buf) const = 0;
361
362 // Creates an attribute object with the given type and smallest length.
363 static StunAttribute* Create(StunAttributeValueType value_type,
364 uint16_t type,
365 uint16_t length,
366 StunMessage* owner);
367 // TODO(?): Allow these create functions to take parameters, to reduce
368 // the amount of work callers need to do to initialize attributes.
369 static std::unique_ptr<StunAddressAttribute> CreateAddress(uint16_t type);
370 static std::unique_ptr<StunXorAddressAttribute> CreateXorAddress(
371 uint16_t type);
372 static std::unique_ptr<StunUInt32Attribute> CreateUInt32(uint16_t type);
373 static std::unique_ptr<StunUInt64Attribute> CreateUInt64(uint16_t type);
374 static std::unique_ptr<StunByteStringAttribute> CreateByteString(
375 uint16_t type);
Jonas Oreland1721de12019-11-20 12:10:39 +0100376 static std::unique_ptr<StunUInt16ListAttribute> CreateUInt16ListAttribute(
377 uint16_t type);
Patrik Höglund56d94522019-11-18 15:53:32 +0100378 static std::unique_ptr<StunErrorCodeAttribute> CreateErrorCode();
379 static std::unique_ptr<StunUInt16ListAttribute> CreateUnknownAttributes();
380
381 protected:
382 StunAttribute(uint16_t type, uint16_t length);
383 void SetLength(uint16_t length) { length_ = length; }
384 void WritePadding(rtc::ByteBufferWriter* buf) const;
385 void ConsumePadding(rtc::ByteBufferReader* buf) const;
386
387 private:
388 uint16_t type_;
389 uint16_t length_;
390};
391
392// Implements STUN attributes that record an Internet address.
393class StunAddressAttribute : public StunAttribute {
394 public:
395 static const uint16_t SIZE_UNDEF = 0;
396 static const uint16_t SIZE_IP4 = 8;
397 static const uint16_t SIZE_IP6 = 20;
398 StunAddressAttribute(uint16_t type, const rtc::SocketAddress& addr);
399 StunAddressAttribute(uint16_t type, uint16_t length);
400
401 StunAttributeValueType value_type() const override;
402
403 StunAddressFamily family() const {
404 switch (address_.ipaddr().family()) {
405 case AF_INET:
406 return STUN_ADDRESS_IPV4;
407 case AF_INET6:
408 return STUN_ADDRESS_IPV6;
409 }
410 return STUN_ADDRESS_UNDEF;
411 }
412
413 const rtc::SocketAddress& GetAddress() const { return address_; }
414 const rtc::IPAddress& ipaddr() const { return address_.ipaddr(); }
415 uint16_t port() const { return address_.port(); }
416
417 void SetAddress(const rtc::SocketAddress& addr) {
418 address_ = addr;
419 EnsureAddressLength();
420 }
421 void SetIP(const rtc::IPAddress& ip) {
422 address_.SetIP(ip);
423 EnsureAddressLength();
424 }
425 void SetPort(uint16_t port) { address_.SetPort(port); }
426
427 bool Read(rtc::ByteBufferReader* buf) override;
428 bool Write(rtc::ByteBufferWriter* buf) const override;
429
430 private:
431 void EnsureAddressLength() {
432 switch (family()) {
433 case STUN_ADDRESS_IPV4: {
434 SetLength(SIZE_IP4);
435 break;
436 }
437 case STUN_ADDRESS_IPV6: {
438 SetLength(SIZE_IP6);
439 break;
440 }
441 default: {
442 SetLength(SIZE_UNDEF);
443 break;
444 }
445 }
446 }
447 rtc::SocketAddress address_;
448};
449
450// Implements STUN attributes that record an Internet address. When encoded
451// in a STUN message, the address contained in this attribute is XORed with the
452// transaction ID of the message.
453class StunXorAddressAttribute : public StunAddressAttribute {
454 public:
455 StunXorAddressAttribute(uint16_t type, const rtc::SocketAddress& addr);
456 StunXorAddressAttribute(uint16_t type, uint16_t length, StunMessage* owner);
457
458 StunAttributeValueType value_type() const override;
459 void SetOwner(StunMessage* owner) override;
460 bool Read(rtc::ByteBufferReader* buf) override;
461 bool Write(rtc::ByteBufferWriter* buf) const override;
462
463 private:
464 rtc::IPAddress GetXoredIP() const;
465 StunMessage* owner_;
466};
467
468// Implements STUN attributes that record a 32-bit integer.
469class StunUInt32Attribute : public StunAttribute {
470 public:
471 static const uint16_t SIZE = 4;
472 StunUInt32Attribute(uint16_t type, uint32_t value);
473 explicit StunUInt32Attribute(uint16_t type);
474
475 StunAttributeValueType value_type() const override;
476
477 uint32_t value() const { return bits_; }
478 void SetValue(uint32_t bits) { bits_ = bits; }
479
480 bool GetBit(size_t index) const;
481 void SetBit(size_t index, bool value);
482
483 bool Read(rtc::ByteBufferReader* buf) override;
484 bool Write(rtc::ByteBufferWriter* buf) const override;
485
486 private:
487 uint32_t bits_;
488};
489
490class StunUInt64Attribute : public StunAttribute {
491 public:
492 static const uint16_t SIZE = 8;
493 StunUInt64Attribute(uint16_t type, uint64_t value);
494 explicit StunUInt64Attribute(uint16_t type);
495
496 StunAttributeValueType value_type() const override;
497
498 uint64_t value() const { return bits_; }
499 void SetValue(uint64_t bits) { bits_ = bits; }
500
501 bool Read(rtc::ByteBufferReader* buf) override;
502 bool Write(rtc::ByteBufferWriter* buf) const override;
503
504 private:
505 uint64_t bits_;
506};
507
508// Implements STUN attributes that record an arbitrary byte string.
509class StunByteStringAttribute : public StunAttribute {
510 public:
511 explicit StunByteStringAttribute(uint16_t type);
Tommie83500e2022-06-03 14:28:59 +0200512 StunByteStringAttribute(uint16_t type, absl::string_view str);
Patrik Höglund56d94522019-11-18 15:53:32 +0100513 StunByteStringAttribute(uint16_t type, const void* bytes, size_t length);
514 StunByteStringAttribute(uint16_t type, uint16_t length);
515 ~StunByteStringAttribute() override;
516
517 StunAttributeValueType value_type() const override;
518
519 const char* bytes() const { return bytes_; }
Tommie83500e2022-06-03 14:28:59 +0200520 absl::string_view string_view() const {
521 return absl::string_view(bytes_, length());
522 }
Patrik Höglund56d94522019-11-18 15:53:32 +0100523
Tommie83500e2022-06-03 14:28:59 +0200524 [[deprecated]] std::string GetString() const {
525 return std::string(bytes_, length());
526 }
527
Patrik Höglund56d94522019-11-18 15:53:32 +0100528 void CopyBytes(const void* bytes, size_t length);
Tommie83500e2022-06-03 14:28:59 +0200529 void CopyBytes(absl::string_view bytes);
Patrik Höglund56d94522019-11-18 15:53:32 +0100530
531 uint8_t GetByte(size_t index) const;
532 void SetByte(size_t index, uint8_t value);
533
534 bool Read(rtc::ByteBufferReader* buf) override;
535 bool Write(rtc::ByteBufferWriter* buf) const override;
536
537 private:
538 void SetBytes(char* bytes, size_t length);
539
540 char* bytes_;
541};
542
543// Implements STUN attributes that record an error code.
544class StunErrorCodeAttribute : public StunAttribute {
545 public:
546 static const uint16_t MIN_SIZE;
547 StunErrorCodeAttribute(uint16_t type, int code, const std::string& reason);
548 StunErrorCodeAttribute(uint16_t type, uint16_t length);
549 ~StunErrorCodeAttribute() override;
550
551 StunAttributeValueType value_type() const override;
552
553 // The combined error and class, e.g. 0x400.
554 int code() const;
555 void SetCode(int code);
556
557 // The individual error components.
558 int eclass() const { return class_; }
559 int number() const { return number_; }
560 const std::string& reason() const { return reason_; }
561 void SetClass(uint8_t eclass) { class_ = eclass; }
562 void SetNumber(uint8_t number) { number_ = number; }
563 void SetReason(const std::string& reason);
564
565 bool Read(rtc::ByteBufferReader* buf) override;
566 bool Write(rtc::ByteBufferWriter* buf) const override;
567
568 private:
569 uint8_t class_;
570 uint8_t number_;
571 std::string reason_;
572};
573
574// Implements STUN attributes that record a list of attribute names.
575class StunUInt16ListAttribute : public StunAttribute {
576 public:
577 StunUInt16ListAttribute(uint16_t type, uint16_t length);
578 ~StunUInt16ListAttribute() override;
579
580 StunAttributeValueType value_type() const override;
581
582 size_t Size() const;
583 uint16_t GetType(int index) const;
584 void SetType(int index, uint16_t value);
585 void AddType(uint16_t value);
Jonas Oreland63737a92019-11-21 15:12:14 +0100586 void AddTypeAtIndex(uint16_t index, uint16_t value);
Patrik Höglund56d94522019-11-18 15:53:32 +0100587
588 bool Read(rtc::ByteBufferReader* buf) override;
589 bool Write(rtc::ByteBufferWriter* buf) const override;
590
591 private:
592 std::vector<uint16_t>* attr_types_;
593};
594
Jonas Oreland9a52bd72019-12-11 11:35:48 +0100595// Return a string e.g "STUN BINDING request".
596std::string StunMethodToString(int msg_type);
597
Patrik Höglund56d94522019-11-18 15:53:32 +0100598// Returns the (successful) response type for the given request type.
Artem Titov0e61fdd2021-07-25 21:50:14 +0200599// Returns -1 if `request_type` is not a valid request type.
Patrik Höglund56d94522019-11-18 15:53:32 +0100600int GetStunSuccessResponseType(int request_type);
601
602// Returns the error response type for the given request type.
Artem Titov0e61fdd2021-07-25 21:50:14 +0200603// Returns -1 if `request_type` is not a valid request type.
Patrik Höglund56d94522019-11-18 15:53:32 +0100604int GetStunErrorResponseType(int request_type);
605
606// Returns whether a given message is a request type.
607bool IsStunRequestType(int msg_type);
608
609// Returns whether a given message is an indication type.
610bool IsStunIndicationType(int msg_type);
611
612// Returns whether a given response is a success type.
613bool IsStunSuccessResponseType(int msg_type);
614
615// Returns whether a given response is an error type.
616bool IsStunErrorResponseType(int msg_type);
617
618// Computes the STUN long-term credential hash.
619bool ComputeStunCredentialHash(const std::string& username,
620 const std::string& realm,
621 const std::string& password,
622 std::string* hash);
623
Artem Titov0e61fdd2021-07-25 21:50:14 +0200624// Make a copy af `attribute` and return a new StunAttribute.
Patrik Höglund56d94522019-11-18 15:53:32 +0100625// This is useful if you don't care about what kind of attribute you
626// are handling.
627//
628// The implementation copies by calling Write() followed by Read().
629//
Artem Titov0e61fdd2021-07-25 21:50:14 +0200630// If `tmp_buffer` is supplied this buffer will be used, otherwise
Patrik Höglund56d94522019-11-18 15:53:32 +0100631// a buffer will created in the method.
632std::unique_ptr<StunAttribute> CopyStunAttribute(
633 const StunAttribute& attribute,
634 rtc::ByteBufferWriter* tmp_buffer_ptr = 0);
635
636// TODO(?): Move the TURN/ICE stuff below out to separate files.
637extern const char TURN_MAGIC_COOKIE_VALUE[4];
638
639// "GTURN" STUN methods.
640// TODO(?): Rename these methods to GTURN_ to make it clear they aren't
641// part of standard STUN/TURN.
642enum RelayMessageType {
643 // For now, using the same defs from TurnMessageType below.
644 // STUN_ALLOCATE_REQUEST = 0x0003,
645 // STUN_ALLOCATE_RESPONSE = 0x0103,
646 // STUN_ALLOCATE_ERROR_RESPONSE = 0x0113,
647 STUN_SEND_REQUEST = 0x0004,
648 STUN_SEND_RESPONSE = 0x0104,
649 STUN_SEND_ERROR_RESPONSE = 0x0114,
650 STUN_DATA_INDICATION = 0x0115,
651};
652
653// "GTURN"-specific STUN attributes.
654// TODO(?): Rename these attributes to GTURN_ to avoid conflicts.
655enum RelayAttributeType {
656 STUN_ATTR_LIFETIME = 0x000d, // UInt32
657 STUN_ATTR_MAGIC_COOKIE = 0x000f, // ByteString, 4 bytes
658 STUN_ATTR_BANDWIDTH = 0x0010, // UInt32
659 STUN_ATTR_DESTINATION_ADDRESS = 0x0011, // Address
660 STUN_ATTR_SOURCE_ADDRESS2 = 0x0012, // Address
661 STUN_ATTR_DATA = 0x0013, // ByteString
662 STUN_ATTR_OPTIONS = 0x8001, // UInt32
663};
664
665// A "GTURN" STUN message.
666class RelayMessage : public StunMessage {
Tommi408143d2022-06-01 15:29:31 +0200667 public:
668 using StunMessage::StunMessage;
669
Patrik Höglund56d94522019-11-18 15:53:32 +0100670 protected:
671 StunAttributeValueType GetAttributeValueType(int type) const override;
672 StunMessage* CreateNew() const override;
673};
674
675// Defined in TURN RFC 5766.
Tommi408143d2022-06-01 15:29:31 +0200676enum TurnMessageType : uint16_t {
Patrik Höglund56d94522019-11-18 15:53:32 +0100677 STUN_ALLOCATE_REQUEST = 0x0003,
678 STUN_ALLOCATE_RESPONSE = 0x0103,
679 STUN_ALLOCATE_ERROR_RESPONSE = 0x0113,
680 TURN_REFRESH_REQUEST = 0x0004,
681 TURN_REFRESH_RESPONSE = 0x0104,
682 TURN_REFRESH_ERROR_RESPONSE = 0x0114,
683 TURN_SEND_INDICATION = 0x0016,
684 TURN_DATA_INDICATION = 0x0017,
685 TURN_CREATE_PERMISSION_REQUEST = 0x0008,
686 TURN_CREATE_PERMISSION_RESPONSE = 0x0108,
687 TURN_CREATE_PERMISSION_ERROR_RESPONSE = 0x0118,
688 TURN_CHANNEL_BIND_REQUEST = 0x0009,
689 TURN_CHANNEL_BIND_RESPONSE = 0x0109,
690 TURN_CHANNEL_BIND_ERROR_RESPONSE = 0x0119,
691};
692
693enum TurnAttributeType {
694 STUN_ATTR_CHANNEL_NUMBER = 0x000C, // UInt32
695 STUN_ATTR_TURN_LIFETIME = 0x000d, // UInt32
696 STUN_ATTR_XOR_PEER_ADDRESS = 0x0012, // XorAddress
697 // TODO(mallinath) - Uncomment after RelayAttributes are renamed.
698 // STUN_ATTR_DATA = 0x0013, // ByteString
699 STUN_ATTR_XOR_RELAYED_ADDRESS = 0x0016, // XorAddress
700 STUN_ATTR_EVEN_PORT = 0x0018, // ByteString, 1 byte.
701 STUN_ATTR_REQUESTED_TRANSPORT = 0x0019, // UInt32
702 STUN_ATTR_DONT_FRAGMENT = 0x001A, // No content, Length = 0
703 STUN_ATTR_RESERVATION_TOKEN = 0x0022, // ByteString, 8 bytes.
704 // TODO(mallinath) - Rename STUN_ATTR_TURN_LIFETIME to STUN_ATTR_LIFETIME and
705 // STUN_ATTR_TURN_DATA to STUN_ATTR_DATA. Also rename RelayMessage attributes
706 // by appending G to attribute name.
707};
708
709// RFC 5766-defined errors.
710enum TurnErrorType {
711 STUN_ERROR_FORBIDDEN = 403,
712 STUN_ERROR_ALLOCATION_MISMATCH = 437,
713 STUN_ERROR_WRONG_CREDENTIALS = 441,
714 STUN_ERROR_UNSUPPORTED_PROTOCOL = 442
715};
716
717extern const int SERVER_NOT_REACHABLE_ERROR;
718
719extern const char STUN_ERROR_REASON_FORBIDDEN[];
720extern const char STUN_ERROR_REASON_ALLOCATION_MISMATCH[];
721extern const char STUN_ERROR_REASON_WRONG_CREDENTIALS[];
722extern const char STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL[];
723class TurnMessage : public StunMessage {
Tommi408143d2022-06-01 15:29:31 +0200724 public:
725 using StunMessage::StunMessage;
726
Patrik Höglund56d94522019-11-18 15:53:32 +0100727 protected:
728 StunAttributeValueType GetAttributeValueType(int type) const override;
729 StunMessage* CreateNew() const override;
730};
731
732enum IceAttributeType {
733 // RFC 5245 ICE STUN attributes.
734 STUN_ATTR_PRIORITY = 0x0024, // UInt32
735 STUN_ATTR_USE_CANDIDATE = 0x0025, // No content, Length = 0
736 STUN_ATTR_ICE_CONTROLLED = 0x8029, // UInt64
737 STUN_ATTR_ICE_CONTROLLING = 0x802A, // UInt64
738 // The following attributes are in the comprehension-optional range
739 // (0xC000-0xFFFF) and are not registered with IANA. These STUN attributes are
740 // intended for ICE and should NOT be used in generic use cases of STUN
741 // messages.
742 //
743 // Note that the value 0xC001 has already been assigned by IANA to
744 // ENF-FLOW-DESCRIPTION
745 // (https://www.iana.org/assignments/stun-parameters/stun-parameters.xml).
746 STUN_ATTR_NOMINATION = 0xC001, // UInt32
747 // UInt32. The higher 16 bits are the network ID. The lower 16 bits are the
748 // network cost.
Jonas Orelandfa543642020-09-16 10:44:54 +0200749 STUN_ATTR_GOOG_NETWORK_INFO = 0xC057,
Patrik Höglund56d94522019-11-18 15:53:32 +0100750 // Experimental: Transaction ID of the last connectivity check received.
Jonas Orelandfa543642020-09-16 10:44:54 +0200751 STUN_ATTR_GOOG_LAST_ICE_CHECK_RECEIVED = 0xC058,
Jonas Oreland1721de12019-11-20 12:10:39 +0100752 // Uint16List. Miscellaneous attributes for future extension.
753 STUN_ATTR_GOOG_MISC_INFO = 0xC059,
Jonas Orelandfa543642020-09-16 10:44:54 +0200754 // Obsolete.
755 STUN_ATTR_GOOG_OBSOLETE_1 = 0xC05A,
756 STUN_ATTR_GOOG_CONNECTION_ID = 0xC05B, // Not yet implemented.
757 STUN_ATTR_GOOG_DELTA = 0xC05C, // Not yet implemented.
758 STUN_ATTR_GOOG_DELTA_ACK = 0xC05D, // Not yet implemented.
Jonas Oreland63737a92019-11-21 15:12:14 +0100759 // MESSAGE-INTEGRITY truncated to 32-bit.
760 STUN_ATTR_GOOG_MESSAGE_INTEGRITY_32 = 0xC060,
Patrik Höglund56d94522019-11-18 15:53:32 +0100761};
762
Jonas Oreland1721de12019-11-20 12:10:39 +0100763// When adding new attributes to STUN_ATTR_GOOG_MISC_INFO
764// (which is a list of uint16_t), append the indices of these attributes below
Jonas Oreland9a52bd72019-12-11 11:35:48 +0100765// and do NOT change the existing indices. The indices of attributes must be
Jonas Oreland1721de12019-11-20 12:10:39 +0100766// consistent with those used in ConnectionRequest::Prepare when forming a STUN
767// message for the ICE connectivity check, and they are used when parsing a
768// received STUN message.
Jonas Oreland219d8ce2020-01-15 15:29:48 +0100769enum class IceGoogMiscInfoBindingRequestAttributeIndex {
770 SUPPORT_GOOG_PING_VERSION = 0,
771};
Jonas Oreland9a52bd72019-12-11 11:35:48 +0100772
773enum class IceGoogMiscInfoBindingResponseAttributeIndex {
774 SUPPORT_GOOG_PING_VERSION = 0,
775};
Jonas Oreland1721de12019-11-20 12:10:39 +0100776
Patrik Höglund56d94522019-11-18 15:53:32 +0100777// RFC 5245-defined errors.
778enum IceErrorCode {
779 STUN_ERROR_ROLE_CONFLICT = 487,
780};
781extern const char STUN_ERROR_REASON_ROLE_CONFLICT[];
782
783// A RFC 5245 ICE STUN message.
784class IceMessage : public StunMessage {
Tommi408143d2022-06-01 15:29:31 +0200785 public:
786 using StunMessage::StunMessage;
787
Patrik Höglund56d94522019-11-18 15:53:32 +0100788 protected:
789 StunAttributeValueType GetAttributeValueType(int type) const override;
790 StunMessage* CreateNew() const override;
791};
792
793} // namespace cricket
794
795#endif // API_TRANSPORT_STUN_H_