pijul_org / pijul

Reset key files' permissions to 600 on Unix

By mpevnev on November 24, 2018
This patch is not signed.
885EePVNrfjZrKozEmf2pYsDyqiFKQ5yLk31rdetHft4VxgE6MGQaqRfJNiG8cEk8LnAx31DGYa6rWSSj6iYRFLp
This patch is in the following branches:
latest
master
testing























1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
        #[cfg(unix)]
        {
            reset_permissions(&mut f)?;
        }
        #[cfg(unix)]
        {
            reset_permissions(&mut f)?;
        }
}

fn reset_permissions(f: &File) -> Result<(), Error> {
    let mut perms = match f.metadata() {
        Ok(meta) => meta.permissions(),
        Err(e) => {
            eprintln!("Warning: failed to obtain key file's metadata: {:?}", e);
            return Ok(());
        }
    perms.set_mode(0o600);
    match f.set_permissions(perms) {
        Ok(_) => (),
        Err(e) => eprintln!("Warning: failed to reset key file permissions: {:?}", e),
    }
    Ok(())
use commands::remote::{parse_remote, Remote};
use dirs;
use error::Error;
use libpijul::fs_representation::RepoRoot;
use sequoia_openpgp::parse::Parse;
use sequoia_openpgp::serialize::Serialize;
use sequoia_openpgp::tpk::{CipherSuite, TPKBuilder};
use sequoia_openpgp::TSK;
use std;
use std::collections::BTreeMap;
use std::fs::{create_dir_all, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use thrussh_keys::key::KeyPair;
use toml;

pub const DEFAULT_REMOTE: &'static str = "remote";

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Repository {
    pub address: String,
    pub port: Option<u16>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Meta {
    #[serde(default)]
    pub authors: Vec<String>,
    pub editor: Option<String>,
    pub pull: Option<String>,
    pub push: Option<String>,
    #[serde(default)]
    pub remote: BTreeMap<String, Repository>,
    pub signing_key: Option<String>,
}

impl Meta {
    pub fn load(r: &RepoRoot<impl AsRef<Path>>) -> Result<Meta, Error> {
        let mut str = String::new();
        {
            let mut f = File::open(r.meta_file())?;
            f.read_to_string(&mut str)?;
        }
        Ok(toml::from_str(&str)?)
    }
    pub fn new() -> Meta {
        Meta {
            authors: Vec::new(),
            editor: None,
            pull: None,
            push: None,
            remote: BTreeMap::new(),
            signing_key: None,
        }
    }
    pub fn save(&self, r: &RepoRoot<impl AsRef<Path>>) -> Result<(), Error> {
        let mut f = File::create(r.meta_file())?;
        let s: String = toml::to_string(&self)?;
        f.write_all(s.as_bytes())?;
        Ok(())
    }

    fn parse_remote<'a>(
        &'a self,
        remote: &'a str,
        port: Option<u16>,
        base_path: Option<&'a Path>,
        local_repo_root: Option<&'a Path>,
    ) -> Remote<'a> {
        if let Some(repo) = self.remote.get(remote) {
            parse_remote(
                &repo.address,
                port.or(repo.port),
                base_path,
                local_repo_root,
            )
        } else {
            parse_remote(remote, port, base_path, local_repo_root)
        }
    }

    fn get_remote<'a>(
        &'a self,
        remote: Option<&'a str>,
        default_remote: Option<&'a String>,
        port: Option<u16>,
        base_path: Option<&'a Path>,
        local_repo_root: Option<&'a Path>,
    ) -> Result<Remote<'a>, Error> {
        if let Some(remote) = remote {
            Ok(self.parse_remote(remote, port, base_path, local_repo_root))
        } else if let Some(ref remote) = default_remote {
            Ok(self.parse_remote(remote, port, base_path, local_repo_root))
        } else if self.remote.len() == 1 {
            let remote = self.remote.keys().next().unwrap();
            Ok(self.parse_remote(remote, port, base_path, local_repo_root))
        } else {
            Err(Error::MissingRemoteRepository)
        }
    }

    pub fn pull<'a>(
        &'a self,
        remote: Option<&'a str>,
        port: Option<u16>,
        base_path: Option<&'a Path>,
        local_repo_root: Option<&'a Path>,
    ) -> Result<Remote<'a>, Error> {
        self.get_remote(remote, self.pull.as_ref(), port, base_path, local_repo_root)
    }

    pub fn push<'a>(
        &'a self,
        remote: Option<&'a str>,
        port: Option<u16>,
        base_path: Option<&'a Path>,
        local_repo_root: Option<&'a Path>,
    ) -> Result<Remote<'a>, Error> {
        self.get_remote(remote, self.push.as_ref(), port, base_path, local_repo_root)
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Global {
    pub author: Option<String>,
    pub editor: Option<String>,
    pub signing_key: Option<String>,
}

pub fn global_path() -> Result<PathBuf, Error> {
    if let Ok(var) = std::env::var("PIJUL_CONFIG_DIR") {
        let mut path = PathBuf::new();
        path.push(var);
        Ok(path)
    } else if let Ok(var) = std::env::var("XDG_DATA_HOME") {
        let mut path = PathBuf::new();
        path.push(var);
        path.push("pijul");
        std::fs::create_dir_all(&path)?;
        path.push("config");
        Ok(path)
    } else {
        if let Some(mut path) = dirs::home_dir() {
            path.push(".pijulconfig");
            Ok(path)
        } else {
            Err(Error::NoHomeDir)
        }
    }
}

pub fn generate_ssh_key<P: AsRef<Path>>(
    dot_pijul: P,
    password: Option<(u32, &[u8])>,
) -> Result<(), Error> {
    use thrussh_keys::{encode_pkcs8_pem, encode_pkcs8_pem_encrypted, write_public_key_base64};
    let key = KeyPair::generate_ed25519().unwrap();
    create_dir_all(dot_pijul.as_ref())?;

    let mut f = dot_pijul.as_ref().join("id_ed25519");
    debug!("generate_key: {:?}", f);
    if std::fs::metadata(&f).is_err() {
        let mut f = File::create(&f)?;
        if let Some((rounds, pass)) = password {
            encode_pkcs8_pem_encrypted(&key, pass, rounds, &mut f)?
        } else {
            encode_pkcs8_pem(&key, &mut f)?
        }
        f.flush().unwrap();
        set_key_permissions(&f, "private key file");
    } else {
        return Err(Error::WillNotOverwriteKeyFile { path: f });
    }
    f.set_extension("pub");
    {
        let mut f = File::create(&f)?;
        let pk = key.clone_public_key();
        write_public_key_base64(&mut f, &pk)?;
        f.write(b"\n")?;
        f.flush()?;
        set_key_permissions(&f, "public key file");
    }
    Ok(())
}

pub fn generate_signing_key<P: AsRef<Path>>(
    dot_pijul: P,
    identity: &str,
    password: Option<String>,
) -> Result<PathBuf, Error> {
    create_dir_all(dot_pijul.as_ref())?;

    let mut f = dot_pijul.as_ref().join("signing_secret_key");
    if std::fs::metadata(&f).is_err() {
        let (tpk, sig) = TPKBuilder::default()
            .set_cipher_suite(CipherSuite::Cv25519)
            .add_userid(identity)
            .add_signing_subkey()
            .set_password(password.map(From::from))
            .generate()
            .unwrap();

        let tsk = tpk.into_tsk();
        let mut keyfile = File::create(&f)?;
        tsk.serialize(&mut keyfile).unwrap();
        set_key_permissions(&keyfile, "signing key file");

        f.set_extension("revocation_cert");
        let mut revoc_cert = File::create(&f)?;
        sig.serialize(&mut revoc_cert).unwrap();
        set_key_permissions(&revoc_cert, "revocation certificate");

        f.set_extension("");
        Ok(f)
    } else {
        return Err(Error::WillNotOverwriteKeyFile { path: f });
    }
}

pub struct SigningKeys {
    pub keys: Vec<sequoia_openpgp::crypto::KeyPair>,
    pub tsk: TSK,
    pub user_id: String,
}

impl SigningKeys {
    pub fn check_author(&self, authors: &[String]) -> Result<(), Error> {
        let author_uid = regex::Regex::new("^[^<>]*<?([^<>]+)>?[^<>]*$").unwrap();
        if self.keys.is_empty() {
            if !authors.iter().any(|auth| {
                auth == &self.user_id
                    || (if let Some(cap) = author_uid.captures(&auth) {
                        cap[1] == self.user_id
                    } else {
                        false
                    })
            }) {
                return Err(Error::NotSigningAuthor);
            }
        }
        Ok(())
    }
}

pub fn load_signing_key<P: AsRef<Path>>(path: P) -> Result<SigningKeys, Error> {
    // let path: PathBuf = path.as_ref().join("signing_secret_key");
    debug!("load_signing_key: {:?}", path.as_ref());
    let tsk = sequoia_openpgp::TPK::from_reader(&std::fs::File::open(&path)?)?.into_tsk();
    use sequoia_openpgp::crypto::KeyPair;
    use sequoia_openpgp::packet::key::SecretKey;
    let mut keys = Vec::new();
    for key in tsk.select_signing_keys(None) {
        if let Some(mut secret) = key.secret() {
            debug!("secret");
            let secret_mpis = match secret {
                SecretKey::Encrypted { .. } => {
                    let password = rpassword::prompt_password_stderr(&format!(
                        "Please enter password to decrypt {:?}/{}: ",
                        path.as_ref(),
                        key
                    ))?;
                    secret.decrypt(key.pk_algo(), &password.into())?
                }
                SecretKey::Unencrypted { ref mpis } => mpis.clone(),
            };
            keys.push(KeyPair::new(key.clone(), secret_mpis)?)
        } else {
            debug!("no secret");
        }
    }
    debug!("found {:?} keys", keys.len());
    Ok(SigningKeys {
        keys,
        tsk,
        user_id: String::new(),
    })
}

pub fn generate_global_ssh_key() -> Result<(), Error> {
    generate_ssh_key(&global_path()?, None)
}

#[cfg(unix)]
fn set_key_permissions(f: &File, key_type: &str) {
    use std::os::unix::fs::PermissionsExt;
    match f.set_permissions(std::fs::Permissions::from_mode(0o600)) {
        Err(e) => eprintln!(
            "Warning: failed to set permissions on {}: {:?}",
            key_type, e
        ),
        Ok(()) => (),
    };