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
// Copyright 2018 Zach Miller
//
// Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT License (https://opensource.org/licenses/MIT), at your option.
//
// This file may not be copied, modified, or distributed except according to those terms.

use bincode;
use hmac::{Hmac, Mac};
use sha2::Sha256;

use serde::de::DeserializeOwned;
use serde::ser::Serialize;

use error::Error;
use storage::{CommittedCheckpoint, Storage, UncommittedCheckpoint};

type HmacSha256 = Hmac<Sha256>;

/// Adds HMAC verification to checkpoint data.
///
/// Currently the Sha256 checksum algorithm is used.
#[derive(Debug)]
pub struct HmacWrapper<S: Storage> {
    inner: S,
    secret_key: Vec<u8>,
}

impl<S: Storage> HmacWrapper<S> {
    /// Adds an `HmacWrapper` around a `Storage` object.
    pub fn wrap(inner: S, secret_key: &[u8]) -> Self {
        Self {
            inner,
            secret_key: secret_key.to_vec(),
        }
    }
}

impl<S: Storage> Storage for HmacWrapper<S> {
    type Committed = Committed<S::Committed>;
    type Uncommitted = Uncommitted<S::Uncommitted>;

    fn create_checkpoint(&mut self, identifier: &str) -> Result<Self::Uncommitted, Error> {
        let inner = self.inner.create_checkpoint(identifier)?;
        let hmac = HmacSha256::new_varkey(&self.secret_key).map_err(|_| {
            Error::initialization(format!(
                "Invalid HMAC key length when initializing checkpoint: {} - ",
                identifier
            ))
        })?;

        Ok(Self::Uncommitted { inner, hmac })
    }

    fn commit_checkpoint(
        &mut self,
        uncommitted: Self::Uncommitted,
    ) -> Result<Self::Committed, Error> {
        let inner = self.inner.commit_checkpoint(uncommitted.inner)?;
        Ok(Self::Committed {
            inner,
            hmac: uncommitted.hmac,
        })
    }

    fn load_checkpoint(&mut self, identifier: &str) -> Result<Self::Committed, Error> {
        let inner = self.inner.load_checkpoint(identifier)?;
        let hmac = HmacSha256::new_varkey(&self.secret_key).map_err(|_| {
            Error::initialization(format!(
                "Failed to initialize storage for {}: Invalid HMAC key length",
                identifier
            ))
        })?;
        Ok(Self::Committed { inner, hmac })
    }

    fn remove_checkpoint(&mut self, identifier: &str) -> Result<(), Error> {
        self.inner.remove_checkpoint(identifier)
    }

    fn checkpoint_identifiers(&mut self) -> Result<Vec<String>, Error> {
        self.inner.checkpoint_identifiers()
    }
}

/// Wraps the `CommittedCheckpoint` objects from the underlying storage to verify checkpoint data
/// when it is retrieved.
#[derive(Debug)]
pub struct Committed<C: CommittedCheckpoint> {
    inner: C,
    hmac: HmacSha256,
}

impl<C: CommittedCheckpoint> CommittedCheckpoint for Committed<C> {
    fn get<T: DeserializeOwned + Serialize>(&mut self, key: &str) -> Result<T, Error> {
        let helper: Helper = self.inner.get(key)?;
        let identifier = self.identifier()?.to_string();
        self.hmac.input(identifier.as_bytes());
        self.hmac.input(&helper.bytes);

        if self.hmac.verify(&helper.hmac).is_err() {
            Err(Error::integrity(format!(
                "HMAC integrity check failed for checkpoint: {}, key: {}",
                identifier, key
            )))?;
        }

        let value = bincode::deserialize(&helper.bytes).map_err(|_| {
            Error::deserialize(format!(
                "Failed to deserialize value from checkpoint: {}, key: {}",
                identifier, key
            ))
        })?;

        Ok(value)
    }

    fn keys(&mut self) -> Result<Vec<String>, Error> {
        self.inner.keys()
    }

    fn identifier(&mut self) -> Result<&str, Error> {
        self.inner.identifier()
    }
}

/// Wraps the `UncommittedCheckpoint` objects from the underlying storage to add an HMAC when
/// checkpoint data is stored and to verify checkpoint data when it is retrieved.
#[derive(Debug)]
pub struct Uncommitted<U: UncommittedCheckpoint> {
    inner: U,
    hmac: HmacSha256,
}

impl<U: UncommittedCheckpoint> UncommittedCheckpoint for Uncommitted<U> {
    fn get<T: DeserializeOwned + Serialize>(&mut self, key: &str) -> Result<T, Error> {
        let helper: Helper = self.inner.get(key)?;
        let identifier = self.identifier()?.to_string();
        self.hmac.input(identifier.as_bytes());
        self.hmac.input(&helper.bytes);

        if self.hmac.verify(&helper.hmac).is_err() {
            Err(Error::integrity(format!(
                "HMAC integrity check failed for checkpoint: {}, key: {}",
                identifier, key
            )))?;
        }

        let value = bincode::deserialize(&helper.bytes).map_err(|_| {
            Error::deserialize(format!(
                "Failed to deserialize value from checkpoint: {}, key: {}",
                identifier, key
            ))
        })?;

        Ok(value)
    }

    fn keys(&mut self) -> Result<Vec<String>, Error> {
        self.inner.keys()
    }

    fn identifier(&mut self) -> Result<&str, Error> {
        self.inner.identifier()
    }

    fn put<T: DeserializeOwned + Serialize>(&mut self, key: &str, value: &T) -> Result<(), Error> {
        let identifier = self.identifier()?.to_string();
        let bytes = bincode::serialize(value).map_err(|_| {
            Error::serialize(format!(
                "Failed to serialize value into checkpoint: {}, key: {}",
                identifier, key
            ))
        })?;

        self.hmac.input(identifier.as_bytes());
        self.hmac.input(&bytes);
        let helper = Helper {
            bytes,
            hmac: self.hmac.result().code().to_vec(),
        };

        self.inner.put(key, &helper)?;
        Ok(())
    }

    fn remove(&mut self, key: &str) -> Result<(), Error> {
        self.inner.remove(key)
    }
}

// Used to add an HMAC to the values being inserted into the checkpoint.
#[derive(Debug, Deserialize, Serialize)]
struct Helper {
    bytes: Vec<u8>,
    hmac: Vec<u8>,
}

#[cfg(all(test, feature = "filestorage-tests"))]
mod test {
    use std::fs::File;
    use std::io::{Read, Write};

    use error::ErrorKind;
    use storage::{CommittedCheckpoint, FileStorage, Storage, UncommittedCheckpoint};
    use test_utils::create_test_directory_with_checkpoint_folders;
    use wrappers::HmacWrapper;

    // Verify that checkpoint data can be read properly when data corruption does not occur.
    #[test]
    fn no_corruption() {
        let dir = create_test_directory_with_checkpoint_folders();
        let path = dir.path();

        let mut storage = HmacWrapper::wrap(FileStorage::open(&path).unwrap(), b"Secret Key");
        let mut uncommitted = storage.create_checkpoint("CP").unwrap();
        uncommitted.put("Key", &"Test String".to_string()).unwrap();
        storage.commit_checkpoint(uncommitted).unwrap();

        let mut file_path = path.join("committed");
        file_path.push("CP");
        file_path.push("Key");
        let mut loaded = storage.load_checkpoint("CP").unwrap();
        assert_eq!(loaded.get::<String>("Key").unwrap(), "Test String");
    }

    // Verify that corruption of checkpoint data is detected properly.
    #[test]
    fn corruption_in_stored_data() {
        let dir = create_test_directory_with_checkpoint_folders();
        let path = dir.path();

        let mut storage = HmacWrapper::wrap(FileStorage::open(&path).unwrap(), b"Secret Key");
        let mut uncommitted = storage.create_checkpoint("CP").unwrap();
        uncommitted.put("Key", &"Test String".to_string()).unwrap();
        storage.commit_checkpoint(uncommitted).unwrap();

        let mut file_path = path.join("committed");
        file_path.push("CP");
        file_path.push("Key");

        let mut bytes = Vec::new();
        let mut file = File::open(&file_path).unwrap();
        file.read_to_end(&mut bytes).unwrap();
        bytes[16] = b'?';

        let mut file = File::create(&file_path).unwrap();
        file.write(&bytes).unwrap();

        let mut loaded = storage.load_checkpoint("CP").unwrap();
        assert_eq!(
            loaded.get::<String>("Key").unwrap_err().kind(),
            ErrorKind::Integrity
        );
    }

    // Verify that corruption of the HMAC is detected properly.
    #[test]
    fn corruption_in_hmac() {
        let dir = create_test_directory_with_checkpoint_folders();
        let path = dir.path();

        let mut storage = HmacWrapper::wrap(FileStorage::open(&path).unwrap(), b"Secret Key");
        let mut uncommitted = storage.create_checkpoint("CP").unwrap();
        uncommitted.put("Key", &"Test String".to_string()).unwrap();
        storage.commit_checkpoint(uncommitted).unwrap();

        let mut file_path = path.join("committed");
        file_path.push("CP");
        file_path.push("Key");

        let mut bytes = Vec::new();
        let mut file = File::open(&file_path).unwrap();
        file.read_to_end(&mut bytes).unwrap();
        bytes[35] = b'?';

        let mut file = File::create(&file_path).unwrap();
        file.write(&bytes).unwrap();

        let mut loaded = storage.load_checkpoint("CP").unwrap();
        assert_eq!(
            loaded.get::<String>("Key").unwrap_err().kind(),
            ErrorKind::Integrity
        );
    }

    // Verify that data signed with an unexpected key is detected properly.
    #[test]
    fn wrong_hmac_key() {
        let dir = create_test_directory_with_checkpoint_folders();
        let path = dir.path();

        let mut storage = HmacWrapper::wrap(FileStorage::open(&path).unwrap(), b"Secret Key1");
        let mut uncommitted = storage.create_checkpoint("CP").unwrap();
        uncommitted.put("Key", &"Test String".to_string()).unwrap();
        storage.commit_checkpoint(uncommitted).unwrap();

        let mut storage = HmacWrapper::wrap(FileStorage::open(&path).unwrap(), b"Secret Key2");

        let mut loaded = storage.load_checkpoint("CP").unwrap();
        assert_eq!(
            loaded.get::<String>("Key").unwrap_err().kind(),
            ErrorKind::Integrity
        );
    }
}