github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/securelaunch/measurement/collectors.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 provides different collectors to hash files, disks, dmi info and cpuid info.
     6  package measurement
     7  
     8  import (
     9  	"encoding/json"
    10  	"fmt"
    11  )
    12  
    13  // PCR number to extend all measurements taken by the securelaunch package.
    14  const pcr = uint32(22)
    15  
    16  // All collectors (e.g., cpuid, dmi, etc.) should satisfy this interface.
    17  // Collectors collect data and extend its hash into a PCR.
    18  type Collector interface {
    19  	Collect() error
    20  }
    21  
    22  var supportedCollectors = map[string]func([]byte) (Collector, error){
    23  	"storage": NewStorageCollector,
    24  	"dmi":     NewDmiCollector,
    25  	"files":   NewFileCollector,
    26  	"cpuid":   NewCPUIDCollector,
    27  }
    28  
    29  // GetCollector calls the appropriate init handlers for a particular
    30  // collector JSON object argument and returns a new Collector Interface.
    31  //
    32  // An error is returned if unmarshalling fails or an unsupported collector is
    33  // passed as an argument.
    34  func GetCollector(config []byte) (Collector, error) {
    35  	var header struct {
    36  		Type string `json:"type"`
    37  	}
    38  	err := json.Unmarshal(config, &header)
    39  	if err != nil {
    40  		fmt.Printf("Measurement: Unmarshal error\n")
    41  		return nil, err
    42  	}
    43  
    44  	if init, ok := supportedCollectors[header.Type]; ok {
    45  		return init(config)
    46  	}
    47  
    48  	return nil, fmt.Errorf("unsupported collector %s", header.Type)
    49  }