...

Source file src/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k.go

Documentation: github.com/ProtonMail/go-crypto/openpgp/s2k

     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.
     8  package s2k // import "github.com/ProtonMail/go-crypto/openpgp/s2k"
     9  
    10  import (
    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  
    21  type Mode uint8
    22  
    23  // Defines the default S2KMode constants
    24  //
    25  //	0 (simple), 1(salted), 3(iterated), 4(argon2)
    26  const (
    27  	SimpleS2K         Mode = 0
    28  	SaltedS2K         Mode = 1
    29  	IteratedSaltedS2K Mode = 3
    30  	Argon2S2K         Mode = 4
    31  	GnuS2K            Mode = 101
    32  )
    33  
    34  const Argon2SaltSize int = 16
    35  
    36  // Params contains all the parameters of the s2k packet
    37  type 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.
    66  func 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.
    83  func 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.
    92  func 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
   108  func 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.
   114  func Simple(out []byte, h hash.Hash, in []byte) {
   115  	Salted(out, h, in, nil)
   116  }
   117  
   118  var 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.
   122  func 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.
   142  func 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)
   177  func 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.
   184  func 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.
   229  func 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.
   240  func 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  		return params, nil
   287  	case GnuS2K:
   288  		// This is a GNU extension. See
   289  		// https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=doc/DETAILS;h=fe55ae16ab4e26d8356dc574c9e8bc935e71aef1;hb=23191d7851eae2217ecdac6484349849a24fd94a#l1109
   290  		if _, err = io.ReadFull(r, buf[:5]); err != nil {
   291  			return nil, err
   292  		}
   293  		params.hashId = buf[0]
   294  		if buf[1] == 'G' && buf[2] == 'N' && buf[3] == 'U' && buf[4] == 1 {
   295  			return params, nil
   296  		}
   297  		return nil, errors.UnsupportedError("GNU S2K extension")
   298  	}
   299  
   300  	return nil, errors.UnsupportedError("S2K function")
   301  }
   302  
   303  func (params *Params) Dummy() bool {
   304  	return params != nil && params.mode == GnuS2K
   305  }
   306  
   307  func (params *Params) salt() []byte {
   308  	switch params.mode {
   309  		case SaltedS2K, IteratedSaltedS2K: return params.saltBytes[:8]
   310  		case Argon2S2K: return params.saltBytes[:Argon2SaltSize]
   311  		default: return nil
   312  	}
   313  }
   314  
   315  func (params *Params) Function() (f func(out, in []byte), err error) {
   316  	if params.Dummy() {
   317  		return nil, errors.ErrDummyPrivateKey("dummy key found")
   318  	}
   319  	var hashObj crypto.Hash
   320  	if params.mode != Argon2S2K {
   321  		var ok bool
   322  		hashObj, ok = algorithm.HashIdToHashWithSha1(params.hashId)
   323  		if !ok {
   324  			return nil, errors.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(params.hashId)))
   325  		}
   326  		if !hashObj.Available() {
   327  			return nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashObj)))
   328  		}
   329  	}
   330  
   331  	switch params.mode {
   332  	case SimpleS2K:
   333  		f := func(out, in []byte) {
   334  			Simple(out, hashObj.New(), in)
   335  		}
   336  
   337  		return f, nil
   338  	case SaltedS2K:
   339  		f := func(out, in []byte) {
   340  			Salted(out, hashObj.New(), in, params.salt())
   341  		}
   342  
   343  		return f, nil
   344  	case IteratedSaltedS2K:
   345  		f := func(out, in []byte) {
   346  			Iterated(out, hashObj.New(), in, params.salt(), decodeCount(params.countByte))
   347  		}
   348  
   349  		return f, nil
   350  	case Argon2S2K:
   351  		f := func(out, in []byte) {
   352  			Argon2(out, in, params.salt(), params.passes, params.parallelism, params.memoryExp)
   353  		}
   354  		return f, nil
   355  	}
   356  
   357  	return nil, errors.UnsupportedError("S2K function")
   358  }
   359  
   360  func (params *Params) Serialize(w io.Writer) (err error) {
   361  	if _, err = w.Write([]byte{uint8(params.mode)}); err != nil {
   362  		return
   363  	}
   364  	if params.mode != Argon2S2K {
   365  		if _, err = w.Write([]byte{params.hashId}); err != nil {
   366  			return
   367  		}
   368  	}
   369  	if params.Dummy() {
   370  		_, err = w.Write(append([]byte("GNU"), 1))
   371  		return
   372  	}
   373  	if params.mode > 0 {
   374  		if _, err = w.Write(params.salt()); err != nil {
   375  			return
   376  		}
   377  		if params.mode == IteratedSaltedS2K {
   378  			_, err = w.Write([]byte{params.countByte})
   379  		}
   380  		if params.mode == Argon2S2K {
   381  			_, err = w.Write([]byte{params.passes, params.parallelism, params.memoryExp})
   382  		}
   383  	}
   384  	return
   385  }
   386  
   387  // Serialize salts and stretches the given passphrase and writes the
   388  // resulting key into key. It also serializes an S2K descriptor to
   389  // w. The key stretching can be configured with c, which may be
   390  // nil. In that case, sensible defaults will be used.
   391  func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte, c *Config) error {
   392  	params, err := Generate(rand, c)
   393  	if err != nil {
   394  		return err
   395  	}
   396  	err = params.Serialize(w)
   397  	if err != nil {
   398  		return err
   399  	}
   400  
   401  	f, err := params.Function()
   402  	if err != nil {
   403  		return err
   404  	}
   405  	f(key, passphrase)
   406  	return nil
   407  }
   408  

View as plain text