keys.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. if _, ok := err.(errors.UnsupportedError); ok {
  176. lastUnsupportedError = err
  177. err = readToNextPublicKey(packets)
  178. }
  179. if err == io.EOF {
  180. err = nil
  181. break
  182. }
  183. if err != nil {
  184. el = nil
  185. break
  186. }
  187. } else {
  188. el = append(el, e)
  189. }
  190. }
  191. if len(el) == 0 && err == nil {
  192. err = lastUnsupportedError
  193. }
  194. return
  195. }
  196. // readToNextPublicKey reads packets until the start of the entity and leaves
  197. // the first packet of the new entity in the Reader.
  198. func readToNextPublicKey(packets *packet.Reader) (err error) {
  199. var p packet.Packet
  200. for {
  201. p, err = packets.Next()
  202. if err == io.EOF {
  203. return
  204. } else if err != nil {
  205. if _, ok := err.(errors.UnsupportedError); ok {
  206. err = nil
  207. continue
  208. }
  209. return
  210. }
  211. if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey {
  212. packets.Unread(p)
  213. return
  214. }
  215. }
  216. panic("unreachable")
  217. }
  218. // readEntity reads an entity (public key, identities, subkeys etc) from the
  219. // given Reader.
  220. func readEntity(packets *packet.Reader) (*Entity, error) {
  221. e := new(Entity)
  222. e.Identities = make(map[string]*Identity)
  223. p, err := packets.Next()
  224. if err != nil {
  225. return nil, err
  226. }
  227. var ok bool
  228. if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok {
  229. if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok {
  230. packets.Unread(p)
  231. return nil, errors.StructuralError("first packet was not a public/private key")
  232. } else {
  233. e.PrimaryKey = &e.PrivateKey.PublicKey
  234. }
  235. }
  236. if !e.PrimaryKey.PubKeyAlgo.CanSign() {
  237. return nil, errors.StructuralError("primary key cannot be used for signatures")
  238. }
  239. var current *Identity
  240. EachPacket:
  241. for {
  242. p, err := packets.Next()
  243. if err == io.EOF {
  244. break
  245. } else if err != nil {
  246. return nil, err
  247. }
  248. switch pkt := p.(type) {
  249. case *packet.UserId:
  250. current = new(Identity)
  251. current.Name = pkt.Id
  252. current.UserId = pkt
  253. e.Identities[pkt.Id] = current
  254. for {
  255. p, err = packets.Next()
  256. if err == io.EOF {
  257. return nil, io.ErrUnexpectedEOF
  258. } else if err != nil {
  259. return nil, err
  260. }
  261. sig, ok := p.(*packet.Signature)
  262. if !ok {
  263. return nil, errors.StructuralError("user ID packet not followed by self-signature")
  264. }
  265. if (sig.SigType == packet.SigTypePositiveCert || sig.SigType == packet.SigTypeGenericCert) && sig.IssuerKeyId != nil && *sig.IssuerKeyId == e.PrimaryKey.KeyId {
  266. if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, sig); err != nil {
  267. return nil, errors.StructuralError("user ID self-signature invalid: " + err.Error())
  268. }
  269. current.SelfSignature = sig
  270. break
  271. }
  272. current.Signatures = append(current.Signatures, sig)
  273. }
  274. case *packet.Signature:
  275. if current == nil {
  276. return nil, errors.StructuralError("signature packet found before user id packet")
  277. }
  278. current.Signatures = append(current.Signatures, pkt)
  279. case *packet.PrivateKey:
  280. if pkt.IsSubkey == false {
  281. packets.Unread(p)
  282. break EachPacket
  283. }
  284. err = addSubkey(e, packets, &pkt.PublicKey, pkt)
  285. if err != nil {
  286. return nil, err
  287. }
  288. case *packet.PublicKey:
  289. if pkt.IsSubkey == false {
  290. packets.Unread(p)
  291. break EachPacket
  292. }
  293. err = addSubkey(e, packets, pkt, nil)
  294. if err != nil {
  295. return nil, err
  296. }
  297. default:
  298. // we ignore unknown packets
  299. }
  300. }
  301. if len(e.Identities) == 0 {
  302. return nil, errors.StructuralError("entity without any identities")
  303. }
  304. return e, nil
  305. }
  306. func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error {
  307. var subKey Subkey
  308. subKey.PublicKey = pub
  309. subKey.PrivateKey = priv
  310. p, err := packets.Next()
  311. if err == io.EOF {
  312. return io.ErrUnexpectedEOF
  313. }
  314. if err != nil {
  315. return errors.StructuralError("subkey signature invalid: " + err.Error())
  316. }
  317. var ok bool
  318. subKey.Sig, ok = p.(*packet.Signature)
  319. if !ok {
  320. return errors.StructuralError("subkey packet not followed by signature")
  321. }
  322. if subKey.Sig.SigType != packet.SigTypeSubkeyBinding {
  323. return errors.StructuralError("subkey signature with wrong type")
  324. }
  325. err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig)
  326. if err != nil {
  327. return errors.StructuralError("subkey signature invalid: " + err.Error())
  328. }
  329. e.Subkeys = append(e.Subkeys, subKey)
  330. return nil
  331. }
  332. const defaultRSAKeyBits = 2048
  333. // NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a
  334. // single identity composed of the given full name, comment and email, any of
  335. // which may be empty but must not contain any of "()<>\x00".
  336. // If config is nil, sensible defaults will be used.
  337. func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) {
  338. currentTime := config.Now()
  339. uid := packet.NewUserId(name, comment, email)
  340. if uid == nil {
  341. return nil, errors.InvalidArgumentError("user id field contained invalid characters")
  342. }
  343. signingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
  344. if err != nil {
  345. return nil, err
  346. }
  347. encryptingPriv, err := rsa.GenerateKey(config.Random(), defaultRSAKeyBits)
  348. if err != nil {
  349. return nil, err
  350. }
  351. e := &Entity{
  352. PrimaryKey: packet.NewRSAPublicKey(currentTime, &signingPriv.PublicKey),
  353. PrivateKey: packet.NewRSAPrivateKey(currentTime, signingPriv),
  354. Identities: make(map[string]*Identity),
  355. }
  356. isPrimaryId := true
  357. e.Identities[uid.Id] = &Identity{
  358. Name: uid.Name,
  359. UserId: uid,
  360. SelfSignature: &packet.Signature{
  361. CreationTime: currentTime,
  362. SigType: packet.SigTypePositiveCert,
  363. PubKeyAlgo: packet.PubKeyAlgoRSA,
  364. Hash: config.Hash(),
  365. IsPrimaryId: &isPrimaryId,
  366. FlagsValid: true,
  367. FlagSign: true,
  368. FlagCertify: true,
  369. IssuerKeyId: &e.PrimaryKey.KeyId,
  370. },
  371. }
  372. e.Subkeys = make([]Subkey, 1)
  373. e.Subkeys[0] = Subkey{
  374. PublicKey: packet.NewRSAPublicKey(currentTime, &encryptingPriv.PublicKey),
  375. PrivateKey: packet.NewRSAPrivateKey(currentTime, encryptingPriv),
  376. Sig: &packet.Signature{
  377. CreationTime: currentTime,
  378. SigType: packet.SigTypeSubkeyBinding,
  379. PubKeyAlgo: packet.PubKeyAlgoRSA,
  380. Hash: config.Hash(),
  381. FlagsValid: true,
  382. FlagEncryptStorage: true,
  383. FlagEncryptCommunications: true,
  384. IssuerKeyId: &e.PrimaryKey.KeyId,
  385. },
  386. }
  387. e.Subkeys[0].PublicKey.IsSubkey = true
  388. e.Subkeys[0].PrivateKey.IsSubkey = true
  389. return e, nil
  390. }
  391. // SerializePrivate serializes an Entity, including private key material, to
  392. // the given Writer. For now, it must only be used on an Entity returned from
  393. // NewEntity.
  394. // If config is nil, sensible defaults will be used.
  395. func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) {
  396. err = e.PrivateKey.Serialize(w)
  397. if err != nil {
  398. return
  399. }
  400. for _, ident := range e.Identities {
  401. err = ident.UserId.Serialize(w)
  402. if err != nil {
  403. return
  404. }
  405. err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config)
  406. if err != nil {
  407. return
  408. }
  409. err = ident.SelfSignature.Serialize(w)
  410. if err != nil {
  411. return
  412. }
  413. }
  414. for _, subkey := range e.Subkeys {
  415. err = subkey.PrivateKey.Serialize(w)
  416. if err != nil {
  417. return
  418. }
  419. err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config)
  420. if err != nil {
  421. return
  422. }
  423. err = subkey.Sig.Serialize(w)
  424. if err != nil {
  425. return
  426. }
  427. }
  428. return nil
  429. }
  430. // Serialize writes the public part of the given Entity to w. (No private
  431. // key material will be output).
  432. func (e *Entity) Serialize(w io.Writer) error {
  433. err := e.PrimaryKey.Serialize(w)
  434. if err != nil {
  435. return err
  436. }
  437. for _, ident := range e.Identities {
  438. err = ident.UserId.Serialize(w)
  439. if err != nil {
  440. return err
  441. }
  442. err = ident.SelfSignature.Serialize(w)
  443. if err != nil {
  444. return err
  445. }
  446. for _, sig := range ident.Signatures {
  447. err = sig.Serialize(w)
  448. if err != nil {
  449. return err
  450. }
  451. }
  452. }
  453. for _, subkey := range e.Subkeys {
  454. err = subkey.PublicKey.Serialize(w)
  455. if err != nil {
  456. return err
  457. }
  458. err = subkey.Sig.Serialize(w)
  459. if err != nil {
  460. return err
  461. }
  462. }
  463. return nil
  464. }
  465. // SignIdentity adds a signature to e, from signer, attesting that identity is
  466. // associated with e. The provided identity must already be an element of
  467. // e.Identities and the private key of signer must have been decrypted if
  468. // necessary.
  469. // If config is nil, sensible defaults will be used.
  470. func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error {
  471. if signer.PrivateKey == nil {
  472. return errors.InvalidArgumentError("signing Entity must have a private key")
  473. }
  474. if signer.PrivateKey.Encrypted {
  475. return errors.InvalidArgumentError("signing Entity's private key must be decrypted")
  476. }
  477. ident, ok := e.Identities[identity]
  478. if !ok {
  479. return errors.InvalidArgumentError("given identity string not found in Entity")
  480. }
  481. sig := &packet.Signature{
  482. SigType: packet.SigTypeGenericCert,
  483. PubKeyAlgo: signer.PrivateKey.PubKeyAlgo,
  484. Hash: config.Hash(),
  485. CreationTime: config.Now(),
  486. IssuerKeyId: &signer.PrivateKey.KeyId,
  487. }
  488. if err := sig.SignKey(e.PrimaryKey, signer.PrivateKey, config); err != nil {
  489. return err
  490. }
  491. ident.Signatures = append(ident.Signatures, sig)
  492. return nil
  493. }