You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

326 lines
8.2 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 s2k implements the various OpenPGP string-to-key transforms as
  5. // specified in RFC 4800 section 3.7.1.
  6. package s2k // import "github.com/keybase/go-crypto/openpgp/s2k"
  7. import (
  8. "crypto"
  9. "hash"
  10. "io"
  11. "strconv"
  12. "github.com/keybase/go-crypto/openpgp/errors"
  13. )
  14. // Config collects configuration parameters for s2k key-stretching
  15. // transformatioms. A nil *Config is valid and results in all default
  16. // values. Currently, Config is used only by the Serialize function in
  17. // this package.
  18. type Config struct {
  19. // Hash is the default hash function to be used. If
  20. // nil, SHA1 is used.
  21. Hash crypto.Hash
  22. // S2KCount is only used for symmetric encryption. It
  23. // determines the strength of the passphrase stretching when
  24. // the said passphrase is hashed to produce a key. S2KCount
  25. // should be between 1024 and 65011712, inclusive. If Config
  26. // is nil or S2KCount is 0, the value 65536 used. Not all
  27. // values in the above range can be represented. S2KCount will
  28. // be rounded up to the next representable value if it cannot
  29. // be encoded exactly. When set, it is strongly encrouraged to
  30. // use a value that is at least 65536. See RFC 4880 Section
  31. // 3.7.1.3.
  32. S2KCount int
  33. }
  34. func (c *Config) hash() crypto.Hash {
  35. if c == nil || uint(c.Hash) == 0 {
  36. // SHA1 is the historical default in this package.
  37. return crypto.SHA1
  38. }
  39. return c.Hash
  40. }
  41. func (c *Config) encodedCount() uint8 {
  42. if c == nil || c.S2KCount == 0 {
  43. return 96 // The common case. Correspoding to 65536
  44. }
  45. i := c.S2KCount
  46. switch {
  47. // Behave like GPG. Should we make 65536 the lowest value used?
  48. case i < 1024:
  49. i = 1024
  50. case i > 65011712:
  51. i = 65011712
  52. }
  53. return encodeCount(i)
  54. }
  55. // encodeCount converts an iterative "count" in the range 1024 to
  56. // 65011712, inclusive, to an encoded count. The return value is the
  57. // octet that is actually stored in the GPG file. encodeCount panics
  58. // if i is not in the above range (encodedCount above takes care to
  59. // pass i in the correct range). See RFC 4880 Section 3.7.7.1.
  60. func encodeCount(i int) uint8 {
  61. if i < 1024 || i > 65011712 {
  62. panic("count arg i outside the required range")
  63. }
  64. for encoded := 0; encoded < 256; encoded++ {
  65. count := decodeCount(uint8(encoded))
  66. if count >= i {
  67. return uint8(encoded)
  68. }
  69. }
  70. return 255
  71. }
  72. // decodeCount returns the s2k mode 3 iterative "count" corresponding to
  73. // the encoded octet c.
  74. func decodeCount(c uint8) int {
  75. return (16 + int(c&15)) << (uint32(c>>4) + 6)
  76. }
  77. // Simple writes to out the result of computing the Simple S2K function (RFC
  78. // 4880, section 3.7.1.1) using the given hash and input passphrase.
  79. func Simple(out []byte, h hash.Hash, in []byte) {
  80. Salted(out, h, in, nil)
  81. }
  82. var zero [1]byte
  83. // Salted writes to out the result of computing the Salted S2K function (RFC
  84. // 4880, section 3.7.1.2) using the given hash, input passphrase and salt.
  85. func Salted(out []byte, h hash.Hash, in []byte, salt []byte) {
  86. done := 0
  87. var digest []byte
  88. for i := 0; done < len(out); i++ {
  89. h.Reset()
  90. for j := 0; j < i; j++ {
  91. h.Write(zero[:])
  92. }
  93. h.Write(salt)
  94. h.Write(in)
  95. digest = h.Sum(digest[:0])
  96. n := copy(out[done:], digest)
  97. done += n
  98. }
  99. }
  100. // Iterated writes to out the result of computing the Iterated and Salted S2K
  101. // function (RFC 4880, section 3.7.1.3) using the given hash, input passphrase,
  102. // salt and iteration count.
  103. func Iterated(out []byte, h hash.Hash, in []byte, salt []byte, count int) {
  104. combined := make([]byte, len(in)+len(salt))
  105. copy(combined, salt)
  106. copy(combined[len(salt):], in)
  107. if count < len(combined) {
  108. count = len(combined)
  109. }
  110. done := 0
  111. var digest []byte
  112. for i := 0; done < len(out); i++ {
  113. h.Reset()
  114. for j := 0; j < i; j++ {
  115. h.Write(zero[:])
  116. }
  117. written := 0
  118. for written < count {
  119. if written+len(combined) > count {
  120. todo := count - written
  121. h.Write(combined[:todo])
  122. written = count
  123. } else {
  124. h.Write(combined)
  125. written += len(combined)
  126. }
  127. }
  128. digest = h.Sum(digest[:0])
  129. n := copy(out[done:], digest)
  130. done += n
  131. }
  132. }
  133. func parseGNUExtensions(r io.Reader) (f func(out, in []byte), err error) {
  134. var buf [9]byte
  135. // A three-byte string identifier
  136. _, err = io.ReadFull(r, buf[:3])
  137. if err != nil {
  138. return
  139. }
  140. gnuExt := string(buf[:3])
  141. if gnuExt != "GNU" {
  142. return nil, errors.UnsupportedError("Malformed GNU extension: " + gnuExt)
  143. }
  144. _, err = io.ReadFull(r, buf[:1])
  145. if err != nil {
  146. return
  147. }
  148. gnuExtType := int(buf[0])
  149. switch gnuExtType {
  150. case 1:
  151. return nil, nil
  152. case 2:
  153. // Read a serial number, which is prefixed by a 1-byte length.
  154. // The maximum length is 16.
  155. var lenBuf [1]byte
  156. _, err = io.ReadFull(r, lenBuf[:])
  157. if err != nil {
  158. return
  159. }
  160. maxLen := 16
  161. ivLen := int(lenBuf[0])
  162. if ivLen > maxLen {
  163. ivLen = maxLen
  164. }
  165. ivBuf := make([]byte, ivLen)
  166. // For now we simply discard the IV
  167. _, err = io.ReadFull(r, ivBuf)
  168. if err != nil {
  169. return
  170. }
  171. return nil, nil
  172. default:
  173. return nil, errors.UnsupportedError("unknown S2K GNU protection mode: " + strconv.Itoa(int(gnuExtType)))
  174. }
  175. }
  176. // Parse reads a binary specification for a string-to-key transformation from r
  177. // and returns a function which performs that transform.
  178. func Parse(r io.Reader) (f func(out, in []byte), err error) {
  179. var buf [9]byte
  180. _, err = io.ReadFull(r, buf[:2])
  181. if err != nil {
  182. return
  183. }
  184. // GNU Extensions; handle them before we try to look for a hash, which won't
  185. // be needed in most cases anyway.
  186. if buf[0] == 101 {
  187. return parseGNUExtensions(r)
  188. }
  189. hash, ok := HashIdToHash(buf[1])
  190. if !ok {
  191. return nil, errors.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(buf[1])))
  192. }
  193. if !hash.Available() {
  194. return nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hash)))
  195. }
  196. h := hash.New()
  197. switch buf[0] {
  198. case 0:
  199. f := func(out, in []byte) {
  200. Simple(out, h, in)
  201. }
  202. return f, nil
  203. case 1:
  204. _, err = io.ReadFull(r, buf[:8])
  205. if err != nil {
  206. return
  207. }
  208. f := func(out, in []byte) {
  209. Salted(out, h, in, buf[:8])
  210. }
  211. return f, nil
  212. case 3:
  213. _, err = io.ReadFull(r, buf[:9])
  214. if err != nil {
  215. return
  216. }
  217. count := decodeCount(buf[8])
  218. f := func(out, in []byte) {
  219. Iterated(out, h, in, buf[:8], count)
  220. }
  221. return f, nil
  222. }
  223. return nil, errors.UnsupportedError("S2K function")
  224. }
  225. // Serialize salts and stretches the given passphrase and writes the
  226. // resulting key into key. It also serializes an S2K descriptor to
  227. // w. The key stretching can be configured with c, which may be
  228. // nil. In that case, sensible defaults will be used.
  229. func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte, c *Config) error {
  230. var buf [11]byte
  231. buf[0] = 3 /* iterated and salted */
  232. buf[1], _ = HashToHashId(c.hash())
  233. salt := buf[2:10]
  234. if _, err := io.ReadFull(rand, salt); err != nil {
  235. return err
  236. }
  237. encodedCount := c.encodedCount()
  238. count := decodeCount(encodedCount)
  239. buf[10] = encodedCount
  240. if _, err := w.Write(buf[:]); err != nil {
  241. return err
  242. }
  243. Iterated(key, c.hash().New(), passphrase, salt, count)
  244. return nil
  245. }
  246. // hashToHashIdMapping contains pairs relating OpenPGP's hash identifier with
  247. // Go's crypto.Hash type. See RFC 4880, section 9.4.
  248. var hashToHashIdMapping = []struct {
  249. id byte
  250. hash crypto.Hash
  251. name string
  252. }{
  253. {1, crypto.MD5, "MD5"},
  254. {2, crypto.SHA1, "SHA1"},
  255. {3, crypto.RIPEMD160, "RIPEMD160"},
  256. {8, crypto.SHA256, "SHA256"},
  257. {9, crypto.SHA384, "SHA384"},
  258. {10, crypto.SHA512, "SHA512"},
  259. {11, crypto.SHA224, "SHA224"},
  260. }
  261. // HashIdToHash returns a crypto.Hash which corresponds to the given OpenPGP
  262. // hash id.
  263. func HashIdToHash(id byte) (h crypto.Hash, ok bool) {
  264. for _, m := range hashToHashIdMapping {
  265. if m.id == id {
  266. return m.hash, true
  267. }
  268. }
  269. return 0, false
  270. }
  271. // HashIdToString returns the name of the hash function corresponding to the
  272. // given OpenPGP hash id, or panics if id is unknown.
  273. func HashIdToString(id byte) (name string, ok bool) {
  274. for _, m := range hashToHashIdMapping {
  275. if m.id == id {
  276. return m.name, true
  277. }
  278. }
  279. return "", false
  280. }
  281. // HashIdToHash returns an OpenPGP hash id which corresponds the given Hash.
  282. func HashToHashId(h crypto.Hash) (id byte, ok bool) {
  283. for _, m := range hashToHashIdMapping {
  284. if m.hash == h {
  285. return m.id, true
  286. }
  287. }
  288. return 0, false
  289. }