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
//! Connection parameters
use super::cp_url::format_as_url;
use crate::{ConnectParamsBuilder, HdbError, HdbResult, IntoConnectParams};
use rustls::ClientConfig;
use secstr::SecUtf8;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;

/// An immutable struct with all information necessary to open a new connection
/// to a HANA database.
///
/// # Instantiating a `ConnectParams` using the `ConnectParamsBuilder`
///
/// See [`ConnectParamsBuilder`](struct.ConnectParamsBuilder.html) for details.
///
/// ```rust,no_run
/// use hdbconnect::{ConnectParams, ServerCerts};
/// # fn read_certificate() -> String {String::from("can't do that")};
/// let certificate: String = read_certificate();
/// let connect_params = ConnectParams::builder()
///    .hostname("the_host")
///    .port(2222)
///    .dbuser("my_user")
///    .password("my_passwd")
///    .tls_with(ServerCerts::Direct(certificate))
///    .build()
///    .unwrap();
/// ```
///  
/// # Instantiating a `ConnectParams` from a URL
///
/// See module [`url`](url/index.html) for details about the supported URLs.
///
/// ```rust
/// use hdbconnect::IntoConnectParams;
/// let conn_params = "hdbsql://my_user:my_passwd@the_host:2222"
///     .into_connect_params()
///     .unwrap();
/// ```
#[derive(Clone, Debug)]
pub struct ConnectParams {
    host: String,
    addr: String,
    dbuser: String,
    dbname: Option<String>,
    network_group: Option<String>,
    password: SecUtf8,
    clientlocale: Option<String>,
    server_certs: Vec<ServerCerts>,
    #[cfg(feature = "alpha_nonblocking")]
    use_nonblocking: bool,
}
impl ConnectParams {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        host: String,
        port: u16,
        dbuser: String,
        password: SecUtf8,
        dbname: Option<String>,
        network_group: Option<String>,
        clientlocale: Option<String>,
        server_certs: Vec<ServerCerts>,
        #[cfg(feature = "alpha_nonblocking")] use_nonblocking: bool,
    ) -> Self {
        Self {
            addr: format!("{}:{}", host, port),
            host,
            dbuser,
            password,
            clientlocale,
            server_certs,
            dbname,
            network_group,
            #[cfg(feature = "alpha_nonblocking")]
            use_nonblocking,
        }
    }

    /// Returns a new builder for `ConnectParams`.
    pub fn builder() -> ConnectParamsBuilder {
        ConnectParamsBuilder::new()
    }

    pub(crate) fn redirect(&self, host: &str, port: u16) -> ConnectParams {
        let mut new_params = self.clone();
        new_params.host = host.to_string();
        new_params.addr = format!("{}:{}", host, port);
        new_params
    }

    /// Reads a url from the given file and converts it into `ConnectParams`.
    ///
    /// # Errors
    /// `HdbError::ConnParams`
    pub fn from_file<P: AsRef<Path>>(path: P) -> HdbResult<Self> {
        std::fs::read_to_string(path)
            .map_err(|e| HdbError::ConnParams {
                source: Box::new(e),
            })?
            .into_connect_params()
    }

    /// The `ServerCerts`.
    pub fn server_certs(&self) -> &Vec<ServerCerts> {
        &self.server_certs
    }

    /// The host.
    pub fn host(&self) -> &str {
        &self.host
    }

    /// The socket address.
    pub fn addr(&self) -> &str {
        &self.addr
    }

    /// Whether TLS or a plain TCP connection is to be used.
    pub fn use_tls(&self) -> bool {
        !self.server_certs.is_empty()
    }

    /// The database user.
    pub fn dbuser(&self) -> &str {
        self.dbuser.as_str()
    }

    /// The password.
    pub fn password(&self) -> &SecUtf8 {
        &self.password
    }

    /// The client locale.
    pub fn clientlocale(&self) -> Option<&str> {
        self.clientlocale.as_deref()
    }

    /// The name of the (MDC) database.
    pub fn dbname(&self) -> Option<String> {
        self.dbname.as_ref().map(ToString::to_string)
    }

    /// The name of a network group.
    pub fn network_group(&self) -> Option<String> {
        self.network_group.as_ref().map(ToString::to_string)
    }

    pub(crate) fn rustls_clientconfig(&self) -> std::io::Result<ClientConfig> {
        let mut config = ClientConfig::new();
        for server_cert in self.server_certs() {
            match server_cert {
                ServerCerts::None => {
                    config
                        .dangerous()
                        .set_certificate_verifier(Arc::new(NoCertificateVerification {}));
                }
                ServerCerts::RootCertificates => {
                    config
                        .root_store
                        .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
                }
                ServerCerts::Direct(pem) => {
                    let mut cursor = std::io::Cursor::new(pem);
                    let (n_ok, n_err) = config
                        .root_store
                        .add_pem_file(&mut cursor)
                        .unwrap_or((0, 0));
                    if n_ok == 0 {
                        info!("None of the directly provided server certificates was accepted");
                    } else if n_err > 0 {
                        info!("Not all directly provided server certificates were accepted");
                    }
                }
                ServerCerts::Environment(env_var) => match std::env::var(env_var) {
                    Ok(value) => {
                        let mut cursor = std::io::Cursor::new(value);
                        let (n_ok, n_err) = config
                            .root_store
                            .add_pem_file(&mut cursor)
                            .unwrap_or((0, 0));
                        if n_ok == 0 {
                            info!("None of the env-provided server certificates was accepted");
                        } else if n_err > 0 {
                            info!("Not all env-provided server certificates were accepted");
                        }
                    }
                    Err(e) => {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidInput,
                            format!("Environment variable {} not found, reason: {}", env_var, e),
                        ));
                    }
                },
                ServerCerts::Directory(trust_anchor_dir) => {
                    #[allow(clippy::filter_map)]
                    let trust_anchor_files: Vec<PathBuf> = std::fs::read_dir(trust_anchor_dir)?
                        .filter_map(Result::ok)
                        .filter(|dir_entry| {
                            dir_entry.file_type().is_ok()
                                && dir_entry.file_type().unwrap().is_file()
                        })
                        .filter(|dir_entry| {
                            let path = dir_entry.path();
                            let ext = path.extension();
                            Some(AsRef::<std::ffi::OsStr>::as_ref("pem")) == ext
                        })
                        .map(|dir_entry| dir_entry.path())
                        .collect();
                    let mut t_ok = 0;
                    let mut t_err = 0;
                    for trust_anchor_file in trust_anchor_files {
                        trace!("Trying trust anchor file {:?}", trust_anchor_file);
                        let mut rd =
                            std::io::BufReader::new(std::fs::File::open(trust_anchor_file)?);
                        #[allow(clippy::map_err_ignore)]
                        let (n_ok, n_err) =
                            config.root_store.add_pem_file(&mut rd).map_err(|_| {
                                std::io::Error::new(
                                    std::io::ErrorKind::InvalidInput,
                                    "server certificates in directory could not be parsed",
                                )
                            })?;
                        t_ok += n_ok;
                        t_err += n_err;
                    }
                    if t_ok == 0 {
                        warn!("None of the server certificates in the directory was accepted");
                    } else if t_err > 0 {
                        warn!("Not all server certificates in the directory were accepted");
                    }
                }
            }
        }
        Ok(config)
    }
}

impl std::fmt::Display for ConnectParams {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        format_as_url(
            self.use_tls(),
            &self.addr,
            &self.dbuser,
            &self.dbname,
            &self.network_group,
            &self.server_certs,
            &self.clientlocale,
            f,
        )
    }
}

/// Expresses where Certificates for TLS are read from.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ServerCerts {
    /// Server Certificates are read from files in the specified folder.
    Directory(String),
    /// Server Certificates are read from the specified environment variable.
    Environment(String),
    /// The Server Certificate is given directly.
    Direct(String),
    /// Defines that the server roots from https://mkcert.org/ should be added to the
    /// trust store for TLS.
    RootCertificates,
    /// Defines that the server's identity is not validated. Don't use this
    /// option in productive setups!
    None,
}

struct NoCertificateVerification {}
impl rustls::ServerCertVerifier for NoCertificateVerification {
    fn verify_server_cert(
        &self,
        _roots: &rustls::RootCertStore,
        _presented_certs: &[rustls::Certificate],
        _dns_name: webpki::DNSNameRef<'_>,
        _ocsp: &[u8],
    ) -> Result<rustls::ServerCertVerified, rustls::TLSError> {
        Ok(rustls::ServerCertVerified::assertion())
    }

    // fn verify_tls12_signature(
    //     &self,
    //     _message: &[u8],
    //     _cert: &rustls::Certificate,
    //     _dss: &rustls::internal::msgs::handshake::DigitallySignedStruct,
    // ) -> Result<rustls::HandshakeSignatureValid, rustls::TLSError> {
    //     Ok(rustls::HandshakeSignatureValid::assertion())
    // }

    // fn verify_tls13_signature(
    //     &self,
    //     _message: &[u8],
    //     _cert: &rustls::Certificate,
    //     _dss: &rustls::internal::msgs::handshake::DigitallySignedStruct,
    // ) -> Result<rustls::HandshakeSignatureValid, rustls::TLSError> {
    //     Ok(rustls::HandshakeSignatureValid::assertion())
    // }
}

#[cfg(test)]
mod tests {
    use super::IntoConnectParams;
    use super::ServerCerts;

    #[test]
    fn test_params_from_url() {
        {
            let params = "hdbsql://meier:schLau@abcd123:2222"
                .into_connect_params()
                .unwrap();

            assert_eq!("meier", params.dbuser());
            assert_eq!("schLau", params.password().unsecure());
            assert_eq!("abcd123:2222", params.addr());
            assert_eq!(None, params.clientlocale);
            assert!(params.server_certs().is_empty());
        }
        {
            let params = "hdbsqls://meier:schLau@abcd123:2222\
                          ?client_locale=CL1\
                          &tls_certificate_dir=TCD\
                          &use_mozillas_root_certificates"
                .into_connect_params()
                .unwrap();

            assert_eq!("meier", params.dbuser());
            assert_eq!("schLau", params.password().unsecure());
            assert_eq!(Some("CL1".to_string()), params.clientlocale);
            assert_eq!(
                ServerCerts::Directory("TCD".to_string()),
                *params.server_certs().get(0).unwrap()
            );
            assert_eq!(
                ServerCerts::RootCertificates,
                *params.server_certs().get(1).unwrap()
            );
            assert_eq!(
                params.to_string(),
                "hdbsqls://meier@abcd123:2222\
                ?tls_certificate_dir=TCD\
                &use_mozillas_root_certificates&client_locale=CL1"
                    .to_owned() // no password
            )
        }
        {
            let params = "hdbsqls://meier:schLau@abcd123:2222\
                          ?insecure_omit_server_certificate_check"
                .into_connect_params()
                .unwrap();

            assert_eq!("meier", params.dbuser());
            assert_eq!("schLau", params.password().unsecure());
            assert_eq!(ServerCerts::None, *params.server_certs().get(0).unwrap());
            assert_eq!(
                params.to_string(),
                "hdbsqls://meier@abcd123:2222?insecure_omit_server_certificate_check".to_owned() // no password
            )
        }
    }

    #[test]
    fn test_errors() {
        assert!("hdbsql://schLau@abcd123:2222"
            .into_connect_params()
            .is_err());
        assert!("hdbsql://meier@abcd123:2222".into_connect_params().is_err());
        assert!("hdbsql://meier:schLau@:2222".into_connect_params().is_err());
        assert!("hdbsql://meier:schLau@abcd123"
            .into_connect_params()
            .is_err());
    }
}