blob: e0124e2924518e686f639185ad8717f568a13c32 [file] [log] [blame]
Mateusz Zalega356b8962021-08-10 17:27:15 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17// This package implements the minimum of functionality needed to generate and
18// map dm-verity images. It's provided in order to avoid a perceived higher
19// long term cost of packaging, linking against and maintaining the original C
20// veritysetup tool.
21//
22// dm-verity is a Linux device mapper target that allows integrity verification of
23// a read-only block device. The block device whose integrity should be checked
24// (the 'data device') must be first processed by a tool like veritysetup to
25// generate a hash device and root hash.
26// The original data device, hash device and root hash are then set up as a device
27// mapper target, and any read performed from the data device through the verity
28// target will be verified for integrity by Linux using the hash device and root
29// hash.
30//
31// Internally, the hash device is a Merkle tree of all the bytes in the data
32// device, layed out as layers of 'hash blocks'. Starting with data bytes, layers
33// are built recursively, with each layer's output hash blocks becoming the next
34// layer's data input, ending with the single root hash.
35//
36// For more information about the internals, see the Linux and cryptsetup
37// upstream code:
38//
39// https://gitlab.com/cryptsetup/cryptsetup/wikis/DMVerity
40package verity
41
42import (
43 "bytes"
44 "crypto/rand"
45 "crypto/sha256"
46 "encoding/binary"
47 "encoding/hex"
48 "fmt"
49 "io"
50 "strconv"
51 "strings"
52)
53
54// superblock represents data layout inside of a dm-verity hash block
55// device superblock. It follows a preexisting verity implementation:
56//
57// https://gitlab.com/cryptsetup/cryptsetup/wikis/DMVerity#verity-superblock-format
58type superblock struct {
59 // signature is the magic signature of a verity hash device superblock,
60 // "verity\0\0".
61 signature [8]byte
62 // version specifies a superblock format. This structure describes version
63 // '1'.
64 version uint32
65 // hashType defaults to '1' outside Chrome OS, according to scarce dm-verity
66 // documentation.
67 hashType uint32
68 // uuid contains a UUID of the hash device.
69 uuid [16]byte
70 // algorithm stores an ASCII-encoded name of the hash function used.
71 algorithm [32]byte
72
73 // dataBlockSize specifies a size of a single data device block, in bytes.
74 dataBlockSize uint32
75 // hashBlockSize specifies a size of a single hash device block, in bytes.
76 hashBlockSize uint32
77 // dataBlocks contains a count of blocks available on the data device.
78 dataBlocks uint64
79
80 // saltSize encodes the size of hash block salt, up to the maximum of 256 bytes.
81 saltSize uint16
82
83 // padding
84 _ [6]byte
85 // exactly saltSize bytes of salt are prepended to data blocks before hashing.
86 saltBuffer [256]byte
87 // padding
88 _ [168]byte
89}
90
91// newSuperblock builds a dm-verity hash device superblock based on
92// hardcoded defaults. dataBlocks is the only field left for later
93// initialization.
94// It returns either a partially initialized superblock, or an error.
95func newSuperblock() (*superblock, error) {
96 // This implementation only handles SHA256-based verity hash images
97 // with a specific 4096-byte block size.
98 // Block sizes can be updated by adjusting the struct literal below.
99 // A change of a hashing algorithm would require a refactor of
100 // saltedDigest, and references to sha256.Size.
101 //
102 // Fill in the defaults (compare with superblock definition).
103 sb := superblock{
104 signature: [8]byte{'v', 'e', 'r', 'i', 't', 'y', 0, 0},
105 version: 1,
106 hashType: 1,
107 algorithm: [32]byte{'s', 'h', 'a', '2', '5', '6'},
108 saltSize: 64,
109 dataBlockSize: 4096,
110 hashBlockSize: 4096,
111 }
112
113 // Fill in the superblock UUID and cryptographic salt.
114 if _, err := rand.Read(sb.uuid[:]); err != nil {
115 return nil, fmt.Errorf("when generating UUID: %w", err)
116 }
117 if _, err := rand.Read(sb.saltBuffer[:]); err != nil {
118 return nil, fmt.Errorf("when generating salt: %w", err)
119 }
120
121 return &sb, nil
122}
123
124// salt returns a slice of sb.saltBuffer actually occupied by
125// salt bytes, of sb.saltSize length.
126func (sb *superblock) salt() []byte {
127 return sb.saltBuffer[:int(sb.saltSize)]
128}
129
130// algorithmName returns a name of the algorithm used to hash data block
131// digests.
132func (sb *superblock) algorithmName() string {
133 size := bytes.IndexByte(sb.algorithm[:], 0x00)
134 return string(sb.algorithm[:size])
135}
136
137// saltedDigest computes and returns a SHA256 sum of a block prepended
138// with a Superblock-defined salt.
139func (sb *superblock) saltedDigest(data []byte) (digest [sha256.Size]byte) {
140 h := sha256.New()
141 h.Write(sb.salt())
142 h.Write(data)
143 copy(digest[:], h.Sum(nil))
144 return
145}
146
147// dataBlocksPerHashBlock returns the count of hash operation outputs that
148// fit in a hash device block. This is also the amount of data device
149// blocks it takes to populate a hash device block.
150func (sb *superblock) dataBlocksPerHashBlock() uint64 {
151 return uint64(sb.hashBlockSize) / sha256.Size
152}
153
154// computeHashBlock reads at most sb.dataBlocksPerHashBlock blocks from
155// the given reader object, returning a padded hash block of length
156// defined by sb.hashBlockSize, the count of digests output, and an
157// error, if encountered.
158// In case a non-nil block is returned, it's guaranteed to contain at
159// least one hash. An io.EOF signals that there is no more to be read.
160func (sb *superblock) computeHashBlock(r io.Reader) ([]byte, uint64, error) {
161 // dcnt stores the total count of data blocks processed, which is the
162 // as the count of digests output.
163 var dcnt uint64
164 // Preallocate a whole hash block.
165 hblk := bytes.NewBuffer(make([]byte, 0, sb.hashBlockSize))
166
167 // For every data block, compute a hash and place it in hblk. Continue
168 // till EOF.
169 for b := uint64(0); b < sb.dataBlocksPerHashBlock(); b++ {
170 dbuf := make([]byte, sb.dataBlockSize)
171 // Attempt to read enough data blocks to make a complete hash block.
172 n, err := io.ReadFull(r, dbuf)
173 // If any data was read, make a hash and add it to the hash buffer.
174 if n != 0 {
175 hash := sb.saltedDigest(dbuf)
176 hblk.Write(hash[:])
177 dcnt++
178 }
179 // Handle the read errors.
180 switch err {
181 case nil:
182 case io.ErrUnexpectedEOF, io.EOF:
183 // io.ReadFull returns io.ErrUnexpectedEOF after a partial read,
184 // and io.EOF if no bytes were read. In both cases it's possible
185 // to end up with a partially filled hash block.
186 if hblk.Len() != 0 {
187 // Return a zero-padded hash block if any hashes were written
188 // to it, and signal that no more blocks can be built.
189 res := hblk.Bytes()
190 return res[:cap(res)], dcnt, io.EOF
191 }
192 // Return nil if the block doesn't contain any hashes.
193 return nil, 0, io.EOF
194 default:
195 // Wrap unhandled read errors.
196 return nil, 0, fmt.Errorf("while computing a hash block: %w", err)
197 }
198 }
199 // Return a completely filled hash block.
200 res := hblk.Bytes()
201 return res[:cap(res)], dcnt, nil
202}
203
204// WriteTo writes a verity superblock to a given writer object.
205// It returns the count of bytes written, and a write error, if
206// encountered.
207func (sb *superblock) WriteTo(w io.Writer) (int64, error) {
208 // Write the superblock.
209 if err := binary.Write(w, binary.LittleEndian, sb); err != nil {
210 return -1, fmt.Errorf("while writing a header: %w", err)
211 }
212
213 // Get the padding size by substracting current offset from a hash block
214 // size.
215 co := int(binary.Size(sb))
216 pbc := int(sb.hashBlockSize) - int(co)
217 if pbc <= 0 {
218 return int64(co), fmt.Errorf("hash device block size smaller than dm-verity superblock")
219 }
220
221 // Write the padding bytes at the end of the block.
222 n, err := w.Write(bytes.Repeat([]byte{0}, pbc))
223 co += n
224 if err != nil {
225 return int64(co), fmt.Errorf("while writing padding: %w", err)
226 }
227 return int64(co), nil
228}
229
230// computeLevel produces a verity hash tree level based on data read from
231// a given reader object.
232// It returns a byte slice containing one or more hash blocks, or an
233// error.
234// BUG(mz): Current implementation requires a 1/128th of the data image
235// size to be allocatable on the heap.
236func (sb *superblock) computeLevel(r io.Reader) ([]byte, error) {
237 // hbuf will store all the computed hash blocks.
238 var hbuf bytes.Buffer
239 // Compute one or more hash blocks, reading all data available in the
240 // 'r' reader object, and write them into hbuf.
241 for {
242 hblk, _, err := sb.computeHashBlock(r)
243 if err != nil && err != io.EOF {
244 return nil, fmt.Errorf("while building a hash tree level: %w", err)
245 }
246 if hblk != nil {
247 _, err := hbuf.Write(hblk)
248 if err != nil {
249 return nil, fmt.Errorf("while writing to hash block buffer: %w", err)
250 }
251 }
252 if err == io.EOF {
253 break
254 }
255 }
256 return hbuf.Bytes(), nil
257}
258
259// hashTree stores hash tree levels, each level comprising one or more
260// Verity hash blocks. Levels are ordered from bottom to top.
261type hashTree [][]byte
262
263// push appends a level to the hash tree.
264func (ht *hashTree) push(nl []byte) {
265 *ht = append(*ht, nl)
266}
267
268// top returns the topmost level of the hash tree.
269func (ht *hashTree) top() []byte {
270 if len(*ht) == 0 {
271 return nil
272 }
273 return (*ht)[len(*ht)-1]
274}
275
276// WriteTo writes a verity-formatted hash tree to the given writer
277// object.
278// It returns a write error, if encountered.
279func (ht *hashTree) WriteTo(w io.Writer) (int64, error) {
280 // t keeps the count of bytes written to w.
281 var t int64
282 // Write the hash tree levels from top to bottom.
283 for l := len(*ht) - 1; l >= 0; l-- {
284 level := (*ht)[l]
285 // Call w.Write until a whole level is written.
286 for len(level) != 0 {
287 n, err := w.Write(level)
288 if err != nil {
289 return t, fmt.Errorf("while writing a level: %w", err)
290 }
291 level = level[n:]
292 t += int64(n)
293 }
294 }
295 return t, nil
296}
297
298// MappingTable aggregates data needed to generate a complete Verity
299// mapping table.
300type MappingTable struct {
301 // superblock defines the following elements of the mapping table:
302 // - data device block size
303 // - hash device block size
304 // - total count of data blocks
305 // - hash algorithm used
306 // - cryptographic salt used
307 superblock *superblock
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100308 // DataDevicePath is the filesystem path of the data device used as part
Mateusz Zalega356b8962021-08-10 17:27:15 +0200309 // of the Verity Device Mapper target.
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100310 DataDevicePath string
311 // HashDevicePath is the filesystem path of the hash device used as part
Mateusz Zalega356b8962021-08-10 17:27:15 +0200312 // of the Verity Device Mapper target.
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100313 HashDevicePath string
314 // HashStart marks the starting block of the Verity hash tree.
315 HashStart int64
Mateusz Zalega356b8962021-08-10 17:27:15 +0200316 // rootHash stores a cryptographic hash of the top hash tree block.
317 rootHash []byte
318}
319
320// VerityParameterList returns a list of Verity target parameters, ordered
321// as they would appear in a parameter string.
322func (t *MappingTable) VerityParameterList() []string {
323 return []string{
324 "1",
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100325 t.DataDevicePath,
326 t.HashDevicePath,
Mateusz Zalega356b8962021-08-10 17:27:15 +0200327 strconv.FormatUint(uint64(t.superblock.dataBlockSize), 10),
328 strconv.FormatUint(uint64(t.superblock.hashBlockSize), 10),
329 strconv.FormatUint(uint64(t.superblock.dataBlocks), 10),
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100330 strconv.FormatInt(int64(t.HashStart), 10),
Mateusz Zalega356b8962021-08-10 17:27:15 +0200331 t.superblock.algorithmName(),
332 hex.EncodeToString(t.rootHash),
333 hex.EncodeToString(t.superblock.salt()),
334 }
335}
336
337// TargetParameters returns the mapping table as a list of Device Mapper
338// target parameters, ordered as they would appear in a parameter string
339// (see: String).
340func (t *MappingTable) TargetParameters() []string {
341 return append(
342 []string{
343 "0",
344 strconv.FormatUint(t.Length(), 10),
345 "verity",
346 },
347 t.VerityParameterList()...,
348 )
349}
350
351// String returns a string-formatted mapping table for use with Device
352// Mapper.
353// BUG(mz): unescaped whitespace can appear in block device paths
354func (t *MappingTable) String() string {
355 return strings.Join(t.TargetParameters(), " ")
356}
357
358// Length returns the data device length, represented as a number of
359// 512-byte sectors.
360func (t *MappingTable) Length() uint64 {
361 return t.superblock.dataBlocks * uint64(t.superblock.dataBlockSize) / 512
362}
363
364// encoder transforms data blocks written into it into a verity hash
365// tree. It writes out the hash tree only after Close is called on it.
366type encoder struct {
367 // out is the writer object Encoder will write to.
368 out io.Writer
369 // writeSb, if true, will cause a Verity superblock to be written to the
370 // writer object.
371 writeSb bool
372 // sb contains the most of information needed to build a mapping table.
373 sb *superblock
374 // bottom stands for the bottom level of the hash tree. It contains
375 // complete hash blocks of data written to the encoder.
376 bottom bytes.Buffer
377 // dataBuffer stores incoming data for later processing.
378 dataBuffer bytes.Buffer
379 // rootHash stores the verity root hash set on Close.
380 rootHash []byte
381}
382
383// computeHashTree builds a complete hash tree based on the encoder's
384// state. Levels are appended to the returned hash tree starting from the
385// bottom, with the top level written last.
386// e.sb.dataBlocks is set according to the bottom level's length, which
387// must be divisible by e.sb.hashBlockSize.
388// e.rootHash is set on success.
389// It returns an error, if encountered.
390func (e *encoder) computeHashTree() (*hashTree, error) {
391 // Put b at the bottom of the tree. Don't perform a deep copy.
392 ht := hashTree{e.bottom.Bytes()}
393
394 // Other levels are built by hashing the hash blocks comprising a level
395 // below.
396 for {
397 if len(ht.top()) == int(e.sb.hashBlockSize) {
398 // The last level to compute has a size of exactly one hash block.
399 // That's the root level. Its hash serves as a cryptographic root of
400 // trust and is saved into a encoder for later use.
401 // In case the bottom level consists of only one hash block, no more
402 // levels are computed.
403 sd := e.sb.saltedDigest(ht.top())
404 e.rootHash = sd[:]
405 return &ht, nil
406 }
407
408 // Create the next level by hashing the previous one.
409 nl, err := e.sb.computeLevel(bytes.NewReader(ht.top()))
410 if err != nil {
411 return nil, fmt.Errorf("while computing a level: %w", err)
412 }
413 // Append the resulting next level to a tree.
414 ht.push(nl)
415 }
416}
417
418// processDataBuffer processes data blocks contained in e.dataBuffer
419// until no more data is available to form a completely filled hash block.
420// If 'incomplete' is true, all remaining data in e.dataBuffer will be
421// processed, producing a terminating incomplete block.
422// It returns the count of data blocks processed, or an error, if
423// encountered.
424func (e *encoder) processDataBuffer(incomplete bool) (uint64, error) {
425 // tdcnt stores the total count of data blocks processed.
426 var tdcnt uint64
427 // Compute the count of bytes needed to produce a complete hash block.
428 bph := e.sb.dataBlocksPerHashBlock() * uint64(e.sb.dataBlockSize)
429
430 // Iterate until no more data is available in e.dbuf.
431 for uint64(e.dataBuffer.Len()) >= bph || incomplete && e.dataBuffer.Len() != 0 {
432 hb, dcnt, err := e.sb.computeHashBlock(&e.dataBuffer)
433 if err != nil && err != io.EOF {
434 return 0, fmt.Errorf("while processing a data buffer: %w", err)
435 }
436 // Increment the total count of data blocks processed.
437 tdcnt += dcnt
438 // Write the resulting hash block into the level-zero buffer.
439 e.bottom.Write(hb[:])
440 }
441 return tdcnt, nil
442}
443
444// NewEncoder returns a fully initialized encoder, or an error. The
445// encoder will write to the given io.Writer object.
446// A verity superblock will be written, preceding the hash tree, if
447// writeSb is true.
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100448func NewEncoder(out io.Writer, dataBlockSize, hashBlockSize uint32, writeSb bool) (*encoder, error) {
Mateusz Zalega356b8962021-08-10 17:27:15 +0200449 sb, err := newSuperblock()
450 if err != nil {
451 return nil, fmt.Errorf("while creating a superblock: %w", err)
452 }
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100453 sb.dataBlockSize = dataBlockSize
454 sb.hashBlockSize = hashBlockSize
Mateusz Zalega356b8962021-08-10 17:27:15 +0200455
456 e := encoder{
457 out: out,
458 writeSb: writeSb,
459 sb: sb,
460 }
461 return &e, nil
462}
463
464// Write hashes raw data to form the bottom hash tree level.
465// It returns the number of bytes written, and an error, if encountered.
466func (e *encoder) Write(data []byte) (int, error) {
467 // Copy the input into the data buffer.
468 n, _ := e.dataBuffer.Write(data)
469 // Process only enough data to form a complete hash block. This may
470 // leave excess data in e.dbuf to be processed later on.
471 dcnt, err := e.processDataBuffer(false)
472 if err != nil {
473 return n, fmt.Errorf("while processing the data buffer: %w", err)
474 }
475 // Update the superblock with the count of data blocks written.
476 e.sb.dataBlocks += dcnt
477 return n, nil
478}
479
480// Close builds a complete hash tree based on cached bottom level blocks,
481// then writes it to a preconfigured io.Writer object. A Verity superblock
482// is written, if e.writeSb is true. No data, nor the superblock is written
483// if the encoder is empty.
484// It returns an error, if one was encountered.
485func (e *encoder) Close() error {
486 // Process all buffered data, including data blocks that may not form
487 // a complete hash block.
488 dcnt, err := e.processDataBuffer(true)
489 if err != nil {
490 return fmt.Errorf("while processing the data buffer: %w", err)
491 }
492 // Update the superblock with the count of data blocks written.
493 e.sb.dataBlocks += dcnt
494
495 // Don't write anything if nothing was written to the encoder.
496 if e.bottom.Len() == 0 {
497 return nil
498 }
499
500 // Compute remaining hash tree levels based on the bottom level: e.bottom.
501 ht, err := e.computeHashTree()
502 if err != nil {
503 return fmt.Errorf("while encoding a hash tree: %w", err)
504 }
505
506 // Write the Verity superblock if the encoder was configured to do so.
507 if e.writeSb {
508 if _, err = e.sb.WriteTo(e.out); err != nil {
509 return fmt.Errorf("while writing a superblock: %w", err)
510 }
511 }
512 // Write the hash tree.
513 _, err = ht.WriteTo(e.out)
514 if err != nil {
515 return fmt.Errorf("while writing a hash tree: %w", err)
516 }
517
518 // Reset the encoder.
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100519 e, err = NewEncoder(e.out, e.sb.dataBlockSize, e.sb.hashBlockSize, e.writeSb)
Mateusz Zalega356b8962021-08-10 17:27:15 +0200520 if err != nil {
521 return fmt.Errorf("while resetting an encoder: %w", err)
522 }
523 return nil
524}
525
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100526// MappingTable returns a complete, string-convertible Verity target mapping
527// table for use with Device Mapper, or an error. Close must be called on the
528// encoder before calling this function. dataDevicePath, hashDevicePath, and
529// hashStart parameters are parts of the mapping table. See:
530// https://www.kernel.org/doc/html/latest/admin-guide/device-mapper/verity.html
531func (e *encoder) MappingTable(dataDevicePath, hashDevicePath string, hashStart int64) (*MappingTable, error) {
Mateusz Zalega356b8962021-08-10 17:27:15 +0200532 if e.rootHash == nil {
533 if e.bottom.Len() != 0 {
534 return nil, fmt.Errorf("encoder wasn't closed.")
535 }
536 return nil, fmt.Errorf("encoder is empty.")
537 }
538
Mateusz Zalega356b8962021-08-10 17:27:15 +0200539 if e.writeSb {
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100540 // Account for the superblock.
541 hashStart += 1
Mateusz Zalega356b8962021-08-10 17:27:15 +0200542 }
543 return &MappingTable{
544 superblock: e.sb,
Mateusz Zalegaba1da9d2022-01-25 19:12:02 +0100545 DataDevicePath: dataDevicePath,
546 HashDevicePath: hashDevicePath,
547 HashStart: hashStart,
Mateusz Zalega356b8962021-08-10 17:27:15 +0200548 rootHash: e.rootHash,
549 }, nil
550}