forked from NLnetLabs/kmip-protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
227 lines (187 loc) · 7.5 KB
/
main.rs
File metadata and controls
227 lines (187 loc) · 7.5 KB
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
#[cfg(not(any(
feature = "tls-with-openssl",
feature = "tls-with-openssl-vendored",
feature = "tls-with-rustls",
feature = "tls-with-tokio-native-tls",
feature = "tls-with-tokio-rustls",
feature = "tls-with-async-tls"
)))]
compile_error!("This demo requires one of the tls-with-xxx features to be enabled.");
mod config;
mod util;
use std::time::Duration;
use kmip_protocol::client::{Client, ClientCertificate, ConnectionSettings};
use kmip_protocol::types::traits::ReadWrite;
use log::info;
use structopt::StructOpt;
use util::init_logging;
use crate::{
config::Opt,
util::{SelfLoggingError, ToCsvString},
};
#[cfg(any(
feature = "tls-with-openssl",
feature = "tls-with-openssl-vendored",
feature = "tls-with-rustls"
))]
fn main() {
let opt = Opt::from_args();
init_logging(&opt);
cfg_if::cfg_if! {
if #[cfg(any(feature = "tls-with-openssl", feature = "tls-with-openssl-vendored"))] {
let client = kmip_protocol::client::tls::openssl::connect(&opt.into());
} else if #[cfg(feature = "tls-with-rustls")] {
let client = kmip_protocol::client::tls::rustls::connect(&opt.into());
}
}
let client = client.expect("Failed to establish TLS connection");
let mut thread_handles = vec![];
for i in 0..=1 {
let thread_client = client.clone();
let handle = std::thread::spawn(move || {
exec_test_requests(thread_client, &format!("test_{}", i)).unwrap();
});
thread_handles.push(handle);
}
for handle in thread_handles {
handle.join().unwrap();
}
}
#[cfg(feature = "tls-with-async-tls")]
#[async_std::main]
async fn main() {
let opt = Opt::from_args();
init_logging(&opt);
let client = kmip_protocol::client::tls::async_tls::connect(&opt.into()).await;
let client = client.expect("Failed to establish TLS connection");
exec_test_requests(client, "test").await.unwrap();
}
#[cfg(any(feature = "tls-with-tokio-native-tls", feature = "tls-with-tokio-rustls",))]
#[tokio::main]
async fn main() {
let opt = Opt::from_args();
init_logging(&opt);
cfg_if::cfg_if! {
if #[cfg(feature = "tls-with-tokio-native-tls")] {
let client = kmip_protocol::client::tls::tokio_native_tls::connect(&opt.into()).await;
} else if #[cfg(feature = "tls-with-tokio-rustls")] {
let client = kmip_protocol::client::tls::tokio_rustls::connect(&opt.into()).await;
}
}
let client = client.expect("Failed to establish TLS connection");
exec_test_requests(client, "test").await.unwrap();
}
#[maybe_async::maybe_async]
async fn exec_test_requests<T: ReadWrite>(
client: Client<T>,
key_name_prefix: &str,
) -> Result<(), kmip_protocol::client::Error> {
query_server_properties(&client).await?;
// TODO: Maybe key creation should return a key object with further operations on it such as revoke, delete,
// sign, etc, instead of following the KMIP functional model?
info!("Creating RSA key pair");
if let Ok((private_key_id, public_key_id)) = client
.create_rsa_key_pair(
2048,
format!("{}_private_key", key_name_prefix),
format!("{}_public_key", key_name_prefix),
)
.await
.log_error(&client)
{
info!("Created key pair:");
info!(" Private key ID: {}", private_key_id);
info!(" Public key ID : {}", public_key_id);
let mut key_needs_revoking = false;
info!("Activating private key {}..", private_key_id);
if client.activate_key(&private_key_id).await.log_error(&client).is_ok() {
key_needs_revoking = true;
info!("Signing with private key {}..", private_key_id);
if let Ok(payload) = client
.sign(&private_key_id, &[1u8, 2u8, 3u8, 4u8, 5u8])
.await
.log_error(&client)
{
info!("{}", hex::encode_upper(payload.signature_data));
}
}
info!("Deleting public key {}..", public_key_id);
client.destroy_key(&public_key_id).await.log_error(&client).ok();
if key_needs_revoking {
info!("Revoking private key {}..", private_key_id);
client.revoke_key(&private_key_id).await.log_error(&client).ok();
}
info!("Deleting private key {}..", private_key_id);
client.destroy_key(&private_key_id).await.log_error(&client).ok();
}
info!("Requesting 32 random bytes..");
if let Ok(payload) = client.rng_retrieve(32).await.log_error(&client) {
info!("{}", hex::encode_upper(payload.data));
}
Ok(())
}
#[maybe_async::maybe_async]
#[rustfmt::skip]
async fn query_server_properties<T: ReadWrite>(client: &Client<T>) -> Result<(), kmip_protocol::client::Error> {
info!("Querying server properties..");
let server_props = client.query().await?;
info!("Server identification: {}", server_props.vendor_identification.unwrap_or("Not available".into()));
info!("Server supported operations: {}", server_props.operations.to_csv_string());
info!("Server supported object types: {}", server_props.object_types.to_csv_string());
Ok(())
}
fn load_binary_file(path: &std::path::PathBuf) -> Vec<u8> {
use std::{fs::File, io::Read};
let mut bytes = Vec::new();
File::open(path)
.expect(&format!("Failed to open open file '{:?}'", path))
.read_to_end(&mut bytes)
.expect(&format!("Failed to read data from file '{:?}'", path));
bytes
}
impl From<Opt> for ConnectionSettings {
fn from(opt: Opt) -> Self {
let password = std::env::var("HSM_PASSWORD").ok();
let client_cert = {
match (&opt.client_cert_path, &opt.client_key_path, &opt.client_pkcs12_path) {
(None, None, None) => None,
(None, None, Some(path)) => Some(ClientCertificate::CombinedPkcs12 {
cert_bytes: load_binary_file(path),
}),
(Some(path), None, None) => Some(ClientCertificate::SeparatePem {
cert_bytes: load_binary_file(path),
key_bytes: None,
}),
(None, Some(_), None) => {
panic!("Client certificate key path requires a client certificate path")
}
(_, Some(_), Some(_)) | (Some(_), _, Some(_)) => {
panic!("Use either but not both of: client certificate and key PEM file paths, or a PCKS#12 certficate file path")
}
(Some(cert_path), Some(key_path), None) => Some(ClientCertificate::SeparatePem {
cert_bytes: load_binary_file(cert_path),
key_bytes: Some(load_binary_file(key_path)),
}),
}
};
let server_cert = opt.server_cert_path.map(|path| load_binary_file(&path));
let ca_cert = opt.ca_cert_path.map(|path| load_binary_file(&path));
let connect_timeout = Some(Duration::from_secs(opt.connect_timeout));
let read_timeout = Some(Duration::from_secs(opt.read_timeout));
let write_timeout = Some(Duration::from_secs(opt.write_timeout));
ConnectionSettings {
host: opt.host,
port: opt.port,
username: opt.username,
password,
insecure: opt.insecure,
client_cert,
server_cert,
ca_cert,
connect_timeout,
read_timeout,
write_timeout,
max_response_bytes: Some(4096),
}
}
}