internet 0.0.4

Network library for rust
Documentation
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
//! Handshake encoding following [RFC 2246].
//!
//! Encoding is supported for the following structures:
//!
//!  - [`HandshakeType`]
//!  - [`Handshake`]
//!  - [`HelloRequest`]
//!  - [`Random`]
//!  - [`SessionId`]
//!  - [`CompressionMethod`]
//!  - [`ClientHello`]
//!  - [`ServerHello`]
//!  - [`Asn1Cert`]
//!  - [`Certificate`]
//!  - [`KeyExchangeAlgorithm`]
//!  - [`SignatureAlgorithm`]
//!  - [`ClientCertificateType`]
//!  - [`Signature`]
//!  - [`CertificateRequest`]
//!  - [`ServerHelloDone`]
//!  - [`CertificateVerify`]
//!  - [`Finished`]
//!
//! [RFC 2246]: https://datatracker.ietf.org/doc/html/rfc2246

use crate::{
    Buf,
    BufError::{self},
    BufMut, BufResult, Codec, Cursor,
    tls::{LengthPrefix, ProtocolVersion, TlsVec, u24},
    tls1_0::CipherSuite,
};

/// A Handshake Type following [Section A.4.1].
///
/// [Section A.4.1]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.1
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum HandshakeType {
    /// hello_request(0)
    HelloRequest = 0,
    /// client_hello(1)
    ClientHello = 1,
    /// server_hello(2)
    ServerHello = 2,
    /// certificate(11)
    Certificate = 11,
    /// server_key_exchange(12)
    ServerKeyExchange = 12,
    /// certificate_request(13)
    CertificateRequest = 13,
    /// server_hello_done(14)
    ServerHelloDone = 14,
    /// certificate_verify(15)
    CertificateVerify = 15,
    /// client_key_exchange(16)
    ClientKeyExchange = 16,
    /// finished(20)
    Finished = 20,
}

impl Codec for HandshakeType {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        (*self as u8).encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match u8::decode(reader, ())? {
            x if x == (Self::HelloRequest as u8) => Ok(Self::HelloRequest),
            x if x == (Self::ClientHello as u8) => Ok(Self::ClientHello),
            x if x == (Self::ServerHello as u8) => Ok(Self::ServerHello),
            x if x == (Self::Certificate as u8) => Ok(Self::Certificate),
            x if x == (Self::ServerKeyExchange as u8) => Ok(Self::ServerKeyExchange),
            x if x == (Self::CertificateRequest as u8) => Ok(Self::CertificateRequest),
            x if x == (Self::ServerHelloDone as u8) => Ok(Self::ServerHelloDone),
            x if x == (Self::CertificateVerify as u8) => Ok(Self::CertificateVerify),
            x if x == (Self::ClientKeyExchange as u8) => Ok(Self::ClientKeyExchange),
            x if x == (Self::Finished as u8) => Ok(Self::Finished),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A Handshake message following [Section A.4.2].
///
/// [Section A.4.2]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.2
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Handshake {
    /// The type of the handshake message.
    pub msg_type: HandshakeType,
    /// The body of the handshake message.
    pub msg: Vec<u8>,
}

impl Codec for Handshake {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.msg_type.encode(writer, ())?;
        let len = u24::from_usize(self.msg.len())?;
        len.encode(writer, ())?;
        writer.write_slice(&self.msg)
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let msg_type = HandshakeType::decode(reader, ())?;
        let length_u24 = u24::decode(reader, ())?;
        let length = length_u24.as_usize();

        if reader.remaining() < length {
            return Err(BufError::UnexpectedEof);
        }

        let mut msg = vec![0u8; length];
        reader.read_into(&mut msg)?;

        Ok(Self { msg_type, msg })
    }
}

/// A Hello Request message following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HelloRequest;

impl Codec for HelloRequest {
    fn encode<W: BufMut>(&self, _writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Ok(())
    }

    fn decode<R: Buf>(_reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self)
    }
}

/// A Random structure following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Random(pub [u8; 32]);

impl Random {
    /// Creates a new Random structure with placeholder values.
    pub fn random() -> Self {
        Self([0x32u8; 32])
    }
}

impl Codec for Random {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        writer.write_array(&self.0)
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(reader.read_array::<32>()?))
    }
}

/// A Session ID following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SessionId(pub TlsVec<u8, u8>);

impl Codec for SessionId {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<u8, u8>::decode(reader, ())?))
    }
}

/// A Compression Method following [Section A.3].
///
/// [Section A.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.3
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum CompressionMethod {
    /// null(0)
    Null = 0,
}

impl Codec for CompressionMethod {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        (*self as u8).encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match u8::decode(reader, ())? {
            x if x == (Self::Null as u8) => Ok(Self::Null),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A Client Hello message following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ClientHello {
    /// The protocol version.
    pub client_version: ProtocolVersion,
    /// The random structure.
    pub random: Random,
    /// The session ID.
    pub session_id: SessionId,
    /// The cipher suites.
    pub cipher_suites: TlsVec<CipherSuite, u16>,
    /// The compression methods.
    pub compression_methods: TlsVec<CompressionMethod, u8>,
}

impl Codec for ClientHello {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.client_version.encode(writer, ())?;
        self.random.encode(writer, ())?;
        self.session_id.encode(writer, ())?;
        self.cipher_suites.encode(writer, ())?;
        self.compression_methods.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            client_version: ProtocolVersion::decode(reader, ())?,
            random: Random::decode(reader, ())?,
            session_id: SessionId::decode(reader, ())?,
            cipher_suites: TlsVec::<CipherSuite, u16>::decode(reader, ())?,
            compression_methods: TlsVec::<CompressionMethod, u8>::decode(reader, ())?,
        })
    }
}

/// A Server Hello message following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServerHello {
    /// The protocol version.
    pub server_version: ProtocolVersion,
    /// The random structure.
    pub random: Random,
    /// The session ID.
    pub session_id: SessionId,
    /// The cipher suite.
    pub cipher_suite: CipherSuite,
    /// The compression method.
    pub compression_method: CompressionMethod,
}

impl Codec for ServerHello {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.server_version.encode(writer, ())?;
        self.random.encode(writer, ())?;
        self.session_id.encode(writer, ())?;
        self.cipher_suite.encode(writer, ())?;
        self.compression_method.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            server_version: ProtocolVersion::decode(reader, ())?,
            random: Random::decode(reader, ())?,
            session_id: SessionId::decode(reader, ())?,
            cipher_suite: CipherSuite::decode(reader, ())?,
            compression_method: CompressionMethod::decode(reader, ())?,
        })
    }
}

/// An ASN.1 Certificate following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Asn1Cert(pub TlsVec<u8, u24>);

impl Codec for Asn1Cert {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<u8, u24>::decode(reader, ())?))
    }
}

/// A Certificate message following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Certificate {
    /// The list of certificates.
    pub certificate_list: TlsVec<Asn1Cert, u24>,
}

impl Codec for Certificate {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.certificate_list.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            certificate_list: TlsVec::<Asn1Cert, u24>::decode(reader, ())?,
        })
    }
}

/// A Key Exchange Algorithm following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum KeyExchangeAlgorithm {
    /// rsa
    Rsa = 0,
    /// diffie_hellman
    DiffieHellman = 1,
}

impl Codec for KeyExchangeAlgorithm {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        (*self as u8).encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match u8::decode(reader, ())? {
            x if x == (Self::Rsa as u8) => Ok(Self::Rsa),
            x if x == (Self::DiffieHellman as u8) => Ok(Self::DiffieHellman),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A Signature Algorithm following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum SignatureAlgorithm {
    /// anonymous
    Anonymous = 0,
    /// rsa
    Rsa = 1,
    /// dsa
    Dsa = 2,
}

impl Codec for SignatureAlgorithm {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        (*self as u8).encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match u8::decode(reader, ())? {
            x if x == (Self::Anonymous as u8) => Ok(Self::Anonymous),
            x if x == (Self::Rsa as u8) => Ok(Self::Rsa),
            x if x == (Self::Dsa as u8) => Ok(Self::Dsa),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A Client Certificate Type following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum ClientCertificateType {
    /// rsa_sign(1)
    RsaSign = 1,
    /// dss_sign(2)
    DssSign = 2,
    /// rsa_fixed_dh(3)
    RsaFixedDh = 3,
    /// dss_fixed_dh(4)
    DssFixedDh = 4,
}

impl Codec for ClientCertificateType {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        (*self as u8).encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match u8::decode(reader, ())? {
            x if x == (Self::RsaSign as u8) => Ok(Self::RsaSign),
            x if x == (Self::DssSign as u8) => Ok(Self::DssSign),
            x if x == (Self::RsaFixedDh as u8) => Ok(Self::RsaFixedDh),
            x if x == (Self::DssFixedDh as u8) => Ok(Self::DssFixedDh),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A Signature following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Signature(pub TlsVec<u8, u16>);

impl Codec for Signature {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<u8, u16>::decode(reader, ())?))
    }
}

/// A Distinguished Name following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DistinguishedName(pub TlsVec<u8, u16>);

impl Codec for DistinguishedName {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(TlsVec::<u8, u16>::decode(reader, ())?))
    }
}

/// A Certificate Request message following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CertificateRequest {
    /// The certificate types.
    pub certificate_types: TlsVec<ClientCertificateType, u8>,
    /// The certificate authorities.
    pub certificate_authorities: TlsVec<DistinguishedName, u16>,
}

impl Codec for CertificateRequest {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.certificate_types.encode(writer, ())?;
        self.certificate_authorities.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            certificate_types: TlsVec::<ClientCertificateType, u8>::decode(reader, ())?,
            certificate_authorities: TlsVec::<DistinguishedName, u16>::decode(reader, ())?,
        })
    }
}

/// A Server Hello Done message following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ServerHelloDone;

impl Codec for ServerHelloDone {
    fn encode<W: BufMut>(&self, _writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Ok(())
    }

    fn decode<R: Buf>(_reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self)
    }
}

/// A Certificate Verify message following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CertificateVerify {
    /// The signature.
    pub signature: Signature,
}

impl Codec for CertificateVerify {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.signature.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            signature: Signature::decode(reader, ())?,
        })
    }
}

/// A Finished message following [Section A.4.3].
///
/// [Section A.4.3]: https://datatracker.ietf.org/doc/html/rfc2246#appendix-A.4.3
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Finished {
    /// The verify data.
    pub verify_data: [u8; 12],
}

impl Codec for Finished {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.verify_data.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self {
            verify_data: reader.read_array::<12>()?,
        })
    }
}

#[cfg(test)]
mod tests {
    use core::fmt::Debug;

    use super::{HandshakeType, HelloRequest};
    use crate::{Codec, Cursor};

    fn codec_roundtrip<T: Codec<C> + Debug + Eq, C: Copy>(
        etalon_struct: T,
        etalon_bytes: &[u8],
        context: C,
    ) {
        let mut encoded_bytes = vec![];
        {
            let writer = &mut Cursor::new(&mut encoded_bytes);
            etalon_struct.encode(writer, context).unwrap();
        }
        assert_eq!(etalon_bytes, &encoded_bytes);

        let decoded_struct = {
            let reader = &mut Cursor::new(&mut encoded_bytes);
            T::decode(reader, context).unwrap()
        };
        assert_eq!(etalon_struct, decoded_struct);

        encoded_bytes.fill(0x00);
        {
            let writer = &mut Cursor::new(&mut encoded_bytes);
            decoded_struct.encode(writer, context).unwrap();
        }
        assert_eq!(etalon_bytes, &encoded_bytes);
    }

    #[test]
    fn handshake_type() {
        let etalon_bytes = &[0x01];
        let etalon_struct = HandshakeType::ClientHello;

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn hello_request() {
        let etalon_bytes = &[];
        let etalon_struct = HelloRequest;

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }
}