keys.go 15 KB

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