| 1 |
use anyhow::Context; |
| 2 |
|
| 3 |
use openpgp::packet::key; |
| 4 |
use openpgp::packet::signature::subpacket::SubpacketTag; |
| 5 |
use openpgp::packet::signature::SignatureBuilder; |
| 6 |
use openpgp::packet::Key; |
| 7 |
use openpgp::packet::Signature; |
| 8 |
use openpgp::policy::Policy; |
| 9 |
use openpgp::serialize::Serialize; |
| 10 |
use openpgp::types::KeyFlags; |
| 11 |
use openpgp::types::SignatureType; |
| 12 |
use openpgp::Cert; |
| 13 |
use openpgp::KeyHandle; |
| 14 |
use openpgp::Packet; |
| 15 |
use openpgp::Result; |
| 16 |
use sequoia_openpgp as openpgp; |
| 17 |
|
| 18 |
use crate::Sq; |
| 19 |
use crate::cli; |
| 20 |
use cli::types::EncryptPurpose; |
| 21 |
use crate::common::password; |
| 22 |
use crate::sq::TrustThreshold; |
| 23 |
|
| 24 |
pub fn bind(sq: Sq, command: cli::key::subkey::bind::Command) -> Result<()> |
| 25 |
{ |
| 26 |
let cert = sq.resolve_cert(&command.cert, TrustThreshold::Full)?.0; |
| 27 |
|
| 28 |
let null_policy_; |
| 29 |
let adoptee_policy: &dyn Policy = if command.allow_broken_crypto { |
| 30 |
null_policy_ = unsafe { openpgp::policy::NullPolicy::new() }; |
| 31 |
&null_policy_ |
| 32 |
} else { |
| 33 |
sq.policy |
| 34 |
}; |
| 35 |
|
| 36 |
// Find the corresponding keys. |
| 37 |
let wanted: Vec<( |
| 38 |
KeyHandle, |
| 39 |
Result<( |
| 40 |
Cert, |
| 41 |
Key<key::PublicParts, key::SubordinateRole>, |
| 42 |
SignatureBuilder, |
| 43 |
)>, |
| 44 |
)> = command.key |
| 45 |
.into_iter() |
| 46 |
.map(|kh| { |
| 47 |
let cert = match sq.lookup_with_policy( |
| 48 |
std::iter::once(kh.clone()), None, false, true, |
| 49 |
adoptee_policy, sq.time) |
| 50 |
{ |
| 51 |
Ok(certs) => certs.into_iter().next().unwrap(), |
| 52 |
Err(err) => return (kh, Err(err)), |
| 53 |
}; |
| 54 |
|
| 55 |
|
| 56 |
let key = cert.keys().key_handle(kh.clone()) |
| 57 |
.next().expect("have key"); |
| 58 |
|
| 59 |
use openpgp::cert::amalgamation::ValidateAmalgamation; |
| 60 |
let sig = key.with_policy(adoptee_policy, sq.time) |
| 61 |
.map(|k| k.binding_signature()) |
| 62 |
.ok(); |
| 63 |
let builder: SignatureBuilder = match sig { |
| 64 |
Some(sig) if sig.typ() == SignatureType::SubkeyBinding => { |
| 65 |
sig.clone().into() |
| 66 |
} |
| 67 |
Some(sig) if sig.typ() == SignatureType::DirectKey |
| 68 |
|| sig.typ() == SignatureType::PositiveCertification |
| 69 |
|| sig.typ() == SignatureType::CasualCertification |
| 70 |
|| sig.typ() == SignatureType::PersonaCertification |
| 71 |
|| sig.typ() == SignatureType::GenericCertification => |
| 72 |
{ |
| 73 |
// Convert to a binding signature. |
| 74 |
let kf = match sig.key_flags().context( |
| 75 |
"Missing required subpacket, KeyFlags") |
| 76 |
{ |
| 77 |
Ok(kh) => kh, |
| 78 |
Err(err) => return (kh, Err(err)), |
| 79 |
}; |
| 80 |
match SignatureBuilder::new(SignatureType::SubkeyBinding) |
| 81 |
.set_key_flags(kf) |
| 82 |
{ |
| 83 |
Ok(b) => b, |
| 84 |
Err(err) => return (kh, Err(err)), |
| 85 |
} |
| 86 |
} |
| 87 |
None => { |
| 88 |
SignatureBuilder::new(SignatureType::SubkeyBinding) |
| 89 |
} |
| 90 |
_ => panic!("Unsupported binding signature: {:?}", sig), |
| 91 |
}; |
| 92 |
|
| 93 |
let builder = match builder.set_signature_creation_time(sq.time) { |
| 94 |
Ok(b) => b, |
| 95 |
Err(err) => return (kh, Err(err)), |
| 96 |
}; |
| 97 |
|
| 98 |
let mut key_flags = builder.key_flags() |
| 99 |
.unwrap_or(KeyFlags::empty()); |
| 100 |
if command.can_sign { |
| 101 |
key_flags = key_flags.set_signing(); |
| 102 |
} |
| 103 |
if command.cannot_sign { |
| 104 |
key_flags = key_flags.clear_signing(); |
| 105 |
} |
| 106 |
if command.can_authenticate { |
| 107 |
key_flags = key_flags.set_authentication(); |
| 108 |
} |
| 109 |
if command.cannot_authenticate { |
| 110 |
key_flags = key_flags.clear_authentication(); |
| 111 |
} |
| 112 |
if let Some(purpose) = command.can_encrypt.as_ref() { |
| 113 |
match purpose { |
| 114 |
EncryptPurpose::Universal => { |
| 115 |
key_flags = key_flags.set_storage_encryption() |
| 116 |
.set_transport_encryption(); |
| 117 |
} |
| 118 |
EncryptPurpose::Storage => { |
| 119 |
key_flags = key_flags.set_storage_encryption(); |
| 120 |
} |
| 121 |
EncryptPurpose::Transport => { |
| 122 |
key_flags = key_flags.set_transport_encryption(); |
| 123 |
} |
| 124 |
} |
| 125 |
} |
| 126 |
if command.cannot_encrypt { |
| 127 |
key_flags = key_flags.clear_storage_encryption(); |
| 128 |
key_flags = key_flags.clear_transport_encryption(); |
| 129 |
} |
| 130 |
|
| 131 |
let builder = match builder.set_key_flags(key_flags) { |
| 132 |
Ok(b) => b, |
| 133 |
Err(err) => return (kh, Err(err)), |
| 134 |
}; |
| 135 |
|
| 136 |
let mut key = key.key().clone().role_into_subordinate(); |
| 137 |
|
| 138 |
if let Some(creation_time) = &command.creation_time { |
| 139 |
match creation_time.to_system_time(sq.time) |
| 140 |
.and_then(|t| key.set_creation_time(t)) |
| 141 |
{ |
| 142 |
Ok(_) => (), |
| 143 |
Err(err) => return (kh, Err(err)), |
| 144 |
} |
| 145 |
} else if key.creation_time() == std::time::UNIX_EPOCH { |
| 146 |
// We have a bare key. Set the creation time to now. |
| 147 |
match key.set_creation_time(sq.time) { |
| 148 |
Ok(_) => (), |
| 149 |
Err(err) => return (kh, Err(err)), |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
(kh, Ok((cert, key, builder))) |
| 154 |
}) |
| 155 |
.collect(); |
| 156 |
|
| 157 |
// If we are missing any keys, stop now. |
| 158 |
let mut missing = false; |
| 159 |
let wanted = wanted.into_iter() |
| 160 |
.filter_map(|(id, keyo)| { |
| 161 |
match keyo { |
| 162 |
Ok((cert, key, builder)) => Some((cert, key, builder)), |
| 163 |
Err(err) => { |
| 164 |
if ! missing { |
| 165 |
weprintln!("Missing keys:"); |
| 166 |
} |
| 167 |
|
| 168 |
weprintln!(initial_indent = " - ", "{}: {}", id, err); |
| 169 |
|
| 170 |
missing = true; |
| 171 |
None |
| 172 |
} |
| 173 |
} |
| 174 |
}) |
| 175 |
.collect::<Vec<_>>(); |
| 176 |
if missing { |
| 177 |
return Err(anyhow::anyhow!("Missing some keys")); |
| 178 |
} |
| 179 |
|
| 180 |
// Get a signer. |
| 181 |
let pk = cert.primary_key().key(); |
| 182 |
let mut pk_signer = sq.get_primary_key(&cert, None) |
| 183 |
.with_context(|| { |
| 184 |
format!("Getting signer for {}'s primary key", |
| 185 |
cert.fingerprint()) |
| 186 |
})?; |
| 187 |
|
| 188 |
// Add the keys and signatures to cert. |
| 189 |
let mut packets: Vec<Packet> = vec![]; |
| 190 |
for (cert, mut key, mut builder) in wanted.into_iter() { |
| 191 |
// Set key expiration. |
| 192 |
if let Some(e) = command.expiration.value().to_system_time(sq.time)? { |
| 193 |
builder = builder.set_key_expiration_time(&key, e)?; |
| 194 |
} |
| 195 |
|
| 196 |
let key_flags = builder.key_flags().unwrap_or(KeyFlags::empty()); |
| 197 |
if key_flags.is_empty() { |
| 198 |
return Err(anyhow::anyhow!( |
| 199 |
"{} has no key capabilities. Pass at least one of \ |
| 200 |
--can-sign, --can-authenticate, and --can-encrypt to \ |
| 201 |
bind this key.", |
| 202 |
key.fingerprint())); |
| 203 |
}; |
| 204 |
|
| 205 |
// If the key we got from the certificate does not contain a |
| 206 |
// secret (for example, because we got it from the cert |
| 207 |
// store), try to get it from the key store. This will only |
| 208 |
// succeed for the softkeys backend. But, for the softkeys |
| 209 |
// backend it is necessary to actually get the secret key |
| 210 |
// material, so that we have secret key material to import |
| 211 |
// back into the softkeys backend. |
| 212 |
// |
| 213 |
// Note that keys backed by the softkeys backend can also |
| 214 |
// bind keys with material backed by hardware keys. In this |
| 215 |
// case, we'll import the public key and binding signature |
| 216 |
// into the cert store, and the change will not be reflected |
| 217 |
// in the key store. |
| 218 |
|
| 219 |
// If we have to prompt for a password in order to identify |
| 220 |
// the right key, at least store the keypair so that we don't |
| 221 |
// have to ask again. |
| 222 |
let mut keypair = None; |
| 223 |
|
| 224 |
if key.optional_secret().is_none() { |
| 225 |
let ks = sq.key_store_or_else()?; |
| 226 |
let mut ks = ks.lock().unwrap(); |
| 227 |
|
| 228 |
// Try to get secrets from the store. |
| 229 |
let secrets = ks.find_key(key.key_handle())?.into_iter() |
| 230 |
.filter_map(|mut k| k.export().ok()).collect::<Vec<_>>(); |
| 231 |
|
| 232 |
match secrets.len() { |
| 233 |
0 => (), |
| 234 |
1 => key = secrets.into_iter().next().unwrap().into(), |
| 235 |
_ => if secrets.iter().all(|k| ! k.secret().is_encrypted()) { |
| 236 |
// There is more than one variant of the secret |
| 237 |
// key, and all of them are unlocked. Pick one. |
| 238 |
let k = secrets.into_iter().next().unwrap(); |
| 239 |
keypair = |
| 240 |
Some(k.clone().into_keypair()?); |
| 241 |
key = k.into(); |
| 242 |
} else { |
| 243 |
// There is more than one variant of the secret |
| 244 |
// key. Prompt for a password to unlock one, so |
| 245 |
// that we know which one the user wants. This is |
| 246 |
// a bit annoying, but on the plus side we don't |
| 247 |
// need to ask the user again to create the |
| 248 |
// primary key binding signature. |
| 249 |
let uid = sq.best_userid(&cert, true); |
| 250 |
|
| 251 |
'password_loop: loop { |
| 252 |
let p = password::prompt_to_unlock(&sq, &format!( |
| 253 |
"{}/{}, {}", |
| 254 |
cert.keyid(), key.keyid(), uid.display()))?; |
| 255 |
|
| 256 |
// Empty password given and a key without |
| 257 |
// encryption? Pick it. |
| 258 |
if p.map(|p| p.is_empty()) { |
| 259 |
if let Some(k) = secrets.iter() |
| 260 |
.find(|k| ! k.secret().is_encrypted()) |
| 261 |
{ |
| 262 |
keypair = |
| 263 |
Some(k.clone().into_keypair()?); |
| 264 |
key = k.clone().into(); |
| 265 |
break; |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
let mut err = None; |
| 270 |
for k in &secrets { |
| 271 |
match k.secret().clone().decrypt(&key, &p) { |
| 272 |
Ok(decrypted) => { |
| 273 |
// Keep the decrypted keypair. |
| 274 |
keypair = Some({ |
| 275 |
let k = key.add_secret(decrypted).0; |
| 276 |
k.clone().into_keypair()? |
| 277 |
}); |
| 278 |
// Bind the encrypted key. |
| 279 |
key = k.clone().into(); |
| 280 |
break 'password_loop; |
| 281 |
}, |
| 282 |
|
| 283 |
Err(e) => err = Some(e), |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
if p == "".into() { |
| 288 |
weprintln!("Giving up."); |
| 289 |
return Err(anyhow::anyhow!( |
| 290 |
"Failed to unlock key: {}", |
| 291 |
err.expect("must be set when we came here"))); |
| 292 |
} |
| 293 |
} |
| 294 |
}, |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
// If we need a valid backsig, create it. |
| 299 |
if key_flags.for_signing() || key_flags.for_certification() { |
| 300 |
// Derive a signer. |
| 301 |
let ka = cert.keys().key_handle(key.fingerprint()) |
| 302 |
.next() |
| 303 |
.expect("have key"); |
| 304 |
|
| 305 |
let mut subkey_signer = if let Some(k) = keypair { |
| 306 |
Box::new(k) |
| 307 |
} else { |
| 308 |
sq.get_signer(&ka) |
| 309 |
.with_context(|| { |
| 310 |
format!("Getting signer for {}", ka.key().fingerprint()) |
| 311 |
})? |
| 312 |
}; |
| 313 |
|
| 314 |
let backsig = builder |
| 315 |
.embedded_signatures() |
| 316 |
.find(|backsig| { |
| 317 |
(*backsig) |
| 318 |
.clone() |
| 319 |
.verify_primary_key_binding(cert.primary_key().key(), &key) |
| 320 |
.is_ok() |
| 321 |
}) |
| 322 |
.map(|sig| SignatureBuilder::from(sig.clone())) |
| 323 |
.unwrap_or_else(|| { |
| 324 |
SignatureBuilder::new(SignatureType::PrimaryKeyBinding) |
| 325 |
}) |
| 326 |
.set_signature_creation_time(sq.time)? |
| 327 |
.sign_primary_key_binding(&mut subkey_signer, pk, &key)?; |
| 328 |
|
| 329 |
builder = builder.set_embedded_signature(backsig)?; |
| 330 |
} else { |
| 331 |
builder = builder.modify_hashed_area(|mut a| { |
| 332 |
a.remove_all(SubpacketTag::EmbeddedSignature); |
| 333 |
Ok(a) |
| 334 |
})?; |
| 335 |
} |
| 336 |
|
| 337 |
let sig = builder.sign_subkey_binding(&mut pk_signer, pk, &key)?; |
| 338 |
|
| 339 |
// Verify it. |
| 340 |
assert!(sig |
| 341 |
.verify_subkey_binding(pk_signer.public(), pk, &key) |
| 342 |
.is_ok()); |
| 343 |
|
| 344 |
packets.push(key.into()); |
| 345 |
packets.push(sig.into()); |
| 346 |
} |
| 347 |
|
| 348 |
let cert = cert.clone().insert_packets(packets.clone())?.0; |
| 349 |
|
| 350 |
let vc = cert.with_policy(sq.policy, None).expect("still valid"); |
| 351 |
for pair in packets[..].chunks(2) { |
| 352 |
let newkey: &Key<key::PublicParts, key::UnspecifiedRole> = match pair[0] |
| 353 |
{ |
| 354 |
Packet::PublicKey(ref k) => k.into(), |
| 355 |
Packet::PublicSubkey(ref k) => k.into(), |
| 356 |
Packet::SecretKey(ref k) => k.into(), |
| 357 |
Packet::SecretSubkey(ref k) => k.into(), |
| 358 |
ref p => panic!("Expected a key, got: {:?}", p), |
| 359 |
}; |
| 360 |
let newsig: &Signature = match pair[1] { |
| 361 |
Packet::Signature(ref s) => s, |
| 362 |
ref p => panic!("Expected a sig, got: {:?}", p), |
| 363 |
}; |
| 364 |
|
| 365 |
let mut found = false; |
| 366 |
for key in vc.keys() { |
| 367 |
if key.key().fingerprint() == newkey.fingerprint() { |
| 368 |
for sig in key.self_signatures() { |
| 369 |
if sig == newsig { |
| 370 |
found = true; |
| 371 |
break; |
| 372 |
} |
| 373 |
} |
| 374 |
} |
| 375 |
} |
| 376 |
assert!(found, "Subkey: {:?}\nSignature: {:?}", newkey, newsig); |
| 377 |
} |
| 378 |
|
| 379 |
if let Some(output) = command.output { |
| 380 |
let path = output.path().map(Clone::clone); |
| 381 |
let mut sink = output.for_secrets().create_safe(&sq)?; |
| 382 |
if false { |
| 383 |
cert.as_tsk().serialize(&mut sink)?; |
| 384 |
} else { |
| 385 |
cert.as_tsk().armored().serialize(&mut sink)?; |
| 386 |
} |
| 387 |
|
| 388 |
if let Some(path) = path { |
| 389 |
sq.hint(format_args!( |
| 390 |
"Updated key written to {}. \ |
| 391 |
To make the update effective, it has to be published \ |
| 392 |
so that others can find it, for example using:", |
| 393 |
path.display())) |
| 394 |
.sq().arg("network").arg("keyserver").arg("publish") |
| 395 |
.arg_value("--cert-file", path.display()) |
| 396 |
.done(); |
| 397 |
} else { |
| 398 |
sq.hint(format_args!( |
| 399 |
"To make the update effective, it has to be published \ |
| 400 |
so that others can find it.")); |
| 401 |
} |
| 402 |
} else { |
| 403 |
// Import it into the key store. |
| 404 |
let fipr = cert.fingerprint(); |
| 405 |
let result = if cert.is_tsk() { |
| 406 |
sq.import_key(cert, &mut Default::default()).err() |
| 407 |
} else { |
| 408 |
sq.import_cert(cert).err() |
| 409 |
}; |
| 410 |
if let Some(err) = result { |
| 411 |
weprintln!("Error importing updated cert: {}", err); |
| 412 |
return Err(err); |
| 413 |
} else { |
| 414 |
sq.hint(format_args!( |
| 415 |
"Imported updated cert into the cert store. \ |
| 416 |
To make the update effective, it has to be published \ |
| 417 |
so that others can find it, for example using:")) |
| 418 |
.sq().arg("network").arg("keyserver").arg("publish") |
| 419 |
.arg_value("--cert", fipr) |
| 420 |
.done(); |
| 421 |
} |
| 422 |
} |
| 423 |
|
| 424 |
Ok(()) |
| 425 |
} |