keys.go 15 KB

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