blob: d0f001485de9d1223fe65328649aa09f8964a95c [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
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#include "webrtc/p2p/base/stun.h"
12
13#include <string.h>
14
15#include "webrtc/base/byteorder.h"
16#include "webrtc/base/common.h"
17#include "webrtc/base/crc32.h"
18#include "webrtc/base/logging.h"
19#include "webrtc/base/messagedigest.h"
20#include "webrtc/base/scoped_ptr.h"
21#include "webrtc/base/stringencode.h"
22
jbauchf1f87202016-03-30 06:43:37 -070023using rtc::ByteBufferReader;
24using rtc::ByteBufferWriter;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000025
26namespace cricket {
27
28const char STUN_ERROR_REASON_TRY_ALTERNATE_SERVER[] = "Try Alternate Server";
29const char STUN_ERROR_REASON_BAD_REQUEST[] = "Bad Request";
30const char STUN_ERROR_REASON_UNAUTHORIZED[] = "Unauthorized";
31const char STUN_ERROR_REASON_FORBIDDEN[] = "Forbidden";
32const char STUN_ERROR_REASON_STALE_CREDENTIALS[] = "Stale Credentials";
33const char STUN_ERROR_REASON_ALLOCATION_MISMATCH[] = "Allocation Mismatch";
34const char STUN_ERROR_REASON_STALE_NONCE[] = "Stale Nonce";
35const char STUN_ERROR_REASON_WRONG_CREDENTIALS[] = "Wrong Credentials";
36const char STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL[] = "Unsupported Protocol";
37const char STUN_ERROR_REASON_ROLE_CONFLICT[] = "Role Conflict";
38const char STUN_ERROR_REASON_SERVER_ERROR[] = "Server Error";
39
40const char TURN_MAGIC_COOKIE_VALUE[] = { '\x72', '\xC6', '\x4B', '\xC6' };
41const char EMPTY_TRANSACTION_ID[] = "0000000000000000";
Peter Boström0c4e06b2015-10-07 12:23:21 +020042const uint32_t STUN_FINGERPRINT_XOR_VALUE = 0x5354554E;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000043
44// StunMessage
45
46StunMessage::StunMessage()
47 : type_(0),
48 length_(0),
49 transaction_id_(EMPTY_TRANSACTION_ID) {
50 ASSERT(IsValidTransactionId(transaction_id_));
51 attrs_ = new std::vector<StunAttribute*>();
52}
53
54StunMessage::~StunMessage() {
55 for (size_t i = 0; i < attrs_->size(); i++)
56 delete (*attrs_)[i];
57 delete attrs_;
58}
59
60bool StunMessage::IsLegacy() const {
61 if (transaction_id_.size() == kStunLegacyTransactionIdLength)
62 return true;
63 ASSERT(transaction_id_.size() == kStunTransactionIdLength);
64 return false;
65}
66
67bool StunMessage::SetTransactionID(const std::string& str) {
68 if (!IsValidTransactionId(str)) {
69 return false;
70 }
71 transaction_id_ = str;
72 return true;
73}
74
75bool StunMessage::AddAttribute(StunAttribute* attr) {
76 // Fail any attributes that aren't valid for this type of message.
77 if (attr->value_type() != GetAttributeValueType(attr->type())) {
78 return false;
79 }
80 attrs_->push_back(attr);
81 attr->SetOwner(this);
82 size_t attr_length = attr->length();
83 if (attr_length % 4 != 0) {
84 attr_length += (4 - (attr_length % 4));
85 }
Peter Boström0c4e06b2015-10-07 12:23:21 +020086 length_ += static_cast<uint16_t>(attr_length + 4);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000087 return true;
88}
89
90const StunAddressAttribute* StunMessage::GetAddress(int type) const {
91 switch (type) {
92 case STUN_ATTR_MAPPED_ADDRESS: {
93 // Return XOR-MAPPED-ADDRESS when MAPPED-ADDRESS attribute is
94 // missing.
95 const StunAttribute* mapped_address =
96 GetAttribute(STUN_ATTR_MAPPED_ADDRESS);
97 if (!mapped_address)
98 mapped_address = GetAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS);
99 return reinterpret_cast<const StunAddressAttribute*>(mapped_address);
100 }
101
102 default:
103 return static_cast<const StunAddressAttribute*>(GetAttribute(type));
104 }
105}
106
107const StunUInt32Attribute* StunMessage::GetUInt32(int type) const {
108 return static_cast<const StunUInt32Attribute*>(GetAttribute(type));
109}
110
111const StunUInt64Attribute* StunMessage::GetUInt64(int type) const {
112 return static_cast<const StunUInt64Attribute*>(GetAttribute(type));
113}
114
115const StunByteStringAttribute* StunMessage::GetByteString(int type) const {
116 return static_cast<const StunByteStringAttribute*>(GetAttribute(type));
117}
118
119const StunErrorCodeAttribute* StunMessage::GetErrorCode() const {
120 return static_cast<const StunErrorCodeAttribute*>(
121 GetAttribute(STUN_ATTR_ERROR_CODE));
122}
123
124const StunUInt16ListAttribute* StunMessage::GetUnknownAttributes() const {
125 return static_cast<const StunUInt16ListAttribute*>(
126 GetAttribute(STUN_ATTR_UNKNOWN_ATTRIBUTES));
127}
128
129// Verifies a STUN message has a valid MESSAGE-INTEGRITY attribute, using the
130// procedure outlined in RFC 5389, section 15.4.
131bool StunMessage::ValidateMessageIntegrity(const char* data, size_t size,
132 const std::string& password) {
133 // Verifying the size of the message.
134 if ((size % 4) != 0) {
135 return false;
136 }
137
138 // Getting the message length from the STUN header.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200139 uint16_t msg_length = rtc::GetBE16(&data[2]);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140 if (size != (msg_length + kStunHeaderSize)) {
141 return false;
142 }
143
144 // Finding Message Integrity attribute in stun message.
145 size_t current_pos = kStunHeaderSize;
146 bool has_message_integrity_attr = false;
147 while (current_pos < size) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200148 uint16_t attr_type, attr_length;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000149 // Getting attribute type and length.
150 attr_type = rtc::GetBE16(&data[current_pos]);
151 attr_length = rtc::GetBE16(&data[current_pos + sizeof(attr_type)]);
152
153 // If M-I, sanity check it, and break out.
154 if (attr_type == STUN_ATTR_MESSAGE_INTEGRITY) {
155 if (attr_length != kStunMessageIntegritySize ||
156 current_pos + attr_length > size) {
157 return false;
158 }
159 has_message_integrity_attr = true;
160 break;
161 }
162
163 // Otherwise, skip to the next attribute.
164 current_pos += sizeof(attr_type) + sizeof(attr_length) + attr_length;
165 if ((attr_length % 4) != 0) {
166 current_pos += (4 - (attr_length % 4));
167 }
168 }
169
170 if (!has_message_integrity_attr) {
171 return false;
172 }
173
174 // Getting length of the message to calculate Message Integrity.
175 size_t mi_pos = current_pos;
176 rtc::scoped_ptr<char[]> temp_data(new char[current_pos]);
177 memcpy(temp_data.get(), data, current_pos);
178 if (size > mi_pos + kStunAttributeHeaderSize + kStunMessageIntegritySize) {
179 // Stun message has other attributes after message integrity.
180 // Adjust the length parameter in stun message to calculate HMAC.
181 size_t extra_offset = size -
182 (mi_pos + kStunAttributeHeaderSize + kStunMessageIntegritySize);
183 size_t new_adjusted_len = size - extra_offset - kStunHeaderSize;
184
185 // Writing new length of the STUN message @ Message Length in temp buffer.
186 // 0 1 2 3
187 // 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
188 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
189 // |0 0| STUN Message Type | Message Length |
190 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Peter Boström0c4e06b2015-10-07 12:23:21 +0200191 rtc::SetBE16(temp_data.get() + 2, static_cast<uint16_t>(new_adjusted_len));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000192 }
193
194 char hmac[kStunMessageIntegritySize];
195 size_t ret = rtc::ComputeHmac(rtc::DIGEST_SHA_1,
196 password.c_str(), password.size(),
197 temp_data.get(), mi_pos,
198 hmac, sizeof(hmac));
199 ASSERT(ret == sizeof(hmac));
200 if (ret != sizeof(hmac))
201 return false;
202
203 // Comparing the calculated HMAC with the one present in the message.
204 return memcmp(data + current_pos + kStunAttributeHeaderSize,
205 hmac,
206 sizeof(hmac)) == 0;
207}
208
209bool StunMessage::AddMessageIntegrity(const std::string& password) {
210 return AddMessageIntegrity(password.c_str(), password.size());
211}
212
213bool StunMessage::AddMessageIntegrity(const char* key,
214 size_t keylen) {
215 // Add the attribute with a dummy value. Since this is a known attribute, it
216 // can't fail.
217 StunByteStringAttribute* msg_integrity_attr =
218 new StunByteStringAttribute(STUN_ATTR_MESSAGE_INTEGRITY,
219 std::string(kStunMessageIntegritySize, '0'));
220 VERIFY(AddAttribute(msg_integrity_attr));
221
222 // Calculate the HMAC for the message.
jbauchf1f87202016-03-30 06:43:37 -0700223 ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000224 if (!Write(&buf))
225 return false;
226
227 int msg_len_for_hmac = static_cast<int>(
228 buf.Length() - kStunAttributeHeaderSize - msg_integrity_attr->length());
229 char hmac[kStunMessageIntegritySize];
230 size_t ret = rtc::ComputeHmac(rtc::DIGEST_SHA_1,
231 key, keylen,
232 buf.Data(), msg_len_for_hmac,
233 hmac, sizeof(hmac));
234 ASSERT(ret == sizeof(hmac));
235 if (ret != sizeof(hmac)) {
236 LOG(LS_ERROR) << "HMAC computation failed. Message-Integrity "
237 << "has dummy value.";
238 return false;
239 }
240
241 // Insert correct HMAC into the attribute.
242 msg_integrity_attr->CopyBytes(hmac, sizeof(hmac));
243 return true;
244}
245
246// Verifies a message is in fact a STUN message, by performing the checks
247// outlined in RFC 5389, section 7.3, including the FINGERPRINT check detailed
248// in section 15.5.
249bool StunMessage::ValidateFingerprint(const char* data, size_t size) {
250 // Check the message length.
251 size_t fingerprint_attr_size =
252 kStunAttributeHeaderSize + StunUInt32Attribute::SIZE;
253 if (size % 4 != 0 || size < kStunHeaderSize + fingerprint_attr_size)
254 return false;
255
256 // Skip the rest if the magic cookie isn't present.
257 const char* magic_cookie =
258 data + kStunTransactionIdOffset - kStunMagicCookieLength;
259 if (rtc::GetBE32(magic_cookie) != kStunMagicCookie)
260 return false;
261
262 // Check the fingerprint type and length.
263 const char* fingerprint_attr_data = data + size - fingerprint_attr_size;
264 if (rtc::GetBE16(fingerprint_attr_data) != STUN_ATTR_FINGERPRINT ||
Peter Boström0c4e06b2015-10-07 12:23:21 +0200265 rtc::GetBE16(fingerprint_attr_data + sizeof(uint16_t)) !=
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000266 StunUInt32Attribute::SIZE)
267 return false;
268
269 // Check the fingerprint value.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200270 uint32_t fingerprint =
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000271 rtc::GetBE32(fingerprint_attr_data + kStunAttributeHeaderSize);
272 return ((fingerprint ^ STUN_FINGERPRINT_XOR_VALUE) ==
273 rtc::ComputeCrc32(data, size - fingerprint_attr_size));
274}
275
276bool StunMessage::AddFingerprint() {
277 // Add the attribute with a dummy value. Since this is a known attribute,
278 // it can't fail.
279 StunUInt32Attribute* fingerprint_attr =
280 new StunUInt32Attribute(STUN_ATTR_FINGERPRINT, 0);
281 VERIFY(AddAttribute(fingerprint_attr));
282
283 // Calculate the CRC-32 for the message and insert it.
jbauchf1f87202016-03-30 06:43:37 -0700284 ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000285 if (!Write(&buf))
286 return false;
287
288 int msg_len_for_crc32 = static_cast<int>(
289 buf.Length() - kStunAttributeHeaderSize - fingerprint_attr->length());
Peter Boström0c4e06b2015-10-07 12:23:21 +0200290 uint32_t c = rtc::ComputeCrc32(buf.Data(), msg_len_for_crc32);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291
292 // Insert the correct CRC-32, XORed with a constant, into the attribute.
293 fingerprint_attr->SetValue(c ^ STUN_FINGERPRINT_XOR_VALUE);
294 return true;
295}
296
jbauchf1f87202016-03-30 06:43:37 -0700297bool StunMessage::Read(ByteBufferReader* buf) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000298 if (!buf->ReadUInt16(&type_))
299 return false;
300
301 if (type_ & 0x8000) {
302 // RTP and RTCP set the MSB of first byte, since first two bits are version,
303 // and version is always 2 (10). If set, this is not a STUN packet.
304 return false;
305 }
306
307 if (!buf->ReadUInt16(&length_))
308 return false;
309
310 std::string magic_cookie;
311 if (!buf->ReadString(&magic_cookie, kStunMagicCookieLength))
312 return false;
313
314 std::string transaction_id;
315 if (!buf->ReadString(&transaction_id, kStunTransactionIdLength))
316 return false;
317
Peter Boström0c4e06b2015-10-07 12:23:21 +0200318 uint32_t magic_cookie_int =
319 *reinterpret_cast<const uint32_t*>(magic_cookie.data());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000320 if (rtc::NetworkToHost32(magic_cookie_int) != kStunMagicCookie) {
321 // If magic cookie is invalid it means that the peer implements
322 // RFC3489 instead of RFC5389.
323 transaction_id.insert(0, magic_cookie);
324 }
325 ASSERT(IsValidTransactionId(transaction_id));
326 transaction_id_ = transaction_id;
327
328 if (length_ != buf->Length())
329 return false;
330
331 attrs_->resize(0);
332
333 size_t rest = buf->Length() - length_;
334 while (buf->Length() > rest) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200335 uint16_t attr_type, attr_length;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000336 if (!buf->ReadUInt16(&attr_type))
337 return false;
338 if (!buf->ReadUInt16(&attr_length))
339 return false;
340
341 StunAttribute* attr = CreateAttribute(attr_type, attr_length);
342 if (!attr) {
343 // Skip any unknown or malformed attributes.
344 if ((attr_length % 4) != 0) {
345 attr_length += (4 - (attr_length % 4));
346 }
347 if (!buf->Consume(attr_length))
348 return false;
349 } else {
350 if (!attr->Read(buf))
351 return false;
352 attrs_->push_back(attr);
353 }
354 }
355
356 ASSERT(buf->Length() == rest);
357 return true;
358}
359
jbauchf1f87202016-03-30 06:43:37 -0700360bool StunMessage::Write(ByteBufferWriter* buf) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000361 buf->WriteUInt16(type_);
362 buf->WriteUInt16(length_);
363 if (!IsLegacy())
364 buf->WriteUInt32(kStunMagicCookie);
365 buf->WriteString(transaction_id_);
366
367 for (size_t i = 0; i < attrs_->size(); ++i) {
368 buf->WriteUInt16((*attrs_)[i]->type());
Peter Boström0c4e06b2015-10-07 12:23:21 +0200369 buf->WriteUInt16(static_cast<uint16_t>((*attrs_)[i]->length()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000370 if (!(*attrs_)[i]->Write(buf))
371 return false;
372 }
373
374 return true;
375}
376
377StunAttributeValueType StunMessage::GetAttributeValueType(int type) const {
378 switch (type) {
379 case STUN_ATTR_MAPPED_ADDRESS: return STUN_VALUE_ADDRESS;
380 case STUN_ATTR_USERNAME: return STUN_VALUE_BYTE_STRING;
381 case STUN_ATTR_MESSAGE_INTEGRITY: return STUN_VALUE_BYTE_STRING;
382 case STUN_ATTR_ERROR_CODE: return STUN_VALUE_ERROR_CODE;
383 case STUN_ATTR_UNKNOWN_ATTRIBUTES: return STUN_VALUE_UINT16_LIST;
384 case STUN_ATTR_REALM: return STUN_VALUE_BYTE_STRING;
385 case STUN_ATTR_NONCE: return STUN_VALUE_BYTE_STRING;
386 case STUN_ATTR_XOR_MAPPED_ADDRESS: return STUN_VALUE_XOR_ADDRESS;
387 case STUN_ATTR_SOFTWARE: return STUN_VALUE_BYTE_STRING;
388 case STUN_ATTR_ALTERNATE_SERVER: return STUN_VALUE_ADDRESS;
389 case STUN_ATTR_FINGERPRINT: return STUN_VALUE_UINT32;
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000390 case STUN_ATTR_ORIGIN: return STUN_VALUE_BYTE_STRING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000391 case STUN_ATTR_RETRANSMIT_COUNT: return STUN_VALUE_UINT32;
392 default: return STUN_VALUE_UNKNOWN;
393 }
394}
395
396StunAttribute* StunMessage::CreateAttribute(int type, size_t length) /*const*/ {
397 StunAttributeValueType value_type = GetAttributeValueType(type);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200398 return StunAttribute::Create(value_type, type, static_cast<uint16_t>(length),
399 this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000400}
401
402const StunAttribute* StunMessage::GetAttribute(int type) const {
403 for (size_t i = 0; i < attrs_->size(); ++i) {
404 if ((*attrs_)[i]->type() == type)
405 return (*attrs_)[i];
406 }
407 return NULL;
408}
409
410bool StunMessage::IsValidTransactionId(const std::string& transaction_id) {
411 return transaction_id.size() == kStunTransactionIdLength ||
412 transaction_id.size() == kStunLegacyTransactionIdLength;
413}
414
415// StunAttribute
416
Peter Boström0c4e06b2015-10-07 12:23:21 +0200417StunAttribute::StunAttribute(uint16_t type, uint16_t length)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 : type_(type), length_(length) {
419}
420
jbauchf1f87202016-03-30 06:43:37 -0700421void StunAttribute::ConsumePadding(ByteBufferReader* buf) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000422 int remainder = length_ % 4;
423 if (remainder > 0) {
424 buf->Consume(4 - remainder);
425 }
426}
427
jbauchf1f87202016-03-30 06:43:37 -0700428void StunAttribute::WritePadding(ByteBufferWriter* buf) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000429 int remainder = length_ % 4;
430 if (remainder > 0) {
431 char zeroes[4] = {0};
432 buf->WriteBytes(zeroes, 4 - remainder);
433 }
434}
435
436StunAttribute* StunAttribute::Create(StunAttributeValueType value_type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200437 uint16_t type,
438 uint16_t length,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000439 StunMessage* owner) {
440 switch (value_type) {
441 case STUN_VALUE_ADDRESS:
442 return new StunAddressAttribute(type, length);
443 case STUN_VALUE_XOR_ADDRESS:
444 return new StunXorAddressAttribute(type, length, owner);
445 case STUN_VALUE_UINT32:
446 return new StunUInt32Attribute(type);
447 case STUN_VALUE_UINT64:
448 return new StunUInt64Attribute(type);
449 case STUN_VALUE_BYTE_STRING:
450 return new StunByteStringAttribute(type, length);
451 case STUN_VALUE_ERROR_CODE:
452 return new StunErrorCodeAttribute(type, length);
453 case STUN_VALUE_UINT16_LIST:
454 return new StunUInt16ListAttribute(type, length);
455 default:
456 return NULL;
457 }
458}
459
Peter Boström0c4e06b2015-10-07 12:23:21 +0200460StunAddressAttribute* StunAttribute::CreateAddress(uint16_t type) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461 return new StunAddressAttribute(type, 0);
462}
463
Peter Boström0c4e06b2015-10-07 12:23:21 +0200464StunXorAddressAttribute* StunAttribute::CreateXorAddress(uint16_t type) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000465 return new StunXorAddressAttribute(type, 0, NULL);
466}
467
Peter Boström0c4e06b2015-10-07 12:23:21 +0200468StunUInt64Attribute* StunAttribute::CreateUInt64(uint16_t type) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000469 return new StunUInt64Attribute(type);
470}
471
Peter Boström0c4e06b2015-10-07 12:23:21 +0200472StunUInt32Attribute* StunAttribute::CreateUInt32(uint16_t type) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000473 return new StunUInt32Attribute(type);
474}
475
Peter Boström0c4e06b2015-10-07 12:23:21 +0200476StunByteStringAttribute* StunAttribute::CreateByteString(uint16_t type) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477 return new StunByteStringAttribute(type, 0);
478}
479
480StunErrorCodeAttribute* StunAttribute::CreateErrorCode() {
481 return new StunErrorCodeAttribute(
482 STUN_ATTR_ERROR_CODE, StunErrorCodeAttribute::MIN_SIZE);
483}
484
485StunUInt16ListAttribute* StunAttribute::CreateUnknownAttributes() {
486 return new StunUInt16ListAttribute(STUN_ATTR_UNKNOWN_ATTRIBUTES, 0);
487}
488
Peter Boström0c4e06b2015-10-07 12:23:21 +0200489StunAddressAttribute::StunAddressAttribute(uint16_t type,
490 const rtc::SocketAddress& addr)
491 : StunAttribute(type, 0) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000492 SetAddress(addr);
493}
494
Peter Boström0c4e06b2015-10-07 12:23:21 +0200495StunAddressAttribute::StunAddressAttribute(uint16_t type, uint16_t length)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000496 : StunAttribute(type, length) {
497}
498
jbauchf1f87202016-03-30 06:43:37 -0700499bool StunAddressAttribute::Read(ByteBufferReader* buf) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200500 uint8_t dummy;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000501 if (!buf->ReadUInt8(&dummy))
502 return false;
503
Peter Boström0c4e06b2015-10-07 12:23:21 +0200504 uint8_t stun_family;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000505 if (!buf->ReadUInt8(&stun_family)) {
506 return false;
507 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200508 uint16_t port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000509 if (!buf->ReadUInt16(&port))
510 return false;
511 if (stun_family == STUN_ADDRESS_IPV4) {
512 in_addr v4addr;
513 if (length() != SIZE_IP4) {
514 return false;
515 }
516 if (!buf->ReadBytes(reinterpret_cast<char*>(&v4addr), sizeof(v4addr))) {
517 return false;
518 }
519 rtc::IPAddress ipaddr(v4addr);
520 SetAddress(rtc::SocketAddress(ipaddr, port));
521 } else if (stun_family == STUN_ADDRESS_IPV6) {
522 in6_addr v6addr;
523 if (length() != SIZE_IP6) {
524 return false;
525 }
526 if (!buf->ReadBytes(reinterpret_cast<char*>(&v6addr), sizeof(v6addr))) {
527 return false;
528 }
529 rtc::IPAddress ipaddr(v6addr);
530 SetAddress(rtc::SocketAddress(ipaddr, port));
531 } else {
532 return false;
533 }
534 return true;
535}
536
jbauchf1f87202016-03-30 06:43:37 -0700537bool StunAddressAttribute::Write(ByteBufferWriter* buf) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000538 StunAddressFamily address_family = family();
539 if (address_family == STUN_ADDRESS_UNDEF) {
540 LOG(LS_ERROR) << "Error writing address attribute: unknown family.";
541 return false;
542 }
543 buf->WriteUInt8(0);
544 buf->WriteUInt8(address_family);
545 buf->WriteUInt16(address_.port());
546 switch (address_.family()) {
547 case AF_INET: {
548 in_addr v4addr = address_.ipaddr().ipv4_address();
549 buf->WriteBytes(reinterpret_cast<char*>(&v4addr), sizeof(v4addr));
550 break;
551 }
552 case AF_INET6: {
553 in6_addr v6addr = address_.ipaddr().ipv6_address();
554 buf->WriteBytes(reinterpret_cast<char*>(&v6addr), sizeof(v6addr));
555 break;
556 }
557 }
558 return true;
559}
560
Peter Boström0c4e06b2015-10-07 12:23:21 +0200561StunXorAddressAttribute::StunXorAddressAttribute(uint16_t type,
562 const rtc::SocketAddress& addr)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000563 : StunAddressAttribute(type, addr), owner_(NULL) {
564}
565
Peter Boström0c4e06b2015-10-07 12:23:21 +0200566StunXorAddressAttribute::StunXorAddressAttribute(uint16_t type,
567 uint16_t length,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000568 StunMessage* owner)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200569 : StunAddressAttribute(type, length), owner_(owner) {
570}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000571
572rtc::IPAddress StunXorAddressAttribute::GetXoredIP() const {
573 if (owner_) {
574 rtc::IPAddress ip = ipaddr();
575 switch (ip.family()) {
576 case AF_INET: {
577 in_addr v4addr = ip.ipv4_address();
578 v4addr.s_addr =
579 (v4addr.s_addr ^ rtc::HostToNetwork32(kStunMagicCookie));
580 return rtc::IPAddress(v4addr);
581 }
582 case AF_INET6: {
583 in6_addr v6addr = ip.ipv6_address();
584 const std::string& transaction_id = owner_->transaction_id();
585 if (transaction_id.length() == kStunTransactionIdLength) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200586 uint32_t transactionid_as_ints[3];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000587 memcpy(&transactionid_as_ints[0], transaction_id.c_str(),
588 transaction_id.length());
Peter Boström0c4e06b2015-10-07 12:23:21 +0200589 uint32_t* ip_as_ints = reinterpret_cast<uint32_t*>(&v6addr.s6_addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000590 // Transaction ID is in network byte order, but magic cookie
591 // is stored in host byte order.
592 ip_as_ints[0] =
593 (ip_as_ints[0] ^ rtc::HostToNetwork32(kStunMagicCookie));
594 ip_as_ints[1] = (ip_as_ints[1] ^ transactionid_as_ints[0]);
595 ip_as_ints[2] = (ip_as_ints[2] ^ transactionid_as_ints[1]);
596 ip_as_ints[3] = (ip_as_ints[3] ^ transactionid_as_ints[2]);
597 return rtc::IPAddress(v6addr);
598 }
599 break;
600 }
601 }
602 }
603 // Invalid ip family or transaction ID, or missing owner.
604 // Return an AF_UNSPEC address.
605 return rtc::IPAddress();
606}
607
jbauchf1f87202016-03-30 06:43:37 -0700608bool StunXorAddressAttribute::Read(ByteBufferReader* buf) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000609 if (!StunAddressAttribute::Read(buf))
610 return false;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200611 uint16_t xoredport = port() ^ (kStunMagicCookie >> 16);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000612 rtc::IPAddress xored_ip = GetXoredIP();
613 SetAddress(rtc::SocketAddress(xored_ip, xoredport));
614 return true;
615}
616
jbauchf1f87202016-03-30 06:43:37 -0700617bool StunXorAddressAttribute::Write(ByteBufferWriter* buf) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000618 StunAddressFamily address_family = family();
619 if (address_family == STUN_ADDRESS_UNDEF) {
620 LOG(LS_ERROR) << "Error writing xor-address attribute: unknown family.";
621 return false;
622 }
623 rtc::IPAddress xored_ip = GetXoredIP();
624 if (xored_ip.family() == AF_UNSPEC) {
625 return false;
626 }
627 buf->WriteUInt8(0);
628 buf->WriteUInt8(family());
629 buf->WriteUInt16(port() ^ (kStunMagicCookie >> 16));
630 switch (xored_ip.family()) {
631 case AF_INET: {
632 in_addr v4addr = xored_ip.ipv4_address();
633 buf->WriteBytes(reinterpret_cast<const char*>(&v4addr), sizeof(v4addr));
634 break;
635 }
636 case AF_INET6: {
637 in6_addr v6addr = xored_ip.ipv6_address();
638 buf->WriteBytes(reinterpret_cast<const char*>(&v6addr), sizeof(v6addr));
639 break;
640 }
641 }
642 return true;
643}
644
Peter Boström0c4e06b2015-10-07 12:23:21 +0200645StunUInt32Attribute::StunUInt32Attribute(uint16_t type, uint32_t value)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000646 : StunAttribute(type, SIZE), bits_(value) {
647}
648
Peter Boström0c4e06b2015-10-07 12:23:21 +0200649StunUInt32Attribute::StunUInt32Attribute(uint16_t type)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000650 : StunAttribute(type, SIZE), bits_(0) {
651}
652
653bool StunUInt32Attribute::GetBit(size_t index) const {
654 ASSERT(index < 32);
655 return static_cast<bool>((bits_ >> index) & 0x1);
656}
657
658void StunUInt32Attribute::SetBit(size_t index, bool value) {
659 ASSERT(index < 32);
660 bits_ &= ~(1 << index);
661 bits_ |= value ? (1 << index) : 0;
662}
663
jbauchf1f87202016-03-30 06:43:37 -0700664bool StunUInt32Attribute::Read(ByteBufferReader* buf) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000665 if (length() != SIZE || !buf->ReadUInt32(&bits_))
666 return false;
667 return true;
668}
669
jbauchf1f87202016-03-30 06:43:37 -0700670bool StunUInt32Attribute::Write(ByteBufferWriter* buf) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000671 buf->WriteUInt32(bits_);
672 return true;
673}
674
Peter Boström0c4e06b2015-10-07 12:23:21 +0200675StunUInt64Attribute::StunUInt64Attribute(uint16_t type, uint64_t value)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000676 : StunAttribute(type, SIZE), bits_(value) {
677}
678
Peter Boström0c4e06b2015-10-07 12:23:21 +0200679StunUInt64Attribute::StunUInt64Attribute(uint16_t type)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000680 : StunAttribute(type, SIZE), bits_(0) {
681}
682
jbauchf1f87202016-03-30 06:43:37 -0700683bool StunUInt64Attribute::Read(ByteBufferReader* buf) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000684 if (length() != SIZE || !buf->ReadUInt64(&bits_))
685 return false;
686 return true;
687}
688
jbauchf1f87202016-03-30 06:43:37 -0700689bool StunUInt64Attribute::Write(ByteBufferWriter* buf) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000690 buf->WriteUInt64(bits_);
691 return true;
692}
693
Peter Boström0c4e06b2015-10-07 12:23:21 +0200694StunByteStringAttribute::StunByteStringAttribute(uint16_t type)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000695 : StunAttribute(type, 0), bytes_(NULL) {
696}
697
Peter Boström0c4e06b2015-10-07 12:23:21 +0200698StunByteStringAttribute::StunByteStringAttribute(uint16_t type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000699 const std::string& str)
700 : StunAttribute(type, 0), bytes_(NULL) {
701 CopyBytes(str.c_str(), str.size());
702}
703
Peter Boström0c4e06b2015-10-07 12:23:21 +0200704StunByteStringAttribute::StunByteStringAttribute(uint16_t type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000705 const void* bytes,
706 size_t length)
707 : StunAttribute(type, 0), bytes_(NULL) {
708 CopyBytes(bytes, length);
709}
710
Peter Boström0c4e06b2015-10-07 12:23:21 +0200711StunByteStringAttribute::StunByteStringAttribute(uint16_t type, uint16_t length)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000712 : StunAttribute(type, length), bytes_(NULL) {
713}
714
715StunByteStringAttribute::~StunByteStringAttribute() {
716 delete [] bytes_;
717}
718
719void StunByteStringAttribute::CopyBytes(const char* bytes) {
720 CopyBytes(bytes, strlen(bytes));
721}
722
723void StunByteStringAttribute::CopyBytes(const void* bytes, size_t length) {
724 char* new_bytes = new char[length];
725 memcpy(new_bytes, bytes, length);
726 SetBytes(new_bytes, length);
727}
728
Peter Boström0c4e06b2015-10-07 12:23:21 +0200729uint8_t StunByteStringAttribute::GetByte(size_t index) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000730 ASSERT(bytes_ != NULL);
731 ASSERT(index < length());
Peter Boström0c4e06b2015-10-07 12:23:21 +0200732 return static_cast<uint8_t>(bytes_[index]);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000733}
734
Peter Boström0c4e06b2015-10-07 12:23:21 +0200735void StunByteStringAttribute::SetByte(size_t index, uint8_t value) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000736 ASSERT(bytes_ != NULL);
737 ASSERT(index < length());
738 bytes_[index] = value;
739}
740
jbauchf1f87202016-03-30 06:43:37 -0700741bool StunByteStringAttribute::Read(ByteBufferReader* buf) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000742 bytes_ = new char[length()];
743 if (!buf->ReadBytes(bytes_, length())) {
744 return false;
745 }
746
747 ConsumePadding(buf);
748 return true;
749}
750
jbauchf1f87202016-03-30 06:43:37 -0700751bool StunByteStringAttribute::Write(ByteBufferWriter* buf) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000752 buf->WriteBytes(bytes_, length());
753 WritePadding(buf);
754 return true;
755}
756
757void StunByteStringAttribute::SetBytes(char* bytes, size_t length) {
758 delete [] bytes_;
759 bytes_ = bytes;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200760 SetLength(static_cast<uint16_t>(length));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000761}
762
Peter Boström0c4e06b2015-10-07 12:23:21 +0200763StunErrorCodeAttribute::StunErrorCodeAttribute(uint16_t type,
764 int code,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000765 const std::string& reason)
766 : StunAttribute(type, 0) {
767 SetCode(code);
768 SetReason(reason);
769}
770
Peter Boström0c4e06b2015-10-07 12:23:21 +0200771StunErrorCodeAttribute::StunErrorCodeAttribute(uint16_t type, uint16_t length)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000772 : StunAttribute(type, length), class_(0), number_(0) {
773}
774
775StunErrorCodeAttribute::~StunErrorCodeAttribute() {
776}
777
778int StunErrorCodeAttribute::code() const {
779 return class_ * 100 + number_;
780}
781
782void StunErrorCodeAttribute::SetCode(int code) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200783 class_ = static_cast<uint8_t>(code / 100);
784 number_ = static_cast<uint8_t>(code % 100);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000785}
786
787void StunErrorCodeAttribute::SetReason(const std::string& reason) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200788 SetLength(MIN_SIZE + static_cast<uint16_t>(reason.size()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000789 reason_ = reason;
790}
791
jbauchf1f87202016-03-30 06:43:37 -0700792bool StunErrorCodeAttribute::Read(ByteBufferReader* buf) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200793 uint32_t val;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000794 if (length() < MIN_SIZE || !buf->ReadUInt32(&val))
795 return false;
796
797 if ((val >> 11) != 0)
798 LOG(LS_ERROR) << "error-code bits not zero";
799
800 class_ = ((val >> 8) & 0x7);
801 number_ = (val & 0xff);
802
803 if (!buf->ReadString(&reason_, length() - 4))
804 return false;
805
806 ConsumePadding(buf);
807 return true;
808}
809
jbauchf1f87202016-03-30 06:43:37 -0700810bool StunErrorCodeAttribute::Write(ByteBufferWriter* buf) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000811 buf->WriteUInt32(class_ << 8 | number_);
812 buf->WriteString(reason_);
813 WritePadding(buf);
814 return true;
815}
816
Peter Boström0c4e06b2015-10-07 12:23:21 +0200817StunUInt16ListAttribute::StunUInt16ListAttribute(uint16_t type, uint16_t length)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000818 : StunAttribute(type, length) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200819 attr_types_ = new std::vector<uint16_t>();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000820}
821
822StunUInt16ListAttribute::~StunUInt16ListAttribute() {
823 delete attr_types_;
824}
825
826size_t StunUInt16ListAttribute::Size() const {
827 return attr_types_->size();
828}
829
Peter Boström0c4e06b2015-10-07 12:23:21 +0200830uint16_t StunUInt16ListAttribute::GetType(int index) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000831 return (*attr_types_)[index];
832}
833
Peter Boström0c4e06b2015-10-07 12:23:21 +0200834void StunUInt16ListAttribute::SetType(int index, uint16_t value) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000835 (*attr_types_)[index] = value;
836}
837
Peter Boström0c4e06b2015-10-07 12:23:21 +0200838void StunUInt16ListAttribute::AddType(uint16_t value) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000839 attr_types_->push_back(value);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200840 SetLength(static_cast<uint16_t>(attr_types_->size() * 2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841}
842
jbauchf1f87202016-03-30 06:43:37 -0700843bool StunUInt16ListAttribute::Read(ByteBufferReader* buf) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000844 if (length() % 2)
845 return false;
846
847 for (size_t i = 0; i < length() / 2; i++) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200848 uint16_t attr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000849 if (!buf->ReadUInt16(&attr))
850 return false;
851 attr_types_->push_back(attr);
852 }
853 // Padding of these attributes is done in RFC 5389 style. This is
854 // slightly different from RFC3489, but it shouldn't be important.
855 // RFC3489 pads out to a 32 bit boundary by duplicating one of the
856 // entries in the list (not necessarily the last one - it's unspecified).
857 // RFC5389 pads on the end, and the bytes are always ignored.
858 ConsumePadding(buf);
859 return true;
860}
861
jbauchf1f87202016-03-30 06:43:37 -0700862bool StunUInt16ListAttribute::Write(ByteBufferWriter* buf) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000863 for (size_t i = 0; i < attr_types_->size(); ++i) {
864 buf->WriteUInt16((*attr_types_)[i]);
865 }
866 WritePadding(buf);
867 return true;
868}
869
870int GetStunSuccessResponseType(int req_type) {
871 return IsStunRequestType(req_type) ? (req_type | 0x100) : -1;
872}
873
874int GetStunErrorResponseType(int req_type) {
875 return IsStunRequestType(req_type) ? (req_type | 0x110) : -1;
876}
877
878bool IsStunRequestType(int msg_type) {
879 return ((msg_type & kStunTypeMask) == 0x000);
880}
881
882bool IsStunIndicationType(int msg_type) {
883 return ((msg_type & kStunTypeMask) == 0x010);
884}
885
886bool IsStunSuccessResponseType(int msg_type) {
887 return ((msg_type & kStunTypeMask) == 0x100);
888}
889
890bool IsStunErrorResponseType(int msg_type) {
891 return ((msg_type & kStunTypeMask) == 0x110);
892}
893
894bool ComputeStunCredentialHash(const std::string& username,
895 const std::string& realm,
896 const std::string& password,
897 std::string* hash) {
898 // http://tools.ietf.org/html/rfc5389#section-15.4
899 // long-term credentials will be calculated using the key and key is
900 // key = MD5(username ":" realm ":" SASLprep(password))
901 std::string input = username;
902 input += ':';
903 input += realm;
904 input += ':';
905 input += password;
906
907 char digest[rtc::MessageDigest::kMaxSize];
908 size_t size = rtc::ComputeDigest(
909 rtc::DIGEST_MD5, input.c_str(), input.size(),
910 digest, sizeof(digest));
911 if (size == 0) {
912 return false;
913 }
914
915 *hash = std::string(digest, size);
916 return true;
917}
918
919} // namespace cricket