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