pe-sign 0.1.10

pe-sign is a cross-platform tool developed in Rust, designed for parsing and verifying digital signatures in PE files. It provides a simple command-line interface that supports extracting certificates, verifying digital signatures, calculating Authenticode digests, and printing certificate information.
Documentation
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use std::{fmt::Display, io::Read};

use chrono::{DateTime, Local, Utc};
use der::{
    oid::db::rfc5912::{
        ID_SHA_1, ID_SHA_224, ID_SHA_256, ID_SHA_384, ID_SHA_512, MD_5_WITH_RSA_ENCRYPTION,
        RSA_ENCRYPTION, SHA_1_WITH_RSA_ENCRYPTION, SHA_224_WITH_RSA_ENCRYPTION,
        SHA_256_WITH_RSA_ENCRYPTION, SHA_384_WITH_RSA_ENCRYPTION, SHA_512_WITH_RSA_ENCRYPTION,
    },
    Decode, Encode,
};
use digest::{Digest, DynDigest};
use num_traits::ToPrimitive;
use rsa::{pkcs1::DecodeRsaPublicKey, traits::PublicKeyParts, Pkcs1v15Sign, RsaPublicKey};
use sha1::Sha1;
use sha2::{Sha224, Sha256, Sha384, Sha512};

use crate::{
    errors::{PeSignError, PeSignErrorKind, PeSignResult},
    utils::{DisplayBytes, IndentString, TryVecInto},
};

use super::{
    ext::{Extension, Extensions},
    name::RdnSequence,
};

/// Parse Certificate.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Certificate {
    pub version: u8,
    pub serial_number: Vec<u8>,
    pub issuer: RdnSequence,
    pub validity: Validity,
    pub subject: RdnSequence,
    pub subject_public_key_info: SubjectPublicKeyInfo,
    pub extensions: Option<Extensions>,
    pub signature_algorithm: Algorithm,
    pub signature_value: Vec<u8>,
    __inner: x509_cert::Certificate,
}

impl der::Encode for Certificate {
    fn encoded_len(&self) -> der::Result<der::Length> {
        self.__inner.encoded_len()
    }

    fn encode(&self, encoder: &mut impl der::Writer) -> der::Result<()> {
        self.__inner.encode(encoder)
    }
}

impl<'a> der::Decode<'a> for Certificate {
    fn decode<R: der::Reader<'a>>(decoder: &mut R) -> der::Result<Self> {
        let cert = x509_cert::Certificate::decode(decoder)?;

        cert.try_into()
            .map_err(|_| der::Error::new(der::ErrorKind::Failed, der::Length::ZERO))
    }
}

impl der::pem::PemLabel for Certificate {
    const PEM_LABEL: &'static str = "CERTIFICATE";
}

impl Display for Certificate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Certificate:")?;
        writeln!(f, "{}", "Data:".indent(4))?;
        writeln!(
            f,
            "{}",
            format!("Version: {} (0x{:x})", self.version + 1, self.version).indent(8)
        )?;
        writeln!(f, "{}", "Serial Number:".indent(8))?;
        writeln!(
            f,
            "{}",
            self.serial_number.clone().to_bytes_string().indent(12)
        )?;
        writeln!(f, "{}", format!("Issuer: {}", self.issuer).indent(8))?;
        writeln!(f, "{}", self.validity.to_string().indent(8))?;
        writeln!(f, "{}", format!("Subject: {}", self.subject).indent(8))?;
        writeln!(f, "{}", self.subject_public_key_info.to_string().indent(8))?;
        if self.extensions.is_some() {
            writeln!(
                f,
                "{}",
                self.extensions.clone().unwrap().to_string().indent(8)
            )?;
        }
        writeln!(
            f,
            "{}",
            format!("Signature Algorithm: {}", self.signature_algorithm).indent(4)
        )?;
        writeln!(f, "{}", "Signature Value:".indent(4))?;
        write!(
            f,
            "{}",
            self.signature_value.clone().to_bytes_string().indent(12)
        )
    }
}

impl Certificate {
    /// Import certificate from pem str.
    pub fn load_pem_chain(input: &str) -> Result<Vec<Self>, PeSignError> {
        fn find_boundary<T>(haystack: &[T], needle: &[T]) -> Option<usize>
        where
            for<'a> &'a [T]: PartialEq,
        {
            haystack
                .windows(needle.len())
                .position(|window| window == needle)
        }

        let mut certs = Vec::new();
        let mut position: usize = 0;

        let start_boundary = &b"-----BEGIN CERTIFICATE-----"[..];
        let end_boundary = &b"-----END CERTIFICATE-----"[..];

        let mut input = input.as_bytes();

        // Strip the trailing whitespaces
        loop {
            if input.is_empty() {
                break;
            }
            let last_pos = input.len() - 1;

            match input.get(last_pos) {
                Some(b'\r') | Some(b'\n') => {
                    input = &input[..last_pos];
                }
                _ => break,
            }
        }

        while position < input.len() - 1 {
            let rest = &input[position..];
            let start_pos = find_boundary(rest, start_boundary).ok_or(PeSignError {
                kind: PeSignErrorKind::InvalidPEMCertificate,
                message: "".to_owned(),
            })?;
            let end_pos = find_boundary(rest, end_boundary).ok_or(PeSignError {
                kind: PeSignErrorKind::InvalidPEMCertificate,
                message: "".to_owned(),
            })? + end_boundary.len();

            let cert_buf = &rest[start_pos..end_pos];
            // println!("{}", String::from_utf8_lossy(cert_buf));

            // from_pem 会报  PEM Base64 error,PEM 库使用的默认的 64,并不是动态动态判断的
            let mut decoder = pem_rfc7468::Decoder::new_detect_wrap(cert_buf)
                .map_app_err(PeSignErrorKind::InvalidPEMCertificate)?;
            let mut buf = vec![];
            decoder
                .read_to_end(&mut buf)
                .map_app_err(PeSignErrorKind::InvalidPEMCertificate)?;
            let cert = x509_cert::Certificate::from_der(&buf)
                .map_app_err(PeSignErrorKind::InvalidPEMCertificate)?
                .try_into()?;

            certs.push(cert);

            position += end_pos;
        }

        Ok(certs)
    }

    /// Check if it's a CA certificate.
    pub fn is_ca(self: &Self) -> bool {
        match &self.extensions {
            Some(extensions) => {
                match extensions.0.iter().find(|&ext| match ext {
                    Extension::BasicConstraints(_) => true,
                    _ => false,
                }) {
                    Some(Extension::BasicConstraints(basic_constraints)) => basic_constraints.ca,
                    _ => false,
                }
            }
            None => false,
        }
    }

    /// Check if it's a selfsign certificate.
    pub fn is_selfsigned(self: &Self) -> bool {
        if self.issuer == self.subject {
            true
        } else {
            false
        }
    }

    /// Get the tbs_certificate binary data for validating its trustworthiness,
    /// and the decrypted signature is the hash of tbs_certificate.
    pub fn get_tbs_certificate_bytes(self: &Self) -> Vec<u8> {
        self.__inner.tbs_certificate.to_der().unwrap()
    }
}

impl TryFrom<x509_cert::Certificate> for Certificate {
    type Error = PeSignError;

    fn try_from(value: x509_cert::Certificate) -> Result<Self, Self::Error> {
        let __inner_orginal_cert = value.clone();
        let version = value.tbs_certificate.version as u8;
        let serial_number = value.tbs_certificate.serial_number.as_bytes().to_vec();
        let issuer = value.tbs_certificate.issuer.into();
        let validity = value.tbs_certificate.validity.into();
        let subject = value.tbs_certificate.subject.into();
        let subject_public_key_info = value.tbs_certificate.subject_public_key_info.try_into()?;
        let extensions = match value.tbs_certificate.extensions {
            Some(exs) => Some(Extensions(exs.try_vec_into().map_err(|err| {
                Self::Error {
                    kind: PeSignErrorKind::InvalidCertificateExtension,
                    message: err.to_string(),
                }
            })?)),
            None => None,
        };
        let signature_algorithm = value.signature_algorithm.into();
        let signature_value = value.signature.raw_bytes().to_vec();

        Ok(Self {
            version,
            serial_number,
            issuer,
            validity,
            subject,
            subject_public_key_info,
            extensions,
            signature_algorithm,
            signature_value,
            __inner: __inner_orginal_cert,
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Algorithm {
    Sha1,
    Sha224,
    Sha256,
    Sha384,
    Sha512,
    Md5,
    RSA,
    Md5WithRSA,
    Sha1WithRSA,
    Sha224WithRSA,
    Sha256WithRSA,
    Sha384WithRSA,
    Sha512WithRSA,
    Unsupported(String),
}

impl Display for Algorithm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl From<x509_cert::spki::AlgorithmIdentifierOwned> for Algorithm {
    fn from(value: x509_cert::spki::AlgorithmIdentifierOwned) -> Self {
        // let params = match value.parameters {
        //     Some(p) => match p.is_null() {
        //         true => None,
        //         false => Some(p.value().to_vec()),
        //     },
        //     None => None,
        // };

        match value.oid {
            ID_SHA_1 => Self::Sha1,
            ID_SHA_224 => Self::Sha224,
            ID_SHA_256 => Self::Sha256,
            ID_SHA_384 => Self::Sha384,
            ID_SHA_512 => Self::Sha512,
            RSA_ENCRYPTION => Self::RSA,
            MD_5_WITH_RSA_ENCRYPTION => Self::Md5WithRSA,
            SHA_1_WITH_RSA_ENCRYPTION => Self::Sha1WithRSA,
            SHA_224_WITH_RSA_ENCRYPTION => Self::Sha224WithRSA,
            SHA_256_WITH_RSA_ENCRYPTION => Self::Sha256WithRSA,
            SHA_384_WITH_RSA_ENCRYPTION => Self::Sha384WithRSA,
            SHA_512_WITH_RSA_ENCRYPTION => Self::Sha512WithRSA,
            oid => Self::Unsupported(oid.to_string()),
        }
    }
}

impl Algorithm {
    pub fn new_digest(self: &Self) -> Result<Box<dyn DynDigest>, PeSignError> {
        match self {
            Algorithm::Sha1 | Algorithm::Sha1WithRSA => Ok(Sha1::new().box_clone()),
            Algorithm::Sha224 | Algorithm::Sha224WithRSA => Ok(Sha224::new().box_clone()),
            Algorithm::Sha256 | Algorithm::Sha256WithRSA => Ok(Sha256::new().box_clone()),
            Algorithm::Sha384 | Algorithm::Sha384WithRSA => Ok(Sha384::new().box_clone()),
            Algorithm::Sha512 | Algorithm::Sha512WithRSA => Ok(Sha512::new().box_clone()),
            _ => Err(PeSignError {
                kind: PeSignErrorKind::UnsupportedAlgorithm,
                message: format!("digest: {}", self),
            }),
        }
    }

    pub fn new_pkcs1v15sign(self: &Self) -> Result<Pkcs1v15Sign, PeSignError> {
        match self {
            Algorithm::Sha1 | Algorithm::Sha1WithRSA => Ok(Pkcs1v15Sign::new::<Sha1>()),
            Algorithm::Sha224 | Algorithm::Sha224WithRSA => Ok(Pkcs1v15Sign::new::<Sha224>()),
            Algorithm::Sha256 | Algorithm::Sha256WithRSA => Ok(Pkcs1v15Sign::new::<Sha256>()),
            Algorithm::Sha384 | Algorithm::Sha384WithRSA => Ok(Pkcs1v15Sign::new::<Sha384>()),
            Algorithm::Sha512 | Algorithm::Sha512WithRSA => Ok(Pkcs1v15Sign::new::<Sha512>()),
            _ => Err(PeSignError {
                kind: PeSignErrorKind::UnsupportedAlgorithm,
                message: format!("pkcs1v15sign: {}", self),
            }),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Validity {
    pub not_before: DateTime<Utc>,
    pub not_after: DateTime<Utc>,
}

impl From<x509_cert::time::Validity> for Validity {
    fn from(value: x509_cert::time::Validity) -> Self {
        Self {
            not_before: value.not_before.to_system_time().into(),
            not_after: value.not_after.to_system_time().into(),
        }
    }
}

impl Display for Validity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let start_time = self.not_before.with_timezone(&Local);
        let end_time = self.not_after.with_timezone(&Local);

        writeln!(f, "Not Before: {}", start_time)?;
        write!(f, "Not After : {}", end_time)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SubjectPublicKeyInfo {
    pub algorithm: Algorithm,
    pub subject_public_key: Vec<u8>,
    __inner: x509_cert::spki::SubjectPublicKeyInfoOwned,
    __inner_public_key: Option<RsaPublicKey>,
}

impl der::Encode for SubjectPublicKeyInfo {
    fn encoded_len(&self) -> der::Result<der::Length> {
        self.__inner.encoded_len()
    }

    fn encode(&self, encoder: &mut impl der::Writer) -> der::Result<()> {
        self.__inner.encode(encoder)
    }
}

impl<'a> der::Decode<'a> for SubjectPublicKeyInfo {
    fn decode<R: der::Reader<'a>>(decoder: &mut R) -> der::Result<Self> {
        let cert = x509_cert::spki::SubjectPublicKeyInfoOwned::decode(decoder)?;

        cert.try_into()
            .map_err(|_| der::Error::new(der::ErrorKind::Failed, der::Length::ZERO))
    }
}

impl der::pem::PemLabel for SubjectPublicKeyInfo {
    const PEM_LABEL: &'static str = "PUBLIC KEY";
}

impl TryFrom<x509_cert::spki::SubjectPublicKeyInfoOwned> for SubjectPublicKeyInfo {
    type Error = PeSignError;

    fn try_from(value: x509_cert::spki::SubjectPublicKeyInfoOwned) -> Result<Self, Self::Error> {
        let __inner = value.clone();
        let algorithm = value.algorithm.into();
        let mut rsa_publickey = None;

        if algorithm == Algorithm::RSA {
            rsa_publickey = Some(
                RsaPublicKey::from_pkcs1_der(value.subject_public_key.raw_bytes())
                    .map_app_err(PeSignErrorKind::InvalidPublicKey)?,
            );
        }

        Ok(Self {
            algorithm,
            subject_public_key: value.subject_public_key.raw_bytes().to_vec(),
            __inner,
            __inner_public_key: rsa_publickey,
        })
    }
}

impl Display for SubjectPublicKeyInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mudulus = self.get_public_key_modulus();
        let exponent = self.get_public_key_exponent().unwrap_or(0);

        writeln!(f, "Subject Public Key Info:")?;
        writeln!(
            f,
            "{}",
            format!("Algorithm: {:?}", self.algorithm).indent(4)
        )?;
        writeln!(
            f,
            "{}",
            format!("Public-Key: ({} bit)\nModulus:", (mudulus.len() - 1) * 8).indent(4)
        )?;
        writeln!(f, "{}", mudulus.to_bytes_string().indent(8))?;
        write!(
            f,
            "{}",
            format!("Exponent: {} (0x{:x})", exponent, exponent).indent(4)
        )
    }
}

impl SubjectPublicKeyInfo {
    /// Returns the modulus of the key.
    pub fn get_public_key_modulus(self: &Self) -> Vec<u8> {
        match &self.__inner_public_key {
            Some(rsa_public_key) => {
                let mut tmp = rsa_public_key.n().to_bytes_be();
                tmp.insert(0, 0);
                tmp
            }
            None => self.subject_public_key.clone(),
        }
    }

    /// Returns the public exponent of the key.
    pub fn get_public_key_exponent(self: &Self) -> Option<usize> {
        match &self.__inner_public_key {
            Some(rsa_public_key) => rsa_public_key.e().to_usize(),
            None => None,
        }
    }
}