-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage.rs
2471 lines (2310 loc) · 93.7 KB
/
message.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2020 Matthew Waters <matthew@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! STUN Messages
//!
//! Provides types for generating, parsing, and manipulating STUN messages as specified in one of
//! [RFC8489], [RFC5389], or [RFC3489].
//!
//! [RFC8489]: https://tools.ietf.org/html/rfc8489
//! [RFC5389]: https://tools.ietf.org/html/rfc5389
//! [RFC3489]: https://tools.ietf.org/html/rfc3489
//!
//! ## Examples
//!
//! ### Parse a STUN [`Message`]
//!
//! ```
//! use stun_types::prelude::*;
//! use stun_types::attribute::{RawAttribute, PasswordAlgorithm, PasswordAlgorithmValue};
//! use stun_types::message::{Message, MessageType, MessageClass, BINDING};
//!
//! let msg_data = [
//! 0x00, 0x01, 0x00, 0x08, // method, class and length
//! 0x21, 0x12, 0xA4, 0x42, // Fixed STUN magic bytes
//! 0x00, 0x00, 0x00, 0x00, // \
//! 0x00, 0x00, 0x00, 0x00, // } transaction ID
//! 0x00, 0x00, 0x73, 0x92, // /
//! 0x00, 0x1D, 0x00, 0x04, // PasswordAlgorithm attribute header (type and length)
//! 0x00, 0x02, 0x00, 0x00 // PasswordAlgorithm attribute value
//! ];
//! let msg = Message::from_bytes(&msg_data).unwrap();
//!
//! // the various parts of a message can be retreived
//! assert_eq!(msg.get_type(), MessageType::from_class_method(MessageClass::Request, BINDING));
//! assert_eq!(msg.transaction_id(), 0x7392.into());
//!
//! // Attributes can be retrieved as raw values.
//! let msg_attr = msg.raw_attribute(0x1D.into()).unwrap();
//! let attr = RawAttribute::new(0x1D.into(), &[0, 2, 0, 0]);
//! assert_eq!(msg_attr, attr);
//!
//! // Or as typed values
//! let attr = msg.attribute::<PasswordAlgorithm>().unwrap();
//! assert_eq!(attr.algorithm(), PasswordAlgorithmValue::SHA256);
//! ```
//!
//! ### Generating a [`Message`]
//!
//! ```
//! use stun_types::prelude::*;
//! use stun_types::attribute::Software;
//! use stun_types::message::{Message, BINDING};
//!
//! // Automatically generates a transaction ID.
//! let mut msg = Message::builder_request(BINDING);
//!
//! let software_name = "stun-types";
//! let software = Software::new(software_name).unwrap();
//! assert_eq!(software.software(), software_name);
//! msg.add_attribute(&software).unwrap();
//!
//! let attribute_data = [
//! 0x80, 0x22, 0x00, 0x0a, // attribute type (0x8022) and length (0x000a)
//! 0x73, 0x74, 0x75, 0x6E, // s t u n
//! 0x2D, 0x74, 0x79, 0x70, // - t y p
//! 0x65, 0x73, 0x00, 0x00 // e s
//! ];
//!
//! let msg_data = msg.build();
//! // ignores the randomly generated transaction id
//! assert_eq!(msg_data[20..], attribute_data);
//! ```
use std::convert::TryFrom;
use byteorder::{BigEndian, ByteOrder};
use crate::attribute::*;
use tracing::{debug, warn};
/// The value of the magic cookie (in network byte order) as specified in RFC5389, and RFC8489.
pub const MAGIC_COOKIE: u32 = 0x2112A442;
/// The value of the binding message type. Can be used in either a request or an indication
/// message.
pub const BINDING: u16 = 0x0001;
#[derive(Debug, thiserror::Error)]
pub enum StunParseError {
/// Not a STUN message.
#[error("The provided data is not a STUN message")]
NotStun,
/// The message has been truncated
#[error("Not enough data available to parse the packet, expected {}, actual {}", .expected, .actual)]
Truncated {
/// The expeced number of bytes
expected: usize,
/// The encountered number of bytes
actual: usize,
},
/// The message has been truncated
#[error("Too many bytes for this data, expected {}, actual {}", .expected, .actual)]
TooLarge {
/// The expeced number of bytes
expected: usize,
/// The encountered number of bytes
actual: usize,
},
/// Integrity value does not match computed value
#[error("Integrity value does not match")]
IntegrityCheckFailed,
/// An attribute was not found in the message
#[error("Missing attribute {:?}", .0)]
MissingAttribute(AttributeType),
/// An attribute was found after the message integrity attribute
#[error("An attribute {:?} was encountered after a message integrity attribute", .0)]
AttributeAfterIntegrity(AttributeType),
/// An attribute was found after the message integrity attribute
#[error("An attribute {:?} was encountered after a fingerprint attribute", .0)]
AttributeAfterFingerprint(AttributeType),
/// Fingerprint does not match the data.
#[error("Fingerprint does not match")]
FingerprintMismatch,
/// The provided data does not match the message
#[error("The provided data does not match the message")]
DataMismatch,
/// The message has multiple integrity attributes
#[error("Multiple integrity types are used in this message")]
DuplicateIntegrity,
/// The attribute contains invalid data
#[error("The attribute contains invalid data")]
InvalidAttributeData,
/// The attribute does not parse this data
#[error("Cannot parse with this attribute")]
WrongAttributeImplementation,
}
/// Errors produced when writing a STUN message
#[derive(Debug, thiserror::Error)]
pub enum StunWriteError {
/// The message already has this attribute
#[error("The attribute already exists in the message")]
AttributeExists(AttributeType),
/// The fingerprint attribute already exists. Cannot write any further attributes
#[error("The message already contains a fingerprint attribute")]
FingerprintExists,
/// A message integrity attribute already exists. Cannot write any further attributes
#[error("The message already contains a message intregrity attribute")]
MessageIntegrityExists,
/// The message has been truncated
#[error("Too many bytes for this data, expected {}, actual {}", .expected, .actual)]
TooLarge {
/// The expeced number of bytes
expected: usize,
/// The encountered number of bytes
actual: usize,
},
/// The message has been truncated
#[error("Not enough data available to parse the packet, expected {}, actual {}", .expected, .actual)]
TooSmall {
/// The expected number of bytes
expected: usize,
/// The encountered number of bytes
actual: usize,
},
/// Failed to compute integrity
#[error("Failed to compute integrity")]
IntegrityFailed,
/// Out of range input provided
#[error("Out of range input provided")]
OutOfRange {
/// The value provided.
value: usize,
/// The minimum allowed value.
min: usize,
/// The maximum allowed value.
max: usize,
},
}
/// Structure for holding the required credentials for handling long-term STUN credentials
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct LongTermCredentials {
username: String,
password: String,
realm: String,
}
impl LongTermCredentials {
/// Create a new set of [`LongTermCredentials`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::LongTermCredentials;
/// let credentials = LongTermCredentials::new(
/// "user".to_string(),
/// "pass".to_string(),
/// "realm".to_string(),
/// );
/// assert_eq!(credentials.username(), "user");
/// assert_eq!(credentials.password(), "pass");
/// assert_eq!(credentials.realm(), "realm");
/// ```
pub fn new(username: String, password: String, realm: String) -> Self {
Self {
username,
password,
realm,
}
}
/// The configured username
pub fn username(&self) -> &str {
&self.username
}
/// The configured password
pub fn password(&self) -> &str {
&self.password
}
/// The configured realm
pub fn realm(&self) -> &str {
&self.realm
}
}
/// Structure for holding the required credentials for handling short-term STUN credentials
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct ShortTermCredentials {
password: String,
}
impl ShortTermCredentials {
/// Create a new set of [`ShortTermCredentials`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::ShortTermCredentials;
/// let credentials = ShortTermCredentials::new("password".to_string());
/// assert_eq!(credentials.password(), "password");
/// ```
pub fn new(password: String) -> Self {
Self { password }
}
/// The configured password
pub fn password(&self) -> &str {
&self.password
}
}
/// Enum for holding the credentials used to sign or verify a [`Message`]
///
/// This can either be a set of [`ShortTermCredentials`] or [`LongTermCredentials`]`
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum MessageIntegrityCredentials {
ShortTerm(ShortTermCredentials),
LongTerm(LongTermCredentials),
}
impl From<LongTermCredentials> for MessageIntegrityCredentials {
fn from(value: LongTermCredentials) -> Self {
MessageIntegrityCredentials::LongTerm(value)
}
}
impl From<ShortTermCredentials> for MessageIntegrityCredentials {
fn from(value: ShortTermCredentials) -> Self {
MessageIntegrityCredentials::ShortTerm(value)
}
}
impl MessageIntegrityCredentials {
fn make_hmac_key(&self) -> Vec<u8> {
match self {
MessageIntegrityCredentials::ShortTerm(short) => short.password.clone().into(),
MessageIntegrityCredentials::LongTerm(long) => {
use md5::{Digest, Md5};
let data = long.username.clone()
+ ":"
+ &long.realm.clone()
+ ":"
+ &long.password.clone();
let mut digest = Md5::new();
digest.update(&data);
digest.finalize().to_vec()
}
}
}
}
/// The class of a [`Message`].
///
/// There are four classes of [`Message`]s within the STUN protocol:
///
/// - [Request][`MessageClass::Request`] indicates that a request is being made and a
/// response is expected.
/// - An [Indication][`MessageClass::Indication`] is a fire and forget [`Message`] where
/// no response is required or expected.
/// - [Success][`MessageClass::Success`] indicates that a [Request][`MessageClass::Request`]
/// was successfully handled and the
/// - [Error][`MessageClass::Error`] class indicates that an error was produced.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum MessageClass {
Request,
Indication,
Success,
Error,
}
impl MessageClass {
/// Returns whether this [`MessageClass`] is of a response type. i.e. is either
/// [`MessageClass::Success`] or [`MessageClass::Error`].
pub fn is_response(self) -> bool {
matches!(self, MessageClass::Success | MessageClass::Error)
}
fn to_bits(self) -> u16 {
match self {
MessageClass::Request => 0x000,
MessageClass::Indication => 0x010,
MessageClass::Success => 0x100,
MessageClass::Error => 0x110,
}
}
}
/// The type of a [`Message`]. A combination of a [`MessageClass`] and a STUN method.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct MessageType(u16);
impl std::fmt::Display for MessageType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"MessageType(class: {:?}, method: {} ({:#x}))",
self.class(),
self.method(),
self.method()
)
}
}
impl MessageType {
/// Create a new [`MessageType`] from the provided [`MessageClass`] and method
///
/// # Examples
///
/// ```
/// # use stun_types::message::{MessageType, MessageClass, BINDING};
/// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
/// assert_eq!(mtype.has_class(MessageClass::Indication), true);
/// assert_eq!(mtype.has_method(BINDING), true);
/// ```
pub fn from_class_method(class: MessageClass, method: u16) -> Self {
let class_bits = MessageClass::to_bits(class);
let method_bits = method & 0xf | (method & 0x70) << 1 | (method & 0xf80) << 2;
// trace!("MessageType from class {:?} and method {:?} into {:?}", class, method,
// class_bits | method_bits);
Self(class_bits | method_bits)
}
/// Retrieves the class of a [`MessageType`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{MessageType, MessageClass, BINDING};
/// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
/// assert_eq!(mtype.class(), MessageClass::Indication);
/// ```
pub fn class(self) -> MessageClass {
let class = (self.0 & 0x10) >> 4 | (self.0 & 0x100) >> 7;
match class {
0x0 => MessageClass::Request,
0x1 => MessageClass::Indication,
0x2 => MessageClass::Success,
0x3 => MessageClass::Error,
_ => unreachable!(),
}
}
/// Returns whether class of a [`MessageType`] is equal to the provided [`MessageClass`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{MessageType, MessageClass, BINDING};
/// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
/// assert!(mtype.has_class(MessageClass::Indication));
/// ```
pub fn has_class(self, cls: MessageClass) -> bool {
self.class() == cls
}
/// Returns whether the class of a [`MessageType`] indicates a response [`Message`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{MessageType, MessageClass, BINDING};
/// assert_eq!(MessageType::from_class_method(MessageClass::Indication, BINDING)
/// .is_response(), false);
/// assert_eq!(MessageType::from_class_method(MessageClass::Request, BINDING)
/// .is_response(), false);
/// assert_eq!(MessageType::from_class_method(MessageClass::Success, BINDING)
/// .is_response(), true);
/// assert_eq!(MessageType::from_class_method(MessageClass::Error, BINDING)
/// .is_response(), true);
/// ```
pub fn is_response(self) -> bool {
self.class().is_response()
}
/// Returns the method of a [`MessageType`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{MessageType, MessageClass, BINDING};
/// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
/// assert_eq!(mtype.method(), BINDING);
/// ```
pub fn method(self) -> u16 {
self.0 & 0xf | (self.0 & 0xe0) >> 1 | (self.0 & 0x3e00) >> 2
}
/// Returns whether the method of a [`MessageType`] is equal to the provided value
///
/// # Examples
///
/// ```
/// # use stun_types::message::{MessageType, MessageClass, BINDING};
/// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
/// assert_eq!(mtype.has_method(BINDING), true);
/// ```
pub fn has_method(self, method: u16) -> bool {
self.method() == method
}
/// Convert a [`MessageType`] to network bytes
pub fn to_bytes(self) -> Vec<u8> {
let mut ret = vec![0; 2];
BigEndian::write_u16(&mut ret[0..2], self.0);
ret
}
/// Convert a set of network bytes into a [`MessageType`] or return an error
pub fn from_bytes(data: &[u8]) -> Result<Self, StunParseError> {
let data = BigEndian::read_u16(data);
if data & 0xc000 != 0x0 {
/* not a stun packet */
return Err(StunParseError::NotStun);
}
Ok(Self(data))
}
}
impl TryFrom<&[u8]> for MessageType {
type Error = StunParseError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
MessageType::from_bytes(value)
}
}
/// A unique transaction identifier for each message and it's (possible) response.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct TransactionId {
id: u128,
}
impl TransactionId {
/// Generate a new STUN transaction identifier.
pub fn generate() -> TransactionId {
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
rng.gen::<u128>().into()
}
}
impl From<u128> for TransactionId {
fn from(id: u128) -> Self {
Self {
id: id & 0xffff_ffff_ffff_ffff_ffff_ffff,
}
}
}
impl From<TransactionId> for u128 {
fn from(id: TransactionId) -> Self {
id.id
}
}
impl std::fmt::Display for TransactionId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:#x}", self.id)
}
}
/// The fixed length header of a STUN message. Allows reading the message header for a quick
/// check if this message is a valid STUN message. Can also be used to expose the length of the
/// complete message without needing to receive the entire message.
pub struct MessageHeader {
mtype: MessageType,
transaction_id: TransactionId,
length: u16,
}
impl MessageHeader {
/// The length of the STUN message header.
pub const LENGTH: usize = 20;
/// Deserialize a `MessageHeader`
///
/// # Examples
///
/// ```
/// # use stun_types::message::{MessageHeader, MessageType, MessageClass, BINDING};
/// let msg_data = [0, 1, 0, 8, 33, 18, 164, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 232];
/// let message = MessageHeader::from_bytes(&msg_data).unwrap();
/// assert_eq!(message.get_type(), MessageType::from_class_method(MessageClass::Request, BINDING));
/// assert_eq!(message.transaction_id(), 1000.into());
/// assert_eq!(message.data_length(), 8);
/// ```
pub fn from_bytes(data: &[u8]) -> Result<Self, StunParseError> {
if data.len() < 20 {
return Err(StunParseError::Truncated {
expected: 20,
actual: data.len(),
});
}
let mtype = MessageType::from_bytes(data)?;
let mlength = BigEndian::read_u16(&data[2..]);
let tid = BigEndian::read_u128(&data[4..]);
let cookie = (tid >> 96) as u32;
if cookie != MAGIC_COOKIE {
warn!(
"malformed cookie constant {:?} != stored data {:?}",
MAGIC_COOKIE, cookie
);
return Err(StunParseError::NotStun);
}
Ok(Self {
mtype,
transaction_id: tid.into(),
length: mlength,
})
}
/// The number of bytes of content in this [`MessageHeader`]. Adding both `data_length()`
/// and [`MessageHeader::LENGTH`] will result in the size of the complete STUN message.
pub fn data_length(&self) -> u16 {
self.length
}
/// The [`TransactionId`] of this [`MessageHeader`]
pub fn transaction_id(&self) -> TransactionId {
self.transaction_id
}
/// The [`MessageType`] of this [`MessageHeader`]
pub fn get_type(&self) -> MessageType {
self.mtype
}
}
/// The structure that encapsulates the entirety of a STUN message
///
/// Contains the [`MessageType`], a transaction ID, and a list of STUN
/// [`Attribute`]
#[derive(Debug, Clone)]
pub struct Message<'a> {
data: &'a [u8],
}
impl<'a> std::fmt::Display for Message<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Message(class: {:?}, method: {} ({:#x}), transaction: {}, attributes: ",
self.get_type().class(),
self.get_type().method(),
self.get_type().method(),
self.transaction_id()
)?;
let iter = self.iter_attributes();
write!(f, "[")?;
for (i, a) in iter.enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", a)?;
}
write!(f, "]")?;
write!(f, ")")
}
}
/// The supported hashing algorithms for ensuring integrity of a [`Message`]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IntegrityAlgorithm {
Sha1,
Sha256,
}
impl<'a> Message<'a> {
/// Create a new [`Message`] with the provided [`MessageType`] and transaction ID
///
/// Note you probably want to use one of the other helper constructors instead.
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let mtype = MessageType::from_class_method(MessageClass::Indication, BINDING);
/// let message = Message::builder(mtype, 0.into()).build();
/// let message = Message::from_bytes(&message).unwrap();
/// assert!(message.has_class(MessageClass::Indication));
/// assert!(message.has_method(BINDING));
/// ```
pub fn builder<'b>(mtype: MessageType, transaction_id: TransactionId) -> MessageBuilder<'b> {
MessageBuilder {
msg_type: mtype,
transaction_id,
attributes: vec![],
}
}
/// Create a new request [`Message`] of the provided method
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let message = Message::builder_request(BINDING);
/// let data = message.build();
/// let message = Message::from_bytes(&data).unwrap();
/// assert!(message.has_class(MessageClass::Request));
/// assert!(message.has_method(BINDING));
/// ```
pub fn builder_request<'b>(method: u16) -> MessageBuilder<'b> {
Message::builder(
MessageType::from_class_method(MessageClass::Request, method),
TransactionId::generate(),
)
}
/// Create a new success [`Message`] response from the provided request
///
/// # Panics
///
/// When a non-request [`Message`] is passed as the original input [`Message`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let message = Message::builder_request(BINDING);
/// let data = message.build();
/// let message = Message::from_bytes(&data).unwrap();
/// let success = Message::builder_success(&message).build();
/// let success = Message::from_bytes(&success).unwrap();
/// assert!(success.has_class(MessageClass::Success));
/// assert!(success.has_method(BINDING));
/// ```
pub fn builder_success<'b>(orig: &Message) -> MessageBuilder<'b> {
if !orig.has_class(MessageClass::Request) {
panic!(
"A success response message was attempted to be created from a non-request message"
);
}
Message::builder(
MessageType::from_class_method(MessageClass::Success, orig.method()),
orig.transaction_id(),
)
}
/// Create a new error [`Message`] response from the provided request
///
/// # Panics
///
/// When a non-request [`Message`] is passed as the original input [`Message`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let message = Message::builder_request(BINDING);
/// let data = message.build();
/// let message = Message::from_bytes(&data).unwrap();
/// let error = Message::builder_error(&message).build();
/// let error = Message::from_bytes(&error).unwrap();
/// assert!(error.has_class(MessageClass::Error));
/// assert!(error.has_method(BINDING));
/// ```
pub fn builder_error(orig: &Message) -> MessageBuilder<'a> {
if !orig.has_class(MessageClass::Request) {
panic!(
"An error response message was attempted to be created from a non-request message"
);
}
Message::builder(
MessageType::from_class_method(MessageClass::Error, orig.method()),
orig.transaction_id(),
)
}
/// Retrieve the [`MessageType`] of a [`Message`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let message = Message::builder_request(BINDING);
/// let data = message.build();
/// let message = Message::from_bytes(&data).unwrap();
/// assert!(message.get_type().has_class(MessageClass::Request));
/// assert!(message.get_type().has_method(BINDING));
/// ```
pub fn get_type(&self) -> MessageType {
MessageType::try_from(&self.data[..2]).unwrap()
}
/// Retrieve the [`MessageClass`] of a [`Message`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let message = Message::builder_request(BINDING).build();
/// let message = Message::from_bytes(&message).unwrap();
/// assert_eq!(message.class(), MessageClass::Request);
/// ```
pub fn class(&self) -> MessageClass {
self.get_type().class()
}
/// Returns whether the [`Message`] is of the specified [`MessageClass`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let message = Message::builder_request(BINDING).build();
/// let message = Message::from_bytes(&message).unwrap();
/// assert!(message.has_class(MessageClass::Request));
/// ```
pub fn has_class(&self, cls: MessageClass) -> bool {
self.class() == cls
}
/// Returns whether the [`Message`] is a response
///
/// This means that the [`Message`] has a class of either success or error
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let message = Message::builder_request(BINDING).build();
/// let message = Message::from_bytes(&message).unwrap();
/// assert_eq!(message.is_response(), false);
///
/// let error = Message::builder_error(&message).build();
/// let error = Message::from_bytes(&error).unwrap();
/// assert_eq!(error.is_response(), true);
///
/// let success = Message::builder_success(&message).build();
/// let success = Message::from_bytes(&success).unwrap();
/// assert_eq!(success.is_response(), true);
/// ```
pub fn is_response(&self) -> bool {
self.class().is_response()
}
/// Retrieves the method of the [`Message`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let message = Message::builder_request(BINDING).build();
/// let message = Message::from_bytes(&message).unwrap();
/// assert_eq!(message.method(), BINDING);
/// ```
pub fn method(&self) -> u16 {
self.get_type().method()
}
/// Returns whether the [`Message`] is of the specified method
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let message = Message::builder_request(BINDING).build();
/// let message = Message::from_bytes(&message).unwrap();
/// assert_eq!(message.has_method(BINDING), true);
/// assert_eq!(message.has_method(0), false);
/// ```
pub fn has_method(&self, method: u16) -> bool {
self.method() == method
}
/// Retrieves the 96-bit transaction ID of the [`Message`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING, TransactionId};
/// let mtype = MessageType::from_class_method(MessageClass::Request, BINDING);
/// let transaction_id = TransactionId::generate();
/// let message = Message::builder(mtype, transaction_id).build();
/// let message = Message::from_bytes(&message).unwrap();
/// assert_eq!(message.transaction_id(), transaction_id);
/// ```
pub fn transaction_id(&self) -> TransactionId {
BigEndian::read_u128(&self.data[4..]).into()
}
/// Deserialize a `Message`
///
/// # Examples
///
/// ```
/// # use stun_types::attribute::{RawAttribute, Attribute};
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING};
/// let msg_data = vec![0, 1, 0, 8, 33, 18, 164, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 232, 0, 1, 0, 1, 3, 0, 0, 0];
/// let message = Message::from_bytes(&msg_data).unwrap();
/// let attr = RawAttribute::new(1.into(), &[3]);
/// let msg_attr = message.raw_attribute(1.into()).unwrap();
/// assert_eq!(msg_attr, attr);
/// assert_eq!(message.get_type(), MessageType::from_class_method(MessageClass::Request, BINDING));
/// assert_eq!(message.transaction_id(), 1000.into());
/// ```
#[tracing::instrument(
name = "message_from_bytes",
level = "trace",
skip(data),
fields(
data.len = data.len()
)
)]
pub fn from_bytes(data: &'a [u8]) -> Result<Self, StunParseError> {
let orig_data = data;
let header = MessageHeader::from_bytes(data)?;
let mlength = header.data_length() as usize;
if mlength + MessageHeader::LENGTH > data.len() {
// mlength + header
warn!(
"malformed advertised size {:?} and data size {:?} don't match",
mlength + 20,
data.len()
);
return Err(StunParseError::Truncated {
expected: mlength + MessageHeader::LENGTH,
actual: data.len(),
});
}
let mut data_offset = MessageHeader::LENGTH;
let mut data = &data[MessageHeader::LENGTH..];
let mut seen_message_integrity = false;
let mut seen_fingerprint = false;
while !data.is_empty() {
let attr = RawAttribute::from_bytes(data).map_err(|e| {
warn!(
"failed to parse message attribute at offset {data_offset}: {:?}",
e
);
match e {
StunParseError::Truncated { expected, actual } => StunParseError::Truncated {
expected: expected + 4 + data_offset,
actual: actual + 4 + data_offset,
},
StunParseError::TooLarge { expected, actual } => StunParseError::TooLarge {
expected: expected + 4 + data_offset,
actual: actual + 4 + data_offset,
},
e => e,
}
})?;
if seen_message_integrity && attr.get_type() != Fingerprint::TYPE {
// only attribute valid after MESSAGE_INTEGRITY is FINGERPRINT
warn!(
"unexpected attribute {} after MESSAGE_INTEGRITY",
attr.get_type()
);
return Err(StunParseError::AttributeAfterIntegrity(attr.get_type()));
}
if seen_fingerprint {
// no valid attributes after FINGERPRINT
warn!("unexpected attribute {} after FINGERPRINT", attr.get_type());
return Err(StunParseError::AttributeAfterFingerprint(attr.get_type()));
}
if [MessageIntegrity::TYPE, MessageIntegritySha256::TYPE].contains(&attr.get_type()) {
seen_message_integrity = true;
// need credentials to validate the integrity of the message
}
let padded_len = padded_attr_size(&attr);
if padded_len > data.len() {
warn!(
"attribute {:?} extends past the end of the data",
attr.get_type()
);
return Err(StunParseError::Truncated {
expected: data_offset + padded_len,
actual: data_offset + data.len(),
});
}
if attr.get_type() == Fingerprint::TYPE {
seen_fingerprint = true;
let f = Fingerprint::from_raw(&attr)?;
let msg_fingerprint = f.fingerprint();
let mut fingerprint_data = orig_data[..data_offset].to_vec();
BigEndian::write_u16(
&mut fingerprint_data[2..4],
(data_offset + padded_len - MessageHeader::LENGTH) as u16,
);
let calculated_fingerprint = Fingerprint::compute(&fingerprint_data);
if &calculated_fingerprint != msg_fingerprint {
warn!(
"fingerprint mismatch {:?} != {:?}",
calculated_fingerprint, msg_fingerprint
);
return Err(StunParseError::FingerprintMismatch);
}
}
data = &data[padded_len..];
data_offset += padded_len;
}
Ok(Message { data: orig_data })
}
/// Validates the MESSAGE_INTEGRITY attribute with the provided credentials
///
/// The Original data that was used to construct this [`Message`] must be provided in order
/// to successfully validate the [`Message`]
///
/// # Examples
///
/// ```
/// # use stun_types::message::{Message, MessageType, MessageClass, BINDING,
/// MessageIntegrityCredentials, LongTermCredentials, IntegrityAlgorithm};
/// let mut message = Message::builder_request(BINDING);
/// let credentials = LongTermCredentials::new(
/// "user".to_owned(),
/// "pass".to_owned(),
/// "realm".to_owned()
/// ).into();
/// assert!(message.add_message_integrity(&credentials, IntegrityAlgorithm::Sha256).is_ok());
/// let data = message.build();
/// let message = Message::from_bytes(&data).unwrap();
/// assert!(message.validate_integrity(&credentials).is_ok());
/// ```
#[tracing::instrument(
name = "message_validate_integrity",
level = "trace",
skip(self, credentials),
fields(
msg.transaction = %self.transaction_id(),
)
)]
pub fn validate_integrity(
&self,
credentials: &MessageIntegrityCredentials,
) -> Result<(), StunParseError> {
debug!("using credentials {credentials:?}");
let raw_sha1 = self.raw_attribute(MessageIntegrity::TYPE);
let raw_sha256 = self.raw_attribute(MessageIntegritySha256::TYPE);
let (algo, msg_hmac) = match (raw_sha1, raw_sha256) {
(Some(_), Some(_)) => return Err(StunParseError::DuplicateIntegrity),
(Some(sha1), None) => {
let integrity = MessageIntegrity::try_from(&sha1)?;
(IntegrityAlgorithm::Sha1, integrity.hmac().to_vec())
}
(None, Some(sha256)) => {
let integrity = MessageIntegritySha256::try_from(&sha256)?;
(IntegrityAlgorithm::Sha256, integrity.hmac().to_vec())
}
(None, None) => return Err(StunParseError::MissingAttribute(MessageIntegrity::TYPE)),
};
// find the location of the original MessageIntegrity attribute: XXX: maybe encode this into