tlspuffin/tls/rustls/tls13/
mod.rs1use std::fmt;
2
3use ring::{aead, hkdf};
4
5use crate::tls::rustls::cipher::{make_nonce, Iv, MessageDecrypter, MessageEncrypter};
6use crate::tls::rustls::error::Error;
7use crate::tls::rustls::msgs::base::Payload;
8use crate::tls::rustls::msgs::enums::{CipherSuite, ContentType, ProtocolVersion};
9use crate::tls::rustls::msgs::fragmenter::MAX_FRAGMENT_LEN;
10use crate::tls::rustls::msgs::message::{BorrowedPlainMessage, OpaqueMessage, PlainMessage};
11use crate::tls::rustls::suites::{BulkAlgorithm, CipherSuiteCommon, SupportedCipherSuite};
12
13pub mod key_schedule;
14use key_schedule::{derive_traffic_iv, derive_traffic_key};
15use puffin::codec::Codec;
16
17pub static TLS13_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
19 SupportedCipherSuite::Tls13(TLS13_CHACHA20_POLY1305_SHA256_INTERNAL);
20
21pub static TLS13_CHACHA20_POLY1305_SHA256_INTERNAL: &Tls13CipherSuite = &Tls13CipherSuite {
22 common: CipherSuiteCommon {
23 suite: CipherSuite::TLS13_CHACHA20_POLY1305_SHA256,
24 bulk: BulkAlgorithm::Chacha20Poly1305,
25 aead_algorithm: &ring::aead::CHACHA20_POLY1305,
26 },
27 hkdf_algorithm: ring::hkdf::HKDF_SHA256,
28 confidentiality_limit: u64::MAX,
29 integrity_limit: 1 << 36,
30};
31
32pub static TLS13_AES_256_GCM_SHA384: SupportedCipherSuite =
34 SupportedCipherSuite::Tls13(&Tls13CipherSuite {
35 common: CipherSuiteCommon {
36 suite: CipherSuite::TLS13_AES_256_GCM_SHA384,
37 bulk: BulkAlgorithm::Aes256Gcm,
38 aead_algorithm: &ring::aead::AES_256_GCM,
39 },
40 hkdf_algorithm: ring::hkdf::HKDF_SHA384,
41 confidentiality_limit: 1 << 23,
42 integrity_limit: 1 << 52,
43 });
44
45pub static TLS13_AES_128_GCM_SHA256: SupportedCipherSuite =
47 SupportedCipherSuite::Tls13(TLS13_AES_128_GCM_SHA256_INTERNAL);
48
49pub static TLS13_AES_128_GCM_SHA256_INTERNAL: &Tls13CipherSuite = &Tls13CipherSuite {
50 common: CipherSuiteCommon {
51 suite: CipherSuite::TLS13_AES_128_GCM_SHA256,
52 bulk: BulkAlgorithm::Aes128Gcm,
53 aead_algorithm: &ring::aead::AES_128_GCM,
54 },
55 hkdf_algorithm: ring::hkdf::HKDF_SHA256,
56 confidentiality_limit: 1 << 23,
57 integrity_limit: 1 << 52,
58};
59
60pub struct Tls13CipherSuite {
62 pub common: CipherSuiteCommon,
64 pub hkdf_algorithm: ring::hkdf::Algorithm,
65 pub confidentiality_limit: u64,
66 pub integrity_limit: u64,
67}
68
69impl Tls13CipherSuite {
70 pub fn derive_encrypter(&self, secret: &hkdf::Prk) -> Box<dyn MessageEncrypter> {
71 let key = derive_traffic_key(secret, self.common.aead_algorithm);
72 let iv = derive_traffic_iv(secret);
73
74 Box::new(Tls13MessageEncrypter {
75 enc_key: aead::LessSafeKey::new(key),
76 iv,
77 })
78 }
79
80 pub fn derive_decrypter(&self, secret: &hkdf::Prk) -> Box<dyn MessageDecrypter> {
83 let key = derive_traffic_key(secret, self.common.aead_algorithm);
84 let iv = derive_traffic_iv(secret);
85
86 Box::new(Tls13MessageDecrypter {
87 dec_key: aead::LessSafeKey::new(key),
88 iv,
89 })
90 }
91
92 pub fn hash_algorithm(&self) -> &'static ring::digest::Algorithm {
94 self.hkdf_algorithm.hmac_algorithm().digest_algorithm()
95 }
96
97 pub fn can_resume_from(&self, prev: &'static Self) -> Option<&'static Self> {
99 (prev.hash_algorithm() == self.hash_algorithm()).then_some(prev)
100 }
101}
102
103impl From<&'static Tls13CipherSuite> for SupportedCipherSuite {
104 fn from(s: &'static Tls13CipherSuite) -> Self {
105 Self::Tls13(s)
106 }
107}
108
109impl PartialEq for Tls13CipherSuite {
110 fn eq(&self, other: &Self) -> bool {
111 self.common.suite == other.common.suite
112 }
113}
114
115impl fmt::Debug for Tls13CipherSuite {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.debug_struct("Tls13CipherSuite")
118 .field("suite", &self.common.suite)
119 .field("bulk", &self.common.bulk)
120 .finish()
121 }
122}
123
124struct Tls13MessageEncrypter {
125 enc_key: aead::LessSafeKey,
126 iv: Iv,
127}
128
129struct Tls13MessageDecrypter {
130 dec_key: aead::LessSafeKey,
131 iv: Iv,
132}
133
134fn unpad_tls13(v: &mut Vec<u8>) -> ContentType {
135 loop {
136 match v.pop() {
137 Some(0) => {}
138 Some(content_type) => return ContentType::from(content_type),
139 None => return ContentType::Unknown(0),
140 }
141 }
142}
143
144fn make_tls13_aad(len: usize) -> ring::aead::Aad<[u8; TLS13_AAD_SIZE]> {
145 ring::aead::Aad::from([
146 0x17, 0x3, 0x3, (len >> 8) as u8,
150 len as u8,
151 ])
152}
153
154const TLS13_AAD_SIZE: usize = 1 + 2 + 2;
156
157impl MessageEncrypter for Tls13MessageEncrypter {
158 fn encrypt(&self, msg: BorrowedPlainMessage, seq: u64) -> Result<OpaqueMessage, Error> {
159 let total_len = msg.payload.len() + 1 + self.enc_key.algorithm().tag_len();
160 let mut payload = Vec::with_capacity(total_len);
161 payload.extend_from_slice(msg.payload);
162 msg.typ.encode(&mut payload);
163
164 let nonce = make_nonce(&self.iv, seq);
165 let aad = make_tls13_aad(total_len);
166
167 self.enc_key
168 .seal_in_place_append_tag(nonce, aad, &mut payload)
169 .map_err(|_| Error::General("encrypt failed".to_string()))?;
170
171 Ok(OpaqueMessage {
172 typ: ContentType::ApplicationData,
173 version: ProtocolVersion::TLSv1_2,
174 payload: Payload::new(payload),
175 })
176 }
177}
178
179impl MessageDecrypter for Tls13MessageDecrypter {
180 fn decrypt(&self, mut msg: OpaqueMessage, seq: u64) -> Result<PlainMessage, Error> {
181 let payload = &mut msg.payload.0;
182 if payload.len() < self.dec_key.algorithm().tag_len() {
183 return Err(Error::DecryptError);
184 }
185
186 let nonce = make_nonce(&self.iv, seq);
187 let aad = make_tls13_aad(payload.len());
188 let plain_len = self
189 .dec_key
190 .open_in_place(nonce, aad, payload)
191 .map_err(|_| Error::DecryptError)?
192 .len();
193
194 payload.truncate(plain_len);
195
196 if payload.len() > MAX_FRAGMENT_LEN + 1 {
197 return Err(Error::PeerSentOversizedRecord);
198 }
199
200 msg.typ = unpad_tls13(payload);
201 if msg.typ == ContentType::Unknown(0) {
202 let msg = "peer sent bad TLSInnerPlaintext".to_string();
203 return Err(Error::PeerMisbehavedError(msg));
204 }
205
206 if payload.len() > MAX_FRAGMENT_LEN {
207 return Err(Error::PeerSentOversizedRecord);
208 }
209
210 msg.version = ProtocolVersion::TLSv1_3;
211 Ok(msg.into_plain_message())
212 }
213}