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
use std::path::Path;
#[cfg(all(feature = "dns-over-openssl", not(feature = "dns-over-rustls")))]
use openssl::{pkey::PKey, stack::Stack, x509::X509};
#[cfg(feature = "dns-over-rustls")]
use rustls::{Certificate, PrivateKey};
use serde::Deserialize;
use crate::client::error::ParseResult;
use crate::client::rr::domain::Name;
#[cfg(feature = "dnssec")]
use crate::client::rr::{
dnssec::{Algorithm, KeyFormat, KeyPair, Private, SigSigner},
domain::IntoName,
};
#[derive(Deserialize, PartialEq, Debug)]
pub struct KeyConfig {
pub key_path: String,
pub password: Option<String>,
pub algorithm: String,
pub signer_name: Option<String>,
pub is_zone_signing_key: Option<bool>,
pub is_zone_update_auth: Option<bool>,
}
impl KeyConfig {
#[cfg(feature = "dnssec")]
#[cfg_attr(docsrs, doc(cfg(feature = "dnssec")))]
pub fn new(
key_path: String,
password: Option<String>,
algorithm: Algorithm,
signer_name: String,
is_zone_signing_key: bool,
is_zone_update_auth: bool,
) -> Self {
KeyConfig {
key_path,
password,
algorithm: algorithm.as_str().to_string(),
signer_name: Some(signer_name),
is_zone_signing_key: Some(is_zone_signing_key),
is_zone_update_auth: Some(is_zone_update_auth),
}
}
pub fn key_path(&self) -> &Path {
Path::new(&self.key_path)
}
#[cfg(any(feature = "dns-over-tls", feature = "dnssec"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "dns-over-tls", feature = "dnssec"))))]
pub fn format(&self) -> ParseResult<KeyFormat> {
use crate::client::error::ParseErrorKind;
let extension = self.key_path().extension().ok_or_else(|| {
ParseErrorKind::Msg(format!(
"file lacks extension, e.g. '.pk8': {:?}",
self.key_path()
))
})?;
match extension.to_str() {
Some("der") => Ok(KeyFormat::Der),
Some("key") => Ok(KeyFormat::Pem),
Some("pem") => Ok(KeyFormat::Pem),
Some("pk8") => Ok(KeyFormat::Pkcs8),
e => Err(ParseErrorKind::Msg(format!(
"extension not understood, '{:?}': {:?}",
e,
self.key_path()
))
.into()),
}
}
pub fn password(&self) -> Option<&str> {
self.password.as_deref()
}
#[cfg(feature = "dnssec")]
#[cfg_attr(docsrs, doc(cfg(feature = "dnssec")))]
pub fn algorithm(&self) -> ParseResult<Algorithm> {
match self.algorithm.as_str() {
"RSASHA1" => Ok(Algorithm::RSASHA1),
"RSASHA256" => Ok(Algorithm::RSASHA256),
"RSASHA1-NSEC3-SHA1" => Ok(Algorithm::RSASHA1NSEC3SHA1),
"RSASHA512" => Ok(Algorithm::RSASHA512),
"ECDSAP256SHA256" => Ok(Algorithm::ECDSAP256SHA256),
"ECDSAP384SHA384" => Ok(Algorithm::ECDSAP384SHA384),
"ED25519" => Ok(Algorithm::ED25519),
s => Err(format!("unrecognized string {}", s).into()),
}
}
pub fn signer_name(&self) -> ParseResult<Option<Name>> {
if let Some(signer_name) = self.signer_name.as_ref() {
let name = Name::parse(signer_name, None)?;
return Ok(Some(name));
}
Ok(None)
}
pub fn is_zone_signing_key(&self) -> bool {
self.is_zone_signing_key.unwrap_or(false)
}
pub fn is_zone_update_auth(&self) -> bool {
self.is_zone_update_auth.unwrap_or(false)
}
#[cfg(feature = "dnssec")]
#[cfg_attr(docsrs, doc(cfg(feature = "dnssec")))]
pub fn try_into_signer<N: IntoName>(&self, signer_name: N) -> Result<SigSigner, String> {
let signer_name = signer_name
.into_name()
.map_err(|e| format!("error loading signer name: {}", e))?;
let key = load_key(signer_name, self)
.map_err(|e| format!("failed to load key: {:?} msg: {}", self.key_path(), e))?;
key.test_key()
.map_err(|e| format!("key failed test: {}", e))?;
Ok(key)
}
}
#[derive(Deserialize, PartialEq, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CertType {
Pkcs12,
Pem,
}
impl Default for CertType {
fn default() -> Self {
CertType::Pkcs12
}
}
#[derive(Deserialize, PartialEq, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PrivateKeyType {
Pkcs8,
Der,
}
impl Default for PrivateKeyType {
fn default() -> Self {
PrivateKeyType::Der
}
}
#[derive(Deserialize, PartialEq, Debug)]
pub struct TlsCertConfig {
path: String,
endpoint_name: String,
cert_type: Option<CertType>,
password: Option<String>,
private_key: Option<String>,
private_key_type: Option<PrivateKeyType>,
}
impl TlsCertConfig {
pub fn get_path(&self) -> &Path {
Path::new(&self.path)
}
pub fn get_endpoint_name(&self) -> &str {
&self.endpoint_name
}
pub fn get_cert_type(&self) -> CertType {
self.cert_type.unwrap_or_default()
}
pub fn get_password(&self) -> Option<&str> {
self.password.as_deref()
}
pub fn get_private_key(&self) -> Option<&Path> {
self.private_key.as_deref().map(Path::new)
}
pub fn get_private_key_type(&self) -> PrivateKeyType {
self.private_key_type.unwrap_or_default()
}
}
#[cfg(feature = "dnssec")]
fn load_key(zone_name: Name, key_config: &KeyConfig) -> Result<SigSigner, String> {
use log::info;
use std::convert::TryInto;
use std::fs::File;
use std::io::Read;
use time::Duration;
let key_path = key_config.key_path();
let algorithm = key_config
.algorithm()
.map_err(|e| format!("bad algorithm: {}", e))?;
let format = key_config
.format()
.map_err(|e| format!("bad key format: {}", e))?;
let key: KeyPair<Private> = {
info!("reading key: {:?}", key_path);
let mut file = File::open(&key_path)
.map_err(|e| format!("error opening private key file: {:?}: {}", key_path, e))?;
let mut key_bytes = Vec::with_capacity(256);
file.read_to_end(&mut key_bytes)
.map_err(|e| format!("could not read key from: {:?}: {}", key_path, e))?;
format
.decode_key(&key_bytes, key_config.password(), algorithm)
.map_err(|e| format!("could not decode key: {}", e))?
};
let name = key_config
.signer_name()
.map_err(|e| format!("error reading name: {}", e))?
.unwrap_or(zone_name);
let dnskey = key
.to_dnskey(algorithm)
.map_err(|e| format!("error converting to dnskey: {}", e))?;
Ok(SigSigner::dnssec(
dnskey,
key,
name,
Duration::weeks(52)
.try_into()
.map_err(|e| format!("error converting time to std::Duration: {}", e))?,
))
}
#[cfg(all(feature = "dns-over-openssl", not(feature = "dns-over-rustls")))]
pub fn load_cert(
zone_dir: &Path,
tls_cert_config: &TlsCertConfig,
) -> Result<((X509, Option<Stack<X509>>), PKey<Private>), String> {
use log::{info, warn};
use crate::proto::openssl::tls_server::{
read_cert_pem, read_cert_pkcs12, read_key_from_der, read_key_from_pkcs8,
};
let path = zone_dir.to_owned().join(tls_cert_config.get_path());
let cert_type = tls_cert_config.get_cert_type();
let password = tls_cert_config.get_password();
let private_key_path = tls_cert_config
.get_private_key()
.map(|p| zone_dir.to_owned().join(p));
let private_key_type = tls_cert_config.get_private_key_type();
let (cert, cert_chain) = match cert_type {
CertType::Pem => {
info!("loading TLS PEM certificate from: {:?}", path);
read_cert_pem(&path)?
}
CertType::Pkcs12 => {
if private_key_path.is_some() {
warn!(
"ignoring specified key, using the one in the PKCS12 file: {}",
path.display()
);
}
info!("loading TLS PKCS12 certificate from: {:?}", path);
return read_cert_pkcs12(&path, password).map_err(Into::into);
}
};
let key = match (private_key_path, private_key_type) {
(Some(private_key_path), PrivateKeyType::Pkcs8) => {
info!("loading TLS PKCS8 key from: {}", private_key_path.display());
read_key_from_pkcs8(&private_key_path, password)?
}
(Some(private_key_path), PrivateKeyType::Der) => {
info!("loading TLS DER key from: {}", private_key_path.display());
read_key_from_der(&private_key_path)?
}
(None, _) => {
return Err(format!(
"No private key associated with specified certificate"
));
}
};
Ok(((cert, cert_chain), key))
}
#[cfg(feature = "dns-over-rustls")]
#[cfg_attr(docsrs, doc(cfg(feature = "dns-over-rustls")))]
pub fn load_cert(
zone_dir: &Path,
tls_cert_config: &TlsCertConfig,
) -> Result<(Vec<Certificate>, PrivateKey), String> {
use log::{info, warn};
use crate::proto::rustls::tls_server::{read_cert, read_key_from_der, read_key_from_pkcs8};
let path = zone_dir.to_owned().join(tls_cert_config.get_path());
let cert_type = tls_cert_config.get_cert_type();
let password = tls_cert_config.get_password();
let private_key_path = tls_cert_config
.get_private_key()
.map(|p| zone_dir.to_owned().join(p));
let private_key_type = tls_cert_config.get_private_key_type();
let cert = match cert_type {
CertType::Pem => {
info!("loading TLS PEM certificate chain from: {}", path.display());
read_cert(&path).map_err(|e| format!("error reading cert: {}", e))?
}
CertType::Pkcs12 => {
return Err(
"PKCS12 is not supported with Rustls for certificate, use PEM encoding".to_string(),
);
}
};
let key = match (private_key_path, private_key_type) {
(Some(private_key_path), PrivateKeyType::Pkcs8) => {
info!("loading TLS PKCS8 key from: {}", private_key_path.display());
if password.is_some() {
warn!("Password for key supplied, but Rustls does not support encrypted PKCS8");
}
read_key_from_pkcs8(&private_key_path)?
}
(Some(private_key_path), PrivateKeyType::Der) => {
info!("loading TLS DER key from: {}", private_key_path.display());
read_key_from_der(&private_key_path)?
}
(None, _) => return Err("No private key associated with specified certificate".to_string()),
};
Ok((cert, key))
}