cipherrun 0.3.0

A fast, modular, and scalable TLS/SSL security scanner written in Rust
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
// Certificate Routes

use crate::api::{
    models::{
        error::{ApiError, ApiErrorResponse},
        request::CertificateQuery,
        response::{CertificateListResponse, CertificateSummary},
    },
    state::AppState,
};
use crate::db::DatabasePool;
use axum::{
    Json,
    extract::{Path, Query, State},
};
use chrono::Utc;
use sqlx::Row;
use std::sync::Arc;

/// List certificates
///
/// Returns a paginated list of certificates from the inventory
#[utoipa::path(
    get,
    path = "/api/v1/certificates",
    tag = "certificates",
    params(
        CertificateQuery
    ),
    responses(
        (status = 200, description = "Certificate list", body = CertificateListResponse)
    ),
    security(
        ("api_key" = [])
    )
)]
pub async fn list_certificates(
    State(state): State<Arc<AppState>>,
    Query(query): Query<CertificateQuery>,
) -> Result<Json<CertificateListResponse>, ApiError> {
    // Get database pool
    let db_pool = state
        .db_pool
        .as_ref()
        .ok_or_else(|| ApiError::Internal("Database not configured".to_string()))?;

    // Build query with filters
    let mut where_clauses = Vec::new();
    let mut params: Vec<String> = Vec::new();

    // Filter by hostname if provided
    if let Some(ref hostname) = query.hostname {
        where_clauses.push("EXISTS (SELECT 1 FROM scan_certificates sc JOIN scans s ON sc.scan_id = s.scan_id WHERE sc.cert_id = c.cert_id AND s.target_hostname = ?)");
        params.push(hostname.clone());
    }

    // Filter by expiring within days if provided
    if let Some(days) = query.expiring_within_days {
        let cutoff_date = Utc::now() + chrono::Duration::days(days as i64);
        where_clauses.push("c.not_after <= ?");
        params.push(cutoff_date.to_rfc3339());
    }

    let where_clause = if where_clauses.is_empty() {
        String::new()
    } else {
        format!("WHERE {}", where_clauses.join(" AND "))
    };

    // Determine sort order
    let order_by = match query.sort.as_str() {
        "expiry_desc" => "c.not_after DESC",
        "issued_asc" => "c.not_before ASC",
        "issued_desc" => "c.not_before DESC",
        _ => "c.not_after ASC", // expiry_asc (default)
    };

    // Query certificates based on database type
    let (total, certificates) = match db_pool.as_ref() {
        DatabasePool::Postgres(pool) => {
            // Get total count
            let count_query = format!(
                "SELECT COUNT(*) as count FROM certificates c {}",
                where_clause
            );
            let mut count_stmt = sqlx::query(&count_query);
            for param in &params {
                count_stmt = count_stmt.bind(param);
            }
            let total: i64 = count_stmt
                .fetch_one(pool)
                .await
                .map_err(|e| ApiError::Internal(format!("Failed to count certificates: {}", e)))?
                .get("count");

            // Get certificates with pagination
            let list_query = format!(
                r#"
                SELECT
                    c.fingerprint_sha256,
                    c.subject,
                    c.issuer,
                    c.not_before,
                    c.not_after,
                    c.san_domains,
                    ARRAY_AGG(DISTINCT s.target_hostname) as hostnames
                FROM certificates c
                LEFT JOIN scan_certificates sc ON c.cert_id = sc.cert_id
                LEFT JOIN scans s ON sc.scan_id = s.scan_id
                {}
                GROUP BY c.cert_id, c.fingerprint_sha256, c.subject, c.issuer, c.not_before, c.not_after, c.san_domains
                ORDER BY {}
                LIMIT $1 OFFSET $2
                "#,
                where_clause, order_by
            );

            let stmt = sqlx::query(&list_query)
                .bind(query.limit as i64)
                .bind(query.offset as i64);

            let rows = stmt
                .fetch_all(pool)
                .await
                .map_err(|e| ApiError::Internal(format!("Failed to fetch certificates: {}", e)))?;

            let certs = rows
                .into_iter()
                .map(|row| {
                    let fingerprint: String = row.get("fingerprint_sha256");
                    let subject: String = row.get("subject");
                    let issuer: String = row.get("issuer");
                    let not_before: chrono::DateTime<Utc> = row.get("not_before");
                    let not_after: chrono::DateTime<Utc> = row.get("not_after");
                    let san_json: Option<String> = row.try_get("san_domains").ok();
                    let hostnames: Option<Vec<String>> = row.try_get("hostnames").ok();

                    let san: Vec<String> = san_json
                        .and_then(|j| serde_json::from_str(&j).ok())
                        .unwrap_or_default();

                    let common_name = extract_cn_from_subject(&subject);
                    let now = Utc::now();
                    let days_until_expiry = (not_after - now).num_days();

                    CertificateSummary {
                        fingerprint,
                        common_name,
                        san,
                        issuer,
                        valid_from: not_before,
                        valid_until: not_after,
                        days_until_expiry,
                        is_expired: not_after < now,
                        is_expiring_soon: (0..30).contains(&days_until_expiry),
                        hostnames: hostnames.unwrap_or_default(),
                    }
                })
                .collect();

            (total as usize, certs)
        }
        DatabasePool::Sqlite(pool) => {
            // Get total count
            let count_query = format!(
                "SELECT COUNT(*) as count FROM certificates c {}",
                where_clause
            );
            let mut count_stmt = sqlx::query(&count_query);
            for param in &params {
                count_stmt = count_stmt.bind(param);
            }
            let total: i64 = count_stmt
                .fetch_one(pool)
                .await
                .map_err(|e| ApiError::Internal(format!("Failed to count certificates: {}", e)))?
                .get("count");

            // Get certificates with pagination
            let list_query = format!(
                r#"
                SELECT
                    c.fingerprint_sha256,
                    c.subject,
                    c.issuer,
                    c.not_before,
                    c.not_after,
                    c.san_domains,
                    GROUP_CONCAT(DISTINCT s.target_hostname) as hostnames
                FROM certificates c
                LEFT JOIN scan_certificates sc ON c.cert_id = sc.cert_id
                LEFT JOIN scans s ON sc.scan_id = s.scan_id
                {}
                GROUP BY c.cert_id
                ORDER BY {}
                LIMIT ? OFFSET ?
                "#,
                where_clause, order_by
            );

            let stmt = sqlx::query(&list_query)
                .bind(query.limit as i64)
                .bind(query.offset as i64);

            let rows = stmt
                .fetch_all(pool)
                .await
                .map_err(|e| ApiError::Internal(format!("Failed to fetch certificates: {}", e)))?;

            let certs = rows
                .into_iter()
                .map(|row| {
                    let fingerprint: String = row.get("fingerprint_sha256");
                    let subject: String = row.get("subject");
                    let issuer: String = row.get("issuer");
                    let not_before: chrono::DateTime<Utc> = row.get("not_before");
                    let not_after: chrono::DateTime<Utc> = row.get("not_after");
                    let san_json: Option<String> = row.try_get("san_domains").ok();
                    let hostnames_str: Option<String> = row.try_get("hostnames").ok();

                    let san: Vec<String> = san_json
                        .and_then(|j| serde_json::from_str(&j).ok())
                        .unwrap_or_default();

                    let hostnames: Vec<String> = hostnames_str
                        .map(|s| s.split(',').map(|h| h.to_string()).collect())
                        .unwrap_or_default();

                    let common_name = extract_cn_from_subject(&subject);
                    let now = Utc::now();
                    let days_until_expiry = (not_after - now).num_days();

                    CertificateSummary {
                        fingerprint,
                        common_name,
                        san,
                        issuer,
                        valid_from: not_before,
                        valid_until: not_after,
                        days_until_expiry,
                        is_expired: not_after < now,
                        is_expiring_soon: (0..30).contains(&days_until_expiry),
                        hostnames,
                    }
                })
                .collect();

            (total as usize, certs)
        }
    };

    Ok(Json(CertificateListResponse {
        total,
        offset: query.offset,
        limit: query.limit,
        certificates,
    }))
}

/// Get certificate details
///
/// Returns detailed information about a specific certificate
#[utoipa::path(
    get,
    path = "/api/v1/certificates/{fingerprint}",
    tag = "certificates",
    params(
        ("fingerprint" = String, Path, description = "Certificate SHA-256 fingerprint")
    ),
    responses(
        (status = 200, description = "Certificate details", body = CertificateSummary),
        (status = 404, description = "Certificate not found", body = ApiErrorResponse)
    ),
    security(
        ("api_key" = [])
    )
)]
pub async fn get_certificate(
    State(state): State<Arc<AppState>>,
    Path(fingerprint): Path<String>,
) -> Result<Json<CertificateSummary>, ApiError> {
    // Get database pool
    let db_pool = state
        .db_pool
        .as_ref()
        .ok_or_else(|| ApiError::Internal("Database not configured".to_string()))?;

    // Query certificate based on database type
    let cert = match db_pool.as_ref() {
        DatabasePool::Postgres(pool) => {
            let row = sqlx::query(
                r#"
                SELECT
                    c.fingerprint_sha256,
                    c.subject,
                    c.issuer,
                    c.not_before,
                    c.not_after,
                    c.san_domains,
                    ARRAY_AGG(DISTINCT s.target_hostname) as hostnames
                FROM certificates c
                LEFT JOIN scan_certificates sc ON c.cert_id = sc.cert_id
                LEFT JOIN scans s ON sc.scan_id = s.scan_id
                WHERE c.fingerprint_sha256 = $1
                GROUP BY c.cert_id, c.fingerprint_sha256, c.subject, c.issuer, c.not_before, c.not_after, c.san_domains
                "#,
            )
            .bind(&fingerprint)
            .fetch_optional(pool)
            .await
            .map_err(|e| ApiError::Internal(format!("Failed to fetch certificate: {}", e)))?
            .ok_or_else(|| ApiError::NotFound(format!("Certificate {} not found", fingerprint)))?;

            let subject: String = row.get("subject");
            let issuer: String = row.get("issuer");
            let not_before: chrono::DateTime<Utc> = row.get("not_before");
            let not_after: chrono::DateTime<Utc> = row.get("not_after");
            let san_json: Option<String> = row.try_get("san_domains").ok();
            let hostnames: Option<Vec<String>> = row.try_get("hostnames").ok();

            let san: Vec<String> = san_json
                .and_then(|j| serde_json::from_str(&j).ok())
                .unwrap_or_default();

            let common_name = extract_cn_from_subject(&subject);
            let now = Utc::now();
            let days_until_expiry = (not_after - now).num_days();

            CertificateSummary {
                fingerprint: fingerprint.clone(),
                common_name,
                san,
                issuer,
                valid_from: not_before,
                valid_until: not_after,
                days_until_expiry,
                is_expired: not_after < now,
                is_expiring_soon: (0..30).contains(&days_until_expiry),
                hostnames: hostnames.unwrap_or_default(),
            }
        }
        DatabasePool::Sqlite(pool) => {
            let row = sqlx::query(
                r#"
                SELECT
                    c.fingerprint_sha256,
                    c.subject,
                    c.issuer,
                    c.not_before,
                    c.not_after,
                    c.san_domains,
                    GROUP_CONCAT(DISTINCT s.target_hostname) as hostnames
                FROM certificates c
                LEFT JOIN scan_certificates sc ON c.cert_id = sc.cert_id
                LEFT JOIN scans s ON sc.scan_id = s.scan_id
                WHERE c.fingerprint_sha256 = ?
                GROUP BY c.cert_id
                "#,
            )
            .bind(&fingerprint)
            .fetch_optional(pool)
            .await
            .map_err(|e| ApiError::Internal(format!("Failed to fetch certificate: {}", e)))?
            .ok_or_else(|| ApiError::NotFound(format!("Certificate {} not found", fingerprint)))?;

            let subject: String = row.get("subject");
            let issuer: String = row.get("issuer");
            let not_before: chrono::DateTime<Utc> = row.get("not_before");
            let not_after: chrono::DateTime<Utc> = row.get("not_after");
            let san_json: Option<String> = row.try_get("san_domains").ok();
            let hostnames_str: Option<String> = row.try_get("hostnames").ok();

            let san: Vec<String> = san_json
                .and_then(|j| serde_json::from_str(&j).ok())
                .unwrap_or_default();

            let hostnames: Vec<String> = hostnames_str
                .map(|s| s.split(',').map(|h| h.to_string()).collect())
                .unwrap_or_default();

            let common_name = extract_cn_from_subject(&subject);
            let now = Utc::now();
            let days_until_expiry = (not_after - now).num_days();

            CertificateSummary {
                fingerprint: fingerprint.clone(),
                common_name,
                san,
                issuer,
                valid_from: not_before,
                valid_until: not_after,
                days_until_expiry,
                is_expired: not_after < now,
                is_expiring_soon: (0..30).contains(&days_until_expiry),
                hostnames,
            }
        }
    };

    Ok(Json(cert))
}

/// Extract Common Name from X.509 subject string
fn extract_cn_from_subject(subject: &str) -> String {
    subject
        .split(',')
        .find(|part| part.trim().starts_with("CN="))
        .and_then(|cn_part| cn_part.split('=').nth(1))
        .unwrap_or(subject)
        .trim()
        .to_string()
}