github.com/andrewsun2898/u-root@v6.0.1-0.20200616011413-4b2895c1b815+incompatible/pkg/securelaunch/measurement/storage.go (about) 1 // Copyright 2019 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package measurement 6 7 import ( 8 "encoding/json" 9 "fmt" 10 "io" 11 "log" 12 "os" 13 "path/filepath" 14 15 slaunch "github.com/u-root/u-root/pkg/securelaunch" 16 "github.com/u-root/u-root/pkg/securelaunch/tpm" 17 ) 18 19 /* describes the "storage" portion of policy file */ 20 type StorageCollector struct { 21 Type string `json:"type"` 22 Paths []string `json:"paths"` 23 } 24 25 /* 26 * NewStorageCollector extracts the "storage" portion from the policy file. 27 * initializes a new StorageCollector structure. 28 * returns error if unmarshalling of StorageCollector fails 29 */ 30 func NewStorageCollector(config []byte) (Collector, error) { 31 slaunch.Debug("New Storage Collector initialized\n") 32 var sc = new(StorageCollector) 33 err := json.Unmarshal(config, &sc) 34 if err != nil { 35 return nil, err 36 } 37 return sc, nil 38 } 39 40 /* 41 * measureStorageDevice reads the disk path input by user, 42 * and then extends the pcr with it. 43 * 44 * Hashing of buffer is handled by tpm package. 45 * - tpmHandle - tpm device where measurements are stored. 46 * - blkDevicePath - string e.g /dev/sda 47 * returns 48 * - error if Reading the block device fails. 49 */ 50 func measureStorageDevice(tpmHandle io.ReadWriteCloser, blkDevicePath string) error { 51 52 log.Printf("Storage Collector: Measuring block device %s\n", blkDevicePath) 53 file, err := os.Open(blkDevicePath) 54 if err != nil { 55 return fmt.Errorf("couldn't open disk=%s err=%v", blkDevicePath, err) 56 } 57 58 eventDesc := fmt.Sprintf("Storage Collector: Measured %s", blkDevicePath) 59 return tpm.ExtendPCRDebug(tpmHandle, pcr, file, eventDesc) 60 } 61 62 /* 63 * Collect satisfies Collector Interface. It loops over all storage paths provided 64 * by user and calls measureStorageDevice for each storage path. storage path is of 65 * form /dev/sda. measureStorageDevice in turn calls tpm 66 * package which further hashes this buffer and extends pcr. 67 */ 68 func (s *StorageCollector) Collect(tpmHandle io.ReadWriteCloser) error { 69 70 for _, inputVal := range s.Paths { 71 device, e := slaunch.GetStorageDevice(inputVal) // inputVal is blkDevicePath e.g UUID or sda 72 if e != nil { 73 log.Printf("Storage Collector: input = %s, GetStorageDevice: err = %v", inputVal, e) 74 return e 75 } 76 devPath := filepath.Join("/dev", device.Name) 77 err := measureStorageDevice(tpmHandle, devPath) 78 if err != nil { 79 log.Printf("Storage Collector: input = %s, err = %v", inputVal, err) 80 return err 81 } 82 } 83 84 return nil 85 }