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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright 2019 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use anyhow::{bail, Context, Result};
use std::fs::{metadata, set_permissions, OpenOptions};
use std::io::{self, Read, Write};
use std::os::unix::fs::PermissionsExt;
use std::process::{Child, Command, Stdio};
use std::thread::{self, JoinHandle};
use tempfile::{self, TempDir};

#[derive(Debug)]
pub enum VerifyKeys {
    /// Production keys
    Production,
    /// Snake oil key
    #[cfg(test)]
    InsecureTest,
}

#[derive(Debug)]
enum VerifyReport {
    /// Report verification result to stderr
    Stderr,
    /// Report verification result to stderr only if successful
    StderrOnSuccess,
    /// Verify silently
    Ignore,
}

pub struct VerifyReader<R: Read> {
    typ: VerifyType<R>,
}

enum VerifyType<R: Read> {
    None(R),
    Gpg(GpgReader<R>),
}

impl<R: Read> VerifyReader<R> {
    pub fn new(source: R, gpg_signature: Option<&[u8]>, keys: VerifyKeys) -> Result<Self> {
        let typ = if let Some(signature) = gpg_signature {
            VerifyType::Gpg(GpgReader::new(source, signature, keys)?)
        } else {
            VerifyType::None(source)
        };
        Ok(VerifyReader { typ })
    }

    /// Return an error if signature verification fails, and report the
    /// result to stderr
    pub fn verify(&mut self) -> Result<()> {
        match &mut self.typ {
            VerifyType::None(_) => (),
            VerifyType::Gpg(reader) => reader.finish(VerifyReport::Stderr)?,
        }
        Ok(())
    }

    /// Return an error if signature verification fails.  Report the result
    /// to stderr if verification is successful, but not if it fails.
    pub fn verify_without_logging_failure(&mut self) -> Result<()> {
        match &mut self.typ {
            VerifyType::None(_) => (),
            VerifyType::Gpg(reader) => reader.finish(VerifyReport::StderrOnSuccess)?,
        }
        Ok(())
    }
}

impl<R: Read> Read for VerifyReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match &mut self.typ {
            VerifyType::None(reader) => reader.read(buf),
            VerifyType::Gpg(reader) => reader.read(buf),
        }
    }
}

struct GpgReader<R: Read> {
    _gpgdir: TempDir,
    source: R,
    child: Child,
    stderr_thread: Option<JoinHandle<io::Result<Vec<u8>>>>,
}

impl<R: Read> GpgReader<R> {
    fn new(source: R, signature: &[u8], keys: VerifyKeys) -> Result<Self> {
        // create GPG home directory with restrictive mode
        let gpgdir = tempfile::Builder::new()
            .prefix("coreos-installer-")
            .tempdir()
            .context("creating temporary directory")?;
        let meta = metadata(gpgdir.path()).context("getting metadata for temporary directory")?;
        let mut permissions = meta.permissions();
        permissions.set_mode(0o700);
        set_permissions(gpgdir.path(), permissions)
            .context("setting mode for temporary directory")?;

        // import public keys
        let keys = match keys {
            VerifyKeys::Production => &include_bytes!("../signing-keys.asc")[..],
            #[cfg(test)]
            VerifyKeys::InsecureTest => {
                &include_bytes!("../../fixtures/verify/test-key.pub.asc")[..]
            }
        };
        let mut import = Command::new("gpg")
            .arg("--homedir")
            .arg(gpgdir.path())
            .arg("--batch")
            .arg("--quiet")
            .arg("--import")
            .stdin(Stdio::piped())
            .spawn()
            .context("running gpg --import")?;
        import
            .stdin
            .as_mut()
            .unwrap()
            .write_all(keys)
            .context("importing GPG keys")?;
        if !import.wait().context("waiting for gpg --import")?.success() {
            bail!("gpg --import failed");
        }

        // list the public keys we just imported
        let mut list = Command::new("gpg")
            .arg("--homedir")
            .arg(gpgdir.path())
            .arg("--batch")
            .arg("--list-keys")
            .arg("--with-colons")
            .stdout(Stdio::piped())
            .spawn()
            .context("running gpg --list-keys")?;
        let mut list_output = String::new();
        list.stdout
            .as_mut()
            .unwrap()
            .read_to_string(&mut list_output)
            .context("listing GPG keys")?;
        if !list
            .wait()
            .context("waiting for gpg --list-keys")?
            .success()
        {
            bail!("gpg --list-keys failed");
        }

        // accumulate key IDs into trust arguments
        let mut trust: Vec<&str> = Vec::new();
        for line in list_output.lines() {
            let fields: Vec<&str> = line.split(':').collect();
            // only look at public keys
            if fields[0] != "pub" {
                continue;
            }
            // extract key ID
            if fields.len() >= 5 {
                trust.append(&mut vec!["--trusted-key", fields[4]]);
            }
        }

        // mark keys trusted in trustdb
        // We do this as a separate pass to keep the resulting log lines
        // out of the verify output.
        let trustdb = Command::new("gpg")
            .arg("--homedir")
            .arg(gpgdir.path())
            .arg("--batch")
            .arg("--check-trustdb")
            .args(trust)
            .output()
            .context("running gpg --check-trustdb")?;
        if !trustdb.status.success() {
            // copy out its stderr
            eprint!("{}", String::from_utf8_lossy(&trustdb.stderr));
            bail!("gpg --check-trustdb failed");
        }

        // write signature to file
        let mut signature_path = gpgdir.path().to_path_buf();
        signature_path.push("signature");
        let mut signature_file = OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(&signature_path)
            .context("creating signature file")?;
        signature_file
            .write_all(signature)
            .context("writing signature file")?;

        // start verification
        let mut verify = Command::new("gpg")
            .arg("--homedir")
            .arg(gpgdir.path())
            .arg("--batch")
            .arg("--verify")
            .arg(&signature_path)
            .arg("-")
            .stdin(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .context("running gpg --verify")?;

        // spawn stderr reader
        let mut stderr = verify.stderr.take().unwrap();
        let stderr_thread = thread::Builder::new()
            .name("gpg-stderr".into())
            .spawn(move || -> io::Result<Vec<u8>> {
                let mut buf = Vec::new();
                stderr.read_to_end(&mut buf)?;
                Ok(buf)
            })
            .context("spawning GPG stderr reader")?;

        Ok(GpgReader {
            _gpgdir: gpgdir,
            source,
            child: verify,
            stderr_thread: Some(stderr_thread),
        })
    }

    /// Stop GPG, forward its stderr if requested, and check its exit status.
    /// The exit status check happens on every call, but stderr forwarding
    /// only happens on the first call.
    fn finish(&mut self, report: VerifyReport) -> io::Result<()> {
        // do cleanup first: wait for child process and join on thread
        let wait_result = self.child.wait();
        let join_result = self.stderr_thread.take().map(|t| t.join());

        // possibly copy GPG's stderr to ours
        let success = wait_result?.success();
        match join_result {
            // thread returned GPG's stderr
            Some(Ok(Ok(stderr))) => match report {
                VerifyReport::StderrOnSuccess if !success => (),
                // use eprint rather than io::stderr() so the output is
                // captured when running tests
                VerifyReport::Stderr | VerifyReport::StderrOnSuccess => {
                    eprint!("{}", String::from_utf8_lossy(&stderr))
                }
                VerifyReport::Ignore => (),
            },
            // thread returned error
            Some(Ok(Err(e))) => return Err(e),
            // thread panicked; propagate the panic
            Some(Err(e)) => std::panic::resume_unwind(e),
            // already joined the thread on a previous call
            None => (),
        }

        // check GPG exit status
        if !success {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "GPG verification failure",
            ));
        }

        Ok(())
    }
}

impl<R: Read> Read for GpgReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        let count = self.source.read(buf)?;
        if count > 0 {
            // On a partial write we return an error in violation of the
            // API contract.  This should be okay, since it's a fatal error
            // for us anyway.
            self.child
                .stdin
                .as_mut()
                .unwrap()
                .write_all(&buf[0..count])?;
        }
        Ok(count)
    }
}

impl<R: Read> Drop for GpgReader<R> {
    fn drop(&mut self) {
        // if we haven't already forwarded GPG's stderr, avoid doing it now,
        // so we don't imply that we're checking the result
        self.finish(VerifyReport::Ignore).ok();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Read data with valid signature
    #[test]
    fn test_good_signature() {
        let data = include_bytes!("../../fixtures/verify/test-key.priv.asc");
        let sig = include_bytes!("../../fixtures/verify/test-key.priv.asc.sig");

        let mut reader =
            VerifyReader::new(&data[..], Some(&sig[..]), VerifyKeys::InsecureTest).unwrap();
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf).unwrap();
        reader.verify().unwrap();
        reader.verify().unwrap();
        reader.verify_without_logging_failure().unwrap();
        assert_eq!(&buf[..], &data[..]);
    }

    /// Read data with bad signature
    #[test]
    fn test_bad_signature() {
        let mut data = *include_bytes!("../../fixtures/verify/test-key.priv.asc");
        let sig = include_bytes!("../../fixtures/verify/test-key.priv.asc.sig");
        data[data.len() - 1] = b'!';

        let mut reader =
            VerifyReader::new(&data[..], Some(&sig[..]), VerifyKeys::InsecureTest).unwrap();
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf).unwrap();
        reader.verify().unwrap_err();
        reader.verify().unwrap_err();
        reader.verify_without_logging_failure().unwrap_err();
        assert_eq!(&buf[..], &data[..]);
    }

    /// Read truncated data with otherwise-valid signature
    #[test]
    fn test_truncated_data() {
        let data = include_bytes!("../../fixtures/verify/test-key.priv.asc");
        let sig = include_bytes!("../../fixtures/verify/test-key.priv.asc.sig");

        let mut reader =
            VerifyReader::new(&data[..1000], Some(&sig[..]), VerifyKeys::InsecureTest).unwrap();
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf).unwrap();
        reader.verify().unwrap_err();
        reader.verify().unwrap_err();
        reader.verify_without_logging_failure().unwrap_err();
        assert_eq!(&buf[..], &data[..1000]);
    }

    /// Read data with signing key not in keyring
    #[test]
    fn test_no_pubkey() {
        let data = include_bytes!("../../fixtures/verify/test-key.priv.asc");
        let sig = include_bytes!("../../fixtures/verify/test-key.priv.asc.random.sig");

        let mut reader =
            VerifyReader::new(&data[..], Some(&sig[..]), VerifyKeys::InsecureTest).unwrap();
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf).unwrap();
        reader.verify().unwrap_err();
        reader.verify().unwrap_err();
        reader.verify_without_logging_failure().unwrap_err();
        assert_eq!(&buf[..], &data[..]);
    }
}