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
use crate::constants::*;
use crate::errors::*;
use crate::signature::*;
use std::fmt::Write as fmtWrite;
use std::fs;
use std::path::Path;

/// A signature, as well as the metadata required to verify it.
#[derive(Clone)]
pub struct SignatureBox {
    pub(crate) untrusted_comment: String,
    pub(crate) signature: Signature,
    pub(crate) sig_and_trusted_comment: Option<Vec<u8>>,
    pub(crate) global_sig: Option<Vec<u8>>,
    pub(crate) is_prehashed: bool,
}

impl Into<String> for SignatureBox {
    fn into(self) -> String {
        self.into_string()
    }
}

impl Into<SignatureBox> for String {
    fn into(self) -> SignatureBox {
        SignatureBox::from_string(&self).unwrap()
    }
}

impl SignatureBox {
    /// Returns `true` if the signed data was pre-hashed.
    pub fn is_prehashed(&self) -> bool {
        self.is_prehashed
    }

    /// The untrusted comment present in the signature.
    pub fn untrusted_comment(&self) -> Result<String> {
        Ok(self.untrusted_comment.clone())
    }

    /// The trusted comment present in the signature.
    pub fn trusted_comment(&self) -> Result<String> {
        let sig_and_trusted_comment = match &self.sig_and_trusted_comment {
            None => {
                return Err(PError::new(
                    ErrorKind::Misc,
                    "trusted comment is not present",
                ))
            }
            Some(sig_and_trusted_comment) => sig_and_trusted_comment,
        };
        if sig_and_trusted_comment.len() < SIGNATURE_BYTES {
            return Err(PError::new(
                ErrorKind::Encoding,
                "invalid trusted comment encoding",
            ));
        }
        let just_comment = String::from_utf8(sig_and_trusted_comment[SIGNATURE_BYTES..].to_vec())?;
        Ok(just_comment)
    }

    /// Create a new `SignatureBox` from a string.
    pub fn from_string(s: &str) -> Result<SignatureBox> {
        let mut lines = s.lines();
        let untrusted_comment = lines
            .next()
            .ok_or_else(|| PError::new(ErrorKind::Io, "Missing untrusted comment"))?
            .to_string();
        let signature_str = lines
            .next()
            .ok_or_else(|| PError::new(ErrorKind::Io, "Missing signature"))?
            .to_string();
        let mut trusted_comment_str = lines
            .next()
            .ok_or_else(|| PError::new(ErrorKind::Io, "Missing trusted comment"))?
            .to_string();
        let global_sig = lines
            .next()
            .ok_or_else(|| PError::new(ErrorKind::Io, "Missing global signature"))?
            .to_string();
        if !untrusted_comment.starts_with(COMMENT_PREFIX) {
            return Err(PError::new(
                ErrorKind::Verify,
                format!("Untrusted comment must start with: {}", COMMENT_PREFIX),
            ));
        }
        let untrusted_comment = untrusted_comment[COMMENT_PREFIX.len()..].to_string();
        let sig_bytes = base64::decode(signature_str.trim().as_bytes())
            .map_err(|e| PError::new(ErrorKind::Io, e))?;
        let signature = Signature::from_bytes(&sig_bytes)?;
        if !trusted_comment_str.starts_with(TRUSTED_COMMENT_PREFIX) {
            return Err(PError::new(
                ErrorKind::Verify,
                format!(
                    "Trusted comment should start with: {}",
                    TRUSTED_COMMENT_PREFIX
                ),
            ));
        }
        let is_prehashed = match signature.sig_alg {
            SIGALG => false,
            SIGALG_PREHASHED => true,
            _ => {
                return Err(PError::new(
                    ErrorKind::Verify,
                    "Unsupported signature algorithm".to_string(),
                ))
            }
        };
        let _ = trusted_comment_str
            .drain(..TRUSTED_COMMENT_PREFIX_LEN)
            .count();
        let mut sig_and_trusted_comment = signature.sig.to_vec();
        sig_and_trusted_comment.extend_from_slice(trusted_comment_str.trim().as_bytes());
        let global_sig = base64::decode(global_sig.trim().as_bytes())
            .map_err(|e| PError::new(ErrorKind::Io, e))?;
        Ok(SignatureBox {
            untrusted_comment,
            signature,
            sig_and_trusted_comment: Some(sig_and_trusted_comment),
            global_sig: Some(global_sig),
            is_prehashed,
        })
    }

    /// Return a `SignatureBox` for a string, for storage.
    #[allow(clippy::inherent_to_string)]
    pub fn to_string(&self) -> String {
        let mut signature_box = String::new();
        writeln!(
            signature_box,
            "{}{}",
            COMMENT_PREFIX, self.untrusted_comment
        )
        .unwrap();
        writeln!(signature_box, "{}", self.signature.to_string()).unwrap();
        writeln!(
            signature_box,
            "{}{}",
            TRUSTED_COMMENT_PREFIX,
            self.trusted_comment()
                .expect("Incomplete SignatureBox: trusted comment is missing")
        )
        .unwrap();
        let global_sig = self
            .global_sig
            .as_ref()
            .expect("Incomplete SignatureBox: global signature is missing");
        writeln!(signature_box, "{}", base64::encode(&global_sig[..])).unwrap();
        signature_box
    }

    /// Convert a `SignatureBox` to a string, for storage.
    pub fn into_string(self) -> String {
        self.to_string()
    }

    /// Return a byte representation of the signature, for storage.
    pub fn to_bytes(&self) -> Vec<u8> {
        self.to_string().as_bytes().to_vec()
    }

    /// Load a `SignatureBox` from a file.
    pub fn from_file<P>(sig_path: P) -> Result<SignatureBox>
    where
        P: AsRef<Path>,
    {
        let s = fs::read_to_string(sig_path)?;
        SignatureBox::from_string(&s)
    }
}