Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Import key and cert #820

Closed
wants to merge 2 commits into from
Closed
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
45 changes: 39 additions & 6 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,38 @@ func rootCertKey(gun string, privKey data.PrivateKey) (data.PublicKey, error) {
return x509PublicKey, nil
}

// Initialize creates a new repository by using rootKey as the root Key for the
// Initialize creates a new repository by using rootKeyID to identify the root Key for the
// TUF repository. The server must be reachable (and is asked to generate a
// timestamp key and possibly other serverManagedRoles), but the created repository
// result is only stored on local disk, not published to the server. To do that,
// use r.Publish() eventually.
func (r *NotaryRepository) Initialize(rootKeyID string, serverManagedRoles ...string) error {
privKey, _, err := r.CryptoService.GetPrivateKey(rootKeyID)
return r.InitializeWithPubKey(rootKeyID, (data.PublicKey)(nil), serverManagedRoles...)
}

// KeyPairVerifier is used to verify that a private key and public key form a matching keypair
type KeyPairVerifier func(privKey data.PrivateKey, pubKey data.PublicKey) error

func defaultKeyPairVerifier() KeyPairVerifier {
return signed.VerifyPublicKeyMatchesPrivateKey
}

// InitializeWithPubKey creates a new repository by using rootPrivKeyID to identify the root private key for the
// TUF repository.
// If rootPubKey is non-nil, it must form a valid keypair together with the private key identified by rootPrivKeyID,
// otherwise an error is thrown. The repository is then initialized with the given root keypair.
// If rootPubKey is nil, then the root public key is generated automatically.
// The server must be reachable (and is asked to generate a
// timestamp key and possibly other serverManagedRoles), but the created repository
// result is only stored on local disk, not published to the server. To do that,
// use r.Publish() eventually.
func (r *NotaryRepository) InitializeWithPubKey(rootPrivKeyID string, rootPubKey data.PublicKey, serverManagedRoles ...string) error {
return r.InitializeWithPubKeyAndVerifier(rootPrivKeyID, rootPubKey, defaultKeyPairVerifier(), serverManagedRoles...)
}

// InitializeWithPubKeyAndVerifier allows the keyPairVerifier to be overridden for testing
func (r *NotaryRepository) InitializeWithPubKeyAndVerifier(rootPrivKeyID string, rootPubKey data.PublicKey, keyPairVerifier KeyPairVerifier, serverManagedRoles ...string) error {
rootPrivKey, _, err := r.CryptoService.GetPrivateKey(rootPrivKeyID)
if err != nil {
return err
}
Expand Down Expand Up @@ -206,16 +231,24 @@ func (r *NotaryRepository) Initialize(rootKeyID string, serverManagedRoles ...st
}
}

rootKey, err := rootCertKey(r.gun, privKey)
if err != nil {
return err
if rootPubKey == nil {
logrus.Debug("No root public key specified; generating a new one.")
rootPubKey, err = rootCertKey(r.gun, rootPrivKey)
if err != nil {
return err
}
} else {
logrus.Debugf("Verifying user-specified root public key: %s", rootPubKey.ID())
if err := keyPairVerifier(rootPrivKey, rootPubKey); err != nil {
return err
}
}

var (
rootRole = data.NewBaseRole(
data.CanonicalRootRole,
notary.MinThreshold,
rootKey,
rootPubKey,
)
timestampRole data.BaseRole
snapshotRole data.BaseRole
Expand Down
43 changes: 43 additions & 0 deletions client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2017,6 +2017,49 @@ func TestPublishSnapshotLocalKeysCreatedFirst(t *testing.T) {
require.False(t, requestMade)
}

// If there is an error creating the local keys, no call is made to get a
// remote key.
func TestInitializeWithPublicKeyVerifiesKeypairAndFailsIfKeysDontMatch(t *testing.T) {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("/tmp", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
defer os.RemoveAll(tempBaseDir)

repo, rec, privKeyID := createRepoAndKey(
t, data.ECDSAKey, tempBaseDir, "docker.com/notary", "http://localhost")
require.NotNil(t, rec, "Fuck off")
rootPubKey := repo.CryptoService.GetKey(privKeyID)
require.NotNil(t, rootPubKey, "Couldn't get the root public key")

keyPairVerifierFail := func(privKey data.PrivateKey, pubKey data.PublicKey) error {
return fmt.Errorf("Private key %s does not match public key %s", privKey.ID(), pubKey.ID())
}
err = repo.InitializeWithPubKeyAndVerifier(privKeyID, rootPubKey, keyPairVerifierFail, data.CanonicalSnapshotRole)
require.Error(t, err)
require.Equal(t, err.Error(), fmt.Sprintf("Private key %s does not match public key %s", privKeyID, rootPubKey.ID()))
}

func TestInitializeWithPublicKeyVerifiesKeypairAndSucceedsIfKeysMatch(t *testing.T) {
// Temporary directory where test files will be created
tempBaseDir, err := ioutil.TempDir("/tmp", "notary-test-")
require.NoError(t, err, "failed to create a temporary directory")
defer os.RemoveAll(tempBaseDir)

ts, _, _ := simpleTestServer(t)
defer ts.Close()

repo, rec, privKeyID := createRepoAndKey(
t, data.ECDSAKey, tempBaseDir, "docker.com/notary", ts.URL)
require.NotNil(t, rec, "Fuck off")
rootPubKey := repo.CryptoService.GetKey(privKeyID)
require.NotNil(t, rootPubKey, "Couldn't get the root public key")

keyPairVerifierSucceed := func(privKey data.PrivateKey, pubKey data.PublicKey) error { return nil }
err = repo.InitializeWithPubKeyAndVerifier(privKeyID, rootPubKey, keyPairVerifierSucceed, data.CanonicalSnapshotRole)
require.NoError(t, err)
require.Equal(t, rootPubKey.Public(), repo.tufRepo.Root.Signed.Keys[rootPubKey.ID()].Public())
}

func createKey(t *testing.T, repo *NotaryRepository, role string, x509 bool) data.PublicKey {
key, err := repo.CryptoService.Create(role, repo.gun, data.ECDSAKey)
require.NoError(t, err, "error creating key")
Expand Down
70 changes: 69 additions & 1 deletion cmd/notary/tuf.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"encoding/hex"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
Expand All @@ -19,6 +20,8 @@ import (
"github.com/docker/go-connections/tlsconfig"
"github.com/docker/notary"
notaryclient "github.com/docker/notary/client"
"github.com/docker/notary/cryptoservice"
"github.com/docker/notary/trustmanager"
"github.com/docker/notary/trustpinning"
"github.com/docker/notary/tuf/data"
"github.com/docker/notary/utils"
Expand Down Expand Up @@ -90,13 +93,20 @@ type tufCommander struct {
sha256 string
sha512 string

rootCert string
rootKey string

input string
output string
quiet bool
}

func (t *tufCommander) AddToCommand(cmd *cobra.Command) {
cmd.AddCommand(cmdTUFInitTemplate.ToCommand(t.tufInit))
cmdTUFInit := cmdTUFInitTemplate.ToCommand(t.tufInit)
cmdTUFInit.Flags().StringVar(&t.rootCert, "rootcert", "", "Root cert to initialize the repository with. Must correspond to the private key specified in --rootkey")
cmdTUFInit.Flags().StringVar(&t.rootKey, "rootkey", "", "Root key to initialize the repository with.")
cmd.AddCommand(cmdTUFInit)

cmd.AddCommand(cmdTUFStatusTemplate.ToCommand(t.tufStatus))
cmd.AddCommand(cmdTUFPublishTemplate.ToCommand(t.tufPublish))
cmd.AddCommand(cmdTUFLookupTemplate.ToCommand(t.tufLookup))
Expand Down Expand Up @@ -246,6 +256,10 @@ func (t *tufCommander) tufInit(cmd *cobra.Command, args []string) error {
return fmt.Errorf("Must specify a GUN")
}

if t.rootCert != "" && t.rootKey == "" {
return fmt.Errorf("--rootCert specified without --rootKey being specified")
}

config, err := t.configGetter()
if err != nil {
return err
Expand All @@ -268,6 +282,60 @@ func (t *tufCommander) tufInit(cmd *cobra.Command, args []string) error {
return err
}

if t.rootKey != "" {
keyFile, err := os.Open(t.rootKey)
if err != nil {
return fmt.Errorf("Opening file for import: %v", err)
}
defer keyFile.Close()

pemBytes, err := ioutil.ReadAll(keyFile)
if err != nil {
return fmt.Errorf("Error reading input file: %v", err)
}
if err = cryptoservice.CheckRootKeyIsEncrypted(pemBytes); err != nil {
return err
}

privKey, err := trustmanager.ParsePEMPrivateKey(pemBytes, "")
if err != nil {
privKey, _, err = trustmanager.GetPasswdDecryptBytes(t.retriever, pemBytes, "", "imported root")
if err != nil {
return err
}
}
err = nRepo.CryptoService.AddKey(data.CanonicalRootRole, "", privKey)
if err != nil {
return fmt.Errorf("Error importing key: %v", err)
}

// if a key was explicitly passed in, we assume it should be added
// to the root role
if t.rootCert == "" {
if err = nRepo.Initialize(privKey.ID()); err != nil {
return err
}
} else {
// Load the user-specified root cert and initialize the repo with the cert and private key
// Read public key bytes from PEM file
pubKeyBytes, err := ioutil.ReadFile(t.rootCert)
if err != nil {
return fmt.Errorf("unable to read public key from file: %s", t.rootCert)
}

// Parse PEM bytes into type PublicKey
pubKey, err := trustmanager.ParsePEMPublicKey(pubKeyBytes)
if err != nil {
return fmt.Errorf("unable to parse valid public key certificate from PEM file %s: %v", t.rootCert, err)
}

if err = nRepo.InitializeWithPubKey(privKey.ID(), pubKey); err != nil {
return err
}
}
return nil
}

rootKeyList := nRepo.CryptoService.ListKeys(data.CanonicalRootRole)

var rootKeyID string
Expand Down
29 changes: 29 additions & 0 deletions tuf/signed/verify.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package signed

import (
"crypto/rand"
"errors"
"fmt"
"strings"
Expand Down Expand Up @@ -105,3 +106,31 @@ func VerifySignature(msg []byte, sig data.Signature, pk data.PublicKey) error {
}
return nil
}

// VerifyPublicKeyMatchesPrivateKey checks that the specified private key and public key together form a valid keypair.
func VerifyPublicKeyMatchesPrivateKey(privKey data.PrivateKey, pubKey data.PublicKey) error {
// generate a random message
msgLength := 64
msg := make([]byte, msgLength)
_, err := rand.Read(msg)
if err != nil {
return fmt.Errorf("failed to generate random test message: %s", err)
}

// sign the message with the private key
signatureBytes, err := privKey.Sign(rand.Reader, msg, nil)
if err != nil {
return fmt.Errorf("Failed to sign test message:", err)
}

verifier, ok := Verifiers[privKey.SignatureAlgorithm()]
if !ok {
return fmt.Errorf("signing method is not supported: %s\n", privKey.SignatureAlgorithm())
}

if err := verifier.Verify(pubKey, signatureBytes, msg); err != nil {
return fmt.Errorf("Private Key did not match Public Key: %s", err)
}

return nil
}
19 changes: 19 additions & 0 deletions tuf/signed/verify_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package signed

import (
"crypto/rand"
"testing"
"time"

"github.com/docker/go/canonical/json"
"github.com/docker/notary"
"github.com/docker/notary/trustmanager"
"github.com/stretchr/testify/require"

"github.com/docker/notary/tuf/data"
Expand Down Expand Up @@ -173,3 +175,20 @@ func TestVerifyExpiry(t *testing.T) {
require.Error(t, err)
require.IsType(t, ErrExpired{}, err)
}

func TestVerifyPublicKeyMatchesPrivateKeyHappyCase(t *testing.T) {
privKey, err := trustmanager.GenerateECDSAKey(rand.Reader)
require.NoError(t, err)
pubKey := data.PublicKeyFromPrivate(privKey)
err = VerifyPublicKeyMatchesPrivateKey(privKey, pubKey)
require.NoError(t, err)
}

func TestVerifyPublicKeyMatchesPrivateKeyFails(t *testing.T) {
goodPrivKey, err := trustmanager.GenerateECDSAKey(rand.Reader)
badPrivKey, err := trustmanager.GenerateECDSAKey(rand.Reader)
require.NoError(t, err)
badPubKey := data.PublicKeyFromPrivate(badPrivKey)
err = VerifyPublicKeyMatchesPrivateKey(goodPrivKey, badPubKey)
require.Error(t, err)
}