Debian Codegraph @

src/common/key/password.rs

raw
1 use std::path::Path;
2
3 use anyhow::Context;
4
5 use sequoia_openpgp as openpgp;
6 use openpgp::Cert;
7 use openpgp::Packet;
8 use openpgp::Result;
9 use openpgp::cert::amalgamation::key::PrimaryKey;
10 use openpgp::cert::amalgamation::key::ValidErasedKeyAmalgamation;
11 use openpgp::crypto::Password;
12 use openpgp::packet::key::KeyParts;
13 use openpgp::serialize::Serialize;
14
15 use sequoia_keystore as keystore;
16 use keystore::Protection;
17
18 use crate::Convert;
19 use crate::Sq;
20 use crate::cli::types::FileOrStdout;
21 use crate::cli::types::FileStdinOrKeyHandle;
22 use crate::common::password;
23 use crate::common;
24
25 pub fn password<'a, P>(
26 sq: Sq,
27 cert: &Cert,
28 cert_source: FileStdinOrKeyHandle,
29 to_change: Vec<(
30 &'a ValidErasedKeyAmalgamation<'a, P>,
31 Option<Vec<keystore::Key>>
32 )>,
33 clear_password: bool,
34 new_password_file: Option<&Path>,
35 output: Option<FileOrStdout>,
36 binary: bool)
37 -> Result<()>
38 where
39 P: 'a + KeyParts,
40 {
41 make_qprintln!(sq.quiet());
42
43 let mut new_password_ = None;
44 // Some(password) => new password
45 // None => clear password
46 let mut get_new_password = || -> Result<Option<Password>> {
47 if new_password_.is_none() {
48 new_password_ = if clear_password {
49 Some(None)
50 } else if let Some(path) = new_password_file.as_ref() {
51 Some(Some(std::fs::read(path)?.into()))
52 } else {
53 Some(common::password::prompt_for_new_or_none(&sq, "key")?)
54 };
55 }
56
57 Ok(new_password_.clone().unwrap())
58 };
59
60 let uid = sq.best_userid(&cert, true);
61
62 qprintln!("Changing password for {}, {}",
63 cert.fingerprint(), uid.display());
64
65 let ks = matches!(cert_source, FileStdinOrKeyHandle::KeyHandle(_));
66 if ks {
67 // Change the password of the secret key material on the key
68 // store.
69 for (key, remote_keys) in to_change.into_iter() {
70 let remote_keys = remote_keys.expect("have remote keys");
71 assert!(! remote_keys.is_empty());
72 for mut remote_key in remote_keys.into_iter() {
73 let provide_password
74 = if let Protection::Password(hint) = remote_key.locked()?
75 {
76 let mut unlocked = false;
77 for p in sq.cached_passwords() {
78 if remote_key.unlock(p).is_ok() {
79 unlocked = true;
80 break;
81 }
82 }
83
84 if ! unlocked {
85 if let Some(hint) = hint {
86 weprintln!("{}", hint);
87 }
88
89 let time =
90 key.key().creation_time().convert().to_string();
91
92 let flags = if let Some(flags) = key.key_flags() {
93 let mut s = Vec::new();
94 if flags.for_certification() {
95 s.push("certifying");
96 }
97 if flags.for_signing() {
98 s.push("signing");
99 }
100 if flags.for_storage_encryption()
101 && flags.for_transport_encryption()
102 {
103 s.push("encryption");
104 } else if flags.for_storage_encryption() {
105 s.push("storage encryption");
106 } else if flags.for_transport_encryption() {
107 s.push("transport encryption");
108 }
109 if ! s.is_empty() {
110 format!(" for {}", s.join(", "))
111 } else {
112 "".into()
113 }
114 } else {
115 "".into()
116 };
117
118 loop {
119 let p = password::prompt_to_unlock(&sq, &format!(
120 "{}, created {}{}",
121 key.key().fingerprint(), time, flags))?;
122
123 match remote_key.unlock(p.clone()) {
124 Ok(()) => {
125 sq.cache_password(p.clone());
126 break;
127 }
128 Err(err) => {
129 weprintln!("Failed to unlock key: {}", err);
130 }
131 }
132 }
133 }
134 true
135 } else {
136 remote_key.password_source()?.is_inline()
137 };
138
139 let password = if provide_password {
140 if let Some(password) = get_new_password()? {
141 Some(password)
142 } else {
143 // change_password interprets None as prompt for
144 // password, and "" as clear password.
145 Some("".into())
146 }
147 } else {
148 None
149 };
150
151 remote_key.change_password(password.as_ref())
152 .with_context(|| {
153 format!("Changing {}'s password", key.key().fingerprint())
154 })?;
155
156 qprintln!("Changed password for {}", key.key().fingerprint());
157 }
158 }
159 } else {
160 // First, decrypt all secrets.
161 let to_change = to_change.into_iter().map(|(ka, remote)| {
162 let key = ka.key().clone().parts_into_secret()?;
163 let key = sq.decrypt_key(
164 Some(&cert),
165 key,
166 true, // May prompt.
167 false, // Don't allow skipping.
168 )?.parts_into_public();
169 Ok((key, ka.primary(), remote))
170 }).collect::<Result<Vec<_>>>()?;
171
172 let mut packets: Vec<Packet> = Vec::new();
173 if let Some(new) = get_new_password()? {
174 for (key, primary, _remote_keys) in to_change.into_iter() {
175 let key = key.parts_into_secret()
176 .expect("have secret key amterial")
177 .encrypt_secret(&new)?
178 .parts_into_public();
179
180 if primary {
181 packets.push(
182 Packet::PublicKey(key.role_into_primary()));
183 } else {
184 packets.push(
185 Packet::PublicSubkey(key.role_into_subordinate()));
186 }
187 }
188 } else {
189 for (key, primary, _remote_keys) in to_change.into_iter() {
190 let key = key.parts_into_public();
191 if primary {
192 packets.push(
193 Packet::PublicKey(key.role_into_primary()));
194 } else {
195 packets.push(
196 Packet::PublicSubkey(key.role_into_subordinate()));
197 }
198 }
199 }
200
201 let cert = cert.clone().insert_packets(packets)?.0;
202
203 let output = output.unwrap_or_else(|| FileOrStdout::new(None));
204 let mut output = output.for_secrets().create_safe(&sq)?;
205 if binary {
206 cert.as_tsk().serialize(&mut output)?;
207 } else {
208 cert.as_tsk().armored().serialize(&mut output)?;
209 }
210 }
211
212 Ok(())
213 }