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
use bytes::{BufMut, BytesMut};
use core::convert::{TryFrom, TryInto};
use core::time::Duration;
use serde::{Deserialize, Serialize};
use std::time::SystemTime;

use crate::StaticPublicKey;
use crate::{Error, Result};

use ed25519_dalek::Signer;

pub use crate::formats::*;

use std::io::Write;

/// Header of the `SignedPart` that will also be part of the `Certificate`
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
pub struct SignedPartHeader {
    version: u16,
    // Validity start time (unix timestamp)
    valid_from: u32,
    // Signature is invalid after this point in time (unix timestamp)
    not_valid_after: u32,
}

impl SignedPartHeader {
    const VERSION: u16 = 0;

    pub fn serialize_to_writer<T: Write>(&self, writer: &mut T) -> Result<()> {
        let version = self.version.to_le_bytes();
        let valid_from = self.valid_from.to_le_bytes();
        let not_valid_after = self.not_valid_after.to_le_bytes();
        writer
            .write_all(&[&version[..], &valid_from[..], &not_valid_after[..]].concat()[..])
            .unwrap();
        Ok(())
    }

    pub fn from_bytes(b: &[u8]) -> Self {
        debug_assert!(b.len() == 10);
        let version = u16::from_le_bytes([b[0], b[1]]);
        let valid_from = u32::from_le_bytes([b[2], b[3], b[4], b[5]]);
        let not_valid_after = u32::from_le_bytes([b[6], b[7], b[8], b[9]]);
        Self {
            version,
            valid_from,
            not_valid_after,
        }
    }

    pub fn with_duration(valid_for: Duration) -> Result<Self> {
        let valid_from = SystemTime::now();
        let not_valid_after = valid_from + valid_for;
        Ok(Self {
            version: Self::VERSION,
            valid_from: Self::system_time_to_unix_time_u32(&valid_from)?,
            not_valid_after: Self::system_time_to_unix_time_u32(&not_valid_after)?,
        })
    }

    pub fn valid_from(&self) -> SystemTime {
        Self::unix_time_u32_to_system_time(self.valid_from)
            .expect("BUG: cannot provide 'valid_from' time")
    }

    pub fn not_valid_after(&self) -> SystemTime {
        Self::unix_time_u32_to_system_time(self.not_valid_after)
            .expect("BUG: cannot provide 'not_valid_after' time")
    }

    pub fn verify_expiration(&self, now: SystemTime) -> Result<()> {
        let now_timestamp = Self::system_time_to_unix_time_u32(&now)?;
        if now_timestamp < self.valid_from {
            //return Err(ErrorKind::Noise(format!(
            //    "Certificate not yet valid, valid from: {:?}, now: {:?}",
            //    self.valid_from, now
            //))
            //.into());
            return Err(Error {});
        }
        if now_timestamp > self.not_valid_after {
            //return Err(ErrorKind::Noise(format!(
            //    "Certificate expired, not valid after: {:?}, now: {:?}",
            //    self.valid_from, now
            //))
            //.into());
            return Err(Error {});
        }
        Ok(())
    }

    fn system_time_to_unix_time_u32(t: &SystemTime) -> Result<u32> {
        t.duration_since(SystemTime::UNIX_EPOCH)
            .map(|duration| duration.as_secs() as u32)
            .map_err(|_| {
                Error {}
                //ErrorKind::Noise(format!(
                //    "Cannot convert system time to unix timestamp: {}",
                //    e
                //))
                //.into()
            })
    }

    fn unix_time_u32_to_system_time(unix_timestamp: u32) -> Result<SystemTime> {
        SystemTime::UNIX_EPOCH
            .checked_add(Duration::from_secs(unix_timestamp.into()))
            .ok_or(
                Error {}
                //ErrorKind::Noise(
                //    format!(
                //        "Cannot convert unix timestamp ({}) to system time",
                //        unix_timestamp
                //    )
                //    .to_string(),
                //)
                //.into(),
            )
    }
}

/// Helper struct for performing the actual signature of the relevant parts of the certificate
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
pub struct SignedPart {
    pub(crate) header: SignedPartHeader,
    pub(crate) pubkey: StaticPublicKey,
    pub(crate) authority_public_key: ed25519_dalek::PublicKey,
}

impl SignedPart {
    pub fn new(
        header: SignedPartHeader,
        pubkey: StaticPublicKey,
        authority_public_key: ed25519_dalek::PublicKey,
    ) -> Self {
        Self {
            header,
            pubkey,
            authority_public_key,
        }
    }

    fn serialize_to_buf(&self) -> BytesMut {
        let mut signed_part_writer = BytesMut::new().writer();
        let version = &self.header.version.to_le_bytes()[..];
        let valid_from = &self.header.valid_from.to_le_bytes()[..];
        let not_valid_after = &self.header.not_valid_after.to_be_bytes()[..];
        let pub_k = &self.pubkey[..];
        signed_part_writer
            .write_all(&[version, valid_from, not_valid_after, pub_k].concat()[..])
            .unwrap();
        signed_part_writer.into_inner()
    }

    /// Generates the actual ed25519_dalek::Signature that is ready to be embedded into the certificate
    pub fn sign_with(&self, keypair: &ed25519_dalek::Keypair) -> Result<ed25519_dalek::Signature> {
        debug_assert_eq!(
            keypair.public,
            self.authority_public_key,
            "BUG: Signing Authority public key ({}) inside the certificate doesn't match the key \
             we are trying to sign with (its public key is: {})",
            EncodedEd25519PublicKey::new(keypair.public),
            EncodedEd25519PublicKey::new(self.authority_public_key)
        );

        let signed_part_buf = self.serialize_to_buf();
        Ok(keypair.sign(&signed_part_buf[..]))
    }

    /// Verifies the specifed `signature` against this signed part
    pub(crate) fn verify(&self, signature: &ed25519_dalek::Signature) -> Result<()> {
        let signed_part_buf = self.serialize_to_buf();
        self.authority_public_key
            .verify_strict(&signed_part_buf[..], signature)
            .map_err(|_| Error {})?;
        Ok(())
    }

    pub(crate) fn verify_expiration(&self, now: SystemTime) -> Result<()> {
        self.header.verify_expiration(now)
    }
}

/// The payload message that will be appended to the handshake message to proof static key
/// authenticity
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug)]
pub struct SignatureNoiseMessage {
    pub(crate) header: SignedPartHeader,
    pub(crate) signature: ed25519_dalek::Signature,
}

impl SignatureNoiseMessage {
    pub fn serialize_to_writer<T: Write>(&self, writer: &mut T) -> Result<()> {
        // TODO
        // v2::serialization::to_writer(writer, self)?;
        self.header.serialize_to_writer(writer).unwrap();
        writer.write_all(&self.signature.to_bytes()[..]).unwrap();
        Ok(())
    }

    pub fn serialize_to_bytes_mut(&self) -> Result<BytesMut> {
        let mut writer = BytesMut::new().writer();
        self.serialize_to_writer(&mut writer)
            .map_err(|_| Error {})?;
        //.context("Serialize noise message")?;

        let serialized_signature_noise_message = writer.into_inner();

        Ok(serialized_signature_noise_message)
    }

    pub fn with_duration(pub_k: &[u8], priv_k: &[u8], duration: core::time::Duration) -> Self {
        let to_be_signed_keypair =
            crate::generate_keypair().expect("BUG: cannot generate noise static keypair");
        let authority_keypair = ed25519_dalek::Keypair::from_bytes(&[priv_k, pub_k].concat())
            .expect("BUG: cannot generate noise authority keypair");
        let header = SignedPartHeader::with_duration(duration)
            .expect("BUG: cannot prepare certificate header");
        let signed_part = SignedPart::new(
            header.clone(),
            to_be_signed_keypair.public,
            authority_keypair.public,
        );
        let signature = signed_part
            .sign_with(&authority_keypair)
            .expect("BUG: cannot sign");
        Self { header, signature }
    }
}

// Deserialization implementation
impl TryFrom<&[u8]> for SignatureNoiseMessage {
    type Error = Error;

    fn try_from(data: &[u8]) -> Result<Self> {
        debug_assert!(data.len() == 74);
        let header = &data[0..10];
        let siganture = &data[10..74];
        let header = SignedPartHeader::from_bytes(header);
        let signature = ed25519_dalek::Signature::new(siganture.try_into().unwrap());
        Ok(SignatureNoiseMessage { header, signature })
    }
}

#[cfg(test)]
pub(crate) mod test {
    use super::{
        super::{generate_keypair, StaticKeypair},
        *,
    };
    use rand::rngs::OsRng;
    const TEST_CERT_VALIDITY: Duration = Duration::from_secs(3600);

    // Helper that builds a `SignedPart` (as a base e.g. for a noise message or a certificate),
    // testing authority `ed25519_dalek::Keypair` (that actually generated the signature) and the
    // `ed25519_dalek::Signature`
    pub(crate) fn build_test_signed_part_and_auth() -> (
        SignedPart,
        ed25519_dalek::Keypair,
        StaticKeypair,
        ed25519_dalek::Signature,
    ) {
        let mut csprng = OsRng {};
        let to_be_signed_keypair =
            generate_keypair().expect("BUG: cannot generate noise static keypair");
        let authority_keypair = ed25519_dalek::Keypair::generate(&mut csprng);
        let header = SignedPartHeader::with_duration(TEST_CERT_VALIDITY)
            .expect("BUG: cannot prepare certificate header");

        let signed_part = SignedPart::new(
            header,
            to_be_signed_keypair.public.clone(),
            authority_keypair.public,
        );
        let signature = signed_part
            .sign_with(&authority_keypair)
            .expect("BUG: cannot sign");
        (
            signed_part,
            authority_keypair,
            to_be_signed_keypair,
            signature,
        )
    }

    #[test]
    fn header_time_validity_is_valid() {
        let header = SignedPartHeader::with_duration(TEST_CERT_VALIDITY)
            .expect("BUG: cannot build certificate header");
        header
            .verify_expiration(SystemTime::now() + Duration::from_secs(10))
            .expect("BUG: certificate should be evaluated as valid!");
    }

    #[test]
    fn header_time_validity_not_yet_valid() {
        let header = SignedPartHeader::with_duration(TEST_CERT_VALIDITY)
            .expect("BUG: cannot build certificate header");
        let result = header.verify_expiration(SystemTime::now() - Duration::from_secs(10));
        assert!(
            result.is_err(),
            "BUG: Certificate not evaluated as not valid yet: {:?}",
            result
        );
    }

    #[test]
    fn header_time_validity_is_expired() {
        let header = SignedPartHeader::with_duration(TEST_CERT_VALIDITY)
            .expect("BUG: cannot build certificate header");
        let result = header
            .verify_expiration(SystemTime::now() + TEST_CERT_VALIDITY + Duration::from_secs(10));
        assert!(
            result.is_err(),
            "BUG: Certificate not evaluated as expired: {:?}",
            result
        );
    }

    #[test]
    fn signature_noise_message_serialization() {
        let (signed_part, authority_keypair, _static_keypair, _signature) =
            build_test_signed_part_and_auth();

        let noise_message = SignatureNoiseMessage {
            header: signed_part.header.clone(),
            signature: signed_part
                .sign_with(&authority_keypair)
                .expect("BUG: cannot sign"),
        };

        let mut serialized_noise_message_writer = BytesMut::new().writer();
        noise_message
            .serialize_to_writer(&mut serialized_noise_message_writer)
            .expect("BUG: cannot serialize signature noise message");

        let serialized_noise_message_buf = serialized_noise_message_writer.into_inner();
        let deserialized_noise_message =
            SignatureNoiseMessage::try_from(&serialized_noise_message_buf[..])
                .expect("BUG: cannot deserialize signature noise message");

        assert_eq!(
            noise_message, deserialized_noise_message,
            "Signature noise messages don't match each other after serialization cycle"
        )
    }
}