| 1 |
/// Common file handling support. |
| 2 |
|
| 3 |
use std::{ |
| 4 |
io::{self, Write, stdout}, |
| 5 |
path::{Path, PathBuf}, |
| 6 |
}; |
| 7 |
|
| 8 |
use anyhow::{Context, Result}; |
| 9 |
|
| 10 |
use tempfile::NamedTempFile; |
| 11 |
|
| 12 |
use sequoia_openpgp::{ |
| 13 |
self as openpgp, |
| 14 |
armor, |
| 15 |
serialize::stream::{Armorer, Message}, |
| 16 |
}; |
| 17 |
|
| 18 |
use crate::{ |
| 19 |
cli::types::FileOrStdout, |
| 20 |
sq::Sq, |
| 21 |
}; |
| 22 |
|
| 23 |
impl FileOrStdout { |
| 24 |
/// Returns whether the stream is stdout. |
| 25 |
pub fn is_stdout(&self) -> bool { |
| 26 |
self.path().is_none() |
| 27 |
} |
| 28 |
|
| 29 |
/// Opens the file (or stdout) for writing data that is safe for |
| 30 |
/// non-interactive use. |
| 31 |
/// |
| 32 |
/// This is suitable for any kind of OpenPGP data, decrypted or |
| 33 |
/// authenticated payloads. |
| 34 |
pub fn create_safe( |
| 35 |
&self, |
| 36 |
sq: &Sq, |
| 37 |
) -> Result<Box<dyn Write + Sync + Send>> { |
| 38 |
self.create(sq) |
| 39 |
} |
| 40 |
|
| 41 |
/// Opens the file (or stdout) for writing data that is NOT safe |
| 42 |
/// for non-interactive use. |
| 43 |
pub fn create_unsafe( |
| 44 |
&self, |
| 45 |
sq: &Sq, |
| 46 |
) -> Result<Box<dyn Write + Sync + Send>> { |
| 47 |
self.create(sq) |
| 48 |
} |
| 49 |
|
| 50 |
/// Opens the file (or stdout) for writing data that is safe for |
| 51 |
/// non-interactive use because it is an OpenPGP data stream. |
| 52 |
/// |
| 53 |
/// Emitting armored data with the label `armor::Kind::SecretKey` |
| 54 |
/// implicitly configures this output to emit secret keys. |
| 55 |
pub fn create_pgp_safe<'a>( |
| 56 |
&self, |
| 57 |
sq: &Sq, |
| 58 |
binary: bool, |
| 59 |
kind: armor::Kind, |
| 60 |
) -> Result<Message<'a>> { |
| 61 |
// Allow secrets to be emitted if the armor label says secret |
| 62 |
// key. |
| 63 |
let mut o = self.clone(); |
| 64 |
if kind == armor::Kind::SecretKey { |
| 65 |
o = o.for_secrets(); |
| 66 |
} |
| 67 |
let sink = o.create_safe(sq)?; |
| 68 |
|
| 69 |
let mut message = Message::new(sink); |
| 70 |
if ! binary { |
| 71 |
message = Armorer::new(message).kind(kind).build()?; |
| 72 |
} |
| 73 |
Ok(message) |
| 74 |
} |
| 75 |
|
| 76 |
/// Helper function, do not use directly. Instead, use create_or_stdout_safe |
| 77 |
/// or create_or_stdout_unsafe. |
| 78 |
fn create(&self, sq: &Sq) -> Result<Box<dyn Write + Sync + Send>> { |
| 79 |
let sink = self._create_sink(sq)?; |
| 80 |
if self.is_for_secrets() || ! cfg!(debug_assertions) { |
| 81 |
// We either expect secrets, or we are in release mode. |
| 82 |
Ok(sink) |
| 83 |
} else { |
| 84 |
// In debug mode, if we don't expect secrets, scan the |
| 85 |
// output for inadvertently leaked secret keys. |
| 86 |
Ok(Box::new(SecretLeakDetector::new(sink))) |
| 87 |
} |
| 88 |
} |
| 89 |
fn _create_sink(&self, sq: &Sq) -> Result<Box<dyn Write + Sync + Send>> |
| 90 |
{ |
| 91 |
if let Some(path) = self.path() { |
| 92 |
if !path.exists() || sq.overwrite { |
| 93 |
Ok(Box::new( |
| 94 |
PartFileWriter::create(path) |
| 95 |
.context("Failed to create output file")?, |
| 96 |
)) |
| 97 |
} else { |
| 98 |
Err(anyhow::anyhow!( |
| 99 |
"File {} exists, use \"sq --overwrite ...\" to overwrite", |
| 100 |
path.display(), |
| 101 |
)) |
| 102 |
} |
| 103 |
} else { |
| 104 |
Ok(Box::new(stdout())) |
| 105 |
} |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
/// A writer that writes to a temporary file first, then persists the |
| 110 |
/// file under the desired name. |
| 111 |
/// |
| 112 |
/// This has two benefits. First, consumers only see the file once we |
| 113 |
/// are done writing to it, i.e. they don't see a partial file. |
| 114 |
/// |
| 115 |
/// Second, we guarantee not to overwrite the file until the operation |
| 116 |
/// is finished. Therefore, it is safe to use the same file as input |
| 117 |
/// and output. |
| 118 |
struct PartFileWriter { |
| 119 |
path: PathBuf, |
| 120 |
sink: Option<NamedTempFile>, |
| 121 |
} |
| 122 |
|
| 123 |
impl io::Write for PartFileWriter { |
| 124 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 125 |
self.sink()?.write(buf) |
| 126 |
} |
| 127 |
|
| 128 |
fn flush(&mut self) -> io::Result<()> { |
| 129 |
self.sink()?.flush() |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
impl Drop for PartFileWriter { |
| 134 |
fn drop(&mut self) { |
| 135 |
if let Err(e) = self.persist() { |
| 136 |
weprintln!(initial_indent = "Error: ", "{}", e); |
| 137 |
std::process::exit(1); |
| 138 |
} |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
impl PartFileWriter { |
| 143 |
/// Opens a file for writing. |
| 144 |
/// |
| 145 |
/// The file will be created under a different name in the target |
| 146 |
/// directory, and will only be renamed to `path` once |
| 147 |
/// [`PartFileWriter::persist`] is called or the object is |
| 148 |
/// dropped. |
| 149 |
pub fn create<P: AsRef<Path>>(path: P) -> Result<PartFileWriter> { |
| 150 |
let path = path.as_ref().to_path_buf(); |
| 151 |
let parent = path.parent() |
| 152 |
.ok_or(anyhow::anyhow!("cannot write to the root"))?; |
| 153 |
let file_name = path.file_name() |
| 154 |
.ok_or(anyhow::anyhow!("cannot write to .."))?; |
| 155 |
|
| 156 |
let mut sink = tempfile::Builder::new(); |
| 157 |
|
| 158 |
// By default, temporary files are 0x600 on Unix. But, we |
| 159 |
// rather want created files to respect umask. |
| 160 |
platform! { |
| 161 |
unix => { |
| 162 |
use std::os::unix::fs::PermissionsExt; |
| 163 |
let all_read_write = |
| 164 |
std::fs::Permissions::from_mode(0o666); |
| 165 |
|
| 166 |
// The permissions will be masked by the user's umask. |
| 167 |
sink.permissions(all_read_write); |
| 168 |
}, |
| 169 |
windows => { |
| 170 |
// We cannot do the same on Windows. |
| 171 |
}, |
| 172 |
} |
| 173 |
|
| 174 |
let sink = sink |
| 175 |
.prefix(file_name) |
| 176 |
.suffix(".part") |
| 177 |
.tempfile_in(parent)?; |
| 178 |
|
| 179 |
Ok(PartFileWriter { |
| 180 |
path, |
| 181 |
sink: Some(sink), |
| 182 |
}) |
| 183 |
} |
| 184 |
|
| 185 |
/// Returns a mutable reference to the file, or an error. |
| 186 |
fn sink(&mut self) -> io::Result<&mut NamedTempFile> { |
| 187 |
self.sink.as_mut().ok_or(io::Error::new( |
| 188 |
io::ErrorKind::Other, |
| 189 |
anyhow::anyhow!("file already persisted"))) |
| 190 |
} |
| 191 |
|
| 192 |
/// Persists the file under its final name. |
| 193 |
pub fn persist(&mut self) -> Result<()> { |
| 194 |
if let Some(file) = self.sink.take() { |
| 195 |
file.persist(&self.path)?; |
| 196 |
} |
| 197 |
Ok(()) |
| 198 |
} |
| 199 |
} |
| 200 |
|
| 201 |
/// A writer that buffers all data, and scans for secret keys on drop. |
| 202 |
/// |
| 203 |
/// This is used to assert that we only write secret keys in places |
| 204 |
/// where we expect that. As this buffers all data, and has a |
| 205 |
/// performance impact, we only do this in debug builds. |
| 206 |
struct SecretLeakDetector<W: io::Write + Send + Sync> { |
| 207 |
sink: W, |
| 208 |
data: Vec<u8>, |
| 209 |
} |
| 210 |
|
| 211 |
impl<W: io::Write + Send + Sync> io::Write for SecretLeakDetector<W> { |
| 212 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 213 |
let n = self.sink.write(buf)?; |
| 214 |
self.data.extend_from_slice(&buf[..n]); |
| 215 |
Ok(n) |
| 216 |
} |
| 217 |
|
| 218 |
fn flush(&mut self) -> io::Result<()> { |
| 219 |
self.sink.flush() |
| 220 |
} |
| 221 |
} |
| 222 |
|
| 223 |
impl<W: io::Write + Send + Sync> Drop for SecretLeakDetector<W> { |
| 224 |
fn drop(&mut self) { |
| 225 |
let _ = self.detect_leaks(); |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
impl<W: io::Write + Send + Sync> SecretLeakDetector<W> { |
| 230 |
/// Creates a shim around `sink` that scans for inadvertently |
| 231 |
/// leaked secret keys. |
| 232 |
fn new(sink: W) -> Self { |
| 233 |
SecretLeakDetector { |
| 234 |
sink, |
| 235 |
data: Vec::with_capacity(4096), |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
/// Scans the buffered data for secret keys, panic'ing if one is |
| 240 |
/// found. |
| 241 |
fn detect_leaks(&self) -> Result<()> { |
| 242 |
use openpgp::Packet; |
| 243 |
use openpgp::parse::{Parse, PacketParserResult, PacketParser}; |
| 244 |
|
| 245 |
let mut ppr = PacketParser::from_bytes(&self.data)?; |
| 246 |
while let PacketParserResult::Some(pp) = ppr { |
| 247 |
match &pp.packet { |
| 248 |
Packet::SecretKey(_) | Packet::SecretSubkey(_) => |
| 249 |
panic!("Leaked secret key: {:?}", pp.packet), |
| 250 |
_ => (), |
| 251 |
} |
| 252 |
let (_, next_ppr) = pp.recurse()?; |
| 253 |
ppr = next_ppr; |
| 254 |
} |
| 255 |
|
| 256 |
Ok(()) |
| 257 |
} |
| 258 |
} |