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
#[cfg(test)]
mod handshake_message_certificate_request_test;

use std::io::{Read, Write};

use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};

use super::*;
use crate::client_certificate_type::*;
use crate::signature_hash_algorithm::*;

/*
A non-anonymous server can optionally request a certificate from
the client, if appropriate for the selected cipher suite.  This
message, if sent, will immediately follow the ServerKeyExchange
message (if it is sent; otherwise, this message follows the
server's Certificate message).
*/
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HandshakeMessageCertificateRequest {
    pub(crate) certificate_types: Vec<ClientCertificateType>,
    pub(crate) signature_hash_algorithms: Vec<SignatureHashAlgorithm>,
}

const HANDSHAKE_MESSAGE_CERTIFICATE_REQUEST_MIN_LENGTH: usize = 5;

impl HandshakeMessageCertificateRequest {
    pub fn handshake_type(&self) -> HandshakeType {
        HandshakeType::CertificateRequest
    }

    pub fn size(&self) -> usize {
        1 + self.certificate_types.len() + 2 + self.signature_hash_algorithms.len() * 2 + 2
    }

    pub fn marshal<W: Write>(&self, writer: &mut W) -> Result<()> {
        writer.write_u8(self.certificate_types.len() as u8)?;
        for v in &self.certificate_types {
            writer.write_u8(*v as u8)?;
        }

        writer.write_u16::<BigEndian>(2 * self.signature_hash_algorithms.len() as u16)?;
        for v in &self.signature_hash_algorithms {
            writer.write_u8(v.hash as u8)?;
            writer.write_u8(v.signature as u8)?;
        }

        writer.write_all(&[0x00, 0x00])?; // Distinguished Names Length

        Ok(writer.flush()?)
    }

    pub fn unmarshal<R: Read>(reader: &mut R) -> Result<Self> {
        let certificate_types_length = reader.read_u8()?;

        let mut certificate_types = vec![];
        for _ in 0..certificate_types_length {
            let cert_type = reader.read_u8()?.into();
            certificate_types.push(cert_type);
        }

        let signature_hash_algorithms_length = reader.read_u16::<BigEndian>()?;

        let mut signature_hash_algorithms = vec![];
        for _ in (0..signature_hash_algorithms_length).step_by(2) {
            let hash = reader.read_u8()?.into();
            let signature = reader.read_u8()?.into();

            signature_hash_algorithms.push(SignatureHashAlgorithm { hash, signature });
        }

        Ok(HandshakeMessageCertificateRequest {
            certificate_types,
            signature_hash_algorithms,
        })
    }
}