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
//! token serialization/deserialization
//!
//! Biscuit tokens are serialized to Protobuf. There are two levels of serialization:
//!
//! - serialization of Biscuit blocks to Protobuf then `Vec<u8>`
//! - serialization of a wrapper structure containing serialized blocks and the signature
use super::crypto::{KeyPair, TokenSignature};
use crate::crypto::PublicKey;
use curve25519_dalek::ristretto::CompressedRistretto;
use prost::Message;
use rand_core::{CryptoRng, RngCore};

use super::error;
use super::token::Block;

/// Structures generated from the Protobuf schema
pub mod schema;/* {
    include!(concat!(env!("OUT_DIR"), "/biscuit.format.schema.rs"));
}*/

pub mod convert;

use self::convert::*;

/// Intermediate structure for token serialization
///
/// This structure contains the blocks serialized to byte arrays. Those arrays
/// will be used for the signature
#[derive(Clone, Debug)]
pub struct SerializedBiscuit {
    pub authority: Vec<u8>,
    pub blocks: Vec<Vec<u8>>,
    pub keys: Vec<PublicKey>,
    pub signature: TokenSignature,
}

impl SerializedBiscuit {
    pub fn from_slice(slice: &[u8]) -> Result<Self, error::Format> {
        let data = schema::Biscuit::decode(slice).map_err(|e| {
            error::Format::DeserializationError(format!("deserialization error: {:?}", e))
        })?;

        let mut keys = vec![];

        for key in data.keys {
            if key.len() == 32 {
                if let Some(k) = CompressedRistretto::from_slice(&key[..]).decompress() {
                    keys.push(PublicKey(k));
                } else {
                    return Err(error::Format::DeserializationError(
                        "deserialization error: cannot decompress key point".to_string(),
                    ));
                }
            } else {
                return Err(error::Format::DeserializationError(format!(
                    "deserialization error: invalid size for key = {} bytes",
                    key.len()
                )));
            }
        }

        let signature = proto_sig_to_token_sig(data.signature)?;

        let deser = SerializedBiscuit {
            authority: data.authority,
            blocks: data.blocks,
            keys,
            signature,
        };

        match deser.verify() {
            Ok(()) => Ok(deser),
            Err(e) => Err(e),
        }
    }

    /// serializes the token
    pub fn to_proto(&self) -> schema::Biscuit {
        schema::Biscuit {
            authority: self.authority.clone(),
            blocks: self.blocks.clone(),
            keys: self
                .keys
                .iter()
                .map(|k| Vec::from(&k.0.compress().to_bytes()[..]))
                .collect(),
            signature: token_sig_to_proto_sig(&self.signature),
        }
    }

    /// serializes the token
    pub fn to_vec(&self) -> Result<Vec<u8>, error::Format> {
        let b = self.to_proto();

        let mut v = Vec::new();

        b.encode(&mut v)
            .map(|_| v)
            .map_err(|e| error::Format::SerializationError(format!("serialization error: {:?}", e)))
    }

    /// creates a new token
    pub fn new<T: RngCore + CryptoRng>(
        rng: &mut T,
        keypair: &KeyPair,
        authority: &Block,
    ) -> Result<Self, error::Format> {
        let mut v = Vec::new();
        token_block_to_proto_block(authority)
            .encode(&mut v)
            .map_err(|e| {
                error::Format::SerializationError(format!("serialization error: {:?}", e))
            })?;

        let signature = TokenSignature::new(rng, keypair, &v);

        Ok(SerializedBiscuit {
            authority: v,
            blocks: vec![],
            keys: vec![keypair.public()],
            signature,
        })
    }

    /// adds a new block, serializes it and sign a new token
    pub fn append<T: RngCore + CryptoRng>(
        &self,
        rng: &mut T,
        keypair: &KeyPair,
        block: &Block,
    ) -> Result<Self, error::Format> {
        let mut v = Vec::new();
        token_block_to_proto_block(block)
            .encode(&mut v)
            .map_err(|e| {
                error::Format::SerializationError(format!("serialization error: {:?}", e))
            })?;

        let mut blocks = Vec::new();
        blocks.push(self.authority.clone());
        blocks.extend(self.blocks.iter().cloned());

        let signature = self.signature.sign(rng, keypair, &v);

        let mut t = SerializedBiscuit {
            authority: self.authority.clone(),
            blocks: self.blocks.clone(),
            keys: self.keys.clone(),
            signature,
        };

        t.blocks.push(v);
        t.keys.push(keypair.public());

        Ok(t)
    }

    /// checks the signature on a deserialized token
    pub fn verify(&self) -> Result<(), error::Format> {
        if self.keys.is_empty() {
            return Err(error::Format::EmptyKeys);
        }

        let mut blocks = Vec::new();
        blocks.push(self.authority.clone());
        blocks.extend(self.blocks.iter().cloned());

        self.signature
            .verify(&self.keys, &blocks)
            .map_err(error::Format::Signature)
    }

    pub fn check_root_key(&self, root: PublicKey) -> Result<(), error::Format> {
        if self.keys.is_empty() {
            return Err(error::Format::EmptyKeys);
        }
        if self.keys[0] != root {
            return Err(error::Format::UnknownPublicKey);
        }

        Ok(())
    }
}