Skip to content
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

gpg_signing: fix EPIPE handling in verify path #3186

Merged
merged 4 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 41 additions & 30 deletions lib/src/gpg_signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@

#![allow(missing_docs)]

use std::ffi::{OsStr, OsString};
use std::ffi::OsString;
use std::fmt::Debug;
use std::io::Write;
use std::process::{Command, ExitStatus, Stdio};
use std::str;
use std::{io, str};

use thiserror::Error;

Expand Down Expand Up @@ -66,6 +66,33 @@ fn parse_gpg_verify_output(
.ok_or(SignError::InvalidSignatureFormat)
}

fn run_sign_command(command: &mut Command, input: &[u8]) -> Result<Vec<u8>, GpgError> {
let process = command.stderr(Stdio::piped()).spawn()?;
process.stdin.as_ref().unwrap().write_all(input)?;
let output = process.wait_with_output()?;
if output.status.success() {
Ok(output.stdout)
} else {
Err(GpgError::Command {
exit_status: output.status,
stderr: String::from_utf8_lossy(&output.stderr).trim_end().into(),
})
}
}

fn run_verify_command(command: &mut Command, input: &[u8]) -> Result<Vec<u8>, GpgError> {
let process = command.stderr(Stdio::null()).spawn()?;
let write_result = process.stdin.as_ref().unwrap().write_all(input);
let output = process.wait_with_output()?;
match write_result {
Ok(()) => Ok(output.stdout),
// If the signature format is invalid, gpg will terminate early. Writing
// more input data will fail in that case.
Err(err) if err.kind() == io::ErrorKind::BrokenPipe => Ok(vec![]),
Err(err) => Err(err.into()),
}
}

#[derive(Debug)]
pub struct GpgBackend {
program: OsString,
Expand Down Expand Up @@ -117,24 +144,13 @@ impl GpgBackend {
)
}

fn run(&self, input: &[u8], args: &[&OsStr], check: bool) -> Result<Vec<u8>, GpgError> {
let process = Command::new(&self.program)
fn create_command(&self) -> Command {
let mut command = Command::new(&self.program);
command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(if check { Stdio::piped() } else { Stdio::null() })
.args(&self.extra_args)
.args(args)
.spawn()?;
process.stdin.as_ref().unwrap().write_all(input)?;
let output = process.wait_with_output()?;
if check && !output.status.success() {
Err(GpgError::Command {
exit_status: output.status,
stderr: String::from_utf8_lossy(&output.stderr).trim_end().into(),
})
} else {
Ok(output.stdout)
}
.args(&self.extra_args);
command
}
}

Expand All @@ -149,8 +165,8 @@ impl SigningBackend for GpgBackend {

fn sign(&self, data: &[u8], key: Option<&str>) -> Result<Vec<u8>, SignError> {
Ok(match key {
Some(key) => self.run(data, &["-abu".as_ref(), key.as_ref()], true)?,
None => self.run(data, &["-ab".as_ref()], true)?,
Some(key) => run_sign_command(self.create_command().args(["-abu", key]), data)?,
None => run_sign_command(self.create_command().arg("-ab"), data)?,
})
}

Expand All @@ -164,17 +180,12 @@ impl SigningBackend for GpgBackend {

let sig_path = signature_file.into_temp_path();

let output = self.run(
let output = run_verify_command(
self.create_command()
.args(["--keyid-format=long", "--status-fd=1", "--verify"])
.arg(&sig_path)
.arg("-"),
data,
&[
"--keyid-format=long".as_ref(),
"--status-fd=1".as_ref(),
"--verify".as_ref(),
// the only reason we have those .as_refs transmuting to &OsStr everywhere
sig_path.as_os_str(),
"-".as_ref(),
],
false,
)?;

parse_gpg_verify_output(&output, self.allow_expired_keys)
Expand Down
10 changes: 9 additions & 1 deletion lib/tests/test_gpg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,16 @@ fn invalid_signature() {

super duper invalid
-----END PGP SIGNATURE-----";

// Small data: gpg command will exit late.
assert_matches!(
backend.verify(b"a", signature),
Err(SignError::InvalidSignatureFormat)
);

// Large data: gpg command will exit early because the signature is invalid.
assert_matches!(
backend.verify(b"hello world", signature),
backend.verify(&b"a".repeat(100 * 1024), signature),
Err(SignError::InvalidSignatureFormat)
);
}