github.com/olivere/camlistore@v0.0.0-20140121221811-1b7ac2da0199/third_party/code.google.com/p/go.crypto/openpgp/keys.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package openpgp 6 7 import ( 8 "camlistore.org/third_party/code.google.com/p/go.crypto/openpgp/armor" 9 "camlistore.org/third_party/code.google.com/p/go.crypto/openpgp/errors" 10 "camlistore.org/third_party/code.google.com/p/go.crypto/openpgp/packet" 11 "crypto" 12 "crypto/rand" 13 "crypto/rsa" 14 "io" 15 "time" 16 ) 17 18 // PublicKeyType is the armor type for a PGP public key. 19 var PublicKeyType = "PGP PUBLIC KEY BLOCK" 20 21 // PrivateKeyType is the armor type for a PGP private key. 22 var PrivateKeyType = "PGP PRIVATE KEY BLOCK" 23 24 // An Entity represents the components of an OpenPGP key: a primary public key 25 // (which must be a signing key), one or more identities claimed by that key, 26 // and zero or more subkeys, which may be encryption keys. 27 type Entity struct { 28 PrimaryKey *packet.PublicKey 29 PrivateKey *packet.PrivateKey 30 Identities map[string]*Identity // indexed by Identity.Name 31 Subkeys []Subkey 32 33 // Clock optionally specifies an alternate clock function to 34 // use when signing or encrypting using this Entity, instead 35 // of time.Now(). 36 Clock func() time.Time 37 } 38 39 func (e *Entity) timeNow() time.Time { 40 if e.Clock != nil { 41 return e.Clock() 42 } 43 return time.Now() 44 } 45 46 // An Identity represents an identity claimed by an Entity and zero or more 47 // assertions by other entities about that claim. 48 type Identity struct { 49 Name string // by convention, has the form "Full Name (comment) <email@example.com>" 50 UserId *packet.UserId 51 SelfSignature *packet.Signature 52 Signatures []*packet.Signature 53 } 54 55 // A Subkey is an additional public key in an Entity. Subkeys can be used for 56 // encryption. 57 type Subkey struct { 58 PublicKey *packet.PublicKey 59 PrivateKey *packet.PrivateKey 60 Sig *packet.Signature 61 } 62 63 // A Key identifies a specific public key in an Entity. This is either the 64 // Entity's primary key or a subkey. 65 type Key struct { 66 Entity *Entity 67 PublicKey *packet.PublicKey 68 PrivateKey *packet.PrivateKey 69 SelfSignature *packet.Signature 70 } 71 72 // A KeyRing provides access to public and private keys. 73 type KeyRing interface { 74 // KeysById returns the set of keys that have the given key id. 75 KeysById(id uint64) []Key 76 // DecryptionKeys returns all private keys that are valid for 77 // decryption. 78 DecryptionKeys() []Key 79 } 80 81 // primaryIdentity returns the Identity marked as primary or the first identity 82 // if none are so marked. 83 func (e *Entity) primaryIdentity() *Identity { 84 var firstIdentity *Identity 85 for _, ident := range e.Identities { 86 if firstIdentity == nil { 87 firstIdentity = ident 88 } 89 if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId { 90 return ident 91 } 92 } 93 return firstIdentity 94 } 95 96 // encryptionKey returns the best candidate Key for encrypting a message to the 97 // given Entity. 98 func (e *Entity) encryptionKey() Key { 99 candidateSubkey := -1 100 101 for i, subkey := range e.Subkeys { 102 if subkey.Sig.FlagsValid && subkey.Sig.FlagEncryptCommunications && subkey.PublicKey.PubKeyAlgo.CanEncrypt() { 103 candidateSubkey = i 104 break 105 } 106 } 107 108 i := e.primaryIdentity() 109 110 if e.PrimaryKey.PubKeyAlgo.CanEncrypt() { 111 // If we don't have any candidate subkeys for encryption and 112 // the primary key doesn't have any usage metadata then we 113 // assume that the primary key is ok. Or, if the primary key is 114 // marked as ok to encrypt to, then we can obviously use it. 115 if candidateSubkey == -1 && !i.SelfSignature.FlagsValid || i.SelfSignature.FlagEncryptCommunications && i.SelfSignature.FlagsValid { 116 return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature} 117 } 118 } 119 120 if candidateSubkey != -1 { 121 subkey := e.Subkeys[candidateSubkey] 122 return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig} 123 } 124 125 // This Entity appears to be signing only. 126 return Key{} 127 } 128 129 // signingKey return the best candidate Key for signing a message with this 130 // Entity. 131 func (e *Entity) signingKey() Key { 132 candidateSubkey := -1 133 134 for i, subkey := range e.Subkeys { 135 if subkey.Sig.FlagsValid && subkey.Sig.FlagSign && subkey.PublicKey.PubKeyAlgo.CanSign() { 136 candidateSubkey = i 137 break 138 } 139 } 140 141 i := e.primaryIdentity() 142 143 // If we have no candidate subkey then we assume that it's ok to sign 144 // with the primary key. 145 if candidateSubkey == -1 || i.SelfSignature.FlagsValid && i.SelfSignature.FlagSign { 146 return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature} 147 } 148 149 subkey := e.Subkeys[candidateSubkey] 150 return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig} 151 } 152 153 // An EntityList contains one or more Entities. 154 type EntityList []*Entity 155 156 // KeysById returns the set of keys that have the given key id. 157 func (el EntityList) KeysById(id uint64) (keys []Key) { 158 for _, e := range el { 159 if e.PrimaryKey.KeyId == id { 160 var selfSig *packet.Signature 161 for _, ident := range e.Identities { 162 if selfSig == nil { 163 selfSig = ident.SelfSignature 164 } else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId { 165 selfSig = ident.SelfSignature 166 break 167 } 168 } 169 keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig}) 170 } 171 172 for _, subKey := range e.Subkeys { 173 if subKey.PublicKey.KeyId == id { 174 keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig}) 175 } 176 } 177 } 178 return 179 } 180 181 // DecryptionKeys returns all private keys that are valid for decryption. 182 func (el EntityList) DecryptionKeys() (keys []Key) { 183 for _, e := range el { 184 for _, subKey := range e.Subkeys { 185 if subKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) { 186 keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig}) 187 } 188 } 189 } 190 return 191 } 192 193 // ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file. 194 func ReadArmoredKeyRing(r io.Reader) (EntityList, error) { 195 block, err := armor.Decode(r) 196 if err == io.EOF { 197 return nil, errors.InvalidArgumentError("no armored data found") 198 } 199 if err != nil { 200 return nil, err 201 } 202 if block.Type != PublicKeyType && block.Type != PrivateKeyType { 203 return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type) 204 } 205 206 return ReadKeyRing(block.Body) 207 } 208 209 // ReadKeyRing reads one or more public/private keys. Unsupported keys are 210 // ignored as long as at least a single valid key is found. 211 func ReadKeyRing(r io.Reader) (el EntityList, err error) { 212 packets := packet.NewReader(r) 213 var lastUnsupportedError error 214 215 for { 216 var e *Entity 217 e, err = readEntity(packets) 218 if err != nil { 219 if _, ok := err.(errors.UnsupportedError); ok { 220 lastUnsupportedError = err 221 err = readToNextPublicKey(packets) 222 } 223 if err == io.EOF { 224 err = nil 225 break 226 } 227 if err != nil { 228 el = nil 229 break 230 } 231 } else { 232 el = append(el, e) 233 } 234 } 235 236 if len(el) == 0 && err == nil { 237 err = lastUnsupportedError 238 } 239 return 240 } 241 242 // readToNextPublicKey reads packets until the start of the entity and leaves 243 // the first packet of the new entity in the Reader. 244 func readToNextPublicKey(packets *packet.Reader) (err error) { 245 var p packet.Packet 246 for { 247 p, err = packets.Next() 248 if err == io.EOF { 249 return 250 } else if err != nil { 251 if _, ok := err.(errors.UnsupportedError); ok { 252 err = nil 253 continue 254 } 255 return 256 } 257 258 if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey { 259 packets.Unread(p) 260 return 261 } 262 } 263 264 panic("unreachable") 265 } 266 267 // readEntity reads an entity (public key, identities, subkeys etc) from the 268 // given Reader. 269 func readEntity(packets *packet.Reader) (*Entity, error) { 270 e := new(Entity) 271 e.Identities = make(map[string]*Identity) 272 273 p, err := packets.Next() 274 if err != nil { 275 return nil, err 276 } 277 278 var ok bool 279 if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok { 280 if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok { 281 packets.Unread(p) 282 return nil, errors.StructuralError("first packet was not a public/private key") 283 } else { 284 e.PrimaryKey = &e.PrivateKey.PublicKey 285 } 286 } 287 288 if !e.PrimaryKey.PubKeyAlgo.CanSign() { 289 return nil, errors.StructuralError("primary key cannot be used for signatures") 290 } 291 292 var current *Identity 293 EachPacket: 294 for { 295 p, err := packets.Next() 296 if err == io.EOF { 297 break 298 } else if err != nil { 299 return nil, err 300 } 301 302 switch pkt := p.(type) { 303 case *packet.UserId: 304 current = new(Identity) 305 current.Name = pkt.Id 306 current.UserId = pkt 307 e.Identities[pkt.Id] = current 308 309 for { 310 p, err = packets.Next() 311 if err == io.EOF { 312 return nil, io.ErrUnexpectedEOF 313 } else if err != nil { 314 return nil, err 315 } 316 317 sig, ok := p.(*packet.Signature) 318 if !ok { 319 return nil, errors.StructuralError("user ID packet not followed by self-signature") 320 } 321 322 if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId { 323 if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, sig); err != nil { 324 return nil, errors.StructuralError("user ID self-signature invalid: " + err.Error()) 325 } 326 current.SelfSignature = sig 327 break 328 } 329 current.Signatures = append(current.Signatures, sig) 330 } 331 case *packet.Signature: 332 if current == nil { 333 return nil, errors.StructuralError("signature packet found before user id packet") 334 } 335 current.Signatures = append(current.Signatures, pkt) 336 case *packet.PrivateKey: 337 if pkt.IsSubkey == false { 338 packets.Unread(p) 339 break EachPacket 340 } 341 err = addSubkey(e, packets, &pkt.PublicKey, pkt) 342 if err != nil { 343 return nil, err 344 } 345 case *packet.PublicKey: 346 if pkt.IsSubkey == false { 347 packets.Unread(p) 348 break EachPacket 349 } 350 err = addSubkey(e, packets, pkt, nil) 351 if err != nil { 352 return nil, err 353 } 354 default: 355 // we ignore unknown packets 356 } 357 } 358 359 if len(e.Identities) == 0 { 360 return nil, errors.StructuralError("entity without any identities") 361 } 362 363 return e, nil 364 } 365 366 func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error { 367 var subKey Subkey 368 subKey.PublicKey = pub 369 subKey.PrivateKey = priv 370 p, err := packets.Next() 371 if err == io.EOF { 372 return io.ErrUnexpectedEOF 373 } 374 if err != nil { 375 return errors.StructuralError("subkey signature invalid: " + err.Error()) 376 } 377 var ok bool 378 subKey.Sig, ok = p.(*packet.Signature) 379 if !ok { 380 return errors.StructuralError("subkey packet not followed by signature") 381 } 382 if subKey.Sig.SigType != packet.SigTypeSubkeyBinding { 383 return errors.StructuralError("subkey signature with wrong type") 384 } 385 err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig) 386 if err != nil { 387 return errors.StructuralError("subkey signature invalid: " + err.Error()) 388 } 389 e.Subkeys = append(e.Subkeys, subKey) 390 return nil 391 } 392 393 const defaultRSAKeyBits = 2048 394 395 // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a 396 // single identity composed of the given full name, comment and email, any of 397 // which may be empty but must not contain any of "()<>\x00". 398 func NewEntity(rand io.Reader, currentTime time.Time, name, comment, email string) (*Entity, error) { 399 uid := packet.NewUserId(name, comment, email) 400 if uid == nil { 401 return nil, errors.InvalidArgumentError("user id field contained invalid characters") 402 } 403 signingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits) 404 if err != nil { 405 return nil, err 406 } 407 encryptingPriv, err := rsa.GenerateKey(rand, defaultRSAKeyBits) 408 if err != nil { 409 return nil, err 410 } 411 412 e := &Entity{ 413 PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey), 414 PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv), 415 Identities: make(map[string]*Identity), 416 } 417 isPrimaryId := true 418 e.Identities[uid.Id] = &Identity{ 419 Name: uid.Name, 420 UserId: uid, 421 SelfSignature: &packet.Signature{ 422 CreationTime: currentTime, 423 SigType: packet.SigTypePositiveCert, 424 PubKeyAlgo: packet.PubKeyAlgoRSA, 425 Hash: crypto.SHA256, 426 IsPrimaryId: &isPrimaryId, 427 FlagsValid: true, 428 FlagSign: true, 429 FlagCertify: true, 430 IssuerKeyId: &e.PrimaryKey.KeyId, 431 }, 432 } 433 434 e.Subkeys = make([]Subkey, 1) 435 e.Subkeys[0] = Subkey{ 436 PublicKey: packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey), 437 PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv), 438 Sig: &packet.Signature{ 439 CreationTime: currentTime, 440 SigType: packet.SigTypeSubkeyBinding, 441 PubKeyAlgo: packet.PubKeyAlgoRSA, 442 Hash: crypto.SHA256, 443 FlagsValid: true, 444 FlagEncryptStorage: true, 445 FlagEncryptCommunications: true, 446 IssuerKeyId: &e.PrimaryKey.KeyId, 447 }, 448 } 449 e.Subkeys[0].PublicKey.IsSubkey = true 450 e.Subkeys[0].PrivateKey.IsSubkey = true 451 452 return e, nil 453 } 454 455 // SerializePrivate serializes an Entity, including private key material, to 456 // the given Writer. For now, it must only be used on an Entity returned from 457 // NewEntity. 458 func (e *Entity) SerializePrivate(w io.Writer) (err error) { 459 err = e.PrivateKey.Serialize(w) 460 if err != nil { 461 return 462 } 463 for _, ident := range e.Identities { 464 err = ident.UserId.Serialize(w) 465 if err != nil { 466 return 467 } 468 err = ident.SelfSignature.SignUserId(rand.Reader, ident.UserId.Id, e.PrimaryKey, e.PrivateKey) 469 if err != nil { 470 return 471 } 472 err = ident.SelfSignature.Serialize(w) 473 if err != nil { 474 return 475 } 476 } 477 for _, subkey := range e.Subkeys { 478 err = subkey.PrivateKey.Serialize(w) 479 if err != nil { 480 return 481 } 482 err = subkey.Sig.SignKey(rand.Reader, subkey.PublicKey, e.PrivateKey) 483 if err != nil { 484 return 485 } 486 err = subkey.Sig.Serialize(w) 487 if err != nil { 488 return 489 } 490 } 491 return nil 492 } 493 494 // Serialize writes the public part of the given Entity to w. (No private 495 // key material will be output). 496 func (e *Entity) Serialize(w io.Writer) error { 497 err := e.PrimaryKey.Serialize(w) 498 if err != nil { 499 return err 500 } 501 for _, ident := range e.Identities { 502 err = ident.UserId.Serialize(w) 503 if err != nil { 504 return err 505 } 506 err = ident.SelfSignature.Serialize(w) 507 if err != nil { 508 return err 509 } 510 for _, sig := range ident.Signatures { 511 err = sig.Serialize(w) 512 if err != nil { 513 return err 514 } 515 } 516 } 517 for _, subkey := range e.Subkeys { 518 err = subkey.PublicKey.Serialize(w) 519 if err != nil { 520 return err 521 } 522 err = subkey.Sig.Serialize(w) 523 if err != nil { 524 return err 525 } 526 } 527 return nil 528 } 529 530 // SignIdentity adds a signature to e, from signer, attesting that identity is 531 // associated with e. The provided identity must already be an element of 532 // e.Identities and the private key of signer must have been decrypted if 533 // necessary. 534 func (e *Entity) SignIdentity(identity string, signer *Entity) error { 535 if signer.PrivateKey == nil { 536 return errors.InvalidArgumentError("signing Entity must have a private key") 537 } 538 if signer.PrivateKey.Encrypted { 539 return errors.InvalidArgumentError("signing Entity's private key must be decrypted") 540 } 541 ident, ok := e.Identities[identity] 542 if !ok { 543 return errors.InvalidArgumentError("given identity string not found in Entity") 544 } 545 546 sig := &packet.Signature{ 547 SigType: packet.SigTypeGenericCert, 548 PubKeyAlgo: signer.PrivateKey.PubKeyAlgo, 549 Hash: crypto.SHA256, 550 CreationTime: time.Now(), 551 IssuerKeyId: &signer.PrivateKey.KeyId, 552 } 553 if err := sig.SignKey(rand.Reader, e.PrimaryKey, signer.PrivateKey); err != nil { 554 return err 555 } 556 ident.Signatures = append(ident.Signatures, sig) 557 return nil 558 }