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
//! A high level KMIP "operation" oriented client interface for request/response construction & (de)serialization.
pub mod builder;
pub mod tests;
pub mod util;
use std::{
mem::MaybeUninit,
ops::DerefMut,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
};
#[cfg(not(feature = "tokio"))]
use std::sync::Mutex;
#[cfg(feature = "tokio")]
use tokio::sync::Mutex;
use tracing::trace;
use crate::{
net::{
batch_items_to_request,
common::{
error::{NetError, NetResult},
io::read_message_from_stream,
},
payload_to_request,
},
types::{
common::*,
request::{
self, Authentication, BatchItem, CommonTemplateAttribute, KeyWrappingSpecification, MaximumResponseSize,
PrivateKeyTemplateAttribute, PublicKeyTemplateAttribute, QueryFunction, RequestMessage, RequestPayload,
RevocationReason,
},
response::{
self, CreateKeyPairResponsePayload, GetResponsePayload, QueryResponsePayload, ResponseMessage,
ResponsePayload, ResultReason, ResultStatus,
},
traits::*,
},
};
/// A client for serializing KMIP requests and deserializing KMIP responses
/// to/from an established read/write stream.
///
/// Use the [crate::net::ClientBuilder] to build a [Client] instance to work
/// with.
#[derive(Debug)]
pub struct Client<T: ReadWrite> {
auth: Option<Authentication>,
max_message_size: i32,
stream: Arc<Mutex<T>>,
read_buf: Vec<u8>,
write_buf: Vec<MaybeUninit<u8>>,
connection_error_count: Arc<AtomicUsize>,
cached_query_response_payload: Option<QueryResponsePayload>,
}
//--- High level client interface
impl<T: ReadWrite> Client<T> {
/// Serialize a KMIP 1.0 [Query](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581232)
/// request.
///
/// See also: [do_request()](Self::do_request())
#[maybe_async::maybe_async]
pub async fn query(&mut self) -> NetResult<QueryResponsePayload> {
// Don't repeatedly query the server as the result should be the same
// every time for the same client connection. Instead cache the result
// and return it on subsequent requests.
if let Some(payload) = &self.cached_query_response_payload {
return Ok(payload.clone());
}
// Setup the request
let wanted_info = vec![
QueryFunction::QueryOperations,
QueryFunction::QueryObjects,
QueryFunction::QueryServerInformation,
QueryFunction::QueryExtensionList,
];
let request = RequestPayload::Query(wanted_info);
// Execute the request and capture the response
let res = self.do_request_payload(request).await?.try_into()?;
let ResponsePayload::Query(payload) = res else {
return Err(NetError::UnexpectedData(format!(
"Expected Query payload but response has {res}"
)));
};
self.cached_query_response_payload = Some(payload.clone());
Ok(payload)
}
/// Serialize a KMIP 1.0 [Create Key Pair](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581269)
/// request to create an RSA key pair.
///
/// See also: [do_request()](Self::do_request())
///
/// Creates an RSA key pair.
///
/// To create keys of other types or with other parameters you must compose the Create Key Pair request manually
/// and pass it to [do_request()](Self::do_request()) directly.
#[maybe_async::maybe_async]
pub async fn create_rsa_key_pair(
&mut self,
key_length: i32,
private_key_name: String,
public_key_name: String,
) -> NetResult<(String, String)> {
// Setup the request
let request = RequestPayload::CreateKeyPair(
Some(CommonTemplateAttribute::new(vec![
request::Attribute::CryptographicAlgorithm(CryptographicAlgorithm::RSA),
request::Attribute::CryptographicLength(key_length),
])),
Some(PrivateKeyTemplateAttribute::new(vec![
request::Attribute::Name(private_key_name),
request::Attribute::CryptographicUsageMask(CryptographicUsageMask::Sign),
])),
Some(PublicKeyTemplateAttribute::new(vec![
request::Attribute::Name(public_key_name),
request::Attribute::CryptographicUsageMask(CryptographicUsageMask::Verify),
])),
);
// Execute the request and capture the response
let res = self.do_request_payload(request).await?.try_into()?;
// Execute the request and capture the response
let ResponsePayload::CreateKeyPair(payload) = res else {
return Err(NetError::UnexpectedData(format!(
"Expected Query payload but response has {res}"
)));
};
let CreateKeyPairResponsePayload {
private_key_unique_identifier: UniqueIdentifier(prikey),
public_key_unique_identifier: UniqueIdentifier(pubkey),
} = payload;
Ok((prikey, pubkey))
}
/// Serialize a KMIP 1.2 [Rng Retrieve](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613562)
/// operation to retrieve a number of random bytes.
///
/// See also: [do_request()](Self::do_request())
///
#[maybe_async::maybe_async]
pub async fn rng_retrieve(&mut self, num_bytes: i32) -> NetResult<Vec<u8>> {
let request = RequestPayload::RNGRetrieve(DataLength(num_bytes));
// Execute the request and capture the response
let res = self.do_request_payload(request).await?.try_into()?;
let ResponsePayload::RNGRetrieve(payload) = res else {
return Err(NetError::UnexpectedData(format!(
"Expected RNGRetrieve payload but response has {res}"
)));
};
Ok(payload.0.0)
}
/// Serialize a KMIP 1.2 [Sign](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613558)
/// operation to sign the given bytes with the given private key ID.
///
/// See also: [do_request()](Self::do_request())
///
#[maybe_async::maybe_async]
pub async fn sign(&mut self, private_key_id: &str, in_bytes: &[u8]) -> NetResult<Vec<u8>> {
let request = RequestPayload::Sign(
Some(UniqueIdentifier(private_key_id.to_owned())),
Some(
CryptographicParameters::default()
.with_padding_method(PaddingMethod::PKCS1_v1_5)
.with_hashing_algorithm(HashingAlgorithm::SHA256)
.with_cryptographic_algorithm(CryptographicAlgorithm::RSA),
),
Data(in_bytes.to_vec()),
);
// Execute the request and capture the response
let res = self.do_request_payload(request).await?.try_into()?;
let ResponsePayload::Sign(payload) = res else {
return Err(NetError::UnexpectedData(format!(
"Expected Sign payload but response has {res}"
)));
};
Ok(payload.signature_data)
}
/// Serialize a KMIP 1.0 [Activate](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581226)
/// operation to activate a given private key ID.
///
/// See also: [do_request()](Self::do_request())
///
/// To activate other kinds of managed object you must compose the Activate request manually and pass it to
/// [do_request()](Self::do_request()) directly.
#[maybe_async::maybe_async]
pub async fn activate_key(&mut self, private_key_id: &str) -> NetResult<()> {
let request = RequestPayload::Activate(UniqueIdentifier(private_key_id.to_owned()).into());
// Execute the request and capture the response
let res = self.do_request_payload(request).await?.try_into()?;
let ResponsePayload::Activate(_) = res else {
return Err(NetError::UnexpectedData(format!(
"Expected Activate payload but response has {res}"
)));
};
Ok(())
}
/// Serialize a KMIP 1.0 [Revoke](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581227)
/// operation to deactivate a given private key ID.
///
/// See also: [do_request()](Self::do_request())
///
/// To deactivate other kinds of managed object you must compose the Revoke request manually and pass it to
/// [do_request()](Self::do_request()) directly.
#[maybe_async::maybe_async]
pub async fn revoke_key(&mut self, private_key_id: &str) -> NetResult<()> {
let request = RequestPayload::Revoke(
Some(UniqueIdentifier(private_key_id.to_owned())),
RevocationReason(
RevocationReasonCode::CessationOfOperation,
Option::<RevocationMessage>::None,
),
Option::<CompromiseOccurrenceDate>::None,
);
// Execute the request and capture the response
let res = self.do_request_payload(request).await?.try_into()?;
let ResponsePayload::Revoke(_) = res else {
return Err(NetError::UnexpectedData(format!(
"Expected Revoke payload but response has {res}"
)));
};
Ok(())
}
/// Serialize a KMIP 1.0 [Destroy](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581228)
/// operation to destroy a given private key ID.
///
/// See also: [do_request()](Self::do_request())
///
/// To destroy other kinds of managed object you must compose the Destroy request manually and pass it to
/// [do_request()](Self::do_request()) directly.
#[maybe_async::maybe_async]
pub async fn destroy_key(&mut self, key_id: &str) -> NetResult<()> {
let request = RequestPayload::Destroy(Some(UniqueIdentifier(key_id.to_owned())));
// Execute the request and capture the response
let res = self.do_request_payload(request).await?.try_into()?;
let ResponsePayload::Destroy(_) = res else {
return Err(NetError::UnexpectedData(format!(
"Expected Destroy payload but response has {res}"
)));
};
Ok(())
}
/// Serialize a KMIP 1.0 [ModifyAttribute](http://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581222)
/// operation to rename a given key ID.
///
/// See also: [do_request()](Self::do_request())
///
/// To modify other attributes of managed objects you must compose the Modify Attribute request manually and pass
/// it to [do_request()](Self::do_request()) directly.
#[maybe_async::maybe_async]
pub async fn rename_key(&mut self, key_id: &str, new_name: String) -> NetResult<()> {
// Setup the request
let request = RequestPayload::ModifyAttribute(
Some(UniqueIdentifier(key_id.to_string())),
request::Attribute::Name(new_name),
);
// Execute the request and capture the response
let res = self.do_request_payload(request).await?.try_into()?;
let ResponsePayload::ModifyAttribute(_) = res else {
return Err(NetError::UnexpectedData(format!(
"Expected ModifyAttribute payload but response has {res}"
)));
};
Ok(())
}
/// Serialize a KMIP 1.0 [Get](http://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581218)
/// operation to get the details of a given key ID.
///
/// See also: [do_request()](Self::do_request())
#[maybe_async::maybe_async]
pub async fn get_key(&mut self, key_id: &str) -> NetResult<GetResponsePayload> {
// Setup the request
let request = RequestPayload::Get(
Some(UniqueIdentifier(key_id.to_string())),
Option::<KeyFormatType>::None,
Option::<KeyCompressionType>::None,
Option::<KeyWrappingSpecification>::None,
);
// Execute the request and capture the response
let res = self.do_request_payload(request).await?.try_into()?;
let ResponsePayload::Get(payload) = res else {
return Err(NetError::UnexpectedData(format!(
"Expected Get payload but response has {res}"
)));
};
Ok(payload)
}
}
//--- Lower level client interface
//
// For sending requests and receiving responses.
impl<T: ReadWrite> Client<T> {
/// Write request bytes to the given stream and read, deserialize and
/// sanity check the response.
///
/// Tip: For cases when the response is expected to consist of only a
/// single batch item,`TryInto` can be used to simplify handling of the
/// result, e.g.:
///
/// ```ignore
/// // Setup the request.
/// let wanted_info = vec![
/// QueryFunction::QueryOperations,
/// QueryFunction::QueryObjects,
/// QueryFunction::QueryServerInformation,
/// ];
/// let request = RequestPayload::Query(wanted_info);
///
/// // Execute the request and capture the response.
/// let res = client.do_request_payload(request).await?.try_into()?;
/// let ResponsePayload::Query(payload) = res else {
/// return Err(NetError::UnexpectedData(format!(
/// "Expected Query payload but response has {res}"
/// )));
/// };
/// ```
///
/// Note: Enforcing a timeout on this operation is the responsibility of
/// the caller.
#[maybe_async::maybe_async]
pub async fn do_request(&mut self, request: RequestMessage) -> NetResult<Vec<NetResult<response::BatchItem>>> {
trace!("Serializing request to KMIP wire bytes");
let len = self.write_buf.len();
assert!(len <= i32::MAX as usize);
let mut len = len as i32;
let mut stream = Self::get_mut_stream(&self.stream).await?;
let mut formatter;
// TODO: Enforce a timeout on sending the request?
let request_bytes = loop {
formatter = crate::ttlv::Formatter::new(&mut self.write_buf);
if request.format(&mut formatter).is_ok() {
let request_bytes = formatter.filled().as_flattened();
Self::write_to_stream(&mut stream, request_bytes).await?;
break request_bytes;
} else if len >= self.max_message_size {
// Buffer is already at the maximum possible size.
return Err(NetError::SerializeError(format!(
"Message too large: {len} > {}",
self.max_message_size
)));
} else {
// Retry with a larger buffer.
len = i32::max(self.max_message_size, len.saturating_mul(2));
self.write_buf.resize(len as usize, MaybeUninit::uninit());
}
};
trace!("Waiting for a response from the server");
let res = read_message_from_stream(
stream.deref_mut(),
&mut self.read_buf,
self.max_message_size,
ResponseMessage::fast_scan,
self.connection_error_count.clone(),
)
.await?;
trace!("KMIP server response received");
Self::post_process_response(res).await.map_err(|mut err| {
if let NetError::DeserializeError { req, .. } = &mut err {
*req = request_bytes.into();
}
err
})
}
/// Serialize the given request to the stream and deserialize the response.
///
/// Automatically constructs the request message wrapper around the
/// payload including the [crate::types::request::RequestHeader] and
/// [crate::types::request::BatchItem].
///
/// Only supports a single batch item.
///
/// Sets the request operation to [RequestPayload::operation()].
///
/// # Errors
///
/// Will fail if there is a problem serializing the request, writing to or
/// reading from the stream, deserializing the response or if the response
/// does not indicate operation success or contains more than one batch
/// item.
#[maybe_async::maybe_async]
pub async fn do_request_payload(
&mut self,
payload: RequestPayload,
) -> NetResult<Vec<NetResult<response::BatchItem>>> {
self.do_request(payload_to_request(
self.auth.clone(),
Some(MaximumResponseSize(self.max_message_size)),
payload,
)?)
.await
}
#[maybe_async::maybe_async]
pub async fn do_request_batch(
&mut self,
batch_items: Vec<BatchItem>,
) -> NetResult<Vec<NetResult<response::BatchItem>>> {
self.do_request(batch_items_to_request(
self.auth.clone(),
Some(MaximumResponseSize(self.max_message_size)),
batch_items,
)?)
.await
}
}
//------------ Internals -----------------------------------------------------
impl<T: ReadWrite> Client<T> {
#[cfg(feature = "tokio")]
async fn get_mut_stream(stream: &Mutex<T>) -> NetResult<impl DerefMut<Target = T> + '_> {
Ok(stream.lock().await)
}
#[cfg(not(feature = "tokio"))]
fn get_mut_stream(stream: &Mutex<T>) -> NetResult<impl DerefMut<Target = T> + '_> {
Ok(stream.lock()?)
}
#[maybe_async::maybe_async]
async fn post_process_response(mut res: ResponseMessage) -> NetResult<Vec<NetResult<response::BatchItem>>> {
if res.header.batch_count >= 1 && !res.batch_items.is_empty() {
let res = res
.batch_items
.drain(..)
.map(|item| match item.result_status {
ResultStatus::OperationFailed => {
let message = item
.result_message
.unwrap_or_else(|| "No further information available".to_string());
let reason = item
.result_reason
.map(|v| v.to_string())
.unwrap_or_else(|| "Reason unknown".to_string());
let operation = item
.operation
.map(|op| op.to_string())
.unwrap_or_else(|| "unknown".to_string());
let err = format!("Operation {operation} failed: {reason}: {message}");
if matches!(item.result_reason, Some(ResultReason::ItemNotFound)) {
Err(NetError::ItemNotFound(err))
} else {
Err(NetError::ServerError(err))
}
}
ResultStatus::OperationPending => Err(NetError::InternalError(
"Result status 'operation pending' is not supported".into(),
)),
ResultStatus::OperationUndone => Err(NetError::InternalError(
"Result status 'operation undone' is not supported".into(),
)),
ResultStatus::Success => Ok(item),
})
.collect::<Vec<_>>();
Ok(res)
} else {
let err = format!(
"Expected at least one batch item in response but received {}",
res.batch_items.len()
);
Err(NetError::ServerError(err))
}
}
#[maybe_async::maybe_async]
async fn write_to_stream(stream: &mut T, bytes: &[u8]) -> NetResult<()> {
trace!(
"Writing {} bytes to the server: {}",
bytes.len(),
hex::encode_upper(bytes)
);
stream.write_all(bytes).await?;
Ok(())
}
}
impl<T: ReadWrite> Clone for Client<T> {
fn clone(&self) -> Self {
Self {
auth: self.auth.clone(),
max_message_size: self.max_message_size,
stream: self.stream.clone(),
connection_error_count: self.connection_error_count.clone(),
read_buf: vec![0u8; 8192],
write_buf: vec![MaybeUninit::uninit(); 8192],
cached_query_response_payload: self.cached_query_response_payload.clone(),
}
}
}
impl<T: ReadWrite> Client<T> {
/// Get the authentication settings used by this client.
pub fn auth(&self) -> Option<&Authentication> {
self.auth.as_ref()
}
/// Get the maximum message size in bytes permitted by this client.
pub fn max_message_size(&self) -> i32 {
self.max_message_size
}
/// Get the count of connection errors experienced by this Client.
pub fn connection_error_count(&self) -> usize {
self.connection_error_count.load(Ordering::SeqCst)
}
}