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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// Custom TLS Handshake - Build and send real TLS ClientHello messages
// Allows precise control over extensions, cipher suites, and TLS version

use crate::Result;
use crate::data::client_data::ClientProfile;
use crate::protocols::Protocol;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;

/// TLS Extension builder
#[derive(Debug, Clone)]
pub struct TlsExtension {
    pub extension_type: u16,
    pub data: Vec<u8>,
}

impl TlsExtension {
    /// Server Name Indication (SNI) extension
    pub fn server_name(hostname: &str) -> Self {
        let mut data = Vec::new();

        // Server name list length
        let list_len = hostname.len() + 5;
        data.push(((list_len >> 8) & 0xff) as u8);
        data.push((list_len & 0xff) as u8);

        // Name type: host_name (0)
        data.push(0x00);

        // Hostname length
        data.push(((hostname.len() >> 8) & 0xff) as u8);
        data.push((hostname.len() & 0xff) as u8);

        // Hostname
        data.extend_from_slice(hostname.as_bytes());

        Self {
            extension_type: 0x0000, // server_name
            data,
        }
    }

    /// Supported Groups (formerly Elliptic Curves)
    pub fn supported_groups(groups: &[u16]) -> Self {
        let mut data = Vec::new();

        // List length
        let list_len = groups.len() * 2;
        data.push(((list_len >> 8) & 0xff) as u8);
        data.push((list_len & 0xff) as u8);

        // Groups
        for &group in groups {
            data.push(((group >> 8) & 0xff) as u8);
            data.push((group & 0xff) as u8);
        }

        Self {
            extension_type: 0x000a, // supported_groups
            data,
        }
    }

    /// EC Point Formats
    pub fn ec_point_formats() -> Self {
        Self {
            extension_type: 0x000b, // ec_point_formats
            data: vec![0x01, 0x00], // uncompressed
        }
    }

    /// Signature Algorithms
    pub fn signature_algorithms(algorithms: &[(u8, u8)]) -> Self {
        let mut data = Vec::new();

        // Algorithms length
        let list_len = algorithms.len() * 2;
        data.push(((list_len >> 8) & 0xff) as u8);
        data.push((list_len & 0xff) as u8);

        // Algorithms
        for &(hash, sig) in algorithms {
            data.push(hash);
            data.push(sig);
        }

        Self {
            extension_type: 0x000d, // signature_algorithms
            data,
        }
    }

    /// ALPN (Application Layer Protocol Negotiation)
    pub fn alpn(protocols: &[&str]) -> Self {
        let mut data = Vec::new();

        // Calculate total length
        let list_len: usize = protocols.iter().map(|p| p.len() + 1).sum();

        // List length
        data.push(((list_len >> 8) & 0xff) as u8);
        data.push((list_len & 0xff) as u8);

        // Protocols
        for proto in protocols {
            data.push(proto.len() as u8);
            data.extend_from_slice(proto.as_bytes());
        }

        Self {
            extension_type: 0x0010, // application_layer_protocol_negotiation
            data,
        }
    }

    /// Supported Versions (TLS 1.3+)
    pub fn supported_versions(versions: &[u16]) -> Self {
        let mut data = Vec::new();

        // Versions length
        data.push((versions.len() * 2) as u8);

        // Versions
        for &version in versions {
            data.push(((version >> 8) & 0xff) as u8);
            data.push((version & 0xff) as u8);
        }

        Self {
            extension_type: 0x002b, // supported_versions
            data,
        }
    }

    /// Renegotiation Info (RFC 5746)
    pub fn renegotiation_info() -> Self {
        Self {
            extension_type: 0xff01, // renegotiation_info
            data: vec![0x00],       // Empty renegotiation info
        }
    }

    /// Extended Master Secret (RFC 7627)
    pub fn extended_master_secret() -> Self {
        Self {
            extension_type: 0x0017, // extended_master_secret
            data: vec![],
        }
    }

    /// Session Ticket (RFC 5077)
    pub fn session_ticket() -> Self {
        Self {
            extension_type: 0x0023, // session_ticket
            data: vec![],
        }
    }

    /// Encode extension to bytes
    pub fn encode(&self) -> Vec<u8> {
        // Extension type and length
        let mut bytes = vec![
            ((self.extension_type >> 8) & 0xff) as u8,
            (self.extension_type & 0xff) as u8,
            ((self.data.len() >> 8) & 0xff) as u8,
            (self.data.len() & 0xff) as u8,
        ];

        // Extension data
        bytes.extend_from_slice(&self.data);

        bytes
    }
}

/// Custom ClientHello builder
pub struct ClientHelloBuilder {
    version: u16,
    random: [u8; 32],
    cipher_suites: Vec<u16>,
    extensions: Vec<TlsExtension>,
}

impl ClientHelloBuilder {
    /// Create new ClientHello builder
    pub fn new(version: u16) -> Self {
        // Generate random
        let mut random = [0u8; 32];
        use rand::RngCore;
        rand::thread_rng().fill_bytes(&mut random);

        Self {
            version,
            random,
            cipher_suites: Vec::new(),
            extensions: Vec::new(),
        }
    }

    /// Add cipher suite
    pub fn cipher_suite(mut self, cipher: u16) -> Self {
        self.cipher_suites.push(cipher);
        self
    }

    /// Add multiple cipher suites
    pub fn cipher_suites(mut self, ciphers: &[u16]) -> Self {
        self.cipher_suites.extend_from_slice(ciphers);
        self
    }

    /// Add extension
    pub fn extension(mut self, extension: TlsExtension) -> Self {
        self.extensions.push(extension);
        self
    }

    /// Build from client profile
    pub fn from_profile(profile: &ClientProfile, hostname: &str) -> Self {
        let version = match profile.highest_protocol.as_deref() {
            Some("tls1_3") => 0x0303, // TLS 1.2 in record, 1.3 in extension
            Some("tls1_2") => 0x0303,
            Some("tls1_1") => 0x0302,
            Some("tls1") | Some("tls1_0") => 0x0301,
            _ => 0x0303, // Default to TLS 1.2
        };

        let mut builder = Self::new(version);

        // Add cipher suites from profile
        // For now, use a default set of modern ciphers
        // In a real implementation, would parse cipher_string
        let default_ciphers = vec![
            0x1301, // TLS_AES_128_GCM_SHA256
            0x1302, // TLS_AES_256_GCM_SHA384
            0x1303, // TLS_CHACHA20_POLY1305_SHA256
            0xc02f, // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
            0xc030, // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
            0xcca8, // TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
            0xcca9, // TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
            0xc02b, // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
            0xc02c, // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
        ];

        builder = builder.cipher_suites(&default_ciphers);

        // Add common extensions
        builder = builder
            .extension(TlsExtension::server_name(hostname))
            .extension(TlsExtension::supported_groups(&[
                0x001d, // x25519
                0x0017, // secp256r1
                0x0018, // secp384r1
            ]))
            .extension(TlsExtension::ec_point_formats())
            .extension(TlsExtension::signature_algorithms(&[
                (0x04, 0x03), // ecdsa_secp256r1_sha256
                (0x05, 0x03), // ecdsa_secp384r1_sha384
                (0x06, 0x03), // ecdsa_secp521r1_sha512
                (0x08, 0x04), // rsa_pss_rsae_sha256
                (0x08, 0x05), // rsa_pss_rsae_sha384
                (0x08, 0x06), // rsa_pss_rsae_sha512
                (0x04, 0x01), // rsa_pkcs1_sha256
                (0x05, 0x01), // rsa_pkcs1_sha384
                (0x06, 0x01), // rsa_pkcs1_sha512
            ]))
            .extension(TlsExtension::renegotiation_info())
            .extension(TlsExtension::extended_master_secret())
            .extension(TlsExtension::session_ticket());

        // Add ALPN with common protocols
        builder = builder.extension(TlsExtension::alpn(&["h2", "http/1.1"]));

        // Add supported_versions for TLS 1.3
        if matches!(profile.highest_protocol.as_deref(), Some("tls1_3")) {
            builder = builder.extension(TlsExtension::supported_versions(&[
                0x0304, // TLS 1.3
                0x0303, // TLS 1.2
            ]));
        }

        builder
    }

    /// Build the ClientHello message
    pub fn build(self) -> Vec<u8> {
        let mut hello = Vec::new();

        // TLS Record Layer
        hello.push(0x16); // Handshake
        hello.push(((self.version >> 8) & 0xff) as u8);
        hello.push((self.version & 0xff) as u8);

        // Record length placeholder
        let record_len_pos = hello.len();
        hello.push(0x00);
        hello.push(0x00);

        // Handshake header
        hello.push(0x01); // ClientHello

        // Handshake length placeholder
        let hs_len_pos = hello.len();
        hello.push(0x00);
        hello.push(0x00);
        hello.push(0x00);

        // Client Version
        hello.push(((self.version >> 8) & 0xff) as u8);
        hello.push((self.version & 0xff) as u8);

        // Random
        hello.extend_from_slice(&self.random);

        // Session ID (empty)
        hello.push(0x00);

        // Cipher Suites
        let cipher_len = self.cipher_suites.len() * 2;
        hello.push(((cipher_len >> 8) & 0xff) as u8);
        hello.push((cipher_len & 0xff) as u8);

        for cipher in &self.cipher_suites {
            hello.push(((cipher >> 8) & 0xff) as u8);
            hello.push((cipher & 0xff) as u8);
        }

        // Compression Methods
        hello.push(0x01); // Length
        hello.push(0x00); // null compression

        // Extensions
        if !self.extensions.is_empty() {
            let ext_start = hello.len();
            hello.push(0x00);
            hello.push(0x00); // Extensions length placeholder

            for ext in &self.extensions {
                hello.extend_from_slice(&ext.encode());
            }

            // Update extensions length
            let ext_len = hello.len() - ext_start - 2;
            hello[ext_start] = ((ext_len >> 8) & 0xff) as u8;
            hello[ext_start + 1] = (ext_len & 0xff) as u8;
        }

        // Update handshake length
        let hs_len = hello.len() - hs_len_pos - 3;
        hello[hs_len_pos] = ((hs_len >> 16) & 0xff) as u8;
        hello[hs_len_pos + 1] = ((hs_len >> 8) & 0xff) as u8;
        hello[hs_len_pos + 2] = (hs_len & 0xff) as u8;

        // Update record length
        let record_len = hello.len() - record_len_pos - 2;
        hello[record_len_pos] = ((record_len >> 8) & 0xff) as u8;
        hello[record_len_pos + 1] = (record_len & 0xff) as u8;

        hello
    }
}

/// Extended handshake information from ServerHello
#[derive(Debug, Clone)]
pub struct ServerHelloInfo {
    pub protocol: Protocol,
    pub cipher: String,
    pub alpn: Option<String>,
    pub key_exchange_group: Option<u16>,
}

/// Perform custom TLS handshake
pub async fn perform_custom_handshake(
    stream: &mut TcpStream,
    client_hello: &[u8],
    timeout_duration: Duration,
) -> Result<ServerHelloInfo> {
    use tokio::time::timeout;

    // Send ClientHello
    timeout(timeout_duration, stream.write_all(client_hello)).await??;

    // Read ServerHello and extract info
    let mut buffer = vec![0u8; 16384];
    let n = timeout(timeout_duration, stream.read(&mut buffer)).await??;

    if n == 0 {
        return Err(crate::error::TlsError::ConnectionClosed {
            details: "Server closed connection".to_string(),
        });
    }

    // Parse ServerHello with extended info
    parse_server_hello_extended(&buffer[..n])
}

/// Parse ServerHello with extended information (ALPN, key exchange)
fn parse_server_hello_extended(data: &[u8]) -> Result<ServerHelloInfo> {
    // Look for ServerHello (0x02)
    for i in 0..data.len().saturating_sub(10) {
        if data[i] == 0x16 && // Handshake
           i + 5 < data.len() &&
           data[i + 5] == 0x02
        {
            // ServerHello found

            // Extract version (bytes 9-10 in ServerHello)
            if i + 11 < data.len() {
                let version = u16::from_be_bytes([data[i + 9], data[i + 10]]);
                let mut protocol = match version {
                    0x0304 => Protocol::TLS13,
                    0x0303 => Protocol::TLS12,
                    0x0302 => Protocol::TLS11,
                    0x0301 => Protocol::TLS10,
                    0x0300 => Protocol::SSLv3,
                    _ => Protocol::TLS12,
                };

                // Extract cipher suite (after 32-byte random + session ID)
                let mut cipher_name = "Unknown".to_string();
                let mut alpn = None;
                let mut key_exchange_group = None;

                if i + 44 < data.len() {
                    let session_id_len = data[i + 43] as usize;
                    let cipher_pos = i + 44 + session_id_len;

                    if cipher_pos + 1 < data.len() {
                        let cipher = u16::from_be_bytes([data[cipher_pos], data[cipher_pos + 1]]);
                        cipher_name = format_cipher_name(cipher);

                        // Parse extensions (after cipher suite + compression method)
                        let ext_start = cipher_pos + 2 + 1; // +2 for cipher, +1 for compression
                        if ext_start + 2 < data.len() {
                            let ext_len =
                                u16::from_be_bytes([data[ext_start], data[ext_start + 1]]) as usize;
                            let mut ext_pos = ext_start + 2;
                            let ext_end = ext_pos + ext_len;

                            // Parse each extension
                            while ext_pos + 4 <= ext_end && ext_pos + 4 <= data.len() {
                                let ext_type =
                                    u16::from_be_bytes([data[ext_pos], data[ext_pos + 1]]);
                                let ext_data_len =
                                    u16::from_be_bytes([data[ext_pos + 2], data[ext_pos + 3]])
                                        as usize;
                                ext_pos += 4;

                                if ext_pos + ext_data_len > data.len() {
                                    break;
                                }

                                match ext_type {
                                    0x0010 => {
                                        // ALPN extension
                                        if ext_data_len >= 3 {
                                            let list_len = u16::from_be_bytes([
                                                data[ext_pos],
                                                data[ext_pos + 1],
                                            ])
                                                as usize;
                                            if ext_pos + 2 + list_len <= data.len() {
                                                let proto_len = data[ext_pos + 2] as usize;
                                                if ext_pos + 3 + proto_len <= data.len() {
                                                    alpn = String::from_utf8(
                                                        data[ext_pos + 3..ext_pos + 3 + proto_len]
                                                            .to_vec(),
                                                    )
                                                    .ok();
                                                }
                                            }
                                        }
                                    }
                                    0x002b => {
                                        // Supported versions (TLS 1.3)
                                        if ext_data_len >= 2 {
                                            let selected_version = u16::from_be_bytes([
                                                data[ext_pos],
                                                data[ext_pos + 1],
                                            ]);
                                            protocol = match selected_version {
                                                0x0304 => Protocol::TLS13,
                                                0x0303 => Protocol::TLS12,
                                                _ => protocol,
                                            };
                                        }
                                    }
                                    0x0033 => {
                                        // Key share (TLS 1.3)
                                        if ext_data_len >= 2 {
                                            key_exchange_group = Some(u16::from_be_bytes([
                                                data[ext_pos],
                                                data[ext_pos + 1],
                                            ]));
                                        }
                                    }
                                    _ => {}
                                }

                                ext_pos += ext_data_len;
                            }
                        }
                    }
                }

                return Ok(ServerHelloInfo {
                    protocol,
                    cipher: cipher_name,
                    alpn,
                    key_exchange_group,
                });
            }
        }
    }

    Err(crate::error::TlsError::InvalidHandshake {
        details: "Could not parse ServerHello".to_string(),
    })
}

/// Format cipher suite code to human-readable name
fn format_cipher_name(cipher: u16) -> String {
    match cipher {
        // TLS 1.3 cipher suites
        0x1301 => "TLS_AES_128_GCM_SHA256".to_string(),
        0x1302 => "TLS_AES_256_GCM_SHA384".to_string(),
        0x1303 => "TLS_CHACHA20_POLY1305_SHA256".to_string(),
        0x1304 => "TLS_AES_128_CCM_SHA256".to_string(),
        0x1305 => "TLS_AES_128_CCM_8_SHA256".to_string(),

        // TLS 1.2 ECDHE cipher suites
        0xc02b => "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256".to_string(),
        0xc02c => "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384".to_string(),
        0xc02f => "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256".to_string(),
        0xc030 => "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384".to_string(),
        0xcca8 => "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256".to_string(),
        0xcca9 => "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256".to_string(),

        // Other common cipher suites
        0x009e => "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256".to_string(),
        0x009f => "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384".to_string(),

        // Default: hex representation
        _ => format!("0x{:04X}", cipher),
    }
}

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

    #[test]
    fn test_sni_extension() {
        let ext = TlsExtension::server_name("example.com");
        assert_eq!(ext.extension_type, 0x0000);
        let encoded = ext.encode();
        assert!(encoded.len() > 4);
    }

    #[test]
    fn test_client_hello_builder() {
        let hello = ClientHelloBuilder::new(0x0303)
            .cipher_suite(0xc02f)
            .cipher_suite(0xc030)
            .extension(TlsExtension::server_name("test.com"))
            .build();

        assert_eq!(hello[0], 0x16); // Handshake record
        assert_eq!(hello[5], 0x01); // ClientHello
        assert!(hello.len() > 50);
    }
}