Пример #1
0
func TestRotationNewSigMissing(t *testing.T) {
	logrus.SetLevel(logrus.DebugLevel)
	kdb := keys.NewDB()
	signer := signed.NewEd25519()
	repo := tuf.NewRepo(kdb, signer)
	remote := store.NewMemoryStore(nil, nil)
	cache := store.NewMemoryStore(nil, nil)

	// Generate initial root key and role and add to key DB
	rootKey, err := signer.Create("root", data.ED25519Key)
	assert.NoError(t, err, "Error creating root key")
	rootRole, err := data.NewRole("root", 1, []string{rootKey.ID()}, nil, nil)
	assert.NoError(t, err, "Error creating root role")

	kdb.AddKey(rootKey)
	err = kdb.AddRole(rootRole)
	assert.NoError(t, err, "Error adding root role to db")

	// Generate new key and role. These will appear in the root.json
	// but will not be added to the keyDB.
	replacementKey, err := signer.Create("root", data.ED25519Key)
	assert.NoError(t, err, "Error creating replacement root key")
	replacementRole, err := data.NewRole("root", 1, []string{replacementKey.ID()}, nil, nil)
	assert.NoError(t, err, "Error creating replacement root role")

	assert.NotEqual(t, rootKey.ID(), replacementKey.ID(), "Key IDs are the same")

	// Generate a new root with the replacement key and role
	testRoot, err := data.NewRoot(
		map[string]data.PublicKey{replacementKey.ID(): replacementKey},
		map[string]*data.RootRole{"root": &replacementRole.RootRole},
		false,
	)
	assert.NoError(t, err, "Failed to create new root")

	_, ok := testRoot.Signed.Keys[rootKey.ID()]
	assert.False(t, ok, "Old root key appeared in test root")

	// Sign testRoot with both old and new keys
	signedRoot, err := testRoot.ToSigned()
	err = signed.Sign(signer, signedRoot, rootKey)
	assert.NoError(t, err, "Failed to sign root")
	var origKeySig bool
	var replKeySig bool
	for _, sig := range signedRoot.Signatures {
		if sig.KeyID == rootKey.ID() {
			origKeySig = true
		} else if sig.KeyID == replacementKey.ID() {
			replKeySig = true
		}
	}
	assert.True(t, origKeySig, "Original root key signature not present")
	assert.False(t, replKeySig, "Replacement root key signature was present and shouldn't be")

	client := NewClient(repo, remote, kdb, cache)

	err = client.verifyRoot("root", signedRoot, 0)
	assert.Error(t, err, "Should have errored on verify as replacement signature was missing.")

}
Пример #2
0
func TestGetTimestampNewSnapshot(t *testing.T) {
	store := storage.NewMemStorage()
	crypto := signed.NewEd25519()

	snapshot := data.SignedSnapshot{}
	snapshot.Signed.Version = 0
	snapJSON, _ := json.Marshal(snapshot)

	store.UpdateCurrent("gun", storage.MetaUpdate{Role: "snapshot", Version: 0, Data: snapJSON})
	// create a key to be used by GetTimestamp
	_, err := GetOrCreateTimestampKey("gun", store, crypto, data.ED25519Key)
	assert.Nil(t, err, "GetTimestampKey errored")

	ts1, err := GetOrCreateTimestamp("gun", store, crypto)
	assert.Nil(t, err, "GetTimestamp errored")

	snapshot = data.SignedSnapshot{}
	snapshot.Signed.Version = 1
	snapJSON, _ = json.Marshal(snapshot)

	store.UpdateCurrent("gun", storage.MetaUpdate{Role: "snapshot", Version: 1, Data: snapJSON})

	ts2, err := GetOrCreateTimestamp("gun", store, crypto)
	assert.Nil(t, err, "GetTimestamp errored")

	assert.NotEqual(t, ts1, ts2, "Timestamp was not regenerated when snapshot changed")
}
Пример #3
0
func TestUpdateDelegations(t *testing.T) {
	ed25519 := signed.NewEd25519()
	keyDB := keys.NewDB()
	repo := initRepo(t, ed25519, keyDB)

	testKey, err := ed25519.Create("targets/test", data.ED25519Key)
	if err != nil {
		t.Fatal(err)
	}
	role, err := data.NewRole("targets/test", 1, []string{testKey.ID()}, []string{"test"}, []string{})
	if err != nil {
		t.Fatal(err)
	}

	err = repo.UpdateDelegations(role, []data.Key{testKey}, "")
	if err != nil {
		t.Fatal(err)
	}

	testDeepKey, err := ed25519.Create("targets/test/deep", data.ED25519Key)
	if err != nil {
		t.Fatal(err)
	}
	roleDeep, err := data.NewRole("targets/test/deep", 1, []string{testDeepKey.ID()}, []string{"test/deep"}, []string{})
	if err != nil {
		t.Fatal(err)
	}

	err = repo.UpdateDelegations(roleDeep, []data.Key{testDeepKey}, "")
	if err != nil {
		t.Fatal(err)
	}

	writeRepo(t, "/tmp/tufdelegation", repo)
}
Пример #4
0
func TestInitRepo(t *testing.T) {
	ed25519 := signed.NewEd25519()
	signer := signed.NewSigner(ed25519)
	keyDB := keys.NewDB()
	repo := initRepo(t, signer, keyDB)
	writeRepo(t, "/tmp/tufrepo", repo)
}
Пример #5
0
func TestRunBadCerts(t *testing.T) {
	err := Run(
		context.Background(),
		config.ServerConf{},
		signed.NewEd25519(),
	)
	if err == nil {
		t.Fatal("Passed empty certs, Run should have failed")
	}
}
Пример #6
0
func TestRunBadAddr(t *testing.T) {
	config := config.ServerConf{
		Addr:        "testAddr",
		TLSCertFile: "../fixtures/ca.pem",
		TLSKeyFile:  "../fixtures/ca-key.pem",
	}
	err := Run(context.Background(), config, signed.NewEd25519())
	if err == nil {
		t.Fatal("Passed bad addr, Run should have failed")
	}
}
Пример #7
0
func TestRunBadAddr(t *testing.T) {
	err := Run(
		context.Background(),
		"testAddr",
		"../fixtures/ca.pem",
		"../fixtures/ca-key.pem",
		signed.NewEd25519(),
	)
	if err == nil {
		t.Fatal("Passed bad addr, Run should have failed")
	}
}
Пример #8
0
func TestRunBadAddr(t *testing.T) {
	err := Run(
		context.Background(),
		"testAddr",
		"../fixtures/notary-server.crt",
		"../fixtures/notary-server.crt",
		signed.NewEd25519(),
		"",
		nil,
	)
	if err == nil {
		t.Fatal("Passed bad addr, Run should have failed")
	}
}
Пример #9
0
// EmptyRepo creates an in memory key database, crypto service
// and initializes a repo with no targets or delegations.
func EmptyRepo() (*keys.KeyDB, *tuf.Repo, signed.CryptoService) {
	c := signed.NewEd25519()
	kdb := keys.NewDB()
	r := tuf.NewRepo(kdb, c)

	for _, role := range []string{"root", "targets", "snapshot", "timestamp"} {
		key, _ := c.Create(role, data.ED25519Key)
		role, _ := data.NewRole(role, 1, []string{key.ID()}, nil, nil)
		kdb.AddKey(key)
		kdb.AddRole(role)
	}

	r.InitRepo(false)
	return kdb, r, c
}
Пример #10
0
func TestGetTimestamp(t *testing.T) {
	store := storage.NewMemStorage()
	crypto := signed.NewEd25519()

	snapshot := &data.SignedSnapshot{}
	snapJSON, _ := json.Marshal(snapshot)

	store.UpdateCurrent("gun", storage.MetaUpdate{Role: "snapshot", Version: 0, Data: snapJSON})
	// create a key to be used by GetTimestamp
	_, err := GetOrCreateTimestampKey("gun", store, crypto, data.ED25519Key)
	assert.Nil(t, err, "GetTimestampKey errored")

	_, err = GetOrCreateTimestamp("gun", store, crypto)
	assert.Nil(t, err, "GetTimestamp errored")
}
Пример #11
0
func TestGetTimestampKey(t *testing.T) {
	store := storage.NewMemStorage()
	crypto := signed.NewEd25519()
	k, err := GetOrCreateTimestampKey("gun", store, crypto, data.ED25519Key)
	assert.Nil(t, err, "Expected nil error")
	assert.NotNil(t, k, "Key should not be nil")

	k2, err := GetOrCreateTimestampKey("gun", store, crypto, data.ED25519Key)

	assert.Nil(t, err, "Expected nil error")

	// trying to get the same key again should return the same value
	assert.Equal(t, k, k2, "Did not receive same key when attempting to recreate.")
	assert.NotNil(t, k2, "Key should not be nil")
}
Пример #12
0
func TestGetTimestamp(t *testing.T) {
	store := storage.NewMemStorage()
	crypto := signed.NewEd25519()
	signer := signed.NewSigner(crypto)

	snapshot := &data.SignedSnapshot{}
	snapJSON, _ := json.Marshal(snapshot)

	store.UpdateCurrent("gun", "snapshot", 0, snapJSON)
	// create a key to be used by GetTimestamp
	_, err := GetOrCreateTimestampKey("gun", store, crypto)
	assert.Nil(t, err, "GetTimestampKey errored")

	_, err = GetOrCreateTimestamp("gun", store, signer)
	assert.Nil(t, err, "GetTimestamp errored")
}
Пример #13
0
func TestRunReservedPort(t *testing.T) {
	ctx, _ := context.WithCancel(context.Background())

	err := Run(
		ctx,
		"localhost:80",
		"../fixtures/notary.pem",
		"../fixtures/notary.key",
		signed.NewEd25519(),
	)

	if _, ok := err.(*net.OpError); !ok {
		t.Fatalf("Received unexpected err: %s", err.Error())
	}
	if !strings.Contains(err.Error(), "bind: permission denied") {
		t.Fatalf("Received unexpected err: %s", err.Error())
	}
}
Пример #14
0
func TestRunGoodCancel(t *testing.T) {
	ctx, cancelFunc := context.WithCancel(context.Background())

	config := config.ServerConf{
		Addr:        "localhost:8002",
		TLSCertFile: "../fixtures/notary.pem",
		TLSKeyFile:  "../fixtures/notary.key",
	}

	go func() {
		time.Sleep(time.Second * 3)
		cancelFunc()
	}()

	err := Run(ctx, config, signed.NewEd25519())

	if _, ok := err.(*net.OpError); !ok {
		t.Fatalf("Received unexpected err: %s", err.Error())
	}
	if !strings.Contains(err.Error(), "use of closed network connection") {
		t.Fatalf("Received unexpected err: %s", err.Error())
	}
}
Пример #15
0
func main() {
	flag.Usage = usage
	flag.Parse()

	if debug {
		go debugServer(DebugAddress)
	}

	ctx := context.Background()

	filename := filepath.Base(configFile)
	ext := filepath.Ext(configFile)
	configPath := filepath.Dir(configFile)

	viper.SetConfigType(strings.TrimPrefix(ext, "."))
	viper.SetConfigName(strings.TrimSuffix(filename, ext))
	viper.AddConfigPath(configPath)
	err := viper.ReadInConfig()
	if err != nil {
		logrus.Error("Viper Error: ", err.Error())
		logrus.Error("Could not read config at ", configFile)
		os.Exit(1)
	}
	logrus.SetLevel(logrus.Level(viper.GetInt("logging.level")))

	sigHup := make(chan os.Signal)
	sigTerm := make(chan os.Signal)

	signal.Notify(sigHup, syscall.SIGHUP)
	signal.Notify(sigTerm, syscall.SIGTERM)

	var trust signed.CryptoService
	if viper.GetString("trust_service.type") == "remote" {
		logrus.Info("[Notary Server] : Using remote signing service")
		trust = signer.NewRufusSigner(
			viper.GetString("trust_service.hostname"),
			viper.GetString("trust_service.port"),
			viper.GetString("trust_service.tls_ca_file"),
		)
	} else {
		logrus.Info("[Notary Server] : Using local signing service")
		trust = signed.NewEd25519()
	}

	if viper.GetString("store.backend") == "mysql" {
		dbURL := viper.GetString("storage.db_url")
		db, err := sql.Open("mysql", dbURL)
		if err != nil {
			logrus.Fatal("[Notary Server] Error starting DB driver: ", err.Error())
			return // not strictly needed but let's be explicit
		}
		ctx = context.WithValue(ctx, "metaStore", storage.NewMySQLStorage(db))
	} else {
		ctx = context.WithValue(ctx, "metaStore", storage.NewMemStorage())
	}
	logrus.Info("[Notary Server] Starting Server")
	err = server.Run(
		ctx,
		viper.GetString("server.addr"),
		viper.GetString("server.tls_cert_file"),
		viper.GetString("server.tls_key_file"),
		trust,
	)

	logrus.Error("[Notary Server]", err.Error())
	return
}
Пример #16
0
func main() {
	flag.Usage = usage
	flag.Parse()

	if DebugAddress != "" {
		go debugServer(DebugAddress)
	}

	ctx := context.Background()

	conf, err := parseConfig(configFile)
	if err != nil {
		logrus.Fatal("Error parsing config: ", err.Error())
		return // not strictly needed but let's be explicit
	}
	if conf.Logging.Level > 0 {
		logrus.SetLevel(logrus.Level(conf.Logging.Level))
	}

	sigHup := make(chan os.Signal)
	sigTerm := make(chan os.Signal)

	signal.Notify(sigHup, syscall.SIGHUP)
	signal.Notify(sigTerm, syscall.SIGTERM)

	var trust signed.CryptoService
	if conf.TrustService.Type == "remote" {
		logrus.Info("[Notary Server] : Using remote signing service")
		trust = signer.NewRufusSigner(conf.TrustService.Hostname, conf.TrustService.Port, conf.TrustService.TLSCAFile)
	} else {
		logrus.Info("[Notary Server] : Using local signing service")
		trust = signed.NewEd25519()
	}

	db, err := sql.Open("mysql", "dockercondemo:dockercondemo@tcp(notarymysql:3306)/dockercondemo")
	if err != nil {
		logrus.Fatal("Error starting DB driver: ", err.Error())
		return // not strictly needed but let's be explicit
	}
	ctx = context.WithValue(ctx, "versionStore", storage.NewMySQLStorage(db))
	for {
		logrus.Info("[Notary Server] Starting Server")
		childCtx, cancel := context.WithCancel(ctx)
		go server.Run(childCtx, conf.Server, trust)

		for {
			select {
			// On a sighup we cancel and restart a new server
			// with updated config
			case <-sigHup:
				logrus.Infof("[Notary Server] Server restart requested. Attempting to parse config at %s", configFile)
				conf, err = parseConfig(configFile)
				if err != nil {
					logrus.Infof("[Notary Server] Unable to parse config. Old configuration will keep running. Parse Err: %s", err.Error())
					continue
				} else {
					cancel()
					logrus.Info("[Notary Server] Stopping server for restart")
					break
				}
			// On sigkill we cancel and shutdown
			case <-sigTerm:
				cancel()
				logrus.Info("[Notary Server] Shutting Down Hard")
				os.Exit(0)
			}
		}
	}
}
Пример #17
0
func main() {
	flag.Usage = usage
	flag.Parse()

	if debug {
		go debugServer(DebugAddress)
	}

	// when the server starts print the version for debugging and issue logs later
	logrus.Infof("Version: %s, Git commit: %s", version.NotaryVersion, version.GitCommit)

	ctx := context.Background()

	filename := filepath.Base(configFile)
	ext := filepath.Ext(configFile)
	configPath := filepath.Dir(configFile)

	viper.SetConfigType(strings.TrimPrefix(ext, "."))
	viper.SetConfigName(strings.TrimSuffix(filename, ext))
	viper.AddConfigPath(configPath)

	// Automatically accept configuration options from the environment
	viper.SetEnvPrefix("NOTARY_SERVER")
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	viper.AutomaticEnv()

	err := viper.ReadInConfig()
	if err != nil {
		logrus.Error("Viper Error: ", err.Error())
		logrus.Error("Could not read config at ", configFile)
		os.Exit(1)
	}
	lvl, err := logrus.ParseLevel(viper.GetString("logging.level"))
	if err != nil {
		lvl = logrus.ErrorLevel
		logrus.Error("Could not parse log level from config. Defaulting to ErrorLevel")
	}
	logrus.SetLevel(lvl)

	// set up bugsnag and attach to logrus
	bugs := viper.GetString("reporting.bugsnag")
	if bugs != "" {
		apiKey := viper.GetString("reporting.bugsnag_api_key")
		releaseStage := viper.GetString("reporting.bugsnag_release_stage")
		bugsnag.Configure(bugsnag.Configuration{
			APIKey:       apiKey,
			ReleaseStage: releaseStage,
		})
		hook, err := bugsnag_hook.NewBugsnagHook()
		if err != nil {
			logrus.Error("Could not attach bugsnag to logrus: ", err.Error())
		} else {
			logrus.AddHook(hook)
		}
	}
	keyAlgo := viper.GetString("trust_service.key_algorithm")
	if keyAlgo == "" {
		logrus.Fatal("no key algorithm configured.")
		os.Exit(1)
	}
	ctx = context.WithValue(ctx, "keyAlgorithm", keyAlgo)

	var trust signed.CryptoService
	if viper.GetString("trust_service.type") == "remote" {
		logrus.Info("Using remote signing service")
		trust = signer.NewNotarySigner(
			viper.GetString("trust_service.hostname"),
			viper.GetString("trust_service.port"),
			viper.GetString("trust_service.tls_ca_file"),
		)
	} else {
		logrus.Info("Using local signing service")
		trust = signed.NewEd25519()
	}

	if viper.GetString("storage.backend") == "mysql" {
		logrus.Info("Using mysql backend")
		dbURL := viper.GetString("storage.db_url")
		db, err := sql.Open("mysql", dbURL)
		if err != nil {
			logrus.Fatal("Error starting DB driver: ", err.Error())
			return // not strictly needed but let's be explicit
		}
		ctx = context.WithValue(ctx, "metaStore", storage.NewMySQLStorage(db))
	} else {
		logrus.Debug("Using memory backend")
		ctx = context.WithValue(ctx, "metaStore", storage.NewMemStorage())
	}
	logrus.Info("Starting Server")
	err = server.Run(
		ctx,
		viper.GetString("server.addr"),
		viper.GetString("server.tls_cert_file"),
		viper.GetString("server.tls_key_file"),
		trust,
		viper.GetString("auth.type"),
		viper.Get("auth.options"),
	)

	logrus.Error(err.Error())
	return
}