Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

379 rader
11 KiB

  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. "crypto"
  7. "hash"
  8. "io"
  9. "strconv"
  10. "time"
  11. "golang.org/x/crypto/openpgp/armor"
  12. "golang.org/x/crypto/openpgp/errors"
  13. "golang.org/x/crypto/openpgp/packet"
  14. "golang.org/x/crypto/openpgp/s2k"
  15. )
  16. // DetachSign signs message with the private key from signer (which must
  17. // already have been decrypted) and writes the signature to w.
  18. // If config is nil, sensible defaults will be used.
  19. func DetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error {
  20. return detachSign(w, signer, message, packet.SigTypeBinary, config)
  21. }
  22. // ArmoredDetachSign signs message with the private key from signer (which
  23. // must already have been decrypted) and writes an armored signature to w.
  24. // If config is nil, sensible defaults will be used.
  25. func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) (err error) {
  26. return armoredDetachSign(w, signer, message, packet.SigTypeBinary, config)
  27. }
  28. // DetachSignText signs message (after canonicalising the line endings) with
  29. // the private key from signer (which must already have been decrypted) and
  30. // writes the signature to w.
  31. // If config is nil, sensible defaults will be used.
  32. func DetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error {
  33. return detachSign(w, signer, message, packet.SigTypeText, config)
  34. }
  35. // ArmoredDetachSignText signs message (after canonicalising the line endings)
  36. // with the private key from signer (which must already have been decrypted)
  37. // and writes an armored signature to w.
  38. // If config is nil, sensible defaults will be used.
  39. func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error {
  40. return armoredDetachSign(w, signer, message, packet.SigTypeText, config)
  41. }
  42. func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) {
  43. out, err := armor.Encode(w, SignatureType, nil)
  44. if err != nil {
  45. return
  46. }
  47. err = detachSign(out, signer, message, sigType, config)
  48. if err != nil {
  49. return
  50. }
  51. return out.Close()
  52. }
  53. func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) {
  54. if signer.PrivateKey == nil {
  55. return errors.InvalidArgumentError("signing key doesn't have a private key")
  56. }
  57. if signer.PrivateKey.Encrypted {
  58. return errors.InvalidArgumentError("signing key is encrypted")
  59. }
  60. sig := new(packet.Signature)
  61. sig.SigType = sigType
  62. sig.PubKeyAlgo = signer.PrivateKey.PubKeyAlgo
  63. sig.Hash = config.Hash()
  64. sig.CreationTime = config.Now()
  65. sig.IssuerKeyId = &signer.PrivateKey.KeyId
  66. h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType)
  67. if err != nil {
  68. return
  69. }
  70. io.Copy(wrappedHash, message)
  71. err = sig.Sign(h, signer.PrivateKey, config)
  72. if err != nil {
  73. return
  74. }
  75. return sig.Serialize(w)
  76. }
  77. // FileHints contains metadata about encrypted files. This metadata is, itself,
  78. // encrypted.
  79. type FileHints struct {
  80. // IsBinary can be set to hint that the contents are binary data.
  81. IsBinary bool
  82. // FileName hints at the name of the file that should be written. It's
  83. // truncated to 255 bytes if longer. It may be empty to suggest that the
  84. // file should not be written to disk. It may be equal to "_CONSOLE" to
  85. // suggest the data should not be written to disk.
  86. FileName string
  87. // ModTime contains the modification time of the file, or the zero time if not applicable.
  88. ModTime time.Time
  89. }
  90. // SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase.
  91. // The resulting WriteCloser must be closed after the contents of the file have
  92. // been written.
  93. // If config is nil, sensible defaults will be used.
  94. func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) {
  95. if hints == nil {
  96. hints = &FileHints{}
  97. }
  98. key, err := packet.SerializeSymmetricKeyEncrypted(ciphertext, passphrase, config)
  99. if err != nil {
  100. return
  101. }
  102. w, err := packet.SerializeSymmetricallyEncrypted(ciphertext, config.Cipher(), key, config)
  103. if err != nil {
  104. return
  105. }
  106. literaldata := w
  107. if algo := config.Compression(); algo != packet.CompressionNone {
  108. var compConfig *packet.CompressionConfig
  109. if config != nil {
  110. compConfig = config.CompressionConfig
  111. }
  112. literaldata, err = packet.SerializeCompressed(w, algo, compConfig)
  113. if err != nil {
  114. return
  115. }
  116. }
  117. var epochSeconds uint32
  118. if !hints.ModTime.IsZero() {
  119. epochSeconds = uint32(hints.ModTime.Unix())
  120. }
  121. return packet.SerializeLiteral(literaldata, hints.IsBinary, hints.FileName, epochSeconds)
  122. }
  123. // intersectPreferences mutates and returns a prefix of a that contains only
  124. // the values in the intersection of a and b. The order of a is preserved.
  125. func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) {
  126. var j int
  127. for _, v := range a {
  128. for _, v2 := range b {
  129. if v == v2 {
  130. a[j] = v
  131. j++
  132. break
  133. }
  134. }
  135. }
  136. return a[:j]
  137. }
  138. func hashToHashId(h crypto.Hash) uint8 {
  139. v, ok := s2k.HashToHashId(h)
  140. if !ok {
  141. panic("tried to convert unknown hash")
  142. }
  143. return v
  144. }
  145. // Encrypt encrypts a message to a number of recipients and, optionally, signs
  146. // it. hints contains optional information, that is also encrypted, that aids
  147. // the recipients in processing the message. The resulting WriteCloser must
  148. // be closed after the contents of the file have been written.
  149. // If config is nil, sensible defaults will be used.
  150. func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) {
  151. var signer *packet.PrivateKey
  152. if signed != nil {
  153. signKey, ok := signed.signingKey(config.Now())
  154. if !ok {
  155. return nil, errors.InvalidArgumentError("no valid signing keys")
  156. }
  157. signer = signKey.PrivateKey
  158. if signer == nil {
  159. return nil, errors.InvalidArgumentError("no private key in signing key")
  160. }
  161. if signer.Encrypted {
  162. return nil, errors.InvalidArgumentError("signing key must be decrypted")
  163. }
  164. }
  165. // These are the possible ciphers that we'll use for the message.
  166. candidateCiphers := []uint8{
  167. uint8(packet.CipherAES128),
  168. uint8(packet.CipherAES256),
  169. uint8(packet.CipherCAST5),
  170. }
  171. // These are the possible hash functions that we'll use for the signature.
  172. candidateHashes := []uint8{
  173. hashToHashId(crypto.SHA256),
  174. hashToHashId(crypto.SHA512),
  175. hashToHashId(crypto.SHA1),
  176. hashToHashId(crypto.RIPEMD160),
  177. }
  178. // In the event that a recipient doesn't specify any supported ciphers
  179. // or hash functions, these are the ones that we assume that every
  180. // implementation supports.
  181. defaultCiphers := candidateCiphers[len(candidateCiphers)-1:]
  182. defaultHashes := candidateHashes[len(candidateHashes)-1:]
  183. encryptKeys := make([]Key, len(to))
  184. for i := range to {
  185. var ok bool
  186. encryptKeys[i], ok = to[i].encryptionKey(config.Now())
  187. if !ok {
  188. return nil, errors.InvalidArgumentError("cannot encrypt a message to key id " + strconv.FormatUint(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys")
  189. }
  190. sig := to[i].primaryIdentity().SelfSignature
  191. preferredSymmetric := sig.PreferredSymmetric
  192. if len(preferredSymmetric) == 0 {
  193. preferredSymmetric = defaultCiphers
  194. }
  195. preferredHashes := sig.PreferredHash
  196. if len(preferredHashes) == 0 {
  197. preferredHashes = defaultHashes
  198. }
  199. candidateCiphers = intersectPreferences(candidateCiphers, preferredSymmetric)
  200. candidateHashes = intersectPreferences(candidateHashes, preferredHashes)
  201. }
  202. if len(candidateCiphers) == 0 || len(candidateHashes) == 0 {
  203. return nil, errors.InvalidArgumentError("cannot encrypt because recipient set shares no common algorithms")
  204. }
  205. cipher := packet.CipherFunction(candidateCiphers[0])
  206. // If the cipher specified by config is a candidate, we'll use that.
  207. configuredCipher := config.Cipher()
  208. for _, c := range candidateCiphers {
  209. cipherFunc := packet.CipherFunction(c)
  210. if cipherFunc == configuredCipher {
  211. cipher = cipherFunc
  212. break
  213. }
  214. }
  215. var hash crypto.Hash
  216. for _, hashId := range candidateHashes {
  217. if h, ok := s2k.HashIdToHash(hashId); ok && h.Available() {
  218. hash = h
  219. break
  220. }
  221. }
  222. // If the hash specified by config is a candidate, we'll use that.
  223. if configuredHash := config.Hash(); configuredHash.Available() {
  224. for _, hashId := range candidateHashes {
  225. if h, ok := s2k.HashIdToHash(hashId); ok && h == configuredHash {
  226. hash = h
  227. break
  228. }
  229. }
  230. }
  231. if hash == 0 {
  232. hashId := candidateHashes[0]
  233. name, ok := s2k.HashIdToString(hashId)
  234. if !ok {
  235. name = "#" + strconv.Itoa(int(hashId))
  236. }
  237. return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)")
  238. }
  239. symKey := make([]byte, cipher.KeySize())
  240. if _, err := io.ReadFull(config.Random(), symKey); err != nil {
  241. return nil, err
  242. }
  243. for _, key := range encryptKeys {
  244. if err := packet.SerializeEncryptedKey(ciphertext, key.PublicKey, cipher, symKey, config); err != nil {
  245. return nil, err
  246. }
  247. }
  248. encryptedData, err := packet.SerializeSymmetricallyEncrypted(ciphertext, cipher, symKey, config)
  249. if err != nil {
  250. return
  251. }
  252. if signer != nil {
  253. ops := &packet.OnePassSignature{
  254. SigType: packet.SigTypeBinary,
  255. Hash: hash,
  256. PubKeyAlgo: signer.PubKeyAlgo,
  257. KeyId: signer.KeyId,
  258. IsLast: true,
  259. }
  260. if err := ops.Serialize(encryptedData); err != nil {
  261. return nil, err
  262. }
  263. }
  264. if hints == nil {
  265. hints = &FileHints{}
  266. }
  267. w := encryptedData
  268. if signer != nil {
  269. // If we need to write a signature packet after the literal
  270. // data then we need to stop literalData from closing
  271. // encryptedData.
  272. w = noOpCloser{encryptedData}
  273. }
  274. var epochSeconds uint32
  275. if !hints.ModTime.IsZero() {
  276. epochSeconds = uint32(hints.ModTime.Unix())
  277. }
  278. literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds)
  279. if err != nil {
  280. return nil, err
  281. }
  282. if signer != nil {
  283. return signatureWriter{encryptedData, literalData, hash, hash.New(), signer, config}, nil
  284. }
  285. return literalData, nil
  286. }
  287. // signatureWriter hashes the contents of a message while passing it along to
  288. // literalData. When closed, it closes literalData, writes a signature packet
  289. // to encryptedData and then also closes encryptedData.
  290. type signatureWriter struct {
  291. encryptedData io.WriteCloser
  292. literalData io.WriteCloser
  293. hashType crypto.Hash
  294. h hash.Hash
  295. signer *packet.PrivateKey
  296. config *packet.Config
  297. }
  298. func (s signatureWriter) Write(data []byte) (int, error) {
  299. s.h.Write(data)
  300. return s.literalData.Write(data)
  301. }
  302. func (s signatureWriter) Close() error {
  303. sig := &packet.Signature{
  304. SigType: packet.SigTypeBinary,
  305. PubKeyAlgo: s.signer.PubKeyAlgo,
  306. Hash: s.hashType,
  307. CreationTime: s.config.Now(),
  308. IssuerKeyId: &s.signer.KeyId,
  309. }
  310. if err := sig.Sign(s.h, s.signer, s.config); err != nil {
  311. return err
  312. }
  313. if err := s.literalData.Close(); err != nil {
  314. return err
  315. }
  316. if err := sig.Serialize(s.encryptedData); err != nil {
  317. return err
  318. }
  319. return s.encryptedData.Close()
  320. }
  321. // noOpCloser is like an ioutil.NopCloser, but for an io.Writer.
  322. // TODO: we have two of these in OpenPGP packages alone. This probably needs
  323. // to be promoted somewhere more common.
  324. type noOpCloser struct {
  325. w io.Writer
  326. }
  327. func (c noOpCloser) Write(data []byte) (n int, err error) {
  328. return c.w.Write(data)
  329. }
  330. func (c noOpCloser) Close() error {
  331. return nil
  332. }