encryption_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. // Copyright (C) 2019 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package protocol
  7. import (
  8. "bytes"
  9. "fmt"
  10. "reflect"
  11. "regexp"
  12. "strings"
  13. "sync"
  14. "testing"
  15. "github.com/syncthing/syncthing/lib/rand"
  16. "github.com/syncthing/syncthing/lib/sha256"
  17. )
  18. func TestEnDecryptName(t *testing.T) {
  19. pattern := regexp.MustCompile(
  20. fmt.Sprintf("^[0-9A-V]%s/[0-9A-V]{2}/([0-9A-V]{%d}/)*[0-9A-V]{1,%d}$",
  21. regexp.QuoteMeta(encryptedDirExtension),
  22. maxPathComponent, maxPathComponent-1))
  23. makeName := func(n int) string {
  24. b := make([]byte, n)
  25. for i := range b {
  26. b[i] = byte('a' + i%26)
  27. }
  28. return string(b)
  29. }
  30. var key [32]byte
  31. cases := []string{
  32. "",
  33. "foo",
  34. "a longer name/with/slashes and spaces",
  35. makeName(maxPathComponent),
  36. makeName(1 + maxPathComponent),
  37. makeName(2 * maxPathComponent),
  38. makeName(1 + 2*maxPathComponent),
  39. }
  40. for _, tc := range cases {
  41. var prev string
  42. for i := 0; i < 5; i++ {
  43. enc := encryptName(tc, &key)
  44. if prev != "" && prev != enc {
  45. t.Error("name should always encrypt the same")
  46. }
  47. prev = enc
  48. if tc != "" && strings.Contains(enc, tc) {
  49. t.Error("shouldn't contain plaintext")
  50. }
  51. if !pattern.MatchString(enc) {
  52. t.Fatalf("encrypted name %s doesn't match %s",
  53. enc, pattern)
  54. }
  55. dec, err := decryptName(enc, &key)
  56. if err != nil {
  57. t.Error(err)
  58. }
  59. if dec != tc {
  60. t.Error("mismatch after decryption")
  61. }
  62. t.Logf("%q encrypts as %q", tc, enc)
  63. }
  64. }
  65. }
  66. func TestKeyDerivation(t *testing.T) {
  67. folderKey := KeyFromPassword("my folder", "my password")
  68. encryptedName := encryptDeterministic([]byte("filename.txt"), folderKey, nil)
  69. if base32Hex.EncodeToString(encryptedName) != "3T5957I4IOA20VEIEER6JSQG0PEPIRV862II3K7LOF75Q" {
  70. t.Error("encrypted name mismatch")
  71. }
  72. fileKey := FileKey("filename.txt", folderKey)
  73. // fmt.Println(base32Hex.EncodeToString(encryptBytes([]byte("hello world"), fileKey))) => A1IPD...
  74. const encrypted = `A1IPD28ISL7VNPRSSSQM2L31L3IJPC08283RO89J5UG0TI9P38DO9RFGK12DK0KD7PKQP6U51UL2B6H96O`
  75. bs, _ := base32Hex.DecodeString(encrypted)
  76. dec, err := DecryptBytes(bs, fileKey)
  77. if err != nil {
  78. t.Error(err)
  79. }
  80. if string(dec) != "hello world" {
  81. t.Error("decryption mismatch")
  82. }
  83. }
  84. func TestDecryptNameInvalid(t *testing.T) {
  85. key := new([32]byte)
  86. for _, c := range []string{
  87. "T.syncthing-enc/OD",
  88. "T.syncthing-enc/OD/",
  89. "T.wrong-extension/OD/PHVDD67S7FI2K5QQMPSOFSK",
  90. "OD/PHVDD67S7FI2K5QQMPSOFSK",
  91. } {
  92. if _, err := decryptName(c, key); err == nil {
  93. t.Errorf("no error for %q", c)
  94. }
  95. }
  96. }
  97. func TestEnDecryptBytes(t *testing.T) {
  98. var key [32]byte
  99. cases := [][]byte{
  100. {},
  101. {1, 2, 3, 4, 5},
  102. }
  103. for _, tc := range cases {
  104. var prev []byte
  105. for i := 0; i < 5; i++ {
  106. enc := encryptBytes(tc, &key)
  107. if bytes.Equal(enc, prev) {
  108. t.Error("encryption should not repeat")
  109. }
  110. prev = enc
  111. if len(tc) > 0 && bytes.Contains(enc, tc) {
  112. t.Error("shouldn't contain plaintext")
  113. }
  114. dec, err := DecryptBytes(enc, &key)
  115. if err != nil {
  116. t.Error(err)
  117. }
  118. if !bytes.Equal(dec, tc) {
  119. t.Error("mismatch after decryption")
  120. }
  121. }
  122. }
  123. }
  124. func encFileInfo() FileInfo {
  125. return FileInfo{
  126. Name: "hello",
  127. Size: 45,
  128. Permissions: 0755,
  129. ModifiedS: 8080,
  130. Sequence: 1000,
  131. Blocks: []BlockInfo{
  132. {
  133. Offset: 0,
  134. Size: 45,
  135. Hash: []byte{1, 2, 3},
  136. },
  137. {
  138. Offset: 45,
  139. Size: 45,
  140. Hash: []byte{1, 2, 3},
  141. },
  142. },
  143. }
  144. }
  145. func TestEnDecryptFileInfo(t *testing.T) {
  146. var key [32]byte
  147. fi := encFileInfo()
  148. enc := encryptFileInfo(fi, &key)
  149. if bytes.Equal(enc.Blocks[0].Hash, enc.Blocks[1].Hash) {
  150. t.Error("block hashes should not repeat when on different offsets")
  151. }
  152. if enc.RawBlockSize < MinBlockSize {
  153. t.Error("Too small raw block size:", enc.RawBlockSize)
  154. }
  155. if enc.Sequence != fi.Sequence {
  156. t.Error("encrypted fileinfo didn't maintain sequence number")
  157. }
  158. again := encryptFileInfo(fi, &key)
  159. if !bytes.Equal(enc.Blocks[0].Hash, again.Blocks[0].Hash) {
  160. t.Error("block hashes should remain stable (0)")
  161. }
  162. if !bytes.Equal(enc.Blocks[1].Hash, again.Blocks[1].Hash) {
  163. t.Error("block hashes should remain stable (1)")
  164. }
  165. // Simulate the remote setting the sequence number when writing to db
  166. enc.Sequence = 10
  167. dec, err := DecryptFileInfo(enc, &key)
  168. if err != nil {
  169. t.Error(err)
  170. }
  171. if dec.Sequence != enc.Sequence {
  172. t.Error("decrypted fileinfo didn't maintain sequence number")
  173. }
  174. dec.Sequence = fi.Sequence
  175. if !reflect.DeepEqual(fi, dec) {
  176. t.Error("mismatch after decryption")
  177. }
  178. }
  179. func TestEncryptedFileInfoConsistency(t *testing.T) {
  180. var key [32]byte
  181. files := []FileInfo{
  182. encFileInfo(),
  183. encFileInfo(),
  184. }
  185. files[1].SetIgnored()
  186. for i, f := range files {
  187. enc := encryptFileInfo(f, &key)
  188. if err := checkFileInfoConsistency(enc); err != nil {
  189. t.Errorf("%v: %v", i, err)
  190. }
  191. }
  192. }
  193. func TestIsEncryptedParent(t *testing.T) {
  194. comp := rand.String(maxPathComponent)
  195. cases := []struct {
  196. path string
  197. is bool
  198. }{
  199. {"", false},
  200. {".", false},
  201. {"/", false},
  202. {"12" + encryptedDirExtension, false},
  203. {"1" + encryptedDirExtension, true},
  204. {"1" + encryptedDirExtension + "/b", false},
  205. {"1" + encryptedDirExtension + "/bc", true},
  206. {"1" + encryptedDirExtension + "/bcd", false},
  207. {"1" + encryptedDirExtension + "/bc/foo", false},
  208. {"1.12/22", false},
  209. {"1" + encryptedDirExtension + "/bc/" + comp, true},
  210. {"1" + encryptedDirExtension + "/bc/" + comp + "/" + comp, true},
  211. {"1" + encryptedDirExtension + "/bc/" + comp + "a", false},
  212. {"1" + encryptedDirExtension + "/bc/" + comp + "/a/" + comp, false},
  213. }
  214. for _, tc := range cases {
  215. if res := IsEncryptedParent(strings.Split(tc.path, "/")); res != tc.is {
  216. t.Errorf("%v: got %v, expected %v", tc.path, res, tc.is)
  217. }
  218. }
  219. }
  220. var benchmarkFileKey struct {
  221. key [keySize]byte
  222. sync.Once
  223. }
  224. func BenchmarkFileKey(b *testing.B) {
  225. benchmarkFileKey.Do(func() {
  226. sha256.SelectAlgo()
  227. rand.Read(benchmarkFileKey.key[:])
  228. })
  229. b.ResetTimer()
  230. b.ReportAllocs()
  231. for i := 0; i < b.N; i++ {
  232. FileKey("a_kind_of_long_filename.ext", &benchmarkFileKey.key)
  233. }
  234. }