Esempio n. 1
0
func (safs *signAddFindSuite) SetUpTest(c *C) {
	cfg0 := &asserts.DatabaseConfig{}
	db0, err := asserts.OpenDatabase(cfg0)
	c.Assert(err, IsNil)
	safs.signingDB = db0

	pk := testPrivKey0
	err = db0.ImportKey(pk)
	c.Assert(err, IsNil)
	safs.signingKeyID = pk.PublicKey().ID()

	topDir := filepath.Join(c.MkDir(), "asserts-db")
	bs, err := asserts.OpenFSBackstore(topDir)
	c.Assert(err, IsNil)

	trustedKey := testPrivKey0
	cfg := &asserts.DatabaseConfig{
		Backstore: bs,
		Trusted: []asserts.Assertion{
			asserts.BootstrapAccountForTest("canonical"),
			asserts.BootstrapAccountKeyForTest("canonical", trustedKey.PublicKey()),
		},
	}
	db, err := asserts.OpenDatabase(cfg)
	c.Assert(err, IsNil)
	safs.db = db
}
Esempio n. 2
0
func (gkms *gpgKeypairMgrSuite) TestUseInSigningFailure(c *C) {
	mockGPG := func(prev asserts.GPGRunner, input []byte, args ...string) ([]byte, error) {
		if args[1] == "--list-secret-keys" || args[1] == "--export" {
			return prev(input, args...)
		}
		n := len(args)
		c.Assert(args[n-1], Equals, "--detach-sign")
		return nil, fmt.Errorf("boom")
	}
	restore := asserts.MockRunGPG(mockGPG)
	defer restore()

	signDB, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		KeypairManager: gkms.keypairMgr,
	})
	c.Assert(err, IsNil)

	headers := map[string]interface{}{
		"authority-id":  "dev1-id",
		"snap-sha3-384": blobSHA3_384,
		"snap-id":       "snap-id-1",
		"grade":         "devel",
		"snap-size":     "1025",
		"timestamp":     time.Now().Format(time.RFC3339),
	}

	_, err = signDB.Sign(asserts.SnapBuildType, headers, nil, assertstest.DevKeyID)
	c.Check(err, ErrorMatches, "cannot sign assertion: cannot sign using GPG: boom")
}
Esempio n. 3
0
func (chks *checkSuite) TestCheckUnsupportedFormat(c *C) {
	trustedKey := testPrivKey0

	cfg := &asserts.DatabaseConfig{
		Backstore: chks.bs,
		Trusted:   []asserts.Assertion{asserts.BootstrapAccountKeyForTest("canonical", trustedKey.PublicKey())},
	}
	db, err := asserts.OpenDatabase(cfg)
	c.Assert(err, IsNil)

	var a asserts.Assertion
	(func() {
		restore := asserts.MockMaxSupportedFormat(asserts.TestOnlyType, 77)
		defer restore()
		var err error

		headers := map[string]interface{}{
			"authority-id": "canonical",
			"primary-key":  "0",
			"format":       "77",
		}
		a, err = asserts.AssembleAndSignInTest(asserts.TestOnlyType, headers, nil, trustedKey)
		c.Assert(err, IsNil)
	})()

	err = db.Check(a)
	c.Assert(err, FitsTypeOf, &asserts.UnsupportedFormatError{})
	c.Check(err, ErrorMatches, `proposed "test-only" assertion has format 77 but 1 is latest supported`)
}
func getMemoryKeyStore(config ConfigSettings) (*KeypairDatabase, error) {
	db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		KeypairManager: asserts.NewMemoryKeypairManager(),
	})
	kdb := KeypairDatabase{FilesystemStore, db, nil}
	return &kdb, err
}
Esempio n. 5
0
func (s *fetcherSuite) TestFetch(c *C) {
	s.prereqSnapAssertions(c, 10)

	db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		Backstore: asserts.NewMemoryBackstore(),
		Trusted:   s.storeSigning.Trusted,
	})
	c.Assert(err, IsNil)

	ref := &asserts.Ref{
		Type:       asserts.SnapRevisionType,
		PrimaryKey: []string{makeDigest(10)},
	}

	retrieve := func(ref *asserts.Ref) (asserts.Assertion, error) {
		return ref.Resolve(s.storeSigning.Find)
	}

	f := asserts.NewFetcher(db, retrieve, db.Add)

	err = f.Fetch(ref)
	c.Assert(err, IsNil)

	snapRev, err := ref.Resolve(db.Find)
	c.Assert(err, IsNil)
	c.Check(snapRev.(*asserts.SnapRevision).SnapRevision(), Equals, 10)

	snapDecl, err := db.Find(asserts.SnapDeclarationType, map[string]string{
		"series":  "16",
		"snap-id": "snap-id-1",
	})
	c.Assert(err, IsNil)
	c.Check(snapDecl.(*asserts.SnapDeclaration).SnapName(), Equals, "foo")
}
Esempio n. 6
0
func (s *snapassertsSuite) SetUpTest(c *C) {
	rootPrivKey, _ := assertstest.GenerateKey(1024)
	storePrivKey, _ := assertstest.GenerateKey(752)
	s.storeSigning = assertstest.NewStoreStack("can0nical", rootPrivKey, storePrivKey)

	s.dev1Acct = assertstest.NewAccount(s.storeSigning, "developer1", nil, "")

	localDB, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		Backstore: asserts.NewMemoryBackstore(),
		Trusted:   s.storeSigning.Trusted,
	})
	c.Assert(err, IsNil)

	s.localDB = localDB

	// add in prereqs assertions
	err = s.localDB.Add(s.storeSigning.StoreAccountKey(""))
	c.Assert(err, IsNil)
	err = s.localDB.Add(s.dev1Acct)
	c.Assert(err, IsNil)

	headers := map[string]interface{}{
		"series":       "16",
		"snap-id":      "snap-id-1",
		"snap-name":    "foo",
		"publisher-id": s.dev1Acct.AccountID(),
		"timestamp":    time.Now().Format(time.RFC3339),
	}
	snapDecl, err := s.storeSigning.Sign(asserts.SnapDeclarationType, headers, nil, "")
	c.Assert(err, IsNil)
	err = s.localDB.Add(snapDecl)
	c.Assert(err, IsNil)
}
Esempio n. 7
0
func (s *deviceMgrSuite) SetUpTest(c *C) {
	dirs.SetRootDir(c.MkDir())

	rootPrivKey, _ := assertstest.GenerateKey(1024)
	storePrivKey, _ := assertstest.GenerateKey(752)
	s.storeSigning = assertstest.NewStoreStack("canonical", rootPrivKey, storePrivKey)
	s.state = state.New(nil)

	db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		Backstore: asserts.NewMemoryBackstore(),
		Trusted:   s.storeSigning.Trusted,
	})
	c.Assert(err, IsNil)

	s.state.Lock()
	assertstate.ReplaceDB(s.state, db)
	s.state.Unlock()

	err = db.Add(s.storeSigning.StoreAccountKey(""))
	c.Assert(err, IsNil)

	mgr, err := devicestate.Manager(s.state)
	c.Assert(err, IsNil)

	s.db = db
	s.mgr = mgr

	s.state.Lock()
	snapstate.ReplaceStore(s.state, &fakeStore{
		state: s.state,
		db:    s.storeSigning,
	})
	s.state.Unlock()
}
Esempio n. 8
0
func (opens *openSuite) TestOpenDatabaseTrustedAccount(c *C) {
	headers := map[string]interface{}{
		"authority-id": "canonical",
		"account-id":   "trusted",
		"display-name": "Trusted",
		"validation":   "certified",
		"timestamp":    "2015-01-01T14:00:00Z",
	}
	acct, err := asserts.AssembleAndSignInTest(asserts.AccountType, headers, nil, testPrivKey0)
	c.Assert(err, IsNil)

	cfg := &asserts.DatabaseConfig{
		Backstore: asserts.NewMemoryBackstore(),
		Trusted:   []asserts.Assertion{acct},
	}

	db, err := asserts.OpenDatabase(cfg)
	c.Assert(err, IsNil)

	a, err := db.Find(asserts.AccountType, map[string]string{
		"account-id": "trusted",
	})
	c.Assert(err, IsNil)
	acct1 := a.(*asserts.Account)
	c.Check(acct1.AccountID(), Equals, "trusted")
	c.Check(acct1.DisplayName(), Equals, "Trusted")

	c.Check(db.IsTrustedAccount("trusted"), Equals, true)

	// empty account id (invalid) is not trusted
	c.Check(db.IsTrustedAccount(""), Equals, false)
}
Esempio n. 9
0
func (chks *checkSuite) TestCheckForgery(c *C) {
	trustedKey := testPrivKey0

	cfg := &asserts.DatabaseConfig{
		Backstore: chks.bs,
		Trusted:   []asserts.Assertion{asserts.BootstrapAccountKeyForTest("canonical", trustedKey.PublicKey())},
	}
	db, err := asserts.OpenDatabase(cfg)
	c.Assert(err, IsNil)

	encoded := asserts.Encode(chks.a)
	content, encodedSig := chks.a.Signature()
	// forgery
	forgedSig := new(packet.Signature)
	forgedSig.PubKeyAlgo = packet.PubKeyAlgoRSA
	forgedSig.Hash = crypto.SHA512
	forgedSig.CreationTime = time.Now()
	h := crypto.SHA512.New()
	h.Write(content)
	pk1 := packet.NewRSAPrivateKey(time.Unix(1, 0), testPrivKey1RSA)
	err = forgedSig.Sign(h, pk1, &packet.Config{DefaultHash: crypto.SHA512})
	c.Assert(err, IsNil)
	buf := new(bytes.Buffer)
	forgedSig.Serialize(buf)
	b := append([]byte{0x1}, buf.Bytes()...)
	forgedSigEncoded := base64.StdEncoding.EncodeToString(b)
	forgedEncoded := bytes.Replace(encoded, encodedSig, []byte(forgedSigEncoded), 1)
	c.Assert(forgedEncoded, Not(DeepEquals), encoded)

	forgedAssert, err := asserts.Decode(forgedEncoded)
	c.Assert(err, IsNil)

	err = db.Check(forgedAssert)
	c.Assert(err, ErrorMatches, "failed signature verification: .*")
}
Esempio n. 10
0
func (opens *openSuite) TestOpenDatabaseOK(c *C) {
	cfg := &asserts.DatabaseConfig{
		Backstore: asserts.NewMemoryBackstore(),
	}
	db, err := asserts.OpenDatabase(cfg)
	c.Assert(err, IsNil)
	c.Assert(db, NotNil)
}
func getErrorMockKeyStore(config ConfigSettings) (*KeypairDatabase, error) {
	mockStore := new(errorMockKeypairManager)

	db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		KeypairManager: mockStore,
	})
	kdb := KeypairDatabase{FilesystemStore, db, nil}
	return &kdb, err
}
Esempio n. 12
0
func (gkms *gpgKeypairMgrSuite) TestUseInSigning(c *C) {
	store := assertstest.NewStoreStack("trusted", testPrivKey0, testPrivKey1)

	devKey, err := gkms.keypairMgr.Get(assertstest.DevKeyID)
	c.Assert(err, IsNil)

	devAcct := assertstest.NewAccount(store, "devel1", map[string]interface{}{
		"account-id": "dev1-id",
	}, "")
	devAccKey := assertstest.NewAccountKey(store, devAcct, nil, devKey.PublicKey(), "")

	signDB, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		KeypairManager: gkms.keypairMgr,
	})
	c.Assert(err, IsNil)

	checkDB, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		Backstore: asserts.NewMemoryBackstore(),
		Trusted:   store.Trusted,
	})
	c.Assert(err, IsNil)
	// add store key
	err = checkDB.Add(store.StoreAccountKey(""))
	c.Assert(err, IsNil)
	// enable devel key
	err = checkDB.Add(devAcct)
	c.Assert(err, IsNil)
	err = checkDB.Add(devAccKey)
	c.Assert(err, IsNil)

	headers := map[string]interface{}{
		"authority-id":  "dev1-id",
		"snap-sha3-384": blobSHA3_384,
		"snap-id":       "snap-id-1",
		"grade":         "devel",
		"snap-size":     "1025",
		"timestamp":     time.Now().Format(time.RFC3339),
	}
	snapBuild, err := signDB.Sign(asserts.SnapBuildType, headers, nil, assertstest.DevKeyID)
	c.Assert(err, IsNil)

	err = checkDB.Check(snapBuild)
	c.Check(err, IsNil)
}
Esempio n. 13
0
func (chks *checkSuite) TestCheckNoPubKey(c *C) {
	cfg := &asserts.DatabaseConfig{
		Backstore: chks.bs,
	}
	db, err := asserts.OpenDatabase(cfg)
	c.Assert(err, IsNil)

	err = db.Check(chks.a)
	c.Assert(err, ErrorMatches, `no matching public key "[[:alnum:]_-]+" for signature by "canonical"`)
}
Esempio n. 14
0
// GetKeyStore returns the keystore as defined in the config file
func GetKeyStore(config ConfigSettings) (*KeypairDatabase, error) {
	switch config.KeyStoreType {
	case DatabaseStore.Name:
		// Prepare the memory store for the unsealed keys
		memStore := asserts.NewMemoryKeypairManager()
		db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
			KeypairManager: memStore,
		})

		dbOperator := DatabaseKeypairOperator{}

		keypairDB = KeypairDatabase{DatabaseStore, db, &dbOperator}
		return &keypairDB, err

	case TPM20Store.Name:
		// Initalize the TPM store
		tpm20 := TPM20KeypairOperator{config.KeyStorePath, config.KeyStoreSecret, &tpm20Command{}}

		// Prepare the memory store for the unsealed keys
		memStore := asserts.NewMemoryKeypairManager()
		db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
			KeypairManager: memStore,
		})

		keypairDB = KeypairDatabase{TPM20Store, db, &tpm20}
		return &keypairDB, err

	case FilesystemStore.Name:
		fsStore, err := asserts.OpenFSKeypairManager(config.KeyStorePath)
		if err != nil {
			return nil, err
		}
		db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
			KeypairManager: fsStore,
		})

		keypairDB = KeypairDatabase{FilesystemStore, db, nil}
		return &keypairDB, err

	default:
		return nil, ErrorInvalidKeystoreType
	}
}
Esempio n. 15
0
func (dbs *databaseSuite) SetUpTest(c *C) {
	dbs.topDir = filepath.Join(c.MkDir(), "asserts-db")
	fsKeypairMgr, err := asserts.OpenFSKeypairManager(dbs.topDir)
	c.Assert(err, IsNil)
	cfg := &asserts.DatabaseConfig{
		KeypairManager: fsKeypairMgr,
	}
	db, err := asserts.OpenDatabase(cfg)
	c.Assert(err, IsNil)
	dbs.db = db
}
Esempio n. 16
0
func MakeFakeRefreshForSnaps(snaps []string, blobDir string) error {
	storePrivKey, _ := assertstest.ReadPrivKey(systestkeys.TestStorePrivKey)
	db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		KeypairManager: asserts.NewMemoryKeypairManager(),
		Backstore:      asserts.NewMemoryBackstore(),
		Trusted:        sysdb.Trusted(),
	})
	if err != nil {
		return err
	}
	// for signing
	db.ImportKey(storePrivKey)

	var cliConfig client.Config
	cli := client.New(&cliConfig)
	retrieve := func(ref *asserts.Ref) (asserts.Assertion, error) {
		headers := make(map[string]string)
		for i, k := range ref.Type.PrimaryKey {
			headers[k] = ref.PrimaryKey[i]
		}
		as, err := cli.Known(ref.Type.Name, headers)
		if err != nil {
			return nil, err
		}
		switch len(as) {
		case 1:
			return as[0], nil
		case 0:
			return nil, asserts.ErrNotFound
		default:
			panic(fmt.Sprintf("multiple assertions when retrieving by primary key: %v", ref))
		}
	}

	save := func(a asserts.Assertion) error {
		err := db.Add(a)
		if err != nil {
			if _, ok := err.(*asserts.RevisionError); !ok {
				return err
			}
		}
		return writeAssert(a, blobDir)
	}

	f := asserts.NewFetcher(db, retrieve, save)

	for _, snap := range snaps {
		if err := makeFakeRefreshForSnap(snap, blobDir, db, f); err != nil {
			return err
		}
	}
	return nil
}
Esempio n. 17
0
func openDatabaseAt(path string, cfg *asserts.DatabaseConfig) (*asserts.Database, error) {
	bs, err := asserts.OpenFSBackstore(path)
	if err != nil {
		return nil, err
	}
	keypairMgr, err := asserts.OpenFSKeypairManager(path)
	if err != nil {
		return nil, err
	}
	cfg.Backstore = bs
	cfg.KeypairManager = keypairMgr
	return asserts.OpenDatabase(cfg)
}
Esempio n. 18
0
func (chks *checkSuite) TestCheckExpiredPubKey(c *C) {
	trustedKey := testPrivKey0

	cfg := &asserts.DatabaseConfig{
		Backstore: chks.bs,
		Trusted:   []asserts.Assertion{asserts.ExpiredAccountKeyForTest("canonical", trustedKey.PublicKey())},
	}
	db, err := asserts.OpenDatabase(cfg)
	c.Assert(err, IsNil)

	err = db.Check(chks.a)
	c.Assert(err, ErrorMatches, `assertion is signed with expired public key "[[:alnum:]_-]+" from "canonical"`)
}
Esempio n. 19
0
func (opens *openSuite) TestOpenDatabaseTrustedWrongType(c *C) {
	headers := map[string]interface{}{
		"authority-id": "canonical",
		"primary-key":  "0",
	}
	a, err := asserts.AssembleAndSignInTest(asserts.TestOnlyType, headers, nil, testPrivKey0)

	cfg := &asserts.DatabaseConfig{
		Trusted: []asserts.Assertion{a},
	}

	_, err = asserts.OpenDatabase(cfg)
	c.Assert(err, ErrorMatches, "cannot load trusted assertions that are not account-key or account: test-only")
}
Esempio n. 20
0
func (x *cmdSignBuild) Execute(args []string) error {
	if len(args) > 0 {
		return ErrExtraArgs
	}

	snapDigest, snapSize, err := asserts.SnapFileSHA3_384(x.Positional.Filename)
	if err != nil {
		return err
	}

	gkm := asserts.NewGPGKeypairManager()
	privKey, err := gkm.GetByName(x.KeyName)
	if err != nil {
		// TRANSLATORS: %q is the key name, %v the error message
		return fmt.Errorf(i18n.G("cannot use %q key: %v"), x.KeyName, err)
	}

	pubKey := privKey.PublicKey()
	timestamp := time.Now().Format(time.RFC3339)

	headers := map[string]interface{}{
		"developer-id":  x.DeveloperID,
		"authority-id":  x.DeveloperID,
		"snap-sha3-384": snapDigest,
		"snap-id":       x.SnapID,
		"snap-size":     fmt.Sprintf("%d", snapSize),
		"grade":         x.Grade,
		"timestamp":     timestamp,
	}

	adb, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		KeypairManager: gkm,
	})
	if err != nil {
		return fmt.Errorf(i18n.G("cannot open the assertions database: %v"), err)
	}

	a, err := adb.Sign(asserts.SnapBuildType, headers, nil, pubKey.ID())
	if err != nil {
		return fmt.Errorf(i18n.G("cannot sign assertion: %v"), err)
	}

	_, err = Stdout.Write(asserts.Encode(a))
	if err != nil {
		return err
	}

	return nil
}
Esempio n. 21
0
// NewSigningDB creates a test signing assertion db with the given defaults. It panics on error.
func NewSigningDB(authorityID string, privKey asserts.PrivateKey) *SigningDB {
	db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{})
	if err != nil {
		panic(err)
	}
	err = db.ImportKey(privKey)
	if err != nil {
		panic(err)
	}
	return &SigningDB{
		AuthorityID: authorityID,
		KeyID:       privKey.PublicKey().ID(),
		Database:    db,
	}
}
func getTPMKeyStoreWithMockCommand() *KeypairDatabase {
	// Set up the environment variables
	config := ConfigSettings{KeyStorePath: "../keystore", KeyStoreType: "tpm2.0", KeyStoreSecret: "this needs to be 32 bytes long!!"}
	Environ = &Env{Config: config, DB: &mockDB{}}

	tpm20 := TPM20KeypairOperator{config.KeyStorePath, config.KeyStoreSecret, &mockTPM20Command{}}

	// Prepare the memory store for the unsealed keys
	memStore := asserts.NewMemoryKeypairManager()
	db, _ := asserts.OpenDatabase(&asserts.DatabaseConfig{
		KeypairManager: memStore,
	})

	keypairDB = KeypairDatabase{TPM20Store, db, &tpm20}
	return &keypairDB
}
Esempio n. 23
0
// NewStoreStack creates a new store assertion stack. It panics on error.
func NewStoreStack(authorityID string, rootPrivKey, storePrivKey asserts.PrivateKey) *StoreStack {
	rootSigning := NewSigningDB(authorityID, rootPrivKey)
	ts := time.Now().Format(time.RFC3339)
	trustedAcct := NewAccount(rootSigning, authorityID, map[string]interface{}{
		"account-id": authorityID,
		"validation": "certified",
		"timestamp":  ts,
	}, "")
	trustedKey := NewAccountKey(rootSigning, trustedAcct, map[string]interface{}{
		"name":  "root",
		"since": ts,
	}, rootPrivKey.PublicKey(), "")
	trusted := []asserts.Assertion{trustedAcct, trustedKey}

	db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		Backstore: asserts.NewMemoryBackstore(),
		Trusted:   trusted,
	})
	if err != nil {
		panic(err)
	}
	err = db.ImportKey(storePrivKey)
	if err != nil {
		panic(err)
	}
	storeKey := NewAccountKey(rootSigning, trustedAcct, map[string]interface{}{
		"name": "store",
	}, storePrivKey.PublicKey(), "")
	err = db.Add(storeKey)
	if err != nil {
		panic(err)
	}

	return &StoreStack{
		TrustedAccount: trustedAcct,
		TrustedKey:     trustedKey,
		Trusted:        trusted,

		RootSigning: rootSigning,

		SigningDB: &SigningDB{
			AuthorityID: authorityID,
			KeyID:       storeKey.PublicKeyID(),
			Database:    db,
		},
	}
}
Esempio n. 24
0
func (aks *accountKeySuite) openDB(c *C) *asserts.Database {
	trustedKey := testPrivKey0

	topDir := filepath.Join(c.MkDir(), "asserts-db")
	bs, err := asserts.OpenFSBackstore(topDir)
	c.Assert(err, IsNil)
	cfg := &asserts.DatabaseConfig{
		Backstore: bs,
		Trusted: []asserts.Assertion{
			asserts.BootstrapAccountForTest("canonical"),
			asserts.BootstrapAccountKeyForTest("canonical", trustedKey.PublicKey()),
		},
	}
	db, err := asserts.OpenDatabase(cfg)
	c.Assert(err, IsNil)
	return db
}
Esempio n. 25
0
// Sign produces the text of a signed assertion as specified by opts.
func Sign(opts *Options, keypairMgr asserts.KeypairManager) ([]byte, error) {
	var headers map[string]interface{}
	err := json.Unmarshal(opts.Statement, &headers)
	if err != nil {
		return nil, fmt.Errorf("cannot parse the assertion input as JSON: %v", err)
	}
	typCand, ok := headers["type"]
	if !ok {
		return nil, fmt.Errorf("missing assertion type header")
	}
	typStr, ok := typCand.(string)
	if !ok {
		return nil, fmt.Errorf("assertion type must be a string, not: %v", typCand)
	}
	typ := asserts.Type(typStr)
	if typ == nil {
		return nil, fmt.Errorf("invalid assertion type: %v", headers["type"])
	}

	var body []byte
	if bodyCand, ok := headers["body"]; ok {
		bodyStr, ok := bodyCand.(string)
		if !ok {
			return nil, fmt.Errorf("body if specified must be a string")
		}
		body = []byte(bodyStr)
		delete(headers, "body")
	}

	adb, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		KeypairManager: keypairMgr,
	})
	if err != nil {
		return nil, err
	}

	// TODO: teach Sign to cross check keyID and authority-id
	// against an account-key
	a, err := adb.Sign(typ, headers, body, opts.KeyID)
	if err != nil {
		return nil, err
	}

	return asserts.Encode(a), nil
}
Esempio n. 26
0
func makeStoreAndCheckDB(c *C) (storeDB *assertstest.SigningDB, checkDB *asserts.Database) {
	trustedPrivKey := testPrivKey0
	storePrivKey := testPrivKey1

	store := assertstest.NewStoreStack("canonical", trustedPrivKey, storePrivKey)
	cfg := &asserts.DatabaseConfig{
		Backstore: asserts.NewMemoryBackstore(),
		Trusted:   store.Trusted,
	}
	checkDB, err := asserts.OpenDatabase(cfg)
	c.Assert(err, IsNil)

	// add store key
	err = checkDB.Add(store.StoreAccountKey(""))
	c.Assert(err, IsNil)

	return store.SigningDB, checkDB
}
Esempio n. 27
0
func (aks *accountKeySuite) SetUpSuite(c *C) {
	cfg1 := &asserts.DatabaseConfig{}
	accDb, err := asserts.OpenDatabase(cfg1)
	c.Assert(err, IsNil)
	aks.privKey = testPrivKey1
	err = accDb.ImportKey(aks.privKey)
	c.Assert(err, IsNil)
	aks.keyID = aks.privKey.PublicKey().ID()

	pubKey, err := accDb.PublicKey(aks.keyID)
	c.Assert(err, IsNil)
	pubKeyEncoded, err := asserts.EncodePublicKey(pubKey)
	c.Assert(err, IsNil)
	aks.pubKeyBody = string(pubKeyEncoded)

	aks.since, err = time.Parse(time.RFC822, "16 Nov 15 15:04 UTC")
	c.Assert(err, IsNil)
	aks.until = aks.since.AddDate(1, 0, 0)
	aks.sinceLine = "since: " + aks.since.Format(time.RFC3339) + "\n"
	aks.untilLine = "until: " + aks.until.Format(time.RFC3339) + "\n"
}
Esempio n. 28
0
func (gkms *gpgKeypairMgrSuite) TestUseInSigningKeyTooShort(c *C) {
	gkms.importKey(shortPrivKey)
	privk, _ := assertstest.ReadPrivKey(shortPrivKey)

	signDB, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		KeypairManager: gkms.keypairMgr,
	})
	c.Assert(err, IsNil)

	headers := map[string]interface{}{
		"authority-id":  "dev1-id",
		"snap-sha3-384": blobSHA3_384,
		"snap-id":       "snap-id-1",
		"grade":         "devel",
		"snap-size":     "1025",
		"timestamp":     time.Now().Format(time.RFC3339),
	}

	_, err = signDB.Sign(asserts.SnapBuildType, headers, nil, privk.PublicKey().ID())
	c.Check(err, ErrorMatches, `cannot sign assertion: signing needs at least a 4096 bits key, got 2048`)
}
Esempio n. 29
0
func MakeFakeRefreshForSnaps(snaps []string, blobDir string) error {
	storePrivKey, _ := assertstest.ReadPrivKey(systestkeys.TestStorePrivKey)
	db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		KeypairManager: asserts.NewMemoryKeypairManager(),
		Backstore:      asserts.NewMemoryBackstore(),
		Trusted:        sysdb.Trusted(),
	})
	if err != nil {
		return err
	}
	// for signing
	db.ImportKey(storePrivKey)

	// XXX: ideally for consistency we should talk to the local snapd
	// but this allows us to go working until snapd itself
	// start being fully assertion using
	sto := store.New(nil, nil)
	retrieve := func(ref *asserts.Ref) (asserts.Assertion, error) {
		return sto.Assertion(ref.Type, ref.PrimaryKey, nil)
	}

	save := func(a asserts.Assertion) error {
		err := db.Add(a)
		if err != nil {
			if _, ok := err.(*asserts.RevisionError); !ok {
				return err
			}
		}
		return writeAssert(a, blobDir)
	}

	f := asserts.NewFetcher(db, retrieve, save)

	for _, snap := range snaps {
		if err := makeFakeRefreshForSnap(snap, blobDir, db, f); err != nil {
			return err
		}
	}
	return nil
}
Esempio n. 30
0
func fetchSnapAssertions(sto *store.Store, snapPath string, snapInfo *snap.Info, dlOpts *image.DownloadOptions) error {
	db, err := asserts.OpenDatabase(&asserts.DatabaseConfig{
		Backstore: asserts.NewMemoryBackstore(),
		Trusted:   sysdb.Trusted(),
	})
	if err != nil {
		return err
	}

	w, err := os.Create(snapPath + ".assertions")
	if err != nil {
		return fmt.Errorf(i18n.G("cannot create assertions file: %v"), err)
	}
	defer w.Close()

	encoder := asserts.NewEncoder(w)
	save := func(a asserts.Assertion) error {
		return encoder.Encode(a)
	}
	f := image.StoreAssertionFetcher(sto, dlOpts, db, save)

	return image.FetchAndCheckSnapAssertions(snapPath, snapInfo, f, db)
}