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
//! Implements the authentication layer.
use std::borrow::Cow;

use derive_more::{Display, Error};
use hmac::Hmac;
use pbkdf2::pbkdf2;
use serde::{de, ser, Deserialize, Serialize};
use serde_plain::{forward_display_to_serde, forward_from_str_to_serde};
use sha2::Sha256;
use uuid::Uuid;

use crate::crypto::{seal, unseal, PublicKey, SecretKey};
use crate::utils::base64;

const SHARED_SALT: &[u8; 16] = b"nX\xdfu\x1au=\xd7\xe3d.\x1c\xb2\x11P\x0b";

/// Just the Unique ID detached from the authentication.
#[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct UniqueIdentity(Uuid);

impl UniqueIdentity {
    /// Creates a new unique identity.
    pub fn unique() -> UniqueIdentity {
        UniqueIdentity(Uuid::new_v4())
    }

    /// Hashes this unique identity
    pub fn hash(&self) -> HashedIdentity {
        let mut hashed_id = [0u8; 32];
        pbkdf2::<Hmac<Sha256>>(self.0.as_bytes(), SHARED_SALT, 50000, &mut hashed_id);
        HashedIdentity(hashed_id)
    }
}

/// Represents the unique identity of a person with auth info.
///
/// The identity is to kept private on the device and not shared with anyone
/// other than authorities when you are infected.  After it has every been
/// shared it must by cycled.
///
/// For sharing for subscription or cehck-in purposes the hashed identity
/// must be used instead.
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(from = "IdentitySmol")]
pub struct Identity {
    unique_id: UniqueIdentity,
    #[serde(skip_serializing)]
    hashed_id: HashedIdentity,
}

#[derive(Serialize, Deserialize)]
struct IdentitySmol {
    unique_id: UniqueIdentity,
}

impl From<IdentitySmol> for Identity {
    fn from(smol: IdentitySmol) -> Identity {
        Identity {
            unique_id: smol.unique_id,
            hashed_id: smol.unique_id.hash(),
        }
    }
}

/// A hashed identity is a derived version of the real identity.
///
/// This can be more freely shared with authorities for update purposes.  It's
/// derived via PBKDF2-HMAC-SHA256 on 10.000 iterations and a well known salt.
/// This is not ideal but it's a compromise.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct HashedIdentity([u8; 32]);

/// Error for invalid hashed identities.
#[derive(Debug, Error, Display, Clone)]
#[display(fmt = "cannot parse hashed identity")]
pub struct HashedIdentityParseError;

forward_display_to_serde!(HashedIdentity);
forward_from_str_to_serde!(HashedIdentity, |_x| -> HashedIdentityParseError {
    HashedIdentityParseError
});

impl Serialize for HashedIdentity {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: ser::Serializer,
    {
        base64::serialize(&self.0[..], serializer)
    }
}

impl<'de> Deserialize<'de> for HashedIdentity {
    fn deserialize<D>(deserializer: D) -> Result<HashedIdentity, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        let bytes: Cow<'de, [u8]> = base64::deserialize(deserializer)?;
        if bytes.len() == 32 {
            let mut id = [0u8; 32];
            id.copy_from_slice(&bytes);
            Ok(HashedIdentity(id))
        } else {
            use serde::de::Error;
            Err(D::Error::custom("cannot deserialize hashed identity"))
        }
    }
}

/// An identity that can be shared with others.
///
/// This identity should be rotated once every few minutes.  It's an encrypted
/// version of the unique ID and sent to other devices.  Only the central
/// authority's key can decode the contained identity.
#[derive(Clone, Serialize, Deserialize, Hash, PartialEq, Eq)]
pub struct ShareIdentity(#[serde(with = "base64")] Vec<u8>);

/// Error for invalid share identities.
#[derive(Debug, Error, Display, Clone)]
#[display(fmt = "cannot parse share identity")]
pub struct ShareIdentityParseError;

forward_display_to_serde!(ShareIdentity);
forward_from_str_to_serde!(ShareIdentity, |_x| -> ShareIdentityParseError {
    {
        dbg!(_x);
        ShareIdentityParseError
    }
});

impl ShareIdentity {
    /// Reveals the unique identity behind a shared identity
    pub fn reveal(&self, secret_key: &SecretKey) -> Option<UniqueIdentity> {
        unseal(&self.0, secret_key)
            .and_then(|x| Uuid::from_slice(&x).ok())
            .map(UniqueIdentity)
    }
}

impl Identity {
    /// Creates a new random identity.
    pub fn unique() -> Identity {
        let unique_id = UniqueIdentity::unique();
        Identity {
            unique_id,
            hashed_id: unique_id.hash(),
        }
    }

    /// Returns the internal unique identity.
    pub fn unique_id(&self) -> &UniqueIdentity {
        &self.unique_id
    }

    /// Returns the hashed identity.
    pub fn hashed_id(&self) -> &HashedIdentity {
        &self.hashed_id
    }

    /// Creates a new shareable identity.
    pub fn new_share_id(&self, public_key: &PublicKey) -> ShareIdentity {
        ShareIdentity(seal(self.unique_id.0.as_bytes(), public_key))
    }
}