keys.go 15 KB

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