blob: 60367fa100d6a875bf7186b60172b2078329a476 [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
23using rtc::ByteBuffer;
24
25namespace cricket {
26
27const char STUN_ERROR_REASON_TRY_ALTERNATE_SERVER[] = "Try Alternate Server";
28const char STUN_ERROR_REASON_BAD_REQUEST[] = "Bad Request";
29const char STUN_ERROR_REASON_UNAUTHORIZED[] = "Unauthorized";
30const char STUN_ERROR_REASON_FORBIDDEN[] = "Forbidden";
31const char STUN_ERROR_REASON_STALE_CREDENTIALS[] = "Stale Credentials";
32const char STUN_ERROR_REASON_ALLOCATION_MISMATCH[] = "Allocation Mismatch";
33const char STUN_ERROR_REASON_STALE_NONCE[] = "Stale Nonce";
34const char STUN_ERROR_REASON_WRONG_CREDENTIALS[] = "Wrong Credentials";
35const char STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL[] = "Unsupported Protocol";
36const char STUN_ERROR_REASON_ROLE_CONFLICT[] = "Role Conflict";
37const char STUN_ERROR_REASON_SERVER_ERROR[] = "Server Error";
38
39const char TURN_MAGIC_COOKIE_VALUE[] = { '\x72', '\xC6', '\x4B', '\xC6' };
40const char EMPTY_TRANSACTION_ID[] = "0000000000000000";
41const uint32 STUN_FINGERPRINT_XOR_VALUE = 0x5354554E;
42
43// StunMessage
44
45StunMessage::StunMessage()
46 : type_(0),
47 length_(0),
48 transaction_id_(EMPTY_TRANSACTION_ID) {
49 ASSERT(IsValidTransactionId(transaction_id_));
50 attrs_ = new std::vector<StunAttribute*>();
51}
52
53StunMessage::~StunMessage() {
54 for (size_t i = 0; i < attrs_->size(); i++)
55 delete (*attrs_)[i];
56 delete attrs_;
57}
58
59bool StunMessage::IsLegacy() const {
60 if (transaction_id_.size() == kStunLegacyTransactionIdLength)
61 return true;
62 ASSERT(transaction_id_.size() == kStunTransactionIdLength);
63 return false;
64}
65
66bool StunMessage::SetTransactionID(const std::string& str) {
67 if (!IsValidTransactionId(str)) {
68 return false;
69 }
70 transaction_id_ = str;
71 return true;
72}
73
74bool StunMessage::AddAttribute(StunAttribute* attr) {
75 // Fail any attributes that aren't valid for this type of message.
76 if (attr->value_type() != GetAttributeValueType(attr->type())) {
77 return false;
78 }
79 attrs_->push_back(attr);
80 attr->SetOwner(this);
81 size_t attr_length = attr->length();
82 if (attr_length % 4 != 0) {
83 attr_length += (4 - (attr_length % 4));
84 }
85 length_ += static_cast<uint16>(attr_length + 4);
86 return true;
87}
88
89const StunAddressAttribute* StunMessage::GetAddress(int type) const {
90 switch (type) {
91 case STUN_ATTR_MAPPED_ADDRESS: {
92 // Return XOR-MAPPED-ADDRESS when MAPPED-ADDRESS attribute is
93 // missing.
94 const StunAttribute* mapped_address =
95 GetAttribute(STUN_ATTR_MAPPED_ADDRESS);
96 if (!mapped_address)
97 mapped_address = GetAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS);
98 return reinterpret_cast<const StunAddressAttribute*>(mapped_address);
99 }
100
101 default:
102 return static_cast<const StunAddressAttribute*>(GetAttribute(type));
103 }
104}
105
106const StunUInt32Attribute* StunMessage::GetUInt32(int type) const {
107 return static_cast<const StunUInt32Attribute*>(GetAttribute(type));
108}
109
110const StunUInt64Attribute* StunMessage::GetUInt64(int type) const {
111 return static_cast<const StunUInt64Attribute*>(GetAttribute(type));
112}
113
114const StunByteStringAttribute* StunMessage::GetByteString(int type) const {
115 return static_cast<const StunByteStringAttribute*>(GetAttribute(type));
116}
117
118const StunErrorCodeAttribute* StunMessage::GetErrorCode() const {
119 return static_cast<const StunErrorCodeAttribute*>(
120 GetAttribute(STUN_ATTR_ERROR_CODE));
121}
122
123const StunUInt16ListAttribute* StunMessage::GetUnknownAttributes() const {
124 return static_cast<const StunUInt16ListAttribute*>(
125 GetAttribute(STUN_ATTR_UNKNOWN_ATTRIBUTES));
126}
127
128// Verifies a STUN message has a valid MESSAGE-INTEGRITY attribute, using the
129// procedure outlined in RFC 5389, section 15.4.
130bool StunMessage::ValidateMessageIntegrity(const char* data, size_t size,
131 const std::string& password) {
132 // Verifying the size of the message.
133 if ((size % 4) != 0) {
134 return false;
135 }
136
137 // Getting the message length from the STUN header.
138 uint16 msg_length = rtc::GetBE16(&data[2]);
139 if (size != (msg_length + kStunHeaderSize)) {
140 return false;
141 }
142
143 // Finding Message Integrity attribute in stun message.
144 size_t current_pos = kStunHeaderSize;
145 bool has_message_integrity_attr = false;
146 while (current_pos < size) {
147 uint16 attr_type, attr_length;
148 // Getting attribute type and length.
149 attr_type = rtc::GetBE16(&data[current_pos]);
150 attr_length = rtc::GetBE16(&data[current_pos + sizeof(attr_type)]);
151
152 // If M-I, sanity check it, and break out.
153 if (attr_type == STUN_ATTR_MESSAGE_INTEGRITY) {
154 if (attr_length != kStunMessageIntegritySize ||
155 current_pos + attr_length > size) {
156 return false;
157 }
158 has_message_integrity_attr = true;
159 break;
160 }
161
162 // Otherwise, skip to the next attribute.
163 current_pos += sizeof(attr_type) + sizeof(attr_length) + attr_length;
164 if ((attr_length % 4) != 0) {
165 current_pos += (4 - (attr_length % 4));
166 }
167 }
168
169 if (!has_message_integrity_attr) {
170 return false;
171 }
172
173 // Getting length of the message to calculate Message Integrity.
174 size_t mi_pos = current_pos;
175 rtc::scoped_ptr<char[]> temp_data(new char[current_pos]);
176 memcpy(temp_data.get(), data, current_pos);
177 if (size > mi_pos + kStunAttributeHeaderSize + kStunMessageIntegritySize) {
178 // Stun message has other attributes after message integrity.
179 // Adjust the length parameter in stun message to calculate HMAC.
180 size_t extra_offset = size -
181 (mi_pos + kStunAttributeHeaderSize + kStunMessageIntegritySize);
182 size_t new_adjusted_len = size - extra_offset - kStunHeaderSize;
183
184 // Writing new length of the STUN message @ Message Length in temp buffer.
185 // 0 1 2 3
186 // 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
187 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
188 // |0 0| STUN Message Type | Message Length |
189 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
190 rtc::SetBE16(temp_data.get() + 2,
191 static_cast<uint16>(new_adjusted_len));
192 }
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.
223 rtc::ByteBuffer buf;
224 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 ||
265 rtc::GetBE16(fingerprint_attr_data + sizeof(uint16)) !=
266 StunUInt32Attribute::SIZE)
267 return false;
268
269 // Check the fingerprint value.
270 uint32 fingerprint =
271 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.
284 rtc::ByteBuffer buf;
285 if (!Write(&buf))
286 return false;
287
288 int msg_len_for_crc32 = static_cast<int>(
289 buf.Length() - kStunAttributeHeaderSize - fingerprint_attr->length());
290 uint32 c = rtc::ComputeCrc32(buf.Data(), msg_len_for_crc32);
291
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
297bool StunMessage::Read(ByteBuffer* buf) {
298 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
318 uint32 magic_cookie_int =
319 *reinterpret_cast<const uint32*>(magic_cookie.data());
320 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) {
335 uint16 attr_type, attr_length;
336 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
360bool StunMessage::Write(ByteBuffer* buf) const {
361 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());
369 buf->WriteUInt16(static_cast<uint16>((*attrs_)[i]->length()));
370 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;
390 case STUN_ATTR_RETRANSMIT_COUNT: return STUN_VALUE_UINT32;
391 default: return STUN_VALUE_UNKNOWN;
392 }
393}
394
395StunAttribute* StunMessage::CreateAttribute(int type, size_t length) /*const*/ {
396 StunAttributeValueType value_type = GetAttributeValueType(type);
397 return StunAttribute::Create(value_type, type,
398 static_cast<uint16>(length), this);
399}
400
401const StunAttribute* StunMessage::GetAttribute(int type) const {
402 for (size_t i = 0; i < attrs_->size(); ++i) {
403 if ((*attrs_)[i]->type() == type)
404 return (*attrs_)[i];
405 }
406 return NULL;
407}
408
409bool StunMessage::IsValidTransactionId(const std::string& transaction_id) {
410 return transaction_id.size() == kStunTransactionIdLength ||
411 transaction_id.size() == kStunLegacyTransactionIdLength;
412}
413
414// StunAttribute
415
416StunAttribute::StunAttribute(uint16 type, uint16 length)
417 : type_(type), length_(length) {
418}
419
420void StunAttribute::ConsumePadding(rtc::ByteBuffer* buf) const {
421 int remainder = length_ % 4;
422 if (remainder > 0) {
423 buf->Consume(4 - remainder);
424 }
425}
426
427void StunAttribute::WritePadding(rtc::ByteBuffer* buf) const {
428 int remainder = length_ % 4;
429 if (remainder > 0) {
430 char zeroes[4] = {0};
431 buf->WriteBytes(zeroes, 4 - remainder);
432 }
433}
434
435StunAttribute* StunAttribute::Create(StunAttributeValueType value_type,
436 uint16 type, uint16 length,
437 StunMessage* owner) {
438 switch (value_type) {
439 case STUN_VALUE_ADDRESS:
440 return new StunAddressAttribute(type, length);
441 case STUN_VALUE_XOR_ADDRESS:
442 return new StunXorAddressAttribute(type, length, owner);
443 case STUN_VALUE_UINT32:
444 return new StunUInt32Attribute(type);
445 case STUN_VALUE_UINT64:
446 return new StunUInt64Attribute(type);
447 case STUN_VALUE_BYTE_STRING:
448 return new StunByteStringAttribute(type, length);
449 case STUN_VALUE_ERROR_CODE:
450 return new StunErrorCodeAttribute(type, length);
451 case STUN_VALUE_UINT16_LIST:
452 return new StunUInt16ListAttribute(type, length);
453 default:
454 return NULL;
455 }
456}
457
458StunAddressAttribute* StunAttribute::CreateAddress(uint16 type) {
459 return new StunAddressAttribute(type, 0);
460}
461
462StunXorAddressAttribute* StunAttribute::CreateXorAddress(uint16 type) {
463 return new StunXorAddressAttribute(type, 0, NULL);
464}
465
466StunUInt64Attribute* StunAttribute::CreateUInt64(uint16 type) {
467 return new StunUInt64Attribute(type);
468}
469
470StunUInt32Attribute* StunAttribute::CreateUInt32(uint16 type) {
471 return new StunUInt32Attribute(type);
472}
473
474StunByteStringAttribute* StunAttribute::CreateByteString(uint16 type) {
475 return new StunByteStringAttribute(type, 0);
476}
477
478StunErrorCodeAttribute* StunAttribute::CreateErrorCode() {
479 return new StunErrorCodeAttribute(
480 STUN_ATTR_ERROR_CODE, StunErrorCodeAttribute::MIN_SIZE);
481}
482
483StunUInt16ListAttribute* StunAttribute::CreateUnknownAttributes() {
484 return new StunUInt16ListAttribute(STUN_ATTR_UNKNOWN_ATTRIBUTES, 0);
485}
486
487StunAddressAttribute::StunAddressAttribute(uint16 type,
488 const rtc::SocketAddress& addr)
489 : StunAttribute(type, 0) {
490 SetAddress(addr);
491}
492
493StunAddressAttribute::StunAddressAttribute(uint16 type, uint16 length)
494 : StunAttribute(type, length) {
495}
496
497bool StunAddressAttribute::Read(ByteBuffer* buf) {
498 uint8 dummy;
499 if (!buf->ReadUInt8(&dummy))
500 return false;
501
502 uint8 stun_family;
503 if (!buf->ReadUInt8(&stun_family)) {
504 return false;
505 }
506 uint16 port;
507 if (!buf->ReadUInt16(&port))
508 return false;
509 if (stun_family == STUN_ADDRESS_IPV4) {
510 in_addr v4addr;
511 if (length() != SIZE_IP4) {
512 return false;
513 }
514 if (!buf->ReadBytes(reinterpret_cast<char*>(&v4addr), sizeof(v4addr))) {
515 return false;
516 }
517 rtc::IPAddress ipaddr(v4addr);
518 SetAddress(rtc::SocketAddress(ipaddr, port));
519 } else if (stun_family == STUN_ADDRESS_IPV6) {
520 in6_addr v6addr;
521 if (length() != SIZE_IP6) {
522 return false;
523 }
524 if (!buf->ReadBytes(reinterpret_cast<char*>(&v6addr), sizeof(v6addr))) {
525 return false;
526 }
527 rtc::IPAddress ipaddr(v6addr);
528 SetAddress(rtc::SocketAddress(ipaddr, port));
529 } else {
530 return false;
531 }
532 return true;
533}
534
535bool StunAddressAttribute::Write(ByteBuffer* buf) const {
536 StunAddressFamily address_family = family();
537 if (address_family == STUN_ADDRESS_UNDEF) {
538 LOG(LS_ERROR) << "Error writing address attribute: unknown family.";
539 return false;
540 }
541 buf->WriteUInt8(0);
542 buf->WriteUInt8(address_family);
543 buf->WriteUInt16(address_.port());
544 switch (address_.family()) {
545 case AF_INET: {
546 in_addr v4addr = address_.ipaddr().ipv4_address();
547 buf->WriteBytes(reinterpret_cast<char*>(&v4addr), sizeof(v4addr));
548 break;
549 }
550 case AF_INET6: {
551 in6_addr v6addr = address_.ipaddr().ipv6_address();
552 buf->WriteBytes(reinterpret_cast<char*>(&v6addr), sizeof(v6addr));
553 break;
554 }
555 }
556 return true;
557}
558
559StunXorAddressAttribute::StunXorAddressAttribute(uint16 type,
560 const rtc::SocketAddress& addr)
561 : StunAddressAttribute(type, addr), owner_(NULL) {
562}
563
564StunXorAddressAttribute::StunXorAddressAttribute(uint16 type,
565 uint16 length,
566 StunMessage* owner)
567 : StunAddressAttribute(type, length), owner_(owner) {}
568
569rtc::IPAddress StunXorAddressAttribute::GetXoredIP() const {
570 if (owner_) {
571 rtc::IPAddress ip = ipaddr();
572 switch (ip.family()) {
573 case AF_INET: {
574 in_addr v4addr = ip.ipv4_address();
575 v4addr.s_addr =
576 (v4addr.s_addr ^ rtc::HostToNetwork32(kStunMagicCookie));
577 return rtc::IPAddress(v4addr);
578 }
579 case AF_INET6: {
580 in6_addr v6addr = ip.ipv6_address();
581 const std::string& transaction_id = owner_->transaction_id();
582 if (transaction_id.length() == kStunTransactionIdLength) {
583 uint32 transactionid_as_ints[3];
584 memcpy(&transactionid_as_ints[0], transaction_id.c_str(),
585 transaction_id.length());
586 uint32* ip_as_ints = reinterpret_cast<uint32*>(&v6addr.s6_addr);
587 // Transaction ID is in network byte order, but magic cookie
588 // is stored in host byte order.
589 ip_as_ints[0] =
590 (ip_as_ints[0] ^ rtc::HostToNetwork32(kStunMagicCookie));
591 ip_as_ints[1] = (ip_as_ints[1] ^ transactionid_as_ints[0]);
592 ip_as_ints[2] = (ip_as_ints[2] ^ transactionid_as_ints[1]);
593 ip_as_ints[3] = (ip_as_ints[3] ^ transactionid_as_ints[2]);
594 return rtc::IPAddress(v6addr);
595 }
596 break;
597 }
598 }
599 }
600 // Invalid ip family or transaction ID, or missing owner.
601 // Return an AF_UNSPEC address.
602 return rtc::IPAddress();
603}
604
605bool StunXorAddressAttribute::Read(ByteBuffer* buf) {
606 if (!StunAddressAttribute::Read(buf))
607 return false;
608 uint16 xoredport = port() ^ (kStunMagicCookie >> 16);
609 rtc::IPAddress xored_ip = GetXoredIP();
610 SetAddress(rtc::SocketAddress(xored_ip, xoredport));
611 return true;
612}
613
614bool StunXorAddressAttribute::Write(ByteBuffer* buf) const {
615 StunAddressFamily address_family = family();
616 if (address_family == STUN_ADDRESS_UNDEF) {
617 LOG(LS_ERROR) << "Error writing xor-address attribute: unknown family.";
618 return false;
619 }
620 rtc::IPAddress xored_ip = GetXoredIP();
621 if (xored_ip.family() == AF_UNSPEC) {
622 return false;
623 }
624 buf->WriteUInt8(0);
625 buf->WriteUInt8(family());
626 buf->WriteUInt16(port() ^ (kStunMagicCookie >> 16));
627 switch (xored_ip.family()) {
628 case AF_INET: {
629 in_addr v4addr = xored_ip.ipv4_address();
630 buf->WriteBytes(reinterpret_cast<const char*>(&v4addr), sizeof(v4addr));
631 break;
632 }
633 case AF_INET6: {
634 in6_addr v6addr = xored_ip.ipv6_address();
635 buf->WriteBytes(reinterpret_cast<const char*>(&v6addr), sizeof(v6addr));
636 break;
637 }
638 }
639 return true;
640}
641
642StunUInt32Attribute::StunUInt32Attribute(uint16 type, uint32 value)
643 : StunAttribute(type, SIZE), bits_(value) {
644}
645
646StunUInt32Attribute::StunUInt32Attribute(uint16 type)
647 : StunAttribute(type, SIZE), bits_(0) {
648}
649
650bool StunUInt32Attribute::GetBit(size_t index) const {
651 ASSERT(index < 32);
652 return static_cast<bool>((bits_ >> index) & 0x1);
653}
654
655void StunUInt32Attribute::SetBit(size_t index, bool value) {
656 ASSERT(index < 32);
657 bits_ &= ~(1 << index);
658 bits_ |= value ? (1 << index) : 0;
659}
660
661bool StunUInt32Attribute::Read(ByteBuffer* buf) {
662 if (length() != SIZE || !buf->ReadUInt32(&bits_))
663 return false;
664 return true;
665}
666
667bool StunUInt32Attribute::Write(ByteBuffer* buf) const {
668 buf->WriteUInt32(bits_);
669 return true;
670}
671
672StunUInt64Attribute::StunUInt64Attribute(uint16 type, uint64 value)
673 : StunAttribute(type, SIZE), bits_(value) {
674}
675
676StunUInt64Attribute::StunUInt64Attribute(uint16 type)
677 : StunAttribute(type, SIZE), bits_(0) {
678}
679
680bool StunUInt64Attribute::Read(ByteBuffer* buf) {
681 if (length() != SIZE || !buf->ReadUInt64(&bits_))
682 return false;
683 return true;
684}
685
686bool StunUInt64Attribute::Write(ByteBuffer* buf) const {
687 buf->WriteUInt64(bits_);
688 return true;
689}
690
691StunByteStringAttribute::StunByteStringAttribute(uint16 type)
692 : StunAttribute(type, 0), bytes_(NULL) {
693}
694
695StunByteStringAttribute::StunByteStringAttribute(uint16 type,
696 const std::string& str)
697 : StunAttribute(type, 0), bytes_(NULL) {
698 CopyBytes(str.c_str(), str.size());
699}
700
701StunByteStringAttribute::StunByteStringAttribute(uint16 type,
702 const void* bytes,
703 size_t length)
704 : StunAttribute(type, 0), bytes_(NULL) {
705 CopyBytes(bytes, length);
706}
707
708StunByteStringAttribute::StunByteStringAttribute(uint16 type, uint16 length)
709 : StunAttribute(type, length), bytes_(NULL) {
710}
711
712StunByteStringAttribute::~StunByteStringAttribute() {
713 delete [] bytes_;
714}
715
716void StunByteStringAttribute::CopyBytes(const char* bytes) {
717 CopyBytes(bytes, strlen(bytes));
718}
719
720void StunByteStringAttribute::CopyBytes(const void* bytes, size_t length) {
721 char* new_bytes = new char[length];
722 memcpy(new_bytes, bytes, length);
723 SetBytes(new_bytes, length);
724}
725
726uint8 StunByteStringAttribute::GetByte(size_t index) const {
727 ASSERT(bytes_ != NULL);
728 ASSERT(index < length());
729 return static_cast<uint8>(bytes_[index]);
730}
731
732void StunByteStringAttribute::SetByte(size_t index, uint8 value) {
733 ASSERT(bytes_ != NULL);
734 ASSERT(index < length());
735 bytes_[index] = value;
736}
737
738bool StunByteStringAttribute::Read(ByteBuffer* buf) {
739 bytes_ = new char[length()];
740 if (!buf->ReadBytes(bytes_, length())) {
741 return false;
742 }
743
744 ConsumePadding(buf);
745 return true;
746}
747
748bool StunByteStringAttribute::Write(ByteBuffer* buf) const {
749 buf->WriteBytes(bytes_, length());
750 WritePadding(buf);
751 return true;
752}
753
754void StunByteStringAttribute::SetBytes(char* bytes, size_t length) {
755 delete [] bytes_;
756 bytes_ = bytes;
757 SetLength(static_cast<uint16>(length));
758}
759
760StunErrorCodeAttribute::StunErrorCodeAttribute(uint16 type, int code,
761 const std::string& reason)
762 : StunAttribute(type, 0) {
763 SetCode(code);
764 SetReason(reason);
765}
766
767StunErrorCodeAttribute::StunErrorCodeAttribute(uint16 type, uint16 length)
768 : StunAttribute(type, length), class_(0), number_(0) {
769}
770
771StunErrorCodeAttribute::~StunErrorCodeAttribute() {
772}
773
774int StunErrorCodeAttribute::code() const {
775 return class_ * 100 + number_;
776}
777
778void StunErrorCodeAttribute::SetCode(int code) {
779 class_ = static_cast<uint8>(code / 100);
780 number_ = static_cast<uint8>(code % 100);
781}
782
783void StunErrorCodeAttribute::SetReason(const std::string& reason) {
784 SetLength(MIN_SIZE + static_cast<uint16>(reason.size()));
785 reason_ = reason;
786}
787
788bool StunErrorCodeAttribute::Read(ByteBuffer* buf) {
789 uint32 val;
790 if (length() < MIN_SIZE || !buf->ReadUInt32(&val))
791 return false;
792
793 if ((val >> 11) != 0)
794 LOG(LS_ERROR) << "error-code bits not zero";
795
796 class_ = ((val >> 8) & 0x7);
797 number_ = (val & 0xff);
798
799 if (!buf->ReadString(&reason_, length() - 4))
800 return false;
801
802 ConsumePadding(buf);
803 return true;
804}
805
806bool StunErrorCodeAttribute::Write(ByteBuffer* buf) const {
807 buf->WriteUInt32(class_ << 8 | number_);
808 buf->WriteString(reason_);
809 WritePadding(buf);
810 return true;
811}
812
813StunUInt16ListAttribute::StunUInt16ListAttribute(uint16 type, uint16 length)
814 : StunAttribute(type, length) {
815 attr_types_ = new std::vector<uint16>();
816}
817
818StunUInt16ListAttribute::~StunUInt16ListAttribute() {
819 delete attr_types_;
820}
821
822size_t StunUInt16ListAttribute::Size() const {
823 return attr_types_->size();
824}
825
826uint16 StunUInt16ListAttribute::GetType(int index) const {
827 return (*attr_types_)[index];
828}
829
830void StunUInt16ListAttribute::SetType(int index, uint16 value) {
831 (*attr_types_)[index] = value;
832}
833
834void StunUInt16ListAttribute::AddType(uint16 value) {
835 attr_types_->push_back(value);
836 SetLength(static_cast<uint16>(attr_types_->size() * 2));
837}
838
839bool StunUInt16ListAttribute::Read(ByteBuffer* buf) {
840 if (length() % 2)
841 return false;
842
843 for (size_t i = 0; i < length() / 2; i++) {
844 uint16 attr;
845 if (!buf->ReadUInt16(&attr))
846 return false;
847 attr_types_->push_back(attr);
848 }
849 // Padding of these attributes is done in RFC 5389 style. This is
850 // slightly different from RFC3489, but it shouldn't be important.
851 // RFC3489 pads out to a 32 bit boundary by duplicating one of the
852 // entries in the list (not necessarily the last one - it's unspecified).
853 // RFC5389 pads on the end, and the bytes are always ignored.
854 ConsumePadding(buf);
855 return true;
856}
857
858bool StunUInt16ListAttribute::Write(ByteBuffer* buf) const {
859 for (size_t i = 0; i < attr_types_->size(); ++i) {
860 buf->WriteUInt16((*attr_types_)[i]);
861 }
862 WritePadding(buf);
863 return true;
864}
865
866int GetStunSuccessResponseType(int req_type) {
867 return IsStunRequestType(req_type) ? (req_type | 0x100) : -1;
868}
869
870int GetStunErrorResponseType(int req_type) {
871 return IsStunRequestType(req_type) ? (req_type | 0x110) : -1;
872}
873
874bool IsStunRequestType(int msg_type) {
875 return ((msg_type & kStunTypeMask) == 0x000);
876}
877
878bool IsStunIndicationType(int msg_type) {
879 return ((msg_type & kStunTypeMask) == 0x010);
880}
881
882bool IsStunSuccessResponseType(int msg_type) {
883 return ((msg_type & kStunTypeMask) == 0x100);
884}
885
886bool IsStunErrorResponseType(int msg_type) {
887 return ((msg_type & kStunTypeMask) == 0x110);
888}
889
890bool ComputeStunCredentialHash(const std::string& username,
891 const std::string& realm,
892 const std::string& password,
893 std::string* hash) {
894 // http://tools.ietf.org/html/rfc5389#section-15.4
895 // long-term credentials will be calculated using the key and key is
896 // key = MD5(username ":" realm ":" SASLprep(password))
897 std::string input = username;
898 input += ':';
899 input += realm;
900 input += ':';
901 input += password;
902
903 char digest[rtc::MessageDigest::kMaxSize];
904 size_t size = rtc::ComputeDigest(
905 rtc::DIGEST_MD5, input.c_str(), input.size(),
906 digest, sizeof(digest));
907 if (size == 0) {
908 return false;
909 }
910
911 *hash = std::string(digest, size);
912 return true;
913}
914
915} // namespace cricket