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
// The following code has been ported from libcryptsetup

extern crate byteorder;
extern crate uuid;

use std::convert;
use std::io;
use std::io::Read;
use std::mem;
use std::str;

pub trait LuksHeader {
    fn version(&self) -> u16;
    fn cipher_name(&self) -> Result<&str, Error>;
    fn cipher_mode(&self) -> Result<&str, Error>;
    fn hash_spec(&self) -> Result<&str, Error>;
    fn payload_offset(&self) -> u32;
    fn key_bytes(&self) -> u32;
    fn mk_digest(&self) -> &[u8];
    fn mk_digest_salt(&self) -> &[u8];
    fn mk_digest_iterations(&self) -> u32;
    fn uuid(&self) -> Result<uuid::Uuid, Error>;
}

#[derive(Debug)]
pub enum Error {
    InvalidMagic,
    InvalidStringEncoding(str::Utf8Error),
    InvalidVersion,
    InvalidUuid(uuid::ParseError),
    ReadError(io::Error),
    ReadIncorrectHeaderSize,
    HeaderProcessingError,
}

pub struct BlockDevice;

impl BlockDevice {
    pub fn read_luks_header<R: Read>(reader: R) -> Result<raw::luks_phdr, Error> {
        let luks_phdr_size = mem::size_of::<raw::luks_phdr>();
        let mut buf = Vec::<u8>::with_capacity(luks_phdr_size);
        let read_size = try!(reader.take(luks_phdr_size as u64).read_to_end(&mut buf));
        if read_size != luks_phdr_size {
            Err(Error::ReadIncorrectHeaderSize)
        } else {
            raw::luks_phdr::from_buf(&buf)
        }
    }
}

impl convert::From<str::Utf8Error> for Error {
    fn from(error: str::Utf8Error) -> Error {
        Error::InvalidStringEncoding(error)
    }
}

impl convert::From<uuid::ParseError> for Error {
    fn from(error: uuid::ParseError) -> Error {
        Error::InvalidUuid(error)
    }
}

impl convert::From<io::Error> for Error {
    fn from(error: io::Error) -> Error {
        Error::ReadError(error)
    }
}
/* FIXME
impl convert::From<byteorder::Error> for Error {
    fn from(error: byteorder::Error) -> Error {
        match error {
            byteorder::Error::UnexpectedEOF => Error::HeaderProcessingError,
            byteorder::Error::Io(io_error) => Error::ReadError(io_error),
        }
    }
}
*/

pub mod raw {
    #![allow(non_snake_case)]

    use std::convert::From;
    use std::io::{Cursor, Read};
    use std::mem;
    use std::str;

    use byteorder::{BigEndian, ReadBytesExt};
    use uuid;

    const LUKS_VERSION_SUPPORTED: u16 = 1;

    const LUKS_MAGIC_L: usize = 6;
    const LUKS_CIPHERNAME_L: usize = 32;
    const LUKS_CIPHERMODE_L: usize = 32;
    const LUKS_HASHSPEC_L: usize = 32;
    const LUKS_DIGESTSIZE: usize = 20;
    const LUKS_SALTSIZE: usize = 32;
    const UUID_STRING_L: usize = 40;

    const LUKS_MAGIC: &'static [u8; LUKS_MAGIC_L] = b"LUKS\xba\xbe";

    #[repr(C, packed)]
    pub struct luks_phdr {
        pub magic: [u8; LUKS_MAGIC_L],
        pub version: u16,
        pub cipherName: [u8; LUKS_CIPHERNAME_L],
        pub cipherMode: [u8; LUKS_CIPHERMODE_L],
        pub hashSpec: [u8; LUKS_HASHSPEC_L],
        pub payloadOffset: u32,
        pub keyBytes: u32,
        pub mkDigest: [u8; LUKS_DIGESTSIZE],
        pub mkDigestSalt: [u8; LUKS_SALTSIZE],
        pub mkDigestIterations: u32,
        pub uuid: [u8; UUID_STRING_L],
    }

    impl luks_phdr {
        pub fn from_buf(buf: &[u8]) -> Result<luks_phdr, super::Error> {
            // FIXME - this is not particularly pretty

            if buf.len() != mem::size_of::<luks_phdr>() {
                return Err(super::Error::ReadIncorrectHeaderSize);
            }
            let mut cursor = Cursor::new(buf);
            let mut magic_buf = [0u8; LUKS_MAGIC_L];
            let magic_len = try!(cursor.read(&mut magic_buf));

            if magic_len != LUKS_MAGIC_L || magic_buf != &LUKS_MAGIC[..] {
                return Err(super::Error::InvalidMagic);
            }

            let version = try!(cursor.read_u16::<BigEndian>());
            if version != LUKS_VERSION_SUPPORTED {
                return Err(super::Error::InvalidVersion);
            }

            let mut cipher_name_buf = [0u8; LUKS_CIPHERNAME_L];
            let cipher_name_len = try!(cursor.read(&mut cipher_name_buf));
            if cipher_name_len != LUKS_CIPHERNAME_L {
                return Err(super::Error::HeaderProcessingError);
            }

            let mut cipher_mode_buf = [0u8; LUKS_CIPHERMODE_L];
            let cipher_mode_len = try!(cursor.read(&mut cipher_mode_buf));
            if cipher_mode_len != LUKS_CIPHERMODE_L {
                return Err(super::Error::HeaderProcessingError);
            }

            let mut hash_spec_buf = [0u8; LUKS_HASHSPEC_L];
            let hash_spec_len = try!(cursor.read(&mut hash_spec_buf));
            if hash_spec_len != LUKS_HASHSPEC_L {
                return Err(super::Error::HeaderProcessingError);
            }

            let payload_offset = try!(cursor.read_u32::<BigEndian>());
            let key_bytes = try!(cursor.read_u32::<BigEndian>());

            let mut mk_digest_buf = [0u8; LUKS_DIGESTSIZE];
            let mk_digest_len = try!(cursor.read(&mut mk_digest_buf));
            if mk_digest_len != LUKS_DIGESTSIZE {
                return Err(super::Error::HeaderProcessingError);
            }

            let mut mk_digest_salt_buf = [0u8; LUKS_SALTSIZE];
            let mk_digest_salt_len = try!(cursor.read(&mut mk_digest_salt_buf));
            if mk_digest_salt_len != LUKS_SALTSIZE {
                return Err(super::Error::HeaderProcessingError);
            }

            let mk_digest_iterations = try!(cursor.read_u32::<BigEndian>());

            let mut uuid_buf = [0u8; UUID_STRING_L];
            let uuid_len = try!(cursor.read(&mut uuid_buf));
            if uuid_len != UUID_STRING_L {
                return Err(super::Error::HeaderProcessingError);
            }

            let res = luks_phdr {
                magic: magic_buf,
                version: version,
                cipherName: cipher_name_buf,
                cipherMode: cipher_mode_buf,
                hashSpec: hash_spec_buf,
                payloadOffset: payload_offset,
                keyBytes: key_bytes,
                mkDigest: mk_digest_buf,
                mkDigestSalt: mk_digest_salt_buf,
                mkDigestIterations: mk_digest_iterations,
                uuid: uuid_buf,
            };

            Ok(res)
        }
    }

    fn u8_buf_to_str(buf: &[u8]) -> Result<&str, super::Error> {
        if let Some(pos) = buf.iter().position(|&c| c == 0) {
            str::from_utf8(&buf[0..pos]).map_err(From::from)
        } else {
            str::from_utf8(buf).map_err(From::from)
        }
    }

    impl super::LuksHeader for luks_phdr {
        fn version(&self) -> u16 {
            self.version
        }

        fn cipher_name(&self) -> Result<&str, super::Error> {
            u8_buf_to_str(&self.cipherName)
        }

        fn cipher_mode(&self) -> Result<&str, super::Error> {
            u8_buf_to_str(&self.cipherMode)
        }

        fn hash_spec(&self) -> Result<&str, super::Error> {
            u8_buf_to_str(&self.hashSpec)
        }

        fn payload_offset(&self) -> u32 {
            self.payloadOffset
        }

        fn key_bytes(&self) -> u32 {
            self.keyBytes
        }

        fn mk_digest(&self) -> &[u8] {
            &self.mkDigest
        }

        fn mk_digest_salt(&self) -> &[u8] {
            &self.mkDigestSalt
        }

        fn mk_digest_iterations(&self) -> u32 {
            self.mkDigestIterations
        }

        fn uuid(&self) -> Result<uuid::Uuid, super::Error> {
            let uuid_str = try!(u8_buf_to_str(&self.uuid));
            uuid::Uuid::parse_str(uuid_str).map_err(From::from)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;
    use uuid;

    #[test]
    fn test_luks_header_from_byte_buffer() {
        let header = b"LUKS\xba\xbe\x00\x01aes\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00ecb\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00sha256\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00\x00 \xcf^\xb4\xc00q\xbe\xd5\xe6\x90\xc8G\xb3\x00\xbe\xba\xd052qp\x92\x0c\x9c\xa9\x07R\\y_D\x08b\xf1\xe6\x8f\x0c\xa95\xad\xdb\x15+\xa5\xd7\xa7\xbf^\x96B\x90z\x00\x00\x03\xe8a1b49d2d-8a7e-4b04-ab2a-89f3408fd198\x00\x00\x00\x00";
        let mut cursor: Cursor<&[u8]> = Cursor::new(header);
        let luks_header = BlockDevice::read_luks_header(&mut cursor).unwrap();

        assert_eq!(luks_header.version(), 1);
        assert_eq!(luks_header.cipher_name().unwrap(), "aes");
        assert_eq!(luks_header.cipher_mode().unwrap(), "ecb");
        assert_eq!(luks_header.hash_spec().unwrap(), "sha256");
        assert_eq!(luks_header.payload_offset(), 4096);
        assert_eq!(luks_header.key_bytes(), 32);
        assert_eq!(
            luks_header.mk_digest(),
            &[
                207, 94, 180, 192, 48, 113, 190, 213, 230, 144, 200, 71, 179, 0, 190, 186, 208, 53,
                50, 113
            ]
        );
        assert_eq!(
            luks_header.mk_digest_salt(),
            &[
                112, 146, 12, 156, 169, 7, 82, 92, 121, 95, 68, 8, 98, 241, 230, 143, 12, 169, 53,
                173, 219, 21, 43, 165, 215, 167, 191, 94, 150, 66, 144, 122
            ]
        );
        assert_eq!(luks_header.mk_digest_iterations(), 1000);
        assert_eq!(
            luks_header.uuid().unwrap(),
            uuid::Uuid::parse_str("a1b49d2d-8a7e-4b04-ab2a-89f3408fd198").unwrap()
        )
    }
}