github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+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 "log" 11 "os" 12 "path/filepath" 13 14 slaunch "github.com/u-root/u-root/pkg/securelaunch" 15 "github.com/u-root/u-root/pkg/securelaunch/tpm" 16 ) 17 18 /* describes the "storage" portion of policy file */ 19 type StorageCollector struct { 20 Type string `json:"type"` 21 Paths []string `json:"paths"` 22 } 23 24 /* 25 * NewStorageCollector extracts the "storage" portion from the policy file. 26 * initializes a new StorageCollector structure. 27 * returns error if unmarshalling of StorageCollector fails 28 */ 29 func NewStorageCollector(config []byte) (Collector, error) { 30 slaunch.Debug("New Storage Collector initialized\n") 31 var sc = new(StorageCollector) 32 err := json.Unmarshal(config, &sc) 33 if err != nil { 34 return nil, err 35 } 36 return sc, nil 37 } 38 39 /* 40 * measureStorageDevice reads the disk path input by user, 41 * and then extends the pcr with it. 42 * 43 * Hashing of buffer is handled by tpm package. 44 * - blkDevicePath - string e.g /dev/sda 45 * returns 46 * - error if Reading the block device fails. 47 */ 48 func measureStorageDevice(blkDevicePath string) error { 49 50 log.Printf("Storage Collector: Measuring block device %s\n", blkDevicePath) 51 file, err := os.Open(blkDevicePath) 52 if err != nil { 53 return fmt.Errorf("couldn't open disk=%s err=%v", blkDevicePath, err) 54 } 55 56 eventDesc := fmt.Sprintf("Storage Collector: Measured %s", blkDevicePath) 57 return tpm.ExtendPCRDebug(pcr, file, eventDesc) 58 } 59 60 /* 61 * Collect satisfies Collector Interface. It loops over all storage paths provided 62 * by user and calls measureStorageDevice for each storage path. storage path is of 63 * form /dev/sda. measureStorageDevice in turn calls tpm 64 * package which further hashes this buffer and extends pcr. 65 */ 66 func (s *StorageCollector) Collect() error { 67 68 for _, inputVal := range s.Paths { 69 device, e := slaunch.GetStorageDevice(inputVal) // inputVal is blkDevicePath e.g UUID or sda 70 if e != nil { 71 log.Printf("Storage Collector: input = %s, GetStorageDevice: err = %v", inputVal, e) 72 return e 73 } 74 devPath := filepath.Join("/dev", device.Name) 75 err := measureStorageDevice(devPath) 76 if err != nil { 77 log.Printf("Storage Collector: input = %s, err = %v", inputVal, err) 78 return err 79 } 80 } 81 82 return nil 83 }