1package data 2 3import ( 4 "crypto" 5 "crypto/ecdsa" 6 "crypto/rsa" 7 "crypto/sha256" 8 "crypto/x509" 9 "encoding/asn1" 10 "encoding/hex" 11 "errors" 12 "io" 13 "math/big" 14 15 "github.com/agl/ed25519" 16 "github.com/docker/go/canonical/json" 17 "github.com/sirupsen/logrus" 18) 19 20// PublicKey is the necessary interface for public keys 21type PublicKey interface { 22 ID() string 23 Algorithm() string 24 Public() []byte 25} 26 27// PrivateKey adds the ability to access the private key 28type PrivateKey interface { 29 PublicKey 30 Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) 31 Private() []byte 32 CryptoSigner() crypto.Signer 33 SignatureAlgorithm() SigAlgorithm 34} 35 36// KeyPair holds the public and private key bytes 37type KeyPair struct { 38 Public []byte `json:"public"` 39 Private []byte `json:"private"` 40} 41 42// Keys represents a map of key ID to PublicKey object. It's necessary 43// to allow us to unmarshal into an interface via the json.Unmarshaller 44// interface 45type Keys map[string]PublicKey 46 47// UnmarshalJSON implements the json.Unmarshaller interface 48func (ks *Keys) UnmarshalJSON(data []byte) error { 49 parsed := make(map[string]TUFKey) 50 err := json.Unmarshal(data, &parsed) 51 if err != nil { 52 return err 53 } 54 final := make(map[string]PublicKey) 55 for k, tk := range parsed { 56 final[k] = typedPublicKey(tk) 57 } 58 *ks = final 59 return nil 60} 61 62// KeyList represents a list of keys 63type KeyList []PublicKey 64 65// UnmarshalJSON implements the json.Unmarshaller interface 66func (ks *KeyList) UnmarshalJSON(data []byte) error { 67 parsed := make([]TUFKey, 0, 1) 68 err := json.Unmarshal(data, &parsed) 69 if err != nil { 70 return err 71 } 72 final := make([]PublicKey, 0, len(parsed)) 73 for _, tk := range parsed { 74 final = append(final, typedPublicKey(tk)) 75 } 76 *ks = final 77 return nil 78} 79 80// IDs generates a list of the hex encoded key IDs in the KeyList 81func (ks KeyList) IDs() []string { 82 keyIDs := make([]string, 0, len(ks)) 83 for _, k := range ks { 84 keyIDs = append(keyIDs, k.ID()) 85 } 86 return keyIDs 87} 88 89func typedPublicKey(tk TUFKey) PublicKey { 90 switch tk.Algorithm() { 91 case ECDSAKey: 92 return &ECDSAPublicKey{TUFKey: tk} 93 case ECDSAx509Key: 94 return &ECDSAx509PublicKey{TUFKey: tk} 95 case RSAKey: 96 return &RSAPublicKey{TUFKey: tk} 97 case RSAx509Key: 98 return &RSAx509PublicKey{TUFKey: tk} 99 case ED25519Key: 100 return &ED25519PublicKey{TUFKey: tk} 101 } 102 return &UnknownPublicKey{TUFKey: tk} 103} 104 105func typedPrivateKey(tk TUFKey) (PrivateKey, error) { 106 private := tk.Value.Private 107 tk.Value.Private = nil 108 switch tk.Algorithm() { 109 case ECDSAKey: 110 return NewECDSAPrivateKey( 111 &ECDSAPublicKey{ 112 TUFKey: tk, 113 }, 114 private, 115 ) 116 case ECDSAx509Key: 117 return NewECDSAPrivateKey( 118 &ECDSAx509PublicKey{ 119 TUFKey: tk, 120 }, 121 private, 122 ) 123 case RSAKey: 124 return NewRSAPrivateKey( 125 &RSAPublicKey{ 126 TUFKey: tk, 127 }, 128 private, 129 ) 130 case RSAx509Key: 131 return NewRSAPrivateKey( 132 &RSAx509PublicKey{ 133 TUFKey: tk, 134 }, 135 private, 136 ) 137 case ED25519Key: 138 return NewED25519PrivateKey( 139 ED25519PublicKey{ 140 TUFKey: tk, 141 }, 142 private, 143 ) 144 } 145 return &UnknownPrivateKey{ 146 TUFKey: tk, 147 privateKey: privateKey{private: private}, 148 }, nil 149} 150 151// NewPublicKey creates a new, correctly typed PublicKey, using the 152// UnknownPublicKey catchall for unsupported ciphers 153func NewPublicKey(alg string, public []byte) PublicKey { 154 tk := TUFKey{ 155 Type: alg, 156 Value: KeyPair{ 157 Public: public, 158 }, 159 } 160 return typedPublicKey(tk) 161} 162 163// NewPrivateKey creates a new, correctly typed PrivateKey, using the 164// UnknownPrivateKey catchall for unsupported ciphers 165func NewPrivateKey(pubKey PublicKey, private []byte) (PrivateKey, error) { 166 tk := TUFKey{ 167 Type: pubKey.Algorithm(), 168 Value: KeyPair{ 169 Public: pubKey.Public(), 170 Private: private, // typedPrivateKey moves this value 171 }, 172 } 173 return typedPrivateKey(tk) 174} 175 176// UnmarshalPublicKey is used to parse individual public keys in JSON 177func UnmarshalPublicKey(data []byte) (PublicKey, error) { 178 var parsed TUFKey 179 err := json.Unmarshal(data, &parsed) 180 if err != nil { 181 return nil, err 182 } 183 return typedPublicKey(parsed), nil 184} 185 186// UnmarshalPrivateKey is used to parse individual private keys in JSON 187func UnmarshalPrivateKey(data []byte) (PrivateKey, error) { 188 var parsed TUFKey 189 err := json.Unmarshal(data, &parsed) 190 if err != nil { 191 return nil, err 192 } 193 return typedPrivateKey(parsed) 194} 195 196// TUFKey is the structure used for both public and private keys in TUF. 197// Normally it would make sense to use a different structures for public and 198// private keys, but that would change the key ID algorithm (since the canonical 199// JSON would be different). This structure should normally be accessed through 200// the PublicKey or PrivateKey interfaces. 201type TUFKey struct { 202 id string 203 Type string `json:"keytype"` 204 Value KeyPair `json:"keyval"` 205} 206 207// Algorithm returns the algorithm of the key 208func (k TUFKey) Algorithm() string { 209 return k.Type 210} 211 212// ID efficiently generates if necessary, and caches the ID of the key 213func (k *TUFKey) ID() string { 214 if k.id == "" { 215 pubK := TUFKey{ 216 Type: k.Algorithm(), 217 Value: KeyPair{ 218 Public: k.Public(), 219 Private: nil, 220 }, 221 } 222 data, err := json.MarshalCanonical(&pubK) 223 if err != nil { 224 logrus.Error("Error generating key ID:", err) 225 } 226 digest := sha256.Sum256(data) 227 k.id = hex.EncodeToString(digest[:]) 228 } 229 return k.id 230} 231 232// Public returns the public bytes 233func (k TUFKey) Public() []byte { 234 return k.Value.Public 235} 236 237// Public key types 238 239// ECDSAPublicKey represents an ECDSA key using a raw serialization 240// of the public key 241type ECDSAPublicKey struct { 242 TUFKey 243} 244 245// ECDSAx509PublicKey represents an ECDSA key using an x509 cert 246// as the serialized format of the public key 247type ECDSAx509PublicKey struct { 248 TUFKey 249} 250 251// RSAPublicKey represents an RSA key using a raw serialization 252// of the public key 253type RSAPublicKey struct { 254 TUFKey 255} 256 257// RSAx509PublicKey represents an RSA key using an x509 cert 258// as the serialized format of the public key 259type RSAx509PublicKey struct { 260 TUFKey 261} 262 263// ED25519PublicKey represents an ED25519 key using a raw serialization 264// of the public key 265type ED25519PublicKey struct { 266 TUFKey 267} 268 269// UnknownPublicKey is a catchall for key types that are not supported 270type UnknownPublicKey struct { 271 TUFKey 272} 273 274// NewECDSAPublicKey initializes a new public key with the ECDSAKey type 275func NewECDSAPublicKey(public []byte) *ECDSAPublicKey { 276 return &ECDSAPublicKey{ 277 TUFKey: TUFKey{ 278 Type: ECDSAKey, 279 Value: KeyPair{ 280 Public: public, 281 Private: nil, 282 }, 283 }, 284 } 285} 286 287// NewECDSAx509PublicKey initializes a new public key with the ECDSAx509Key type 288func NewECDSAx509PublicKey(public []byte) *ECDSAx509PublicKey { 289 return &ECDSAx509PublicKey{ 290 TUFKey: TUFKey{ 291 Type: ECDSAx509Key, 292 Value: KeyPair{ 293 Public: public, 294 Private: nil, 295 }, 296 }, 297 } 298} 299 300// NewRSAPublicKey initializes a new public key with the RSA type 301func NewRSAPublicKey(public []byte) *RSAPublicKey { 302 return &RSAPublicKey{ 303 TUFKey: TUFKey{ 304 Type: RSAKey, 305 Value: KeyPair{ 306 Public: public, 307 Private: nil, 308 }, 309 }, 310 } 311} 312 313// NewRSAx509PublicKey initializes a new public key with the RSAx509Key type 314func NewRSAx509PublicKey(public []byte) *RSAx509PublicKey { 315 return &RSAx509PublicKey{ 316 TUFKey: TUFKey{ 317 Type: RSAx509Key, 318 Value: KeyPair{ 319 Public: public, 320 Private: nil, 321 }, 322 }, 323 } 324} 325 326// NewED25519PublicKey initializes a new public key with the ED25519Key type 327func NewED25519PublicKey(public []byte) *ED25519PublicKey { 328 return &ED25519PublicKey{ 329 TUFKey: TUFKey{ 330 Type: ED25519Key, 331 Value: KeyPair{ 332 Public: public, 333 Private: nil, 334 }, 335 }, 336 } 337} 338 339// Private key types 340type privateKey struct { 341 private []byte 342} 343 344type signer struct { 345 signer crypto.Signer 346} 347 348// ECDSAPrivateKey represents a private ECDSA key 349type ECDSAPrivateKey struct { 350 PublicKey 351 privateKey 352 signer 353} 354 355// RSAPrivateKey represents a private RSA key 356type RSAPrivateKey struct { 357 PublicKey 358 privateKey 359 signer 360} 361 362// ED25519PrivateKey represents a private ED25519 key 363type ED25519PrivateKey struct { 364 ED25519PublicKey 365 privateKey 366} 367 368// UnknownPrivateKey is a catchall for unsupported key types 369type UnknownPrivateKey struct { 370 TUFKey 371 privateKey 372} 373 374// NewECDSAPrivateKey initializes a new ECDSA private key 375func NewECDSAPrivateKey(public PublicKey, private []byte) (*ECDSAPrivateKey, error) { 376 switch public.(type) { 377 case *ECDSAPublicKey, *ECDSAx509PublicKey: 378 default: 379 return nil, errors.New("invalid public key type provided to NewECDSAPrivateKey") 380 } 381 ecdsaPrivKey, err := x509.ParseECPrivateKey(private) 382 if err != nil { 383 return nil, err 384 } 385 return &ECDSAPrivateKey{ 386 PublicKey: public, 387 privateKey: privateKey{private: private}, 388 signer: signer{signer: ecdsaPrivKey}, 389 }, nil 390} 391 392// NewRSAPrivateKey initialized a new RSA private key 393func NewRSAPrivateKey(public PublicKey, private []byte) (*RSAPrivateKey, error) { 394 switch public.(type) { 395 case *RSAPublicKey, *RSAx509PublicKey: 396 default: 397 return nil, errors.New("invalid public key type provided to NewRSAPrivateKey") 398 } 399 rsaPrivKey, err := x509.ParsePKCS1PrivateKey(private) 400 if err != nil { 401 return nil, err 402 } 403 return &RSAPrivateKey{ 404 PublicKey: public, 405 privateKey: privateKey{private: private}, 406 signer: signer{signer: rsaPrivKey}, 407 }, nil 408} 409 410// NewED25519PrivateKey initialized a new ED25519 private key 411func NewED25519PrivateKey(public ED25519PublicKey, private []byte) (*ED25519PrivateKey, error) { 412 return &ED25519PrivateKey{ 413 ED25519PublicKey: public, 414 privateKey: privateKey{private: private}, 415 }, nil 416} 417 418// Private return the serialized private bytes of the key 419func (k privateKey) Private() []byte { 420 return k.private 421} 422 423// CryptoSigner returns the underlying crypto.Signer for use cases where we need the default 424// signature or public key functionality (like when we generate certificates) 425func (s signer) CryptoSigner() crypto.Signer { 426 return s.signer 427} 428 429// CryptoSigner returns the ED25519PrivateKey which already implements crypto.Signer 430func (k ED25519PrivateKey) CryptoSigner() crypto.Signer { 431 return nil 432} 433 434// CryptoSigner returns the UnknownPrivateKey which already implements crypto.Signer 435func (k UnknownPrivateKey) CryptoSigner() crypto.Signer { 436 return nil 437} 438 439type ecdsaSig struct { 440 R *big.Int 441 S *big.Int 442} 443 444// Sign creates an ecdsa signature 445func (k ECDSAPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) { 446 ecdsaPrivKey, ok := k.CryptoSigner().(*ecdsa.PrivateKey) 447 if !ok { 448 return nil, errors.New("signer was based on the wrong key type") 449 } 450 hashed := sha256.Sum256(msg) 451 sigASN1, err := ecdsaPrivKey.Sign(rand, hashed[:], opts) 452 if err != nil { 453 return nil, err 454 } 455 456 sig := ecdsaSig{} 457 _, err = asn1.Unmarshal(sigASN1, &sig) 458 if err != nil { 459 return nil, err 460 } 461 rBytes, sBytes := sig.R.Bytes(), sig.S.Bytes() 462 octetLength := (ecdsaPrivKey.Params().BitSize + 7) >> 3 463 464 // MUST include leading zeros in the output 465 rBuf := make([]byte, octetLength-len(rBytes), octetLength) 466 sBuf := make([]byte, octetLength-len(sBytes), octetLength) 467 468 rBuf = append(rBuf, rBytes...) 469 sBuf = append(sBuf, sBytes...) 470 return append(rBuf, sBuf...), nil 471} 472 473// Sign creates an rsa signature 474func (k RSAPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) { 475 hashed := sha256.Sum256(msg) 476 if opts == nil { 477 opts = &rsa.PSSOptions{ 478 SaltLength: rsa.PSSSaltLengthEqualsHash, 479 Hash: crypto.SHA256, 480 } 481 } 482 return k.CryptoSigner().Sign(rand, hashed[:], opts) 483} 484 485// Sign creates an ed25519 signature 486func (k ED25519PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) { 487 priv := [ed25519.PrivateKeySize]byte{} 488 copy(priv[:], k.private[ed25519.PublicKeySize:]) 489 return ed25519.Sign(&priv, msg)[:], nil 490} 491 492// Sign on an UnknownPrivateKey raises an error because the client does not 493// know how to sign with this key type. 494func (k UnknownPrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) (signature []byte, err error) { 495 return nil, errors.New("unknown key type, cannot sign") 496} 497 498// SignatureAlgorithm returns the SigAlgorithm for a ECDSAPrivateKey 499func (k ECDSAPrivateKey) SignatureAlgorithm() SigAlgorithm { 500 return ECDSASignature 501} 502 503// SignatureAlgorithm returns the SigAlgorithm for a RSAPrivateKey 504func (k RSAPrivateKey) SignatureAlgorithm() SigAlgorithm { 505 return RSAPSSSignature 506} 507 508// SignatureAlgorithm returns the SigAlgorithm for a ED25519PrivateKey 509func (k ED25519PrivateKey) SignatureAlgorithm() SigAlgorithm { 510 return EDDSASignature 511} 512 513// SignatureAlgorithm returns the SigAlgorithm for an UnknownPrivateKey 514func (k UnknownPrivateKey) SignatureAlgorithm() SigAlgorithm { 515 return "" 516} 517 518// PublicKeyFromPrivate returns a new TUFKey based on a private key, with 519// the private key bytes guaranteed to be nil. 520func PublicKeyFromPrivate(pk PrivateKey) PublicKey { 521 return typedPublicKey(TUFKey{ 522 Type: pk.Algorithm(), 523 Value: KeyPair{ 524 Public: pk.Public(), 525 Private: nil, 526 }, 527 }) 528} 529