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 #821

Closed
wants to merge 4 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
41 changes: 41 additions & 0 deletions client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2017,6 +2017,47 @@ func TestPublishSnapshotLocalKeysCreatedFirst(t *testing.T) {
require.False(t, requestMade)
}

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, "")
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, "")
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
76 changes: 75 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 All @@ -27,6 +30,10 @@ import (
)

var cmdTUFListTemplate = usageTemplate{

var remoteTrustServer string

var cmdTufList = &cobra.Command{
Use: "list [ GUN ]",
Short: "Lists targets for a remote trusted collection.",
Long: "Lists all targets for a remote trusted collection identified by the Globally Unique Name. This is an online operation.",
Expand Down Expand Up @@ -90,13 +97,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 +260,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 +286,62 @@ func (t *tufCommander) tufInit(cmd *cobra.Command, args []string) error {
return err
}

// Handle a root key passed in the command-line
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 t.rootCert == "" {
// A root key was specified on the command-line, but no root cert
// We therefore ask the repo to generate a root cert
if err = nRepo.Initialize(privKey.ID()); err != nil {
return err
}
} else {
// A root keypair (private key + cert) was specified on the
// command-line.
// Read the user-specified root cert from the filesystem
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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than having to sign and verify, I think we should be able to verify that the keys match via the data.PrivateKey.Public() function (or by comparing the modulus of the public key on the cert)

Copy link
Author

@dnwake dnwake Jul 8, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@riyazdf I tried this and it didn't seem to work. Do you have a suggested code sample?

Copy link
Contributor

@riyazdf riyazdf Jul 8, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dnwake I don't have one on-hand -- are you getting an empty public key back? What did you try using?

I've gotten something working but I had to use reflect.DeepEqual instead of a simple == because of how golang treats public keys as interface{} -- that might be what you ran into as well

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hi there the data.PrivateKey.Public() returns a possibly encrypted byte slice, an example translated to string would be 0Y0*�H�*�H�=BM��j�����:�;&�4�����Z�n��� ո�+�C����؋�n���f.�^��>, any idea how I might go about decrypting it?

// 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)
}