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
use std::sync::{Arc};
use rustls::Session;
use std::net::TcpStream;
use std::io::{Write, Error, ErrorKind};
use std::fmt::Debug;
use x509_parser::{parse_x509_der};
use x509_parser::objects::*;
use x509_parser::extensions::*;
use chrono::{Utc, TimeZone, DateTime};
use serde::{Serialize, Deserialize};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct ServerCert {
    pub common_name: String,
    pub signature_algorithm: String,
    pub sans: Vec<String>,
    pub country: String,
    pub state: String,
    pub locality: String,
    pub organization: String,
    pub not_after: DateTime<Utc>,
    pub not_before: DateTime<Utc>,
    pub issuer: String,
    pub is_valid: bool,
    pub time_to_expiration: String,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct IntermediateCert {
    pub common_name: String,
    pub signature_algorithm: String,
    pub country: String,
    pub state: String,
    pub locality: String,
    pub organization: String,
    pub not_after: DateTime<Utc>,
    pub not_before: DateTime<Utc>,
    pub issuer: String,
    pub is_valid: bool,
    pub time_to_expiration: String,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Cert {
    pub server: ServerCert,
    pub intermediate: IntermediateCert
}

pub struct CheckSSL();

impl CheckSSL {
    /// Check ssl from domain with port 443
    ///
    /// Example
    ///
    /// ```no_run
    /// use checkssl::CheckSSL;
    ///
    /// match CheckSSL::from_domain("rust-lang.org") {
    ///   Ok(certificate) => {
    ///     // do something with certificate
    ///     assert!(certificate.server.is_valid);
    ///   }
    ///   Err(e) => {
    ///     // ssl invalid
    ///     eprintln!(e);
    ///   }
    /// }
    /// ```
    pub fn from_domain(domain: &str) -> Result<Cert, std::io::Error> {
        let mut config = rustls::ClientConfig::new();
        config.root_store.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);

        let rc_config = Arc::new(config);
        let site = match webpki::DNSNameRef::try_from_ascii_str(domain) {
            Ok(val) => val,
            Err(e) => return Err(Error::new(ErrorKind::InvalidInput, e.to_string())),
        };

        let mut sess = rustls::ClientSession::new(&rc_config, site);
        let mut sock = TcpStream::connect(format!("{}:443", domain))?;
        let mut tls = rustls::Stream::new(&mut sess, &mut sock);

        let req = format!("GET / HTTP/1.0\r\nHost: {}\r\nConnection: \
                               close\r\nAccept-Encoding: identity\r\n\r\n",
                          domain);
        tls.write_all(req.as_bytes())?;

        let mut server_cert = ServerCert {
            common_name: "".to_string(),
            signature_algorithm: "".to_string(),
            sans: Vec::new(),
            country: "".to_string(),
            state: "".to_string(),
            locality: "".to_string(),
            organization: "".to_string(),
            not_after: Utc::now(),
            not_before: Utc::now(),
            issuer: "".to_string(),
            is_valid: false,
            time_to_expiration: "".to_string(),
        };

        let mut intermediate_cert = IntermediateCert {
            common_name: "".to_string(),
            signature_algorithm: "".to_string(),
            country: "".to_string(),
            state: "".to_string(),
            locality: "".to_string(),
            organization: "".to_string(),
            not_after: Utc::now(),
            not_before: Utc::now(),
            issuer: "".to_string(),
            is_valid: false,
            time_to_expiration: "".to_string(),
        };

        if let Some(certificates) = tls.sess.get_peer_certificates() {
            for certificate in certificates.iter() {
                let x509cert = match parse_x509_der(certificate.as_ref()) {
                    Ok((_, x509cert)) => x509cert,
                    Err(e) => return Err(Error::new(ErrorKind::Other, e.to_string())),
                };

                let is_ca = match x509cert.tbs_certificate.basic_constraints() {
                    Some((_, basic_constraints)) => basic_constraints.ca,
                    None => false,
                };

                //check if it's ca or not, if ca then insert to intermediate certificate
                if is_ca {
                    intermediate_cert.is_valid = x509cert.validity().is_valid();
                    intermediate_cert.not_after = Utc.timestamp(x509cert.tbs_certificate.validity.not_after.timestamp(), 0);
                    intermediate_cert.not_before = Utc.timestamp(x509cert.tbs_certificate.validity.not_before.timestamp(), 0);

                    match oid2sn(&x509cert.signature_algorithm.algorithm) {
                        Ok(s) => {
                            intermediate_cert.signature_algorithm = s.to_string();
                        }
                        Err(_e) =>  return Err(Error::new(ErrorKind::Other, "Error converting Oid to Nid".to_string())),
                    }

                    if let Some(time_to_expiration) = x509cert.tbs_certificate.validity.time_to_expiration() {
                        intermediate_cert.time_to_expiration = format!("{:?} day(s)", time_to_expiration.as_secs() / 60 / 60 / 24)
                    }

                    let issuer = x509cert.issuer();
                    let subject = x509cert.subject();

                    for rdn_seq in &issuer.rdn_seq {
                        match oid2sn(&rdn_seq.set[0].attr_type) {
                            Ok(s) => {
                                let rdn_content = rdn_seq.set[0].attr_value.content.as_str().unwrap().to_string();
                                if s == "CN" {
                                    intermediate_cert.issuer = rdn_content;
                                }
                            }
                            Err(_e) =>  return Err(Error::new(ErrorKind::Other, "Error converting Oid to Nid".to_string())),
                        }
                    }

                    for rdn_seq in &subject.rdn_seq {
                        match oid2sn(&rdn_seq.set[0].attr_type) {
                            Ok(s) => {
                                let rdn_content = rdn_seq.set[0].attr_value.content.as_str().unwrap().to_string();
                                match s {
                                    "C" => intermediate_cert.country = rdn_content,
                                    "ST" => intermediate_cert.state = rdn_content,
                                    "L" => intermediate_cert.locality = rdn_content,
                                    "CN" => intermediate_cert.common_name = rdn_content,
                                    "O" => intermediate_cert.organization = rdn_content,
                                    _ => {}
                                }
                            }
                            Err(_e) =>  return Err(Error::new(ErrorKind::Other, "Error converting Oid to Nid".to_string())),
                        }
                    }
                } else {
                    server_cert.is_valid = x509cert.validity().is_valid();
                    server_cert.not_after = Utc.timestamp(x509cert.tbs_certificate.validity.not_after.timestamp(), 0);
                    server_cert.not_before = Utc.timestamp(x509cert.tbs_certificate.validity.not_before.timestamp(), 0);

                    match oid2sn(&x509cert.signature_algorithm.algorithm) {
                        Ok(s) => {
                            server_cert.signature_algorithm = s.to_string();
                        }
                        Err(_e) =>  return Err(Error::new(ErrorKind::Other, "Error converting Oid to Nid".to_string())),
                    }

                    if let Some((_, san)) = x509cert.tbs_certificate.subject_alternative_name() {
                        for name in san.general_names.iter() {
                            match name {
                                GeneralName::DNSName(dns) => {
                                    server_cert.sans.push(dns.to_string())
                                }
                                _ => {},
                            }
                        }
                    }

                    if let Some(time_to_expiration) = x509cert.tbs_certificate.validity.time_to_expiration() {
                        server_cert.time_to_expiration = format!("{:?} day(s)", time_to_expiration.as_secs() / 60 / 60 / 24)
                    }

                    let issuer = x509cert.issuer();
                    let subject = x509cert.subject();

                    for rdn_seq in &issuer.rdn_seq {
                        match oid2sn(&rdn_seq.set[0].attr_type) {
                            Ok(s) => {
                                let rdn_content = rdn_seq.set[0].attr_value.content.as_str().unwrap().to_string();
                                if s == "CN" {
                                    server_cert.issuer = rdn_content;
                                }
                            }
                            Err(_e) =>  return Err(Error::new(ErrorKind::Other, "Error converting Oid to Nid".to_string())),
                        }
                    }

                    for rdn_seq in &subject.rdn_seq {
                        match oid2sn(&rdn_seq.set[0].attr_type) {
                            Ok(s) => {
                                let rdn_content = rdn_seq.set[0].attr_value.content.as_str().unwrap().to_string();
                                match s {
                                    "C" => server_cert.country = rdn_content,
                                    "ST" => server_cert.state = rdn_content,
                                    "L" => server_cert.locality = rdn_content,
                                    "CN" => server_cert.common_name = rdn_content,
                                    "O" => server_cert.organization = rdn_content,
                                    _ => {}
                                }
                            }
                            Err(_e) =>  return Err(Error::new(ErrorKind::Other, "Error converting Oid to Nid".to_string())),
                        }
                    }
                }
            }

            let cert = Cert{
                server: server_cert,
                intermediate: intermediate_cert,
            };

            Ok(cert)
        } else {
            Err(Error::new(ErrorKind::NotFound, "certificate not found".to_string()))
        }
    }
}

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

    #[test]
    fn test_check_ssl_server_is_valid() {
        assert!(CheckSSL::from_domain("rust-lang.org").unwrap().server.is_valid);
    }

    #[test]
    fn test_check_ssl_server_is_invalid() {
        let actual = CheckSSL::from_domain("expired.badssl.com").map_err(|e| e.kind());
        let expected = Err(ErrorKind::InvalidData);

        assert_eq!(expected, actual);
    }
}