summaryrefslogtreecommitdiff
path: root/libfec/test/fec_unittest.cpp
blob: 421eb501480ba309cb2f6ae91004efe2918bd1cf (plain)
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
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdint.h>
#include <stdlib.h>

#include <string>
#include <vector>

#include <android-base/file.h>
#include <android-base/strings.h>
#include <gtest/gtest.h>
#include <verity/hash_tree_builder.h>

#include "../fec_private.h"
#include "fec/io.h"

class FecUnitTest : public ::testing::Test {
   protected:
    void SetUp() override {
        // Construct a 1 MiB image as file system.
        image_.reserve(1024 * 1024);
        for (unsigned i = 0; i <= 255; i++) {
            std::vector<uint8_t> tmp_vec(4096, i);
            image_.insert(image_.end(), tmp_vec.begin(), tmp_vec.end());
        }
    }
    void BuildHashtree(const std::string &hash_name) {
        // Build the hashtree.
        HashTreeBuilder builder(4096, HashTreeBuilder::HashFunction(hash_name));
        // Use a random salt.
        salt_ = std::vector<uint8_t>(64, 10);
        ASSERT_TRUE(builder.Initialize(image_.size(), salt_));
        ASSERT_TRUE(builder.Update(image_.data(), image_.size()));
        ASSERT_TRUE(builder.BuildHashTree());
        root_hash_ = builder.root_hash();

        TemporaryFile temp_file;
        ASSERT_TRUE(builder.WriteHashTreeToFd(temp_file.fd, 0));
        android::base::ReadFileToString(temp_file.path, &hashtree_content_);
    }

    // Builds the verity metadata and appends the bytes to the image.
    void BuildAndAppendsVerityMetadata() {
        BuildHashtree("sha256");
        // Append the hashtree to the end of image.
        image_.insert(image_.end(), hashtree_content_.begin(),
                      hashtree_content_.end());

        // The metadata table has the format: "1 block_device, block_device,
        // BLOCK_SIZE, BLOCK_SIZE, data_blocks, data_blocks, 'sha256',
        // root_hash, salt".
        std::vector<std::string> table = {
            "1",
            "fake_block_device",
            "fake_block_device",
            "4096",
            "4096",
            "256",
            "256",
            "sha256",
            HashTreeBuilder::BytesArrayToString(root_hash_),
            HashTreeBuilder::BytesArrayToString(salt_),
        };
        verity_table_ = android::base::Join(table, ' ');

        verity_header_ = {
            0xb001b001, 0, {}, static_cast<unsigned int>(verity_table_.size())
        };

        // Construct the verity metadata with header, table, and padding.
        constexpr auto VERITY_META_SIZE = 8 * 4096;
        image_.insert(image_.end(),
                      reinterpret_cast<uint8_t *>(&verity_header_),
                      reinterpret_cast<uint8_t *>(&verity_header_) +
                          sizeof(verity_header_));
        image_.insert(image_.end(), verity_table_.data(),
                      verity_table_.data() + verity_table_.size());
        std::vector<uint8_t> padding(
            VERITY_META_SIZE - sizeof(verity_header_) - verity_table_.size(),
            0);
        image_.insert(image_.end(), padding.begin(), padding.end());
    }

    static void BuildAndAppendsEccImage(const std::string &image_name,
                                        const std::string &fec_name) {
        std::vector<std::string> cmd = { "fec", "--encode", "--roots",
                                         "2",   image_name, fec_name };
        ASSERT_EQ(0, std::system(android::base::Join(cmd, ' ').c_str()));
    }

    void AddAvbHashtreeFooter(const std::string &image_name,
                              std::string algorithm = "sha256") {
        salt_ = std::vector<uint8_t>(64, 10);
        std::vector<std::string> cmd = {
            "avbtool",          "add_hashtree_footer",
            "--salt",           HashTreeBuilder::BytesArrayToString(salt_),
            "--hash_algorithm", algorithm,
            "--image",          image_name,
        };
        ASSERT_EQ(0, std::system(android::base::Join(cmd, ' ').c_str()));

        BuildHashtree(algorithm);
    }

    std::vector<uint8_t> image_;
    std::vector<uint8_t> salt_;
    std::vector<uint8_t> root_hash_;
    std::string hashtree_content_;
    verity_header verity_header_;
    std::string verity_table_;
};

TEST_F(FecUnitTest, LoadVerityImage_ParseVerity) {
    TemporaryFile verity_image;
    BuildAndAppendsVerityMetadata();
    ASSERT_TRUE(android::base::WriteFully(verity_image.fd, image_.data(),
                                          image_.size()));

    struct fec_handle *handle = nullptr;
    ASSERT_EQ(0, fec_open(&handle, verity_image.path, O_RDONLY, FEC_FS_EXT4, 2));
    std::unique_ptr<fec_handle> guard(handle);

    ASSERT_EQ(image_.size(), handle->size);
    ASSERT_EQ(1024 * 1024, handle->data_size);  // filesystem size

    ASSERT_EQ(1024 * 1024 + hashtree_content_.size(),
              handle->verity.metadata_start);
    ASSERT_EQ(verity_header_.length, handle->verity.header.length);
    ASSERT_EQ(verity_table_, handle->verity.table);

    // check the hashtree.
    ASSERT_EQ(salt_, handle->hashtree().salt);
    ASSERT_EQ(1024 * 1024, handle->hashtree().hash_start);
    // the fec hashtree only stores the hash of the lowest level.
    ASSERT_EQ(std::vector<uint8_t>(hashtree_content_.begin() + 4096,
                                   hashtree_content_.end()),
              handle->hashtree().hash_data);

    uint64_t hash_size =
        verity_get_size(handle->hashtree().data_blocks * FEC_BLOCKSIZE, nullptr,
                        nullptr, SHA256_DIGEST_LENGTH);
    ASSERT_EQ(hashtree_content_.size(), hash_size);
}

TEST_F(FecUnitTest, LoadVerityImage_ParseEcc) {
    TemporaryFile verity_image;
    BuildAndAppendsVerityMetadata();
    ASSERT_TRUE(android::base::WriteFully(verity_image.fd, image_.data(),
                                          image_.size()));
    TemporaryFile ecc_image;
    BuildAndAppendsEccImage(verity_image.path, ecc_image.path);
    std::string ecc_content;
    ASSERT_TRUE(android::base::ReadFileToString(ecc_image.path, &ecc_content));
    ASSERT_TRUE(android::base::WriteStringToFd(ecc_content, verity_image.fd));
    struct fec_handle *handle = nullptr;
    ASSERT_EQ(0, fec_open(&handle, verity_image.path, O_RDONLY, FEC_FS_EXT4, 2));
    std::unique_ptr<fec_handle> guard(handle);

    ASSERT_EQ(1024 * 1024, handle->data_size);  // filesystem size
    ASSERT_EQ(1024 * 1024 + hashtree_content_.size(),
              handle->verity.metadata_start);

    fec_verity_metadata verity_metadata{};
    ASSERT_EQ(0, fec_verity_get_metadata(handle, &verity_metadata));
    ASSERT_FALSE(verity_metadata.disabled);
    ASSERT_EQ(1024 * 1024, verity_metadata.data_size);
    ASSERT_EQ(verity_table_, verity_metadata.table);

    fec_ecc_metadata ecc_metadata{};
    ASSERT_EQ(0, fec_ecc_get_metadata(handle, &ecc_metadata));
    ASSERT_TRUE(ecc_metadata.valid);
    ASSERT_EQ(handle->verity.metadata_start + 8 * 4096, ecc_metadata.start);
    ASSERT_EQ(2, ecc_metadata.roots);
    // 256 (data) + 3 (hashtree) + 8 (verity meta)
    ASSERT_EQ(267, ecc_metadata.blocks);
}

TEST_F(FecUnitTest, VerityImage_FecRead) {
    TemporaryFile verity_image;
    BuildAndAppendsVerityMetadata();
    ASSERT_TRUE(android::base::WriteFully(verity_image.fd, image_.data(),
                                          image_.size()));
    TemporaryFile ecc_image;
    BuildAndAppendsEccImage(verity_image.path, ecc_image.path);
    std::string ecc_content;
    ASSERT_TRUE(android::base::ReadFileToString(ecc_image.path, &ecc_content));
    ASSERT_TRUE(android::base::WriteStringToFd(ecc_content, verity_image.fd));

    // Corrupt the last block
    uint64_t corrupt_offset = 4096 * 255;
    ASSERT_EQ(corrupt_offset, lseek64(verity_image.fd, corrupt_offset, 0));
    std::vector<uint8_t> corruption(100, 10);
    ASSERT_TRUE(android::base::WriteFully(verity_image.fd, corruption.data(),
                                          corruption.size()));

    std::vector<uint8_t> read_data(1024, 0);
    struct fec_handle *handle = nullptr;
    ASSERT_EQ(0,
              fec_open(&handle, verity_image.path, O_RDONLY, FEC_FS_EXT4, 2));
    std::unique_ptr<fec_handle> guard(handle);

    ASSERT_EQ(1024, fec_pread(handle, read_data.data(), 1024, corrupt_offset));
    ASSERT_EQ(std::vector<uint8_t>(1024, 255), read_data);
}

TEST_F(FecUnitTest, LoadAvbImage_HashtreeFooter) {
    TemporaryFile avb_image;
    ASSERT_TRUE(
        android::base::WriteFully(avb_image.fd, image_.data(), image_.size()));
    AddAvbHashtreeFooter(avb_image.path);

    struct fec_handle *handle = nullptr;
    ASSERT_EQ(0, fec_open(&handle, avb_image.path, O_RDWR, FEC_FS_EXT4, 2));
    std::unique_ptr<fec_handle> guard(handle);

    ASSERT_EQ(1024 * 1024, handle->data_size);  // filesystem size

    ASSERT_TRUE(handle->avb.valid);

    // check the hashtree.
    ASSERT_EQ(salt_, handle->hashtree().salt);
    ASSERT_EQ(1024 * 1024, handle->hashtree().hash_start);
    // the fec hashtree only stores the hash of the lowest level.
    ASSERT_EQ(std::vector<uint8_t>(hashtree_content_.begin() + 4096,
                                   hashtree_content_.end()),
              handle->hashtree().hash_data);
    uint64_t hash_size =
        verity_get_size(handle->hashtree().data_blocks * FEC_BLOCKSIZE, nullptr,
                        nullptr, SHA256_DIGEST_LENGTH);
    ASSERT_EQ(hashtree_content_.size(), hash_size);

    fec_ecc_metadata ecc_metadata{};
    ASSERT_EQ(0, fec_ecc_get_metadata(handle, &ecc_metadata));
    ASSERT_TRUE(ecc_metadata.valid);
    ASSERT_EQ(1024 * 1024 + hash_size, ecc_metadata.start);
    ASSERT_EQ(259, ecc_metadata.blocks);
}

TEST_F(FecUnitTest, LoadAvbImage_CorrectHashtree) {
    TemporaryFile avb_image;
    ASSERT_TRUE(
        android::base::WriteFully(avb_image.fd, image_.data(), image_.size()));
    AddAvbHashtreeFooter(avb_image.path);

    uint64_t corrupt_offset = 1024 * 1024 + 2 * 4096 + 50;
    ASSERT_EQ(corrupt_offset, lseek64(avb_image.fd, corrupt_offset, 0));
    std::vector<uint8_t> corruption(20, 5);
    ASSERT_TRUE(android::base::WriteFully(avb_image.fd, corruption.data(),
                                          corruption.size()));

    struct fec_handle *handle = nullptr;
    ASSERT_EQ(0, fec_open(&handle, avb_image.path, O_RDWR, FEC_FS_EXT4, 2));
    std::unique_ptr<fec_handle> guard(handle);

    ASSERT_EQ(1024 * 1024, handle->data_size);  // filesystem size
    fec_ecc_metadata ecc_metadata{};
    ASSERT_EQ(0, fec_ecc_get_metadata(handle, &ecc_metadata));
    ASSERT_TRUE(ecc_metadata.valid);
}

TEST_F(FecUnitTest, AvbImage_FecRead) {
    TemporaryFile avb_image;
    ASSERT_TRUE(
        android::base::WriteFully(avb_image.fd, image_.data(), image_.size()));
    AddAvbHashtreeFooter(avb_image.path, "sha1");

    uint64_t corrupt_offset = 4096 * 10;
    ASSERT_EQ(corrupt_offset, lseek64(avb_image.fd, corrupt_offset, 0));
    std::vector<uint8_t> corruption(50, 99);
    ASSERT_TRUE(android::base::WriteFully(avb_image.fd, corruption.data(),
                                          corruption.size()));

    std::vector<uint8_t> read_data(1024, 0);
    struct fec_handle *handle = nullptr;
    ASSERT_EQ(0, fec_open(&handle, avb_image.path, O_RDWR, FEC_FS_EXT4, 2));
    std::unique_ptr<fec_handle> guard(handle);

    // Verify the hashtree has the expected content.
    ASSERT_EQ(std::vector<uint8_t>(hashtree_content_.begin() + 4096,
                                   hashtree_content_.end()),
              handle->hashtree().hash_data);

    // Verify the corruption gets corrected.
    ASSERT_EQ(1024, fec_pread(handle, read_data.data(), 1024, corrupt_offset));
    ASSERT_EQ(std::vector<uint8_t>(1024, 10), read_data);
}