util.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package key
  4. import (
  5. crand "crypto/rand"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "slices"
  12. "go4.org/mem"
  13. )
  14. // rand fills b with cryptographically strong random bytes. Panics if
  15. // no random bytes are available.
  16. func rand(b []byte) {
  17. if _, err := io.ReadFull(crand.Reader, b[:]); err != nil {
  18. panic(fmt.Sprintf("unable to read random bytes from OS: %v", err))
  19. }
  20. }
  21. // clamp25519 clamps b, which must be a 32-byte Curve25519 private
  22. // key, to a safe value.
  23. //
  24. // The clamping effectively constrains the key to a number between
  25. // 2^251 and 2^252-1, which is then multiplied by 8 (the cofactor of
  26. // Curve25519). This produces a value that doesn't have any unsafe
  27. // properties when doing operations like ScalarMult.
  28. //
  29. // See
  30. // https://web.archive.org/web/20210228105330/https://neilmadden.blog/2020/05/28/whats-the-curve25519-clamping-all-about/
  31. // for a more in-depth explanation of the constraints that led to this
  32. // clamping requirement.
  33. //
  34. // PLEASE NOTE that not all Curve25519 values require clamping. When
  35. // implementing a new key type that uses Curve25519, you must evaluate
  36. // whether that particular key's use requires clamping. Here are some
  37. // existing uses and whether you should clamp private keys at
  38. // creation.
  39. //
  40. // - NaCl box: yes, clamp at creation.
  41. // - WireGuard (userspace uapi or kernel): no, do not clamp.
  42. // - Noise protocols: no, do not clamp.
  43. func clamp25519Private(b []byte) {
  44. b[0] &= 248
  45. b[31] = (b[31] & 127) | 64
  46. }
  47. func appendHexKey(dst []byte, prefix string, key []byte) []byte {
  48. dst = slices.Grow(dst, len(prefix)+hex.EncodedLen(len(key)))
  49. dst = append(dst, prefix...)
  50. dst = hexAppendEncode(dst, key)
  51. return dst
  52. }
  53. // TODO(https://go.dev/issue/53693): Use hex.AppendEncode instead.
  54. func hexAppendEncode(dst, src []byte) []byte {
  55. n := hex.EncodedLen(len(src))
  56. dst = slices.Grow(dst, n)
  57. hex.Encode(dst[len(dst):][:n], src)
  58. return dst[:len(dst)+n]
  59. }
  60. // parseHex decodes a key string of the form "<prefix><hex string>"
  61. // into out. The prefix must match, and the decoded base64 must fit
  62. // exactly into out.
  63. //
  64. // Note the errors in this function deliberately do not echo the
  65. // contents of in, because it might be a private key or part of a
  66. // private key.
  67. func parseHex(out []byte, in, prefix mem.RO) error {
  68. if !mem.HasPrefix(in, prefix) {
  69. return fmt.Errorf("key hex string doesn't have expected type prefix %s", prefix.StringCopy())
  70. }
  71. in = in.SliceFrom(prefix.Len())
  72. if want := len(out) * 2; in.Len() != want {
  73. return fmt.Errorf("key hex has the wrong size, got %d want %d", in.Len(), want)
  74. }
  75. for i := range out {
  76. a, ok1 := fromHexChar(in.At(i*2 + 0))
  77. b, ok2 := fromHexChar(in.At(i*2 + 1))
  78. if !ok1 || !ok2 {
  79. return errors.New("invalid hex character in key")
  80. }
  81. out[i] = (a << 4) | b
  82. }
  83. return nil
  84. }
  85. // fromHexChar converts a hex character into its value and a success flag.
  86. func fromHexChar(c byte) (byte, bool) {
  87. switch {
  88. case '0' <= c && c <= '9':
  89. return c - '0', true
  90. case 'a' <= c && c <= 'f':
  91. return c - 'a' + 10, true
  92. case 'A' <= c && c <= 'F':
  93. return c - 'A' + 10, true
  94. }
  95. return 0, false
  96. }
  97. // debug32 returns the Tailscale conventional debug representation of
  98. // a key: the first five base64 digits of the key, in square brackets.
  99. func debug32(k [32]byte) string {
  100. if k == [32]byte{} {
  101. return ""
  102. }
  103. // The goal here is to generate "[" + base64.StdEncoding.EncodeToString(k[:])[:5] + "]".
  104. // Since we only care about the first 5 characters, it suffices to encode the first 4 bytes of k.
  105. // Encoding those 4 bytes requires 8 bytes.
  106. // Make dst have size 9, to fit the leading '[' plus those 8 bytes.
  107. // We slice the unused ones away at the end.
  108. dst := make([]byte, 9)
  109. dst[0] = '['
  110. base64.StdEncoding.Encode(dst[1:], k[:4])
  111. dst[6] = ']'
  112. return string(dst[:7])
  113. }