main
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, and Argon2 specified in
7// draft-ietf-openpgp-crypto-refresh-08 section 3.7.1.4.
8package s2k // import "github.com/ProtonMail/go-crypto/openpgp/s2k"
9
10import (
11 "crypto"
12 "hash"
13 "io"
14 "strconv"
15
16 "github.com/ProtonMail/go-crypto/openpgp/errors"
17 "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm"
18 "golang.org/x/crypto/argon2"
19)
20
21type Mode uint8
22
23// Defines the default S2KMode constants
24//
25// 0 (simple), 1(salted), 3(iterated), 4(argon2)
26const (
27 SimpleS2K Mode = 0
28 SaltedS2K Mode = 1
29 IteratedSaltedS2K Mode = 3
30 Argon2S2K Mode = 4
31 GnuS2K Mode = 101
32)
33
34const Argon2SaltSize int = 16
35
36// Params contains all the parameters of the s2k packet
37type Params struct {
38 // mode is the mode of s2k function.
39 // It can be 0 (simple), 1(salted), 3(iterated)
40 // 2(reserved) 100-110(private/experimental).
41 mode Mode
42 // hashId is the ID of the hash function used in any of the modes
43 hashId byte
44 // salt is a byte array to use as a salt in hashing process or argon2
45 saltBytes [Argon2SaltSize]byte
46 // countByte is used to determine how many rounds of hashing are to
47 // be performed in s2k mode 3. See RFC 4880 Section 3.7.1.3.
48 countByte byte
49 // passes is a parameter in Argon2 to determine the number of iterations
50 // See RFC the crypto refresh Section 3.7.1.4.
51 passes byte
52 // parallelism is a parameter in Argon2 to determine the degree of paralellism
53 // See RFC the crypto refresh Section 3.7.1.4.
54 parallelism byte
55 // memoryExp is a parameter in Argon2 to determine the memory usage
56 // i.e., 2 ** memoryExp kibibytes
57 // See RFC the crypto refresh Section 3.7.1.4.
58 memoryExp byte
59}
60
61// encodeCount converts an iterative "count" in the range 1024 to
62// 65011712, inclusive, to an encoded count. The return value is the
63// octet that is actually stored in the GPG file. encodeCount panics
64// if i is not in the above range (encodedCount above takes care to
65// pass i in the correct range). See RFC 4880 Section 3.7.7.1.
66func encodeCount(i int) uint8 {
67 if i < 65536 || i > 65011712 {
68 panic("count arg i outside the required range")
69 }
70
71 for encoded := 96; encoded < 256; encoded++ {
72 count := decodeCount(uint8(encoded))
73 if count >= i {
74 return uint8(encoded)
75 }
76 }
77
78 return 255
79}
80
81// decodeCount returns the s2k mode 3 iterative "count" corresponding to
82// the encoded octet c.
83func decodeCount(c uint8) int {
84 return (16 + int(c&15)) << (uint32(c>>4) + 6)
85}
86
87// encodeMemory converts the Argon2 "memory" in the range parallelism*8 to
88// 2**31, inclusive, to an encoded memory. The return value is the
89// octet that is actually stored in the GPG file. encodeMemory panics
90// if is not in the above range
91// See OpenPGP crypto refresh Section 3.7.1.4.
92func encodeMemory(memory uint32, parallelism uint8) uint8 {
93 if memory < (8*uint32(parallelism)) || memory > uint32(2147483648) {
94 panic("Memory argument memory is outside the required range")
95 }
96
97 for exp := 3; exp < 31; exp++ {
98 compare := decodeMemory(uint8(exp))
99 if compare >= memory {
100 return uint8(exp)
101 }
102 }
103
104 return 31
105}
106
107// decodeMemory computes the decoded memory in kibibytes as 2**memoryExponent
108func decodeMemory(memoryExponent uint8) uint32 {
109 return uint32(1) << memoryExponent
110}
111
112// Simple writes to out the result of computing the Simple S2K function (RFC
113// 4880, section 3.7.1.1) using the given hash and input passphrase.
114func Simple(out []byte, h hash.Hash, in []byte) {
115 Salted(out, h, in, nil)
116}
117
118var zero [1]byte
119
120// Salted writes to out the result of computing the Salted S2K function (RFC
121// 4880, section 3.7.1.2) using the given hash, input passphrase and salt.
122func Salted(out []byte, h hash.Hash, in []byte, salt []byte) {
123 done := 0
124 var digest []byte
125
126 for i := 0; done < len(out); i++ {
127 h.Reset()
128 for j := 0; j < i; j++ {
129 h.Write(zero[:])
130 }
131 h.Write(salt)
132 h.Write(in)
133 digest = h.Sum(digest[:0])
134 n := copy(out[done:], digest)
135 done += n
136 }
137}
138
139// Iterated writes to out the result of computing the Iterated and Salted S2K
140// function (RFC 4880, section 3.7.1.3) using the given hash, input passphrase,
141// salt and iteration count.
142func Iterated(out []byte, h hash.Hash, in []byte, salt []byte, count int) {
143 combined := make([]byte, len(in)+len(salt))
144 copy(combined, salt)
145 copy(combined[len(salt):], in)
146
147 if count < len(combined) {
148 count = len(combined)
149 }
150
151 done := 0
152 var digest []byte
153 for i := 0; done < len(out); i++ {
154 h.Reset()
155 for j := 0; j < i; j++ {
156 h.Write(zero[:])
157 }
158 written := 0
159 for written < count {
160 if written+len(combined) > count {
161 todo := count - written
162 h.Write(combined[:todo])
163 written = count
164 } else {
165 h.Write(combined)
166 written += len(combined)
167 }
168 }
169 digest = h.Sum(digest[:0])
170 n := copy(out[done:], digest)
171 done += n
172 }
173}
174
175// Argon2 writes to out the key derived from the password (in) with the Argon2
176// function (the crypto refresh, section 3.7.1.4)
177func Argon2(out []byte, in []byte, salt []byte, passes uint8, paralellism uint8, memoryExp uint8) {
178 key := argon2.IDKey(in, salt, uint32(passes), decodeMemory(memoryExp), paralellism, uint32(len(out)))
179 copy(out[:], key)
180}
181
182// Generate generates valid parameters from given configuration.
183// It will enforce the Iterated and Salted or Argon2 S2K method.
184func Generate(rand io.Reader, c *Config) (*Params, error) {
185 var params *Params
186 if c != nil && c.Mode() == Argon2S2K {
187 // handle Argon2 case
188 argonConfig := c.Argon2()
189 params = &Params{
190 mode: Argon2S2K,
191 passes: argonConfig.Passes(),
192 parallelism: argonConfig.Parallelism(),
193 memoryExp: argonConfig.EncodedMemory(),
194 }
195 } else if c != nil && c.PassphraseIsHighEntropy && c.Mode() == SaltedS2K { // Allow SaltedS2K if PassphraseIsHighEntropy
196 hashId, ok := algorithm.HashToHashId(c.hash())
197 if !ok {
198 return nil, errors.UnsupportedError("no such hash")
199 }
200
201 params = &Params{
202 mode: SaltedS2K,
203 hashId: hashId,
204 }
205 } else { // Enforce IteratedSaltedS2K method otherwise
206 hashId, ok := algorithm.HashToHashId(c.hash())
207 if !ok {
208 return nil, errors.UnsupportedError("no such hash")
209 }
210 if c != nil {
211 c.S2KMode = IteratedSaltedS2K
212 }
213 params = &Params{
214 mode: IteratedSaltedS2K,
215 hashId: hashId,
216 countByte: c.EncodedCount(),
217 }
218 }
219 if _, err := io.ReadFull(rand, params.salt()); err != nil {
220 return nil, err
221 }
222 return params, nil
223}
224
225// Parse reads a binary specification for a string-to-key transformation from r
226// and returns a function which performs that transform. If the S2K is a special
227// GNU extension that indicates that the private key is missing, then the error
228// returned is errors.ErrDummyPrivateKey.
229func Parse(r io.Reader) (f func(out, in []byte), err error) {
230 params, err := ParseIntoParams(r)
231 if err != nil {
232 return nil, err
233 }
234
235 return params.Function()
236}
237
238// ParseIntoParams reads a binary specification for a string-to-key
239// transformation from r and returns a struct describing the s2k parameters.
240func ParseIntoParams(r io.Reader) (params *Params, err error) {
241 var buf [Argon2SaltSize + 3]byte
242
243 _, err = io.ReadFull(r, buf[:1])
244 if err != nil {
245 return
246 }
247
248 params = &Params{
249 mode: Mode(buf[0]),
250 }
251
252 switch params.mode {
253 case SimpleS2K:
254 _, err = io.ReadFull(r, buf[:1])
255 if err != nil {
256 return nil, err
257 }
258 params.hashId = buf[0]
259 return params, nil
260 case SaltedS2K:
261 _, err = io.ReadFull(r, buf[:9])
262 if err != nil {
263 return nil, err
264 }
265 params.hashId = buf[0]
266 copy(params.salt(), buf[1:9])
267 return params, nil
268 case IteratedSaltedS2K:
269 _, err = io.ReadFull(r, buf[:10])
270 if err != nil {
271 return nil, err
272 }
273 params.hashId = buf[0]
274 copy(params.salt(), buf[1:9])
275 params.countByte = buf[9]
276 return params, nil
277 case Argon2S2K:
278 _, err = io.ReadFull(r, buf[:Argon2SaltSize+3])
279 if err != nil {
280 return nil, err
281 }
282 copy(params.salt(), buf[:Argon2SaltSize])
283 params.passes = buf[Argon2SaltSize]
284 params.parallelism = buf[Argon2SaltSize+1]
285 params.memoryExp = buf[Argon2SaltSize+2]
286 if err := validateArgon2Params(params); err != nil {
287 return nil, err
288 }
289 return params, nil
290 case GnuS2K:
291 // This is a GNU extension. See
292 // https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=doc/DETAILS;h=fe55ae16ab4e26d8356dc574c9e8bc935e71aef1;hb=23191d7851eae2217ecdac6484349849a24fd94a#l1109
293 if _, err = io.ReadFull(r, buf[:5]); err != nil {
294 return nil, err
295 }
296 params.hashId = buf[0]
297 if buf[1] == 'G' && buf[2] == 'N' && buf[3] == 'U' && buf[4] == 1 {
298 return params, nil
299 }
300 return nil, errors.UnsupportedError("GNU S2K extension")
301 }
302
303 return nil, errors.UnsupportedError("S2K function")
304}
305
306func (params *Params) Mode() Mode {
307 return params.mode
308}
309
310func (params *Params) Dummy() bool {
311 return params != nil && params.mode == GnuS2K
312}
313
314func (params *Params) salt() []byte {
315 switch params.mode {
316 case SaltedS2K, IteratedSaltedS2K:
317 return params.saltBytes[:8]
318 case Argon2S2K:
319 return params.saltBytes[:Argon2SaltSize]
320 default:
321 return nil
322 }
323}
324
325func (params *Params) Function() (f func(out, in []byte), err error) {
326 if params.Dummy() {
327 return nil, errors.ErrDummyPrivateKey("dummy key found")
328 }
329 var hashObj crypto.Hash
330 if params.mode != Argon2S2K {
331 var ok bool
332 hashObj, ok = algorithm.HashIdToHashWithSha1(params.hashId)
333 if !ok {
334 return nil, errors.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(params.hashId)))
335 }
336 if !hashObj.Available() {
337 return nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashObj)))
338 }
339 }
340
341 switch params.mode {
342 case SimpleS2K:
343 f := func(out, in []byte) {
344 Simple(out, hashObj.New(), in)
345 }
346
347 return f, nil
348 case SaltedS2K:
349 f := func(out, in []byte) {
350 Salted(out, hashObj.New(), in, params.salt())
351 }
352
353 return f, nil
354 case IteratedSaltedS2K:
355 f := func(out, in []byte) {
356 Iterated(out, hashObj.New(), in, params.salt(), decodeCount(params.countByte))
357 }
358
359 return f, nil
360 case Argon2S2K:
361 f := func(out, in []byte) {
362 Argon2(out, in, params.salt(), params.passes, params.parallelism, params.memoryExp)
363 }
364 return f, nil
365 }
366
367 return nil, errors.UnsupportedError("S2K function")
368}
369
370func (params *Params) Serialize(w io.Writer) (err error) {
371 if _, err = w.Write([]byte{uint8(params.mode)}); err != nil {
372 return
373 }
374 if params.mode != Argon2S2K {
375 if _, err = w.Write([]byte{params.hashId}); err != nil {
376 return
377 }
378 }
379 if params.Dummy() {
380 _, err = w.Write(append([]byte("GNU"), 1))
381 return
382 }
383 if params.mode > 0 {
384 if _, err = w.Write(params.salt()); err != nil {
385 return
386 }
387 if params.mode == IteratedSaltedS2K {
388 _, err = w.Write([]byte{params.countByte})
389 }
390 if params.mode == Argon2S2K {
391 _, err = w.Write([]byte{params.passes, params.parallelism, params.memoryExp})
392 }
393 }
394 return
395}
396
397// Serialize salts and stretches the given passphrase and writes the
398// resulting key into key. It also serializes an S2K descriptor to
399// w. The key stretching can be configured with c, which may be
400// nil. In that case, sensible defaults will be used.
401func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte, c *Config) error {
402 params, err := Generate(rand, c)
403 if err != nil {
404 return err
405 }
406 err = params.Serialize(w)
407 if err != nil {
408 return err
409 }
410
411 f, err := params.Function()
412 if err != nil {
413 return err
414 }
415 f(key, passphrase)
416 return nil
417}
418
419// validateArgon2Params checks that the argon2 parameters are valid according to RFC9580.
420func validateArgon2Params(params *Params) error {
421 // The number of passes t and the degree of parallelism p MUST be non-zero.
422 if params.parallelism == 0 {
423 return errors.StructuralError("invalid argon2 params: parallelism is 0")
424 }
425 if params.passes == 0 {
426 return errors.StructuralError("invalid argon2 params: iterations is 0")
427 }
428
429 // The encoded memory size MUST be a value from 3+ceil(log2(p)) to 31,
430 // such that the decoded memory size m is a value from 8*p to 2^31.
431 if params.memoryExp > 31 || decodeMemory(params.memoryExp) < 8*uint32(params.parallelism) {
432 return errors.StructuralError("invalid argon2 params: memory is out of bounds")
433 }
434
435 return nil
436}