Repository navigation
ssl: add key logging with a shared host append sink #8655
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| use parking_lot::Mutex; | ||
| use std::{ | ||
| fs::{File, OpenOptions}, | ||
| io::{self, Write}, | ||
| path::Path, | ||
| }; | ||
|
|
||
| /// A replaceable append-only log destination, shared by its owner's consumers. | ||
| /// File replacement and complete record writes are serialized per destination. | ||
| #[derive(Debug, Default)] | ||
| pub struct AppendLog { | ||
| file: Mutex<Option<File>>, | ||
| } | ||
|
|
||
| impl AppendLog { | ||
| /// Close the old destination before opening its replacement. On failure the | ||
| /// log stays disabled. The header is written only to empty regular files. | ||
| pub fn set_path(&self, path: Option<&Path>, header: &[u8]) -> io::Result<()> { | ||
| let mut slot = self.file.lock(); | ||
| *slot = None; | ||
| let Some(path) = path else { | ||
| return Ok(()); | ||
| }; | ||
| let mut file = OpenOptions::new().create(true).append(true).open(path)?; | ||
| let metadata = file.metadata()?; | ||
| if metadata.is_file() && metadata.len() == 0 { | ||
| file.write_all(header)?; | ||
| file.flush()?; | ||
| } | ||
| *slot = Some(file); | ||
| Ok(()) | ||
| } | ||
|
|
||
| pub fn enabled(&self) -> bool { | ||
| self.file.lock().is_some() | ||
| } | ||
|
|
||
| /// Append and flush a complete record, or do nothing if disabled. | ||
| pub fn write(&self, record: &[u8]) -> io::Result<()> { | ||
| if let Some(file) = self.file.lock().as_mut() { | ||
| file.write_all(record)?; | ||
| file.flush()?; | ||
| } | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use core::sync::atomic::{AtomicUsize, Ordering}; | ||
| use std::path::PathBuf; | ||
|
|
||
| struct TestDir(PathBuf); | ||
|
|
||
| impl TestDir { | ||
| fn new() -> Self { | ||
| static NEXT: AtomicUsize = AtomicUsize::new(0); | ||
| loop { | ||
| let path = std::env::temp_dir().join(format!( | ||
| "rustpython-append-log-{}-{}", | ||
| std::process::id(), | ||
| NEXT.fetch_add(1, Ordering::Relaxed) | ||
| )); | ||
| match std::fs::create_dir(&path) { | ||
| Ok(()) => return Self(path), | ||
| Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, | ||
| Err(e) => panic!("create test directory: {e}"), | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Drop for TestDir { | ||
| fn drop(&mut self) { | ||
| std::fs::remove_dir_all(&self.0).unwrap(); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn append_replace_and_disable() { | ||
| let dir = TestDir::new(); | ||
| let first = dir.0.join("first"); | ||
| let second = dir.0.join("second"); | ||
| let log = AppendLog::default(); | ||
| assert!(!log.enabled()); | ||
| log.write(b"ignored\n").unwrap(); | ||
| log.set_path(Some(&first), b"header\n").unwrap(); | ||
| log.write(b"one\n").unwrap(); | ||
| log.set_path(Some(&first), b"header\n").unwrap(); | ||
| log.write(b"two\n").unwrap(); | ||
| log.set_path(Some(&second), b"header\n").unwrap(); | ||
| log.write(b"three\n").unwrap(); | ||
| log.set_path(None, b"header\n").unwrap(); | ||
| log.write(b"ignored\n").unwrap(); | ||
| assert!(!log.enabled()); | ||
| assert_eq!(std::fs::read(first).unwrap(), b"header\none\ntwo\n"); | ||
| assert_eq!(std::fs::read(second).unwrap(), b"header\nthree\n"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn failed_replacement_disables_the_old_destination() { | ||
| let dir = TestDir::new(); | ||
| let path = dir.0.join("log"); | ||
| let log = AppendLog::default(); | ||
| log.set_path(Some(&path), b"header\n").unwrap(); | ||
| assert!( | ||
| log.set_path(Some(&dir.0.join("missing/log")), b"header\n") | ||
| .is_err() | ||
| ); | ||
| assert!(!log.enabled()); | ||
| log.write(b"ignored\n").unwrap(); | ||
| assert_eq!(std::fs::read(path).unwrap(), b"header\n"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn concurrent_records_are_complete() { | ||
| let dir = TestDir::new(); | ||
| let path = dir.0.join("log"); | ||
| let log = AppendLog::default(); | ||
| log.set_path(Some(&path), b"").unwrap(); | ||
| std::thread::scope(|scope| { | ||
| for n in 0..4 { | ||
| let log = &log; | ||
| scope.spawn(move || { | ||
| for _ in 0..100 { | ||
| log.write(format!("{n}\n").as_bytes()).unwrap(); | ||
| } | ||
| }); | ||
| } | ||
| }); | ||
| let contents = std::fs::read_to_string(path).unwrap(); | ||
| assert_eq!(contents.lines().count(), 400); | ||
| for n in 0..4 { | ||
| assert_eq!( | ||
| contents | ||
| .lines() | ||
| .filter(|line| *line == n.to_string()) | ||
| .count(), | ||
| 100 | ||
| ); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| use alloc::sync::Arc; | ||
| use rustpython_host_env::fs::AppendLog; | ||
|
|
||
| pub(super) const HEADER: &[u8] = b"# TLS secrets log file, generated by OpenSSL / Python\n"; | ||
|
|
||
| /// Context-owned sink so existing and cached rustls configurations observe | ||
| /// changes to keylog_filename without rebuilding their session state. | ||
| #[derive(Debug, Default)] | ||
| pub(super) struct KeyLog(pub AppendLog); | ||
|
|
||
| /// Each connection follows its current Python context. This routing state must | ||
| /// not be shared through the context's config cache or an explicit SSLSession. | ||
| #[derive(Debug)] | ||
| pub(super) struct ConnectionKeyLog(parking_lot::RwLock<Arc<KeyLog>>); | ||
|
|
||
| impl ConnectionKeyLog { | ||
| pub(super) fn new(sink: Arc<KeyLog>) -> Self { | ||
| Self(parking_lot::RwLock::new(sink)) | ||
| } | ||
|
|
||
| pub(super) fn set_sink(&self, sink: Arc<KeyLog>) { | ||
| *self.0.write() = sink; | ||
| } | ||
| } | ||
|
|
||
| impl rustls::KeyLog for ConnectionKeyLog { | ||
| fn log(&self, label: &str, client_random: &[u8], secret: &[u8]) { | ||
| self.0.read().log(label, client_random, secret); | ||
| } | ||
|
|
||
| fn will_log(&self, label: &str) -> bool { | ||
| self.0.read().will_log(label) | ||
| } | ||
| } | ||
|
|
||
| fn format_record(label: &str, client_random: &[u8], secret: &[u8]) -> Vec<u8> { | ||
| const HEX: &[u8; 16] = b"0123456789abcdef"; | ||
| let mut line = Vec::with_capacity(label.len() + 2 * (client_random.len() + secret.len()) + 3); | ||
| line.extend_from_slice(label.as_bytes()); | ||
| for bytes in [client_random, secret] { | ||
| line.push(b' '); | ||
| for byte in bytes { | ||
| line.push(HEX[(byte >> 4) as usize]); | ||
| line.push(HEX[(byte & 0xf) as usize]); | ||
| } | ||
| } | ||
| line.push(b'\n'); | ||
| line | ||
| } | ||
|
|
||
| impl rustls::KeyLog for KeyLog { | ||
| fn log(&self, label: &str, client_random: &[u8], secret: &[u8]) { | ||
| // rustls has no error return from this callback. Opening the file fails | ||
| // eagerly in the setter; subsequent writes are best effort. | ||
| let _ = self.0.write(&format_record(label, client_random, secret)); | ||
| } | ||
|
|
||
| fn will_log(&self, _label: &str) -> bool { | ||
| self.0.enabled() | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn nss_record_has_two_lowercase_hex_fields() { | ||
| assert_eq!( | ||
| format_record("CLIENT_RANDOM", &[0x00, 0x1f, 0xa0, 0xff], &[0x09, 0xbc]), | ||
| b"CLIENT_RANDOM 001fa0ff 09bc\n" | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn disabled_by_default() { | ||
| use rustls::KeyLog as _; | ||
| assert!(!KeyLog::default().will_log("CLIENT_RANDOM")); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: RustPython/RustPython
Length of output: 2716
Sensitive Data Exposure (CWE-732): Incorrect Permission Assignment for Critical Resource
Reachability: Internal · Exploitability: Moderate
Create key-log files with restrictive permissions.
AppendLog::set_pathcreates files with platform-default permissions. Apply owner-only permissions or an equivalent ACL when creating and replacing the key-log file. Do not write TLS secrets to an existing file with broader permissions.🤖 Prompt for AI Agents