jwt-hack 2.6.0

Hack the JWT (JSON Web Token) - A tool for JWT security testing and token manipulation
Documentation
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
use anyhow::Result;
use colored::Colorize;
use serde_json::Value;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;

use crate::jwt;
use crate::utils;

/// Options for encoding operations
#[allow(dead_code)]
pub struct EncodeOptions {
    pub secret: Option<String>,
    pub private_key_path: Option<PathBuf>,
    pub algorithm: String,
    pub no_signature: bool,
    pub headers: Vec<(String, String)>,
    pub compress: bool,
    pub jwe: bool,
}

/// Encodes JSON data into a JWT token with various algorithm and signing options
#[allow(clippy::too_many_arguments)]
pub fn execute(
    json_str: &str,
    secret: Option<&str>,
    private_key_path: Option<&PathBuf>,
    algorithm: &str,
    no_signature: bool,
    headers: &[(String, String)],
    compress: bool,
    jwe: bool,
) {
    if jwe {
        if let Err(e) = encode_jwe(json_str, secret) {
            utils::log_error(format!("JWE Encode Error: {e}"));
            utils::log_error("e.g jwt-hack encode {JSON} --jwe --secret={YOUR_SECRET}");
        }
    } else if let Err(e) = encode_json(
        json_str,
        secret,
        private_key_path,
        algorithm,
        no_signature,
        headers,
        compress,
    ) {
        utils::log_error(format!("JSON Encode Error: {e}"));
        utils::log_error("e.g jwt-hack encode {JSON} --secret={YOUR_SECRET}");
        utils::log_error(
            "or with RSA: jwt-hack encode {JSON} --private-key=private.pem --algorithm=RS256",
        );
    }
}

#[allow(clippy::too_many_arguments, deprecated)]
pub fn execute_json(
    json_str: &str,
    secret: Option<&str>,
    private_key_path: Option<&PathBuf>,
    algorithm: &str,
    no_signature: bool,
    headers: &[(String, String)],
    compress: bool,
    jwe: bool,
) -> Result<Value> {
    if jwe {
        let key = secret.unwrap_or("default_jwe_key");
        let token = jwt::encode_jwe_demo(json_str, key)?;
        return Ok(serde_json::json!({
            "success": true,
            "token_type": "jwe",
            "key_mgmt": "dir",
            "encryption": "A256GCM",
            "token": token
        }));
    }

    let claims: Value = serde_json::from_str(json_str)?;
    let header_map = create_header_map(headers);

    let (token, key_info, effective_alg) = if no_signature {
        let options = jwt::EncodeOptions {
            algorithm: "none",
            key_data: jwt::KeyData::None,
            header_params: header_map,
            compress_payload: compress,
        };
        (
            jwt::encode_with_options(&claims, &options)?,
            "none".to_string(),
            "none".to_string(),
        )
    } else if let Some(path) = private_key_path {
        let key_content = fs::read_to_string(path)?;
        let options = jwt::EncodeOptions {
            algorithm,
            key_data: jwt::KeyData::PrivateKeyPem(&key_content),
            header_params: header_map,
            compress_payload: compress,
        };
        (
            jwt::encode_with_options(&claims, &options)?,
            path.display().to_string(),
            algorithm.to_string(),
        )
    } else {
        let options = jwt::EncodeOptions {
            algorithm,
            key_data: jwt::KeyData::Secret(secret.unwrap_or("")),
            header_params: header_map,
            compress_payload: compress,
        };
        (
            jwt::encode_with_options(&claims, &options)?,
            if secret.unwrap_or("").is_empty() {
                "empty".to_string()
            } else {
                "****".to_string()
            },
            algorithm.to_string(),
        )
    };

    Ok(serde_json::json!({
        "success": true,
        "token_type": "jwt",
        "algorithm": effective_alg,
        "key": key_info,
        "headers": headers,
        "compress": compress,
        "token": token
    }))
}

/// Helper function to convert header vector to optional hashmap
fn create_header_map(headers: &[(String, String)]) -> Option<HashMap<&str, &str>> {
    if headers.is_empty() {
        None
    } else {
        let mut map = HashMap::new();
        for (key, value) in headers {
            map.insert(key.as_str(), value.as_str());
        }
        Some(map)
    }
}

/// Helper function to display encoding success information
fn display_encoding_result(
    token: &str,
    algorithm: &str,
    key_info: &str,
    headers: &[(String, String)],
) {
    println!("  {:<14}{}", "Algorithm".bold(), algorithm.cyan());
    println!("  {:<14}{}", "Key".bold(), key_info);

    if !headers.is_empty() {
        println!("\n  {}", "Headers".bold());
        for (key, value) in headers {
            println!("  {:<14}{}", key.to_string().dimmed(), value);
        }
    }

    println!("\n  {}", "Token".bold());
    println!("  {}", utils::format_jwt_token(token));
}

fn encode_json(
    json_str: &str,
    secret: Option<&str>,
    private_key_path: Option<&PathBuf>,
    algorithm: &str,
    no_signature: bool,
    headers: &[(String, String)],
    compress: bool,
) -> Result<()> {
    // Parse the input JSON into a Value object
    let claims: Value = serde_json::from_str(json_str)?;

    // Convert custom header key-value pairs into a hashmap for JWT encoding
    let header_map = create_header_map(headers);

    // Build JWT encoding options based on provided parameters
    // Private key option is handled separately due to Rust lifetime requirements
    let options = if no_signature {
        // Use 'none' algorithm (creates unsigned JWT token)
        jwt::EncodeOptions {
            algorithm: "none",
            key_data: jwt::KeyData::None,
            header_params: header_map,
            compress_payload: compress,
        }
    } else if let Some(path) = private_key_path {
        // Read RSA/EC private key from file for asymmetric algorithms
        let key_content = fs::read_to_string(path)?;

        // Create encoding options with the private key content (keeping ownership in this scope)
        let options = jwt::EncodeOptions {
            algorithm,
            key_data: jwt::KeyData::PrivateKeyPem(&key_content),
            header_params: header_map,
            compress_payload: compress,
        };

        // Encode JWT immediately while private key content is in scope
        let token = jwt::encode_with_options(&claims, &options)?;

        let key_info = format!("{} ({})", path.display(), "Private Key".dimmed());
        display_encoding_result(&token, algorithm, &key_info, headers);

        return Ok(());
    } else {
        // Default case: use HMAC with provided secret (or empty string)
        jwt::EncodeOptions {
            algorithm,
            key_data: jwt::KeyData::Secret(secret.unwrap_or("")),
            header_params: header_map,
            compress_payload: compress,
        }
    };

    // Encode the JWT token using the configured options
    let token = jwt::encode_with_options(&claims, &options)?;

    // Determine key information display based on signature type
    let key_info = if no_signature || secret.unwrap_or("").is_empty() {
        "None (unsigned)".dimmed().to_string()
    } else {
        "****".to_string()
    };

    display_encoding_result(&token, algorithm, &key_info, headers);

    Ok(())
}

#[allow(deprecated)]
fn encode_jwe(json_str: &str, secret: Option<&str>) -> Result<()> {
    let _claims: Value = serde_json::from_str(json_str)?;
    let key = secret.unwrap_or("default_jwe_key");
    let token = jwt::encode_jwe_demo(json_str, key)?;

    println!("  {:<14}{}", "Key Mgmt".bold(), "dir".cyan());
    println!("  {:<14}{}", "Encryption".bold(), "A256GCM".cyan());

    println!("\n  {}", "Token".bold());
    println!("  {}", token);

    Ok(())
}

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

    #[test]
    fn test_create_header_map() {
        // Test empty headers
        let headers = Vec::new();
        assert_eq!(create_header_map(&headers), None);

        // Test single header
        let headers = vec![("key1".to_string(), "value1".to_string())];
        let map = create_header_map(&headers).expect("Should return Some map");
        assert_eq!(map.len(), 1);
        assert_eq!(map.get("key1"), Some(&"value1"));

        // Test multiple headers
        let headers = vec![
            ("key1".to_string(), "value1".to_string()),
            ("key2".to_string(), "value2".to_string()),
        ];
        let map = create_header_map(&headers).expect("Should return Some map");
        assert_eq!(map.len(), 2);
        assert_eq!(map.get("key1"), Some(&"value1"));
        assert_eq!(map.get("key2"), Some(&"value2"));
    }

    #[test]
    fn test_execute_with_secret() {
        // Create a simple JSON payload
        let json_str = r#"{"sub":"1234567890","name":"John Doe"}"#;
        let secret = Some("test_secret");
        let private_key_path = None;
        let algorithm = "HS256";
        let no_signature = false;
        let headers = Vec::new();

        // Execute should not panic
        let result = std::panic::catch_unwind(|| {
            execute(
                json_str,
                secret,
                private_key_path,
                algorithm,
                no_signature,
                &headers,
                false, // compress
                false, // jwe
            );
        });

        assert!(result.is_ok(), "execute() panicked with valid parameters");
    }

    #[test]
    fn test_execute_with_no_signature() {
        // Create a simple JSON payload
        let json_str = r#"{"sub":"1234567890","name":"John Doe"}"#;
        let secret = None;
        let private_key_path = None;
        let algorithm = "none";
        let no_signature = true;
        let headers = Vec::new();

        // Execute should not panic
        let result = std::panic::catch_unwind(|| {
            execute(
                json_str,
                secret,
                private_key_path,
                algorithm,
                no_signature,
                &headers,
                false, // compress
                false, // jwe
            );
        });

        assert!(result.is_ok(), "execute() panicked with no signature");
    }

    #[test]
    fn test_execute_with_custom_headers() {
        // Create a simple JSON payload
        let json_str = r#"{"sub":"1234567890","name":"John Doe"}"#;
        let secret = Some("test_secret");
        let private_key_path = None;
        let algorithm = "HS256";
        let no_signature = false;
        let headers = vec![
            ("kid".to_string(), "1234".to_string()),
            ("typ".to_string(), "JWT+AT".to_string()),
        ];

        // Execute should not panic
        let result = std::panic::catch_unwind(|| {
            execute(
                json_str,
                secret,
                private_key_path,
                algorithm,
                no_signature,
                &headers,
                false, // compress
                false, // jwe
            );
        });

        assert!(result.is_ok(), "execute() panicked with custom headers");
    }

    #[test]
    fn test_execute_with_invalid_json() {
        // Create an invalid JSON payload
        let json_str = r#"{"sub":"1234567890","name":"John Doe"#; // Missing closing brace
        let secret = Some("test_secret");
        let private_key_path = None;
        let algorithm = "HS256";
        let no_signature = false;
        let headers = Vec::new();

        // Execute should handle the error and not panic
        let result = std::panic::catch_unwind(|| {
            execute(
                json_str,
                secret,
                private_key_path,
                algorithm,
                no_signature,
                &headers,
                false, // compress
                false, // jwe
            );
        });

        assert!(result.is_ok(), "execute() panicked with invalid JSON");
    }

    #[test]
    fn test_encode_json_with_rsa_key() {
        // This test requires creating a temporary RSA key file
        let temp_dir = tempdir().expect("Failed to create temp directory");
        let key_path = temp_dir.path().join("test_key.pem");

        // Write sample RSA private key (this is just a placeholder for testing)
        let sample_key = "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAnzyis1ZjfNB0bBgKFMSvvkTtwlvBsaJq7S5wA+kzeVOVpVWw\nkWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHcaT92whREFpLv9cj5lTeJSibyr/Mr\nm/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIytvHWTxZYEcXLgAXFuUuaS3uF9gEi\nNQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0e+lf4s4OxQawWD79J9/5d3Ry0vbV\n3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWbV6L11BWkpzGXSW4Hv43qa+GSYOD2\nQU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9MwIDAQAB\n-----END RSA PRIVATE KEY-----";
        std::fs::write(&key_path, sample_key).expect("Failed to write test key file");

        // Create a simple JSON payload
        let json_str = r#"{"sub":"1234567890","name":"John Doe"}"#;
        let secret = None;
        let private_key_path = Some(&key_path);
        let algorithm = "RS256";
        let no_signature = false;
        let headers = Vec::new();

        // Execute with RSA key shouldn't panic (even if the key is invalid for actual signing)
        let result = std::panic::catch_unwind(|| {
            encode_json(
                json_str,
                secret,
                private_key_path,
                algorithm,
                no_signature,
                &headers,
                false, // compress
            )
        });

        assert!(
            result.is_err() || result.is_ok(),
            "Properly handled RSA key attempt"
        );

        // Clean up
        temp_dir.close().expect("Failed to clean up temp directory");
    }

    #[test]
    fn test_execute_with_jwe_flag() {
        // Test JWE encoding execution
        let json_str = r#"{"sub":"test","name":"JWE User"}"#;
        let secret = Some("test_secret");
        let private_key_path = None;
        let algorithm = "HS256";
        let no_signature = false;
        let headers = Vec::new();
        let compress = false;
        let jwe = true;

        // Execute with JWE flag shouldn't panic
        let result = std::panic::catch_unwind(|| {
            execute(
                json_str,
                secret,
                private_key_path,
                algorithm,
                no_signature,
                &headers,
                compress,
                jwe,
            );
        });

        assert!(result.is_ok(), "execute() with JWE flag should not panic");
    }

    #[test]
    fn test_encode_jwe_function() {
        // Test the encode_jwe function directly
        let json_str = r#"{"sub":"test","name":"JWE User"}"#;
        let secret = Some("test_secret");

        let result = encode_jwe(json_str, secret);
        assert!(result.is_ok(), "encode_jwe should succeed with valid JSON");
    }

    #[test]
    fn test_execute_json_hs256() {
        let json_str = r#"{"sub":"123"}"#;
        let value = execute_json(json_str, Some("s"), None, "HS256", false, &[], false, false)
            .expect("encode json");
        assert_eq!(value.get("success").and_then(|v| v.as_bool()), Some(true));
        assert_eq!(
            value.get("token_type").and_then(|v| v.as_str()),
            Some("jwt")
        );
        assert!(value
            .get("token")
            .and_then(|v| v.as_str())
            .unwrap()
            .contains('.'));
    }
}