Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func NewRandomCommand() *cobra.Command {
const (
long = `subcommand for generating random data.
`
short = "subcommand for for generating random data"
short = "subcommand for generating random data"
)

cmd := command.New("random <command>", short, long, runRandom, []command.Preparer{command.RequireTPMWithoutStorage}, nil)
Expand Down
44 changes: 25 additions & 19 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package cmd

import (
"context"
"fmt"
"os"

"github.com/charmbracelet/colorprofile"
"github.com/charmbracelet/fang"
"github.com/spf13/cobra"

"github.com/smallstep/cli-utils/step"
Expand All @@ -12,28 +15,14 @@ import (
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "step-tpm-plugin",
Short: "🔑 `step` plugin for interacting with TPMs. ",
Long: `🔑 step plugin for interacting with TPMs.
`,
Short: "🔑 `step` plugin for interacting with TPMs.",
Long: `🔑 step plugin for interacting with TPMs.`,
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
// Execute adds all child commands to the root command and prepares the step
// environment. It then invokes the root command in style with fangs.
func Execute() {
// initialize step environment.
if err := step.Init(); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}

err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}

func init() {
rootCmd.SilenceUsage = true
// add all child commands
rootCmd.AddCommand(
NewInfoCommand(),
NewEKCommand(),
Expand All @@ -43,4 +32,21 @@ func init() {
NewSimulatorCommand(),
NewVersionCommand(),
)

// ensure step environment is prepared before every command
rootCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error {
if err := step.Init(); err != nil {
return fmt.Errorf("failed initializing step environment: %w", err)
}

cmd.SetOut(colorprofile.NewWriter(cmd.OutOrStdout(), os.Environ()))
cmd.SetErr(colorprofile.NewWriter(cmd.ErrOrStderr(), os.Environ()))

return nil
}

// execute the command
if err := fang.Execute(context.Background(), rootCmd); err != nil {
os.Exit(1)
}
}
1 change: 0 additions & 1 deletion cmd/simulator/simulator_disabled.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//go:build !tpmsimulator
// +build !tpmsimulator

package simulator

Expand Down
120 changes: 77 additions & 43 deletions cmd/simulator/simulator_enabled.go
Original file line number Diff line number Diff line change
@@ -1,35 +1,49 @@
//go:build tpmsimulator
// +build tpmsimulator

package simulator

import (
"context"
"errors"
"fmt"
"log"
"log/slog"
"net"
"os"
"os/signal"
"path/filepath"
"syscall"

"github.com/jedib0t/go-pretty/table"
"github.com/charmbracelet/colorprofile"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/lipgloss/table"

"github.com/smallstep/panoramix/v5/logware"
"go.step.sm/crypto/randutil"
"go.step.sm/crypto/tpm"
"go.step.sm/crypto/tpm/simulator"

"github.com/smallstep/step-tpm-plugin/internal/flag"
)

const (
loggerName = "tpm"
)

func runSimulator(ctx context.Context) (err error) {
var (
socket = flag.GetString(ctx, flag.FlagSocket)
seed = flag.GetString(ctx, flag.FlagSeed)
verbose = flag.GetBool(ctx, flag.FlagVerbose)
logger *slog.Logger
)

loggerOptions := []logware.Option{logware.WithName(loggerName)}
if verbose {
loggerOptions = append(loggerOptions, logware.WithLevel(slog.LevelDebug))
}

logger = logware.Logger(loggerOptions...)

if seed == "" {
if seed, err = randutil.Hex(16); err != nil {
return fmt.Errorf("failed generating TPM seed: %w", err)
Expand Down Expand Up @@ -86,38 +100,18 @@ func runSimulator(ctx context.Context) (err error) {
}
}()

t1 := table.NewWriter()
t1.SetOutputMirror(os.Stdout)
t1.AppendRows([]table.Row{
{"Version", info.Version},
{"Interface", fmt.Sprintf("%s (simulator)", info.Interface)},
{"Manufacturer", info.Manufacturer},
{"Vendor Info", info.VendorInfo},
{"Firmware Version", info.FirmwareVersion},
})
for _, ek := range eks {
u, err := ek.FingerprintURI()
if err != nil {
return err
}
t1.AppendRow(table.Row{
fmt.Sprintf("EK URI (%s)", ek.Type()), u.String(),
})
if err := printTPMInfo(info, eks, socket, seed); err != nil {
logger.ErrorContext(ctx, "failed printing TPM info", logware.Error(err))
}
t1.AppendRows([]table.Row{
{"UNIX socket", socket},
{"Seed", seed},
})
t1.Render()

logF(true, "TPM simulator available at %q\n", socket)
logger.InfoContext(ctx, "TPM simulator available", slog.String("socket", socket))

// register shutdown signals and perform cleanup
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
logF(true, "stopping TPM simulator at %q\n", socket)
logger.InfoContext(ctx, "stopping TPM simulator ...", slog.String("socket", socket))
os.Remove(socket)
os.Exit(0)
}()
Expand All @@ -130,9 +124,9 @@ func runSimulator(ctx context.Context) (err error) {

// check if connection was established successfully
if err != nil {
logF(true, "connection error: %v\n", err)
logger.ErrorContext(ctx, "connection error", logware.Error(err))
} else {
logF(verbose, "connection established: %v\n", conn)
logger.DebugContext(ctx, "connection established", slog.String("addr", conn.RemoteAddr().String()))
}

// handle the connection in a separate goroutine.
Expand All @@ -143,38 +137,84 @@ func runSimulator(ctx context.Context) (err error) {
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
logF(true, "failed reading from socket: %v", err)
logger.ErrorContext(ctx, "failed reading fom socket", logware.Error(err))
}

logF(verbose, "read from socket: %v", buf[:n])
logger.DebugContext(ctx, "read from socket", slog.Any("bytes", buf[:n]))

nw, err := s.Write(buf[:n])
if err != nil {
logF(true, "failed writing to TPM: %v", err)
logger.ErrorContext(ctx, "failed writing to TPM", logware.Error(err))
}

logF(verbose, "written to TPM: %v", nw)
logger.DebugContext(ctx, "written to TPM", slog.Any("bytes", nw))

newBuf := make([]byte, 4096)
nr, err := s.Read(newBuf)
if err != nil {
logF(true, "failed reading from TPM: %v", err)
logger.ErrorContext(ctx, "failed reading from TPM", logware.Error(err))
}

logF(verbose, "read from TPM: %v", nr)
logger.DebugContext(ctx, "read from TPM", slog.Any("bytes", nr))

_, err = conn.Write(newBuf[:nr])
if err != nil {
logF(true, "failed writing to socket: %v", err)
logger.ErrorContext(ctx, "failed writing to socket", logware.Error(err))
}

logF(verbose, "written to socket: %v", newBuf[:nr])
logger.DebugContext(ctx, "written to socket", slog.Any("bytes", newBuf[:nr]))

// TODO(hs): log at least something about the interaction? The simulator is now very quiet after starting
}(conn)
}
}

var (
purple = lipgloss.Color("99")
gray = lipgloss.Color("245")
lightGray = lipgloss.Color("241")
headerStyle = lipgloss.NewStyle().Foreground(purple).Bold(true).Align(lipgloss.Center)
cellStyle = lipgloss.NewStyle().Padding(0, 1).MaxWidth(80)
oddRowStyle = cellStyle.Foreground(gray)
evenRowStyle = cellStyle.Foreground(lightGray)
)

func printTPMInfo(info *tpm.Info, eks []*tpm.EK, socket, seed string) error {
tbl := table.New().
Border(lipgloss.NormalBorder()).
BorderStyle(lipgloss.NewStyle().Foreground(purple)).
StyleFunc(func(row, col int) lipgloss.Style {
switch {
case row == table.HeaderRow:
return headerStyle
case row%2 == 0:
return evenRowStyle
default:
return oddRowStyle
}
})

tbl.Row("Version", info.Version.String())
tbl.Row("Interface", fmt.Sprintf("%s (simulator)", info.Interface))
tbl.Row("Manufacturer", info.Manufacturer.String())
tbl.Row("Vendor Info", info.VendorInfo)
tbl.Row("Firmware Version", info.FirmwareVersion.String())
for _, ek := range eks {
u, err := ek.FingerprintURI()
if err != nil {
return err
}
tbl.Row(fmt.Sprintf("EK URI (%s)", ek.Type()), u.String())
}
tbl.Row("UNIX socket", socket)
tbl.Row("Seed", seed)

w := colorprofile.NewWriter(os.Stdout, os.Environ())
fmt.Fprintln(w, tbl)

return nil
}

func getTPMSimulatorSocketPath() (sockAddr string, err error) {
paths := []string{"/run", "/var/run"}
for _, dir := range paths {
Expand All @@ -185,9 +225,3 @@ func getTPMSimulatorSocketPath() (sockAddr string, err error) {
}
return "", errors.New("could not automatically determine TPM simulator socket path")
}

func logF(shouldPrint bool, format string, v ...any) {
if shouldPrint {
log.Printf(format, v...)
}
}
Loading