gen-token.go 2.4 KB
Newer Older
1 2 3 4 5
package main // import "github.com/inclavare-containers/runectl"

import (
	"fmt"
	"github.com/opencontainers/runc/libenclave/intelsgx"
6
	"github.com/sirupsen/logrus"
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
	"github.com/urfave/cli"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

var generateTokenCommand = cli.Command{
	Name:  "gen-token",
	Usage: "retrieve a token from aesmd",
	ArgsUsage: `[command options]

EXAMPLE:
For example, generate the token file according to the given signature file:

	# runectl gen-token --signature foo.sig`,
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:  "signature",
			Usage: "path to the input signature file (.sig) containing SIGSTRUCT",
		},
		cli.StringFlag{
			Name:  "token",
			Usage: "path to the output token file (.token) containing EINITTOKEN",
		},
	},
	Action: func(context *cli.Context) error {
		sigPath := context.String("signature")
		if sigPath == "" {
			return fmt.Errorf("signature argument cannot be empty")
		}

		sf, err := os.Open(sigPath)
		if err != nil {
			if os.IsNotExist(err) {
				return fmt.Errorf("signature file %s not found", sigPath)
			}
			return err
		}
		defer sf.Close()

		var sfi os.FileInfo
		sfi, err = sf.Stat()
		if err != nil {
			return err
		}

		if sfi.Size() != intelsgx.SigStructLength {
			return fmt.Errorf("signature file %s not match SIGSTRUCT", sigPath)
		}

		if context.GlobalBool("verbose") {
60
			logrus.SetLevel(logrus.DebugLevel)
61 62
		}

63 64 65
		buf := make([]byte, intelsgx.SigStructLength)
		if _, err = io.ReadFull(sf, buf); err != nil {
			return fmt.Errorf("signature file %s read failed", sigPath)
66 67
		}

68
		tok, err := intelsgx.GetLaunchToken(buf)
69
		if err != nil {
70
			logrus.Print(err)
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
			return err
		}

		tokenPath := context.String("token")
		if tokenPath == "" {
			tokenPath = filepath.Dir(sigPath)
			if tokenPath == "." {
				tokenPath = ""
			} else if strings.HasPrefix(tokenPath, "../") {
				if tokenPath, err = filepath.Abs(tokenPath); err != nil {
					return err
				}
				tokenPath += "/"
			} else {
				tokenPath += "/"
			}

			baseName := filepath.Base(sigPath)
			if strings.HasSuffix(baseName, ".sig") {
				tokenPath += baseName[:strings.LastIndex(baseName, ".sig")]
			}
			tokenPath += ".token"
		}

95
		if err := ioutil.WriteFile(tokenPath, tok, sfi.Mode().Perm()); err != nil {
96 97 98 99 100 101 102 103 104 105 106
			return err
		}

		if context.GlobalBool("verbose") {
			fmt.Printf("token file %s saved\n", tokenPath)
		}

		return nil
	},
	SkipArgReorder: true,
}