github.com/slspeek/camlistore_namedsearch@v0.0.0-20140519202248-ed6f70f7721a/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/rsa" 12 "io" 13 "time" 14 ) 15 16 // PublicKeyType is the armor type for a PGP public key. 17 var PublicKeyType = "PGP PUBLIC KEY BLOCK" 18 19 // PrivateKeyType is the armor type for a PGP private key. 20 var PrivateKeyType = "PGP PRIVATE KEY BLOCK" 21 22 // An Entity represents the components of an OpenPGP key: a primary public key 23 // (which must be a signing key), one or more identities claimed by that key, 24 // and zero or more subkeys, which may be encryption keys. 25 type Entity struct { 26 PrimaryKey *packet.PublicKey 27 PrivateKey *packet.PrivateKey 28 Identities map[string]*Identity // indexed by Identity.Name 29 Subkeys []Subkey 30 } 31 32 // An Identity represents an identity claimed by an Entity and zero or more 33 // assertions by other entities about that claim. 34 type Identity struct { 35 Name string // by convention, has the form "Full Name (comment) <email@example.com>" 36 UserId *packet.UserId 37 SelfSignature *packet.Signature 38 Signatures []*packet.Signature 39 } 40 41 // A Subkey is an additional public key in an Entity. Subkeys can be used for 42 // encryption. 43 type Subkey struct { 44 PublicKey *packet.PublicKey 45 PrivateKey *packet.PrivateKey 46 Sig *packet.Signature 47 } 48 49 // A Key identifies a specific public key in an Entity. This is either the 50 // Entity's primary key or a subkey. 51 type Key struct { 52 Entity *Entity 53 PublicKey *packet.PublicKey 54 PrivateKey *packet.PrivateKey 55 SelfSignature *packet.Signature 56 } 57 58 // A KeyRing provides access to public and private keys. 59 type KeyRing interface { 60 // KeysById returns the set of keys that have the given key id. 61 KeysById(id uint64) []Key 62 // DecryptionKeys returns all private keys that are valid for 63 // decryption. 64 DecryptionKeys() []Key 65 } 66 67 // primaryIdentity returns the Identity marked as primary or the first identity 68 // if none are so marked. 69 func (e *Entity) primaryIdentity() *Identity { 70 var firstIdentity *Identity 71 for _, ident := range e.Identities { 72 if firstIdentity == nil { 73 firstIdentity = ident 74 } 75 if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId { 76 return ident 77 } 78 } 79 return firstIdentity 80 } 81 82 // encryptionKey returns the best candidate Key for encrypting a message to the 83 // given Entity. 84 func (e *Entity) encryptionKey(now time.Time) (Key, bool) { 85 candidateSubkey := -1 86 87 for i, subkey := range e.Subkeys { 88 if subkey.Sig.FlagsValid && 89 subkey.Sig.FlagEncryptCommunications && 90 subkey.PublicKey.PubKeyAlgo.CanEncrypt() && 91 !subkey.Sig.KeyExpired(now) { 92 candidateSubkey = i 93 break 94 } 95 } 96 97 if candidateSubkey != -1 { 98 subkey := e.Subkeys[candidateSubkey] 99 return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig}, true 100 } 101 102 // If we don't have any candidate subkeys for encryption and 103 // the primary key doesn't have any usage metadata then we 104 // assume that the primary key is ok. Or, if the primary key is 105 // marked as ok to encrypt to, then we can obviously use it. 106 i := e.primaryIdentity() 107 if !i.SelfSignature.FlagsValid || i.SelfSignature.FlagEncryptCommunications && 108 e.PrimaryKey.PubKeyAlgo.CanEncrypt() && 109 !i.SelfSignature.KeyExpired(now) { 110 return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature}, true 111 } 112 113 // This Entity appears to be signing only. 114 return Key{}, false 115 } 116 117 // signingKey return the best candidate Key for signing a message with this 118 // Entity. 119 func (e *Entity) signingKey(now time.Time) (Key, bool) { 120 candidateSubkey := -1 121 122 for i, subkey := range e.Subkeys { 123 if subkey.Sig.FlagsValid && 124 subkey.Sig.FlagSign && 125 subkey.PublicKey.PubKeyAlgo.CanSign() && 126 !subkey.Sig.KeyExpired(now) { 127 candidateSubkey = i 128 break 129 } 130 } 131 132 if candidateSubkey != -1 { 133 subkey := e.Subkeys[candidateSubkey] 134 return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig}, true 135 } 136 137 // If we have no candidate subkey then we assume that it's ok to sign 138 // with the primary key. 139 i := e.primaryIdentity() 140 if !i.SelfSignature.FlagsValid || i.SelfSignature.FlagSign && 141 !i.SelfSignature.KeyExpired(now) { 142 return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature}, true 143 } 144 145 return Key{}, false 146 } 147 148 // An EntityList contains one or more Entities. 149 type EntityList []*Entity 150 151 // KeysById returns the set of keys that have the given key id. 152 func (el EntityList) KeysById(id uint64) (keys []Key) { 153 for _, e := range el { 154 if e.PrimaryKey.KeyId == id { 155 var selfSig *packet.Signature 156 for _, ident := range e.Identities { 157 if selfSig == nil { 158 selfSig = ident.SelfSignature 159 } else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId { 160 selfSig = ident.SelfSignature 161 break 162 } 163 } 164 keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig}) 165 } 166 167 for _, subKey := range e.Subkeys { 168 if subKey.PublicKey.KeyId == id { 169 keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig}) 170 } 171 } 172 } 173 return 174 } 175 176 // DecryptionKeys returns all private keys that are valid for decryption. 177 func (el EntityList) DecryptionKeys() (keys []Key) { 178 for _, e := range el { 179 for _, subKey := range e.Subkeys { 180 if subKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) { 181 keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig}) 182 } 183 } 184 } 185 return 186 } 187 188 // ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file. 189 func ReadArmoredKeyRing(r io.Reader) (EntityList, error) { 190 block, err := armor.Decode(r) 191 if err == io.EOF { 192 return nil, errors.InvalidArgumentError("no armored data found") 193 } 194 if err != nil { 195 return nil, err 196 } 197 if block.Type != PublicKeyType && block.Type != PrivateKeyType { 198 return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type) 199 } 200 201 return ReadKeyRing(block.Body) 202 } 203 204 // ReadKeyRing reads one or more public/private keys. Unsupported keys are 205 // ignored as long as at least a single valid key is found. 206 func ReadKeyRing(r io.Reader) (el EntityList, err error) { 207 packets := packet.NewReader(r) 208 var lastUnsupportedError error 209 210 for { 211 var e *Entity 212 e, err = ReadEntity(packets) 213 if err != nil { 214 // TODO: warn about skipped unsupported/unreadable keys 215 if _, ok := err.(errors.UnsupportedError); ok { 216 lastUnsupportedError = err 217 err = readToNextPublicKey(packets) 218 } else if _, ok := err.(errors.StructuralError); ok { 219 // Skip unreadable, badly-formatted keys 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 // If config is nil, sensible defaults will be used. 399 func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) { 400 currentTime := config.Now() 401 402 uid := packet.NewUserId(name, comment, email) 403 if uid == nil { 404 return nil, errors.InvalidArgumentError("user id field contained invalid characters") 405 } 406 signingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits) 407 if err != nil { 408 return nil, err 409 } 410 encryptingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits) 411 if err != nil { 412 return nil, err 413 } 414 415 e := &Entity{ 416 PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey), 417 PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv), 418 Identities: make(map[string]*Identity), 419 } 420 isPrimaryId := true 421 e.Identities[uid.Id] = &Identity{ 422 Name: uid.Name, 423 UserId: uid, 424 SelfSignature: &packet.Signature{ 425 CreationTime: currentTime, 426 SigType: packet.SigTypePositiveCert, 427 PubKeyAlgo: packet.PubKeyAlgoRSA, 428 Hash: config.Hash(), 429 IsPrimaryId: &isPrimaryId, 430 FlagsValid: true, 431 FlagSign: true, 432 FlagCertify: true, 433 IssuerKeyId: &e.PrimaryKey.KeyId, 434 }, 435 } 436 437 e.Subkeys = make([]Subkey, 1) 438 e.Subkeys[0] = Subkey{ 439 PublicKey: packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey), 440 PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv), 441 Sig: &packet.Signature{ 442 CreationTime: currentTime, 443 SigType: packet.SigTypeSubkeyBinding, 444 PubKeyAlgo: packet.PubKeyAlgoRSA, 445 Hash: config.Hash(), 446 FlagsValid: true, 447 FlagEncryptStorage: true, 448 FlagEncryptCommunications: true, 449 IssuerKeyId: &e.PrimaryKey.KeyId, 450 }, 451 } 452 e.Subkeys[0].PublicKey.IsSubkey = true 453 e.Subkeys[0].PrivateKey.IsSubkey = true 454 455 return e, nil 456 } 457 458 // SerializePrivate serializes an Entity, including private key material, to 459 // the given Writer. For now, it must only be used on an Entity returned from 460 // NewEntity. 461 // If config is nil, sensible defaults will be used. 462 func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) { 463 err = e.PrivateKey.Serialize(w) 464 if err != nil { 465 return 466 } 467 for _, ident := range e.Identities { 468 err = ident.UserId.Serialize(w) 469 if err != nil { 470 return 471 } 472 err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config) 473 if err != nil { 474 return 475 } 476 err = ident.SelfSignature.Serialize(w) 477 if err != nil { 478 return 479 } 480 } 481 for _, subkey := range e.Subkeys { 482 err = subkey.PrivateKey.Serialize(w) 483 if err != nil { 484 return 485 } 486 err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config) 487 if err != nil { 488 return 489 } 490 err = subkey.Sig.Serialize(w) 491 if err != nil { 492 return 493 } 494 } 495 return nil 496 } 497 498 // Serialize writes the public part of the given Entity to w. (No private 499 // key material will be output). 500 func (e *Entity) Serialize(w io.Writer) error { 501 err := e.PrimaryKey.Serialize(w) 502 if err != nil { 503 return err 504 } 505 for _, ident := range e.Identities { 506 err = ident.UserId.Serialize(w) 507 if err != nil { 508 return err 509 } 510 err = ident.SelfSignature.Serialize(w) 511 if err != nil { 512 return err 513 } 514 for _, sig := range ident.Signatures { 515 err = sig.Serialize(w) 516 if err != nil { 517 return err 518 } 519 } 520 } 521 for _, subkey := range e.Subkeys { 522 err = subkey.PublicKey.Serialize(w) 523 if err != nil { 524 return err 525 } 526 err = subkey.Sig.Serialize(w) 527 if err != nil { 528 return err 529 } 530 } 531 return nil 532 } 533 534 // SignIdentity adds a signature to e, from signer, attesting that identity is 535 // associated with e. The provided identity must already be an element of 536 // e.Identities and the private key of signer must have been decrypted if 537 // necessary. 538 // If config is nil, sensible defaults will be used. 539 func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error { 540 if signer.PrivateKey == nil { 541 return errors.InvalidArgumentError("signing Entity must have a private key") 542 } 543 if signer.PrivateKey.Encrypted { 544 return errors.InvalidArgumentError("signing Entity's private key must be decrypted") 545 } 546 ident, ok := e.Identities[identity] 547 if !ok { 548 return errors.InvalidArgumentError("given identity string not found in Entity") 549 } 550 551 sig := &packet.Signature{ 552 SigType: packet.SigTypeGenericCert, 553 PubKeyAlgo: signer.PrivateKey.PubKeyAlgo, 554 Hash: config.Hash(), 555 CreationTime: config.Now(), 556 IssuerKeyId: &signer.PrivateKey.KeyId, 557 } 558 if err := sig.SignKey(e.PrimaryKey, signer.PrivateKey, config); err != nil { 559 return err 560 } 561 ident.Signatures = append(ident.Signatures, sig) 562 return nil 563 }