| 1 |
use std::path::PathBuf; |
| 2 |
use std::time::SystemTime; |
| 3 |
|
| 4 |
use anyhow::Context; |
| 5 |
|
| 6 |
use sequoia_openpgp as openpgp; |
| 7 |
use openpgp::armor; |
| 8 |
use openpgp::cert::amalgamation::ValidAmalgamation; |
| 9 |
use openpgp::cert::amalgamation::ValidateAmalgamation; |
| 10 |
use openpgp::crypto; |
| 11 |
use openpgp::packet::signature::SignatureBuilder; |
| 12 |
use openpgp::packet::signature::subpacket::NotationData; |
| 13 |
use openpgp::policy::Policy; |
| 14 |
use openpgp::serialize::stream::Compressor; |
| 15 |
use openpgp::serialize::stream::Encryptor; |
| 16 |
use openpgp::serialize::stream::LiteralWriter; |
| 17 |
use openpgp::serialize::stream::Message; |
| 18 |
use openpgp::serialize::stream::Signer; |
| 19 |
use openpgp::serialize::stream::padding::Padder; |
| 20 |
use openpgp::types::CompressionAlgorithm; |
| 21 |
use openpgp::types::KeyFlags; |
| 22 |
use openpgp::types::RevocationStatus; |
| 23 |
use openpgp::types::SignatureType; |
| 24 |
|
| 25 |
use crate::Convert; |
| 26 |
use crate::Result; |
| 27 |
use crate::Sq; |
| 28 |
use crate::cli::types::EncryptPurpose; |
| 29 |
use crate::cli::types::FileOrStdin; |
| 30 |
use crate::cli; |
| 31 |
use crate::common::password; |
| 32 |
use crate::output::pluralize::Pluralize; |
| 33 |
use crate::print_error_chain; |
| 34 |
use crate::sq::TrustThreshold; |
| 35 |
|
| 36 |
use crate::commands::CompressionMode; |
| 37 |
|
| 38 |
pub fn dispatch(sq: Sq, command: cli::encrypt::Command) -> Result<()> { |
| 39 |
tracer!(TRACE, "decrypt::dispatch"); |
| 40 |
|
| 41 |
let (recipients, errors) = sq.resolve_certs( |
| 42 |
&command.recipients, TrustThreshold::Full)?; |
| 43 |
for error in errors.iter() { |
| 44 |
print_error_chain(error); |
| 45 |
} |
| 46 |
if ! errors.is_empty() { |
| 47 |
return Err(anyhow::anyhow!("Failed to resolve certificates")); |
| 48 |
} |
| 49 |
|
| 50 |
let output = command.output.create_pgp_safe( |
| 51 |
&sq, |
| 52 |
command.binary, |
| 53 |
armor::Kind::Message, |
| 54 |
)?; |
| 55 |
|
| 56 |
let signers = |
| 57 |
sq.resolve_certs_or_fail(&command.signers, |
| 58 |
TrustThreshold::Full)?; |
| 59 |
let signers = sq.get_signing_keys(&signers, None)?; |
| 60 |
|
| 61 |
let notations = command.signature_notations.parse()?; |
| 62 |
|
| 63 |
if signers.is_empty() && ! notations.is_empty() { |
| 64 |
return Err(anyhow::anyhow!("--signature-notation requires signers, \ |
| 65 |
but none are given")); |
| 66 |
} |
| 67 |
|
| 68 |
// Profile. XXX: Currently, this is not actionable. |
| 69 |
let _profile = sq.config.encrypt_profile( |
| 70 |
&command.profile, command.profile_source); |
| 71 |
|
| 72 |
encrypt( |
| 73 |
&sq, |
| 74 |
sq.policy, |
| 75 |
command.input, |
| 76 |
output, |
| 77 |
command.recipients.with_passwords(), |
| 78 |
command.recipients.with_password_files(), |
| 79 |
&recipients, |
| 80 |
signers, |
| 81 |
notations, |
| 82 |
command.mode, |
| 83 |
command.compression, |
| 84 |
Some(sq.time), |
| 85 |
command.use_expired_subkey, |
| 86 |
command.set_metadata_filename, |
| 87 |
)?; |
| 88 |
|
| 89 |
Ok(()) |
| 90 |
} |
| 91 |
|
| 92 |
pub fn encrypt<'a, 'b: 'a>( |
| 93 |
sq: &Sq, |
| 94 |
policy: &'b dyn Policy, |
| 95 |
input: FileOrStdin, |
| 96 |
message: Message<'a>, |
| 97 |
npasswords: usize, |
| 98 |
password_files: &[PathBuf], |
| 99 |
recipients: &'b [openpgp::Cert], |
| 100 |
mut signers: Vec<(openpgp::Cert, Box<dyn crypto::Signer + Send + Sync>)>, |
| 101 |
notations: Vec<(bool, NotationData)>, |
| 102 |
mode: EncryptPurpose, |
| 103 |
compression: CompressionMode, |
| 104 |
time: Option<SystemTime>, |
| 105 |
use_expired_subkey: bool, |
| 106 |
set_metadata_filename: Option<String>, |
| 107 |
) |
| 108 |
-> Result<()> |
| 109 |
{ |
| 110 |
make_qprintln!(sq.quiet()); |
| 111 |
|
| 112 |
let mut passwords: Vec<crypto::Password> = Vec::with_capacity(npasswords); |
| 113 |
for n in 0..npasswords { |
| 114 |
let nprompt; |
| 115 |
let password = password::prompt_for_new( |
| 116 |
sq, |
| 117 |
if npasswords > 1 { |
| 118 |
nprompt = format!("message (password {})", n + 1); |
| 119 |
&nprompt |
| 120 |
} else { |
| 121 |
"message" |
| 122 |
}, |
| 123 |
)?; |
| 124 |
passwords.push(password); |
| 125 |
} |
| 126 |
|
| 127 |
for password_file in password_files { |
| 128 |
let password = std::fs::read(&password_file) |
| 129 |
.with_context(|| { |
| 130 |
format!("Reading {}", password_file.display()) |
| 131 |
})?; |
| 132 |
passwords.push(password.into()); |
| 133 |
} |
| 134 |
|
| 135 |
if recipients.len() + passwords.len() == 0 { |
| 136 |
return Err(anyhow::anyhow!( |
| 137 |
"Neither recipient nor password given")); |
| 138 |
} |
| 139 |
|
| 140 |
let mode = KeyFlags::from(mode); |
| 141 |
|
| 142 |
qprintln!("Composing a message..."); |
| 143 |
|
| 144 |
// Track whether we have a secret for one of the encryption |
| 145 |
// subkeys. |
| 146 |
let mut have_one_secret = false; |
| 147 |
|
| 148 |
// Build a vector of recipients to hand to Encryptor. |
| 149 |
let mut recipient_subkeys = Vec::new(); |
| 150 |
for cert in recipients.iter() { |
| 151 |
// XXX: In this block, instead of using sq.best_userid(&cert, |
| 152 |
// true), it'd be nice to use the cert designator that the |
| 153 |
// user used, instead or additionally. |
| 154 |
|
| 155 |
let mut encryption_keys = 0; |
| 156 |
let mut bad: Vec<String> = Vec::new(); |
| 157 |
|
| 158 |
// This cert's subkeys we selected for encryption. |
| 159 |
let mut selected_keys = Vec::new(); |
| 160 |
|
| 161 |
// As a fallback, we may consider expired keys. |
| 162 |
let mut expired_keys = Vec::new(); |
| 163 |
|
| 164 |
if let RevocationStatus::Revoked(_) |
| 165 |
= cert.revocation_status(policy, time) |
| 166 |
{ |
| 167 |
return Err(anyhow::anyhow!( |
| 168 |
"Can't encrypt to {}, {}: it is revoked", |
| 169 |
cert.fingerprint(), |
| 170 |
sq.best_userid(&cert, true).display())); |
| 171 |
} |
| 172 |
|
| 173 |
let vc = cert.with_policy(policy, time) |
| 174 |
.with_context(|| { |
| 175 |
format!("{}, {} is not valid according to the \ |
| 176 |
current policy", |
| 177 |
cert.fingerprint(), |
| 178 |
sq.best_userid(&cert, true).display()) |
| 179 |
})?; |
| 180 |
|
| 181 |
for ka in vc.keys() { |
| 182 |
let fpr = ka.key().fingerprint(); |
| 183 |
let ka = match ka.with_policy(policy, time) { |
| 184 |
Ok(ka) => ka, |
| 185 |
Err(err) => { |
| 186 |
bad.push(format!("{} is not valid: {}", |
| 187 |
fpr, |
| 188 |
crate::one_line_error_chain(err))); |
| 189 |
continue; |
| 190 |
} |
| 191 |
}; |
| 192 |
|
| 193 |
if let Some(key_flags) = ka.key_flags() { |
| 194 |
if (&key_flags & &mode).is_empty() { |
| 195 |
// Not for encryption. |
| 196 |
continue; |
| 197 |
} |
| 198 |
} else { |
| 199 |
// No key flags. Not for encryption. |
| 200 |
continue; |
| 201 |
} |
| 202 |
encryption_keys += 1; |
| 203 |
|
| 204 |
if ! ka.key().pk_algo().is_supported() { |
| 205 |
bad.push(format!("{} uses {}, which is not supported", |
| 206 |
ka.key().fingerprint(), |
| 207 |
ka.key().pk_algo())); |
| 208 |
continue; |
| 209 |
} |
| 210 |
if let RevocationStatus::Revoked(_sigs) = ka.revocation_status() { |
| 211 |
bad.push(format!("{} is revoked", ka.key().fingerprint())); |
| 212 |
continue; |
| 213 |
} |
| 214 |
if let Err(err) = ka.alive() { |
| 215 |
if let Some(t) = ka.key_expiration_time() { |
| 216 |
if t < sq.time { |
| 217 |
expired_keys.push((ka, t)); |
| 218 |
bad.push(format!("{} expired on {}", |
| 219 |
fpr, t.convert().to_string())); |
| 220 |
} else { |
| 221 |
bad.push(format!("{} is not alive: {}", |
| 222 |
fpr, err)); |
| 223 |
} |
| 224 |
} else { |
| 225 |
bad.push(format!("{} is not alive: {}", |
| 226 |
fpr, err)); |
| 227 |
} |
| 228 |
continue; |
| 229 |
} |
| 230 |
|
| 231 |
selected_keys.push(ka); |
| 232 |
} |
| 233 |
if selected_keys.is_empty() && use_expired_subkey |
| 234 |
&& ! expired_keys.is_empty() |
| 235 |
{ |
| 236 |
expired_keys.sort_by_key(|(_key, t)| *t); |
| 237 |
|
| 238 |
if let Some((key, _expiration_time)) = expired_keys.pop() { |
| 239 |
selected_keys.push(key); |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
if selected_keys.is_empty() { |
| 244 |
// We didn't find any keys for this certificate. |
| 245 |
for ka in cert.keys() { |
| 246 |
let fpr = ka.key().fingerprint(); |
| 247 |
if let Err(err) = ka.with_policy(policy, time) { |
| 248 |
bad.push(format!("{} is not valid: {}", |
| 249 |
fpr, |
| 250 |
crate::one_line_error_chain(err))); |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
if ! bad.is_empty() { |
| 255 |
weprintln!("Cannot encrypt to {}, {}:", |
| 256 |
cert.fingerprint(), |
| 257 |
sq.best_userid(&cert, true).display()); |
| 258 |
for message in bad.into_iter() { |
| 259 |
weprintln!(initial_indent=" - ", "{}", message); |
| 260 |
} |
| 261 |
} |
| 262 |
if ! use_expired_subkey && ! expired_keys.is_empty() { |
| 263 |
sq.hint(format_args!( |
| 264 |
"To use an expired key anyway, pass \ |
| 265 |
--use-expired-subkey")); |
| 266 |
} |
| 267 |
|
| 268 |
if encryption_keys > 0 { |
| 269 |
return Err(anyhow::anyhow!( |
| 270 |
"Cert {}, {} has no suitable encryption key", |
| 271 |
cert, |
| 272 |
sq.best_userid(&cert, true).display())); |
| 273 |
} else { |
| 274 |
return Err(anyhow::anyhow!( |
| 275 |
"Cert {}, {} has no encryption-capable keys", |
| 276 |
cert, |
| 277 |
sq.best_userid(&cert, true).display())); |
| 278 |
} |
| 279 |
} else { |
| 280 |
qprintln!(); |
| 281 |
qprintln!(initial_indent = " - ", "encrypted for {}", |
| 282 |
sq.best_userid(&cert, true).display()); |
| 283 |
qprintln!(initial_indent = " - ", "using {}", |
| 284 |
cert.fingerprint()); |
| 285 |
|
| 286 |
for ka in selected_keys { |
| 287 |
have_one_secret |= sq.have_secret_key(ka.amalgamation()); |
| 288 |
recipient_subkeys.push(ka); |
| 289 |
} |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
if ! passwords.is_empty() { |
| 294 |
qprintln!(); |
| 295 |
qprintln!(initial_indent = " - ", "encrypted using {}", |
| 296 |
passwords.len().of("password")); |
| 297 |
} |
| 298 |
|
| 299 |
if signers.is_empty() { |
| 300 |
sq.hint(format_args!( |
| 301 |
"The message will not be signed. \ |
| 302 |
While the message integrity will be protected \ |
| 303 |
by the encryption, there will be no way for the \ |
| 304 |
recipient to tell whether the message is \ |
| 305 |
authentic. Consider signing the message.")); |
| 306 |
} else { |
| 307 |
for (signer, _) in &signers { |
| 308 |
qprintln!(); |
| 309 |
qprintln!(initial_indent = " - ", "signed by {}", |
| 310 |
sq.best_userid(signer, true).display()); |
| 311 |
qprintln!(initial_indent = " - ", "using {}", |
| 312 |
signer.fingerprint()); |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
if ! have_one_secret && passwords.is_empty() && ! recipients.iter() |
| 317 |
.any(|c| sq.config.encrypt_for_self().contains(&c.fingerprint())) |
| 318 |
{ |
| 319 |
if let Some(home) = &sq.home { |
| 320 |
sq.hint(format_args!( |
| 321 |
"It looks like you won't be able to decrypt the message. \ |
| 322 |
Consider adding yourself as recipient, for example by \ |
| 323 |
adding your cert to `{}` in the configuration file ({}), \ |
| 324 |
and using the `--for-self` argument.", |
| 325 |
cli::encrypt::ENCRYPT_FOR_SELF, |
| 326 |
crate::config::ConfigFile::file_name(home).display())); |
| 327 |
} else { |
| 328 |
sq.hint(format_args!( |
| 329 |
"It looks like you won't be able to decrypt the message. \ |
| 330 |
Consider adding yourself as recipient.")); |
| 331 |
} |
| 332 |
} |
| 333 |
|
| 334 |
// A newline to make it look nice. |
| 335 |
qprintln!(); |
| 336 |
|
| 337 |
// We want to encrypt a literal data packet. |
| 338 |
let encryptor = |
| 339 |
Encryptor::for_recipients(message, recipient_subkeys) |
| 340 |
.add_passwords(passwords); |
| 341 |
|
| 342 |
let mut sink = encryptor.build() |
| 343 |
.context("Failed to create encryptor")?; |
| 344 |
|
| 345 |
match compression { |
| 346 |
CompressionMode::None => (), |
| 347 |
CompressionMode::Pad => sink = Padder::new(sink).build()?, |
| 348 |
CompressionMode::Zip => sink = |
| 349 |
Compressor::new(sink).algo(CompressionAlgorithm::Zip).build()?, |
| 350 |
CompressionMode::Zlib => sink = |
| 351 |
Compressor::new(sink).algo(CompressionAlgorithm::Zlib).build()?, |
| 352 |
CompressionMode::Bzip2 => sink = |
| 353 |
Compressor::new(sink).algo(CompressionAlgorithm::BZip2).build()?, |
| 354 |
} |
| 355 |
|
| 356 |
// Optionally sign message. |
| 357 |
if let Some(first) = signers.pop() { |
| 358 |
// Create a signature template. |
| 359 |
let mut builder = SignatureBuilder::new(SignatureType::Binary); |
| 360 |
for (critical, n) in notations.iter() { |
| 361 |
builder = builder.add_notation( |
| 362 |
n.name(), |
| 363 |
n.value(), |
| 364 |
Some(n.flags().clone()), |
| 365 |
*critical)?; |
| 366 |
} |
| 367 |
|
| 368 |
let mut signer = Signer::with_template(sink, first.1, builder)?; |
| 369 |
|
| 370 |
if let Some(time) = time { |
| 371 |
signer = signer.creation_time(time); |
| 372 |
} |
| 373 |
for s in signers { |
| 374 |
signer = signer.add_signer(s.1)?; |
| 375 |
} |
| 376 |
for r in recipients.iter() { |
| 377 |
signer = signer.add_intended_recipient(r); |
| 378 |
} |
| 379 |
sink = signer.build()?; |
| 380 |
} |
| 381 |
|
| 382 |
let literal_writer = LiteralWriter::new(sink) |
| 383 |
.filename(set_metadata_filename.unwrap_or_default())?; |
| 384 |
|
| 385 |
let mut writer_stack = literal_writer |
| 386 |
.build() |
| 387 |
.context("Failed to create literal writer")?; |
| 388 |
|
| 389 |
// Finally, copy stdin to our writer stack to encrypt the data. |
| 390 |
input.open("data to encrypt")?.copy(&mut writer_stack) |
| 391 |
.context("Failed to encrypt")?; |
| 392 |
|
| 393 |
writer_stack.finalize().context("Failed to encrypt")?; |
| 394 |
|
| 395 |
Ok(()) |
| 396 |
} |