-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathencryptor.rs
328 lines (299 loc) · 12 KB
/
encryptor.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
//
// Copyright 2023 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//! Implementation of the Bidirectional Hybrid Public Key Encryption (HPKE) scheme from RFC9180.
//! <https://www.rfc-editor.org/rfc/rfc9180.html>
//! <https://www.rfc-editor.org/rfc/rfc9180.html#name-bidirectional-encryption>
use crate::{
hpke::{
setup_base_recipient, setup_base_sender, KeyPair, PrivateKey, PublicKey, RecipientContext,
SenderContext,
},
proto::oak::crypto::v1::{AeadEncryptedMessage, EncryptedRequest, EncryptedResponse},
};
use alloc::{boxed::Box, sync::Arc, vec::Vec};
use anyhow::{anyhow, Context};
use async_trait::async_trait;
/// Info string used by Hybrid Public Key Encryption;
pub(crate) const OAK_HPKE_INFO: &[u8] = b"Oak Hybrid Public Key Encryption v1";
pub struct EncryptionKeyProvider {
key_pair: KeyPair,
}
impl Default for EncryptionKeyProvider {
fn default() -> Self {
Self::generate()
}
}
impl EncryptionKeyProvider {
/// Creates a crypto provider with a newly generated key pair.
pub fn generate() -> Self {
Self {
key_pair: KeyPair::generate(),
}
}
pub fn new(private_key: PrivateKey, public_key: PublicKey) -> Self {
Self {
key_pair: KeyPair::new(private_key, public_key),
}
}
pub fn get_private_key(&self) -> Vec<u8> {
self.key_pair.get_private_key()
}
/// Returns a NIST P-256 SEC1 encoded point public key.
/// <https://secg.org/sec1-v2.pdf>
pub fn get_serialized_public_key(&self) -> Vec<u8> {
self.key_pair.get_serialized_public_key()
}
}
pub trait RecipientContextGenerator {
// TODO(#3841): Implement Oak Kernel Crypto API and return corresponding session keys instead.
fn generate_recipient_context(
&self,
encapsulated_public_key: &[u8],
) -> anyhow::Result<RecipientContext>;
}
impl RecipientContextGenerator for EncryptionKeyProvider {
fn generate_recipient_context(
&self,
encapsulated_public_key: &[u8],
) -> anyhow::Result<RecipientContext> {
setup_base_recipient(encapsulated_public_key, &self.key_pair, OAK_HPKE_INFO)
.context("couldn't generate recipient crypto context")
}
}
#[async_trait]
pub trait AsyncRecipientContextGenerator {
async fn generate_recipient_context(
&self,
encapsulated_public_key: &[u8],
) -> anyhow::Result<RecipientContext>;
}
#[async_trait]
impl AsyncRecipientContextGenerator for EncryptionKeyProvider {
async fn generate_recipient_context(
&self,
encapsulated_public_key: &[u8],
) -> anyhow::Result<RecipientContext> {
(self as &dyn RecipientContextGenerator).generate_recipient_context(encapsulated_public_key)
}
}
/// Encryptor object for encrypting client requests that will be sent to the server and decrypting
/// server responses that are received by the client. Each Encryptor object corresponds to a single
/// crypto session between the client and the server.
///
/// Sequence numbers for requests and responses are incremented separately, meaning that there could
/// be multiple responses per request and multiple requests per response.
pub struct ClientEncryptor {
/// Encapsulated public key needed to establish a symmetric session key.
/// Only sent in the initial request message of the session.
serialized_encapsulated_public_key: Option<Vec<u8>>,
sender_context: SenderContext,
}
impl ClientEncryptor {
/// Creates an HPKE crypto context by generating an new ephemeral key pair.
/// The `serialized_server_public_key` must be a NIST P-256 SEC1 encoded point public key.
/// <https://secg.org/sec1-v2.pdf>
pub fn create(serialized_server_public_key: &[u8]) -> anyhow::Result<Self> {
let (serialized_encapsulated_public_key, sender_context) =
setup_base_sender(serialized_server_public_key, OAK_HPKE_INFO)
.context("couldn't create sender crypto context")?;
Ok(Self {
serialized_encapsulated_public_key: Some(serialized_encapsulated_public_key.to_vec()),
sender_context,
})
}
/// Encrypts `plaintext` and authenticates `associated_data` using AEAD.
/// Returns a [`EncryptedRequest`] proto message.
/// <https://datatracker.ietf.org/doc/html/rfc5116>
pub fn encrypt(
&mut self,
plaintext: &[u8],
associated_data: &[u8],
) -> anyhow::Result<EncryptedRequest> {
let nonce = self
.sender_context
.generate_nonce()
.context("couldn't generate nonce")?;
let ciphertext = self
.sender_context
.seal(&nonce, plaintext, associated_data)
.context("couldn't encrypt request")?;
Ok(EncryptedRequest {
encrypted_message: Some(AeadEncryptedMessage {
nonce: nonce.to_vec(),
ciphertext,
associated_data: associated_data.to_vec(),
}),
// Encapsulated public key is only sent in the initial request message of the session.
serialized_encapsulated_public_key: self.serialized_encapsulated_public_key.take(),
})
}
/// Decrypts a [`EncryptedResponse`] proto message using AEAD.
/// Returns a response message plaintext and associated data.
/// <https://datatracker.ietf.org/doc/html/rfc5116>
pub fn decrypt(
&mut self,
encrypted_response: &EncryptedResponse,
) -> anyhow::Result<(Vec<u8>, Vec<u8>)> {
let encrypted_message = encrypted_response
.encrypted_message
.as_ref()
.context("response doesn't contain encrypted message")?;
let plaintext = self
.sender_context
.open(
&encrypted_message.ciphertext,
&encrypted_message.associated_data,
)
.context("couldn't decrypt response")?;
Ok((plaintext, encrypted_message.associated_data.to_vec()))
}
}
/// Encryptor object for decrypting client requests that are received by the server and encrypting
/// server responses that will be sent back to the client. Each Encryptor object corresponds to a
/// single crypto session between the client and the server.
///
/// Sequence numbers for requests and responses are incremented separately, meaning that there could
/// be multiple responses per request and multiple requests per response.
pub struct ServerEncryptor {
recipient_context: RecipientContext,
}
impl ServerEncryptor {
pub fn create(
serialized_encapsulated_public_key: &[u8],
recipient_context_generator: Arc<dyn RecipientContextGenerator>,
) -> anyhow::Result<Self> {
let recipient_context = recipient_context_generator
.generate_recipient_context(serialized_encapsulated_public_key)
.context("couldn't generate recipient crypto context")?;
Ok(Self::new(recipient_context))
}
pub fn new(recipient_context: RecipientContext) -> Self {
Self { recipient_context }
}
/// Decrypts a [`EncryptedRequest`] proto message using AEAD.
/// Returns a response message plaintext and associated data.
/// <https://datatracker.ietf.org/doc/html/rfc5116>
pub fn decrypt(
&mut self,
encrypted_request: &EncryptedRequest,
) -> anyhow::Result<(Vec<u8>, Vec<u8>)> {
let encrypted_message = encrypted_request
.encrypted_message
.as_ref()
.context("request doesn't contain encrypted message")?;
let plaintext = self
.recipient_context
.open(
&encrypted_message.ciphertext,
&encrypted_message.associated_data,
)
.context("couldn't decrypt request")?;
Ok((plaintext, encrypted_message.associated_data.to_vec()))
}
/// Encrypts `plaintext` and authenticates `associated_data` using AEAD.
/// Returns a [`EncryptedResponse`] proto message.
/// <https://datatracker.ietf.org/doc/html/rfc5116>
pub fn encrypt(
&mut self,
plaintext: &[u8],
associated_data: &[u8],
) -> anyhow::Result<EncryptedResponse> {
let nonce = self
.recipient_context
.generate_nonce()
.context("couldn't generate nonce")?;
let ciphertext = self
.recipient_context
.seal(&nonce, plaintext, associated_data)
.context("couldn't encrypt response")?;
Ok(EncryptedResponse {
encrypted_message: Some(AeadEncryptedMessage {
nonce: nonce.to_vec(),
ciphertext,
associated_data: associated_data.to_vec(),
}),
})
}
}
/// Encryptor object for decrypting client requests that are received by the server and encrypting
/// server responses that will be sent back to the client. Each Encryptor object corresponds to a
/// single crypto session between the client and the server.
/// Encryptor state is initialized after receiving an initial request message containing client's
/// encapsulated public key.
///
/// Sequence numbers for requests and responses are incremented separately, meaning that there could
/// be multiple responses per request and multiple requests per response.
// TODO(#4311): Merge `AsyncServerEncryptor` and `ServerEncryptor` once there is `async` support in
// the Restricted Kernel.
pub struct AsyncServerEncryptor<'a, G>
where
G: AsyncRecipientContextGenerator + Send + Sync,
{
recipient_context_generator: &'a G,
inner: Option<ServerEncryptor>,
}
impl<'a, G> AsyncServerEncryptor<'a, G>
where
G: AsyncRecipientContextGenerator + Send + Sync,
{
pub fn new(recipient_context_generator: &'a G) -> Self {
Self {
recipient_context_generator,
inner: None,
}
}
/// Decrypts a [`EncryptedRequest`] proto message using AEAD.
/// Returns a response message plaintext and associated data.
/// <https://datatracker.ietf.org/doc/html/rfc5116>
pub async fn decrypt(
&mut self,
encrypted_request: &EncryptedRequest,
) -> anyhow::Result<(Vec<u8>, Vec<u8>)> {
match &mut self.inner {
Some(inner) => inner.decrypt(encrypted_request),
None => {
let serialized_encapsulated_public_key = encrypted_request
.serialized_encapsulated_public_key
.as_ref()
.context("initial request message doesn't contain encapsulated public key")?;
let recipient_context = self
.recipient_context_generator
.generate_recipient_context(serialized_encapsulated_public_key)
.await
.context("couldn't generate recipient crypto context")?;
let mut inner = ServerEncryptor::new(recipient_context);
let (plaintext, associated_data) = inner.decrypt(encrypted_request)?;
self.inner = Some(inner);
Ok((plaintext, associated_data))
}
}
}
/// Encrypts `plaintext` and authenticates `associated_data` using AEAD.
/// Returns a [`EncryptedResponse`] proto message.
/// <https://datatracker.ietf.org/doc/html/rfc5116>
pub fn encrypt(
&mut self,
plaintext: &[u8],
associated_data: &[u8],
) -> anyhow::Result<EncryptedResponse> {
match &mut self.inner {
Some(inner) => inner.encrypt(plaintext, associated_data),
None => Err(anyhow!(
"couldn't encrypt response because crypto context is not initialized"
)),
}
}
}