github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/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/mvdan/u-root-coreutils/pkg/securelaunch"
    15  	"github.com/mvdan/u-root-coreutils/pkg/securelaunch/tpm"
    16  )
    17  
    18  // StorageCollector describes the "storage" portion of the policy file.
    19  type StorageCollector struct {
    20  	Type  string   `json:"type"`
    21  	Paths []string `json:"paths"`
    22  }
    23  
    24  // NewStorageCollector extracts the "storage" portion from the policy file and
    25  // initializes a new StorageCollector structure.
    26  //
    27  // It returns an error if unmarshalling of StorageCollector fails.
    28  func NewStorageCollector(config []byte) (Collector, error) {
    29  	slaunch.Debug("New Storage Collector initialized\n")
    30  	sc := new(StorageCollector)
    31  	err := json.Unmarshal(config, &sc)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  	return sc, nil
    36  }
    37  
    38  // measureStorageDevice reads the given disk path and measures it into the TPM.
    39  //
    40  // blkDevicePath is a string to a block device (e.g., /dev/sda).
    41  // It returns and error if Reading the block device fails.
    42  func measureStorageDevice(blkDevicePath string) error {
    43  	log.Printf("Storage Collector: Measuring block device %s\n", blkDevicePath)
    44  	file, err := os.Open(blkDevicePath)
    45  	if err != nil {
    46  		return fmt.Errorf("couldn't open disk=%s err=%v", blkDevicePath, err)
    47  	}
    48  
    49  	eventDesc := fmt.Sprintf("Storage Collector: Measured %s", blkDevicePath)
    50  	return tpm.ExtendPCRDebug(pcr, file, eventDesc)
    51  }
    52  
    53  // Collect loops over the given storage paths and for each storage path calls
    54  // measureStorageDevice(), which measures a storage device into the TPM.
    55  //
    56  // It satisfies the Collector interface.
    57  func (s *StorageCollector) Collect() error {
    58  	for _, inputVal := range s.Paths {
    59  		device, e := slaunch.GetStorageDevice(inputVal) // inputVal is blkDevicePath e.g UUID or sda
    60  		if e != nil {
    61  			log.Printf("Storage Collector: input = %s, GetStorageDevice: err = %v", inputVal, e)
    62  			return e
    63  		}
    64  		devPath := filepath.Join("/dev", device.Name)
    65  		err := measureStorageDevice(devPath)
    66  		if err != nil {
    67  			log.Printf("Storage Collector: input = %s, err = %v", inputVal, err)
    68  			return err
    69  		}
    70  	}
    71  
    72  	return nil
    73  }