encryption.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. "context"
  9. "crypto/rand"
  10. "crypto/sha256"
  11. "encoding/base32"
  12. "errors"
  13. "io"
  14. "strings"
  15. "time"
  16. "github.com/gogo/protobuf/proto"
  17. "github.com/miscreant/miscreant.go"
  18. "golang.org/x/crypto/chacha20poly1305"
  19. "golang.org/x/crypto/hkdf"
  20. "golang.org/x/crypto/scrypt"
  21. )
  22. const (
  23. nonceSize = 24 // chacha20poly1305.NonceSizeX
  24. tagSize = 16 // chacha20poly1305.Overhead()
  25. keySize = 32 // fits both chacha20poly1305 and AES-SIV
  26. minPaddedSize = 1024 // smallest block we'll allow
  27. blockOverhead = tagSize + nonceSize
  28. maxPathComponent = 200 // characters
  29. encryptedDirExtension = ".syncthing-enc" // for top level dirs
  30. miscreantAlgo = "AES-SIV"
  31. )
  32. // The encryptedModel sits between the encrypted device and the model. It
  33. // receives encrypted metadata and requests from the untrusted device, so it
  34. // must decrypt those and answer requests by encrypting the data.
  35. type encryptedModel struct {
  36. model Model
  37. folderKeys map[string]*[keySize]byte // folder ID -> key
  38. }
  39. func (e encryptedModel) Index(deviceID DeviceID, folder string, files []FileInfo) error {
  40. if folderKey, ok := e.folderKeys[folder]; ok {
  41. // incoming index data to be decrypted
  42. if err := decryptFileInfos(files, folderKey); err != nil {
  43. return err
  44. }
  45. }
  46. return e.model.Index(deviceID, folder, files)
  47. }
  48. func (e encryptedModel) IndexUpdate(deviceID DeviceID, folder string, files []FileInfo) error {
  49. if folderKey, ok := e.folderKeys[folder]; ok {
  50. // incoming index data to be decrypted
  51. if err := decryptFileInfos(files, folderKey); err != nil {
  52. return err
  53. }
  54. }
  55. return e.model.IndexUpdate(deviceID, folder, files)
  56. }
  57. func (e encryptedModel) Request(deviceID DeviceID, folder, name string, blockNo, size int32, offset int64, hash []byte, weakHash uint32, fromTemporary bool) (RequestResponse, error) {
  58. folderKey, ok := e.folderKeys[folder]
  59. if !ok {
  60. return e.model.Request(deviceID, folder, name, blockNo, size, offset, hash, weakHash, fromTemporary)
  61. }
  62. // Figure out the real file name, offset and size from the encrypted /
  63. // tweaked values.
  64. realName, err := decryptName(name, folderKey)
  65. if err != nil {
  66. return nil, err
  67. }
  68. realSize := size - blockOverhead
  69. realOffset := offset - int64(blockNo*blockOverhead)
  70. if size < minPaddedSize {
  71. return nil, errors.New("short request")
  72. }
  73. // Perform that request and grab the data. Explicitly zero out the
  74. // hashes which are meaningless.
  75. resp, err := e.model.Request(deviceID, folder, realName, blockNo, realSize, realOffset, nil, 0, false)
  76. if err != nil {
  77. return nil, err
  78. }
  79. // Encrypt the response. Blocks smaller than minPaddedSize are padded
  80. // with random data.
  81. data := resp.Data()
  82. if len(data) < minPaddedSize {
  83. nd := make([]byte, minPaddedSize)
  84. copy(nd, data)
  85. if _, err := rand.Read(nd[len(data):]); err != nil {
  86. panic("catastrophic randomness failure")
  87. }
  88. data = nd
  89. }
  90. fileKey := FileKey(realName, folderKey)
  91. enc := encryptBytes(data, fileKey)
  92. resp.Close()
  93. return rawResponse{enc}, nil
  94. }
  95. func (e encryptedModel) DownloadProgress(deviceID DeviceID, folder string, updates []FileDownloadProgressUpdate) error {
  96. if _, ok := e.folderKeys[folder]; !ok {
  97. return e.model.DownloadProgress(deviceID, folder, updates)
  98. }
  99. // Encrypted devices shouldn't send these - ignore them.
  100. return nil
  101. }
  102. func (e encryptedModel) ClusterConfig(deviceID DeviceID, config ClusterConfig) error {
  103. return e.model.ClusterConfig(deviceID, config)
  104. }
  105. func (e encryptedModel) Closed(conn Connection, err error) {
  106. e.model.Closed(conn, err)
  107. }
  108. // The encryptedConnection sits between the model and the encrypted device. It
  109. // encrypts outgoing metadata and decrypts incoming responses.
  110. type encryptedConnection struct {
  111. ConnectionInfo
  112. conn Connection
  113. folderKeys map[string]*[keySize]byte // folder ID -> key
  114. }
  115. func (e encryptedConnection) Start() {
  116. e.conn.Start()
  117. }
  118. func (e encryptedConnection) ID() DeviceID {
  119. return e.conn.ID()
  120. }
  121. func (e encryptedConnection) Index(ctx context.Context, folder string, files []FileInfo) error {
  122. if folderKey, ok := e.folderKeys[folder]; ok {
  123. encryptFileInfos(files, folderKey)
  124. }
  125. return e.conn.Index(ctx, folder, files)
  126. }
  127. func (e encryptedConnection) IndexUpdate(ctx context.Context, folder string, files []FileInfo) error {
  128. if folderKey, ok := e.folderKeys[folder]; ok {
  129. encryptFileInfos(files, folderKey)
  130. }
  131. return e.conn.IndexUpdate(ctx, folder, files)
  132. }
  133. func (e encryptedConnection) Request(ctx context.Context, folder string, name string, blockNo int, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  134. folderKey, ok := e.folderKeys[folder]
  135. if !ok {
  136. return e.conn.Request(ctx, folder, name, blockNo, offset, size, hash, weakHash, fromTemporary)
  137. }
  138. // Encrypt / adjust the request parameters.
  139. origSize := size
  140. if size < minPaddedSize {
  141. // Make a request for minPaddedSize data instead of the smaller
  142. // block. We'll chop of the extra data later.
  143. size = minPaddedSize
  144. }
  145. encName := encryptName(name, folderKey)
  146. encOffset := offset + int64(blockNo*blockOverhead)
  147. encSize := size + blockOverhead
  148. // Perform that request, getting back and encrypted block.
  149. bs, err := e.conn.Request(ctx, folder, encName, blockNo, encOffset, encSize, nil, 0, false)
  150. if err != nil {
  151. return nil, err
  152. }
  153. // Return the decrypted block (or an error if it fails decryption)
  154. fileKey := FileKey(name, folderKey)
  155. bs, err = DecryptBytes(bs, fileKey)
  156. if err != nil {
  157. return nil, err
  158. }
  159. return bs[:origSize], nil
  160. }
  161. func (e encryptedConnection) DownloadProgress(ctx context.Context, folder string, updates []FileDownloadProgressUpdate) {
  162. if _, ok := e.folderKeys[folder]; !ok {
  163. e.conn.DownloadProgress(ctx, folder, updates)
  164. }
  165. // No need to send these
  166. }
  167. func (e encryptedConnection) ClusterConfig(config ClusterConfig) {
  168. e.conn.ClusterConfig(config)
  169. }
  170. func (e encryptedConnection) Close(err error) {
  171. e.conn.Close(err)
  172. }
  173. func (e encryptedConnection) Closed() bool {
  174. return e.conn.Closed()
  175. }
  176. func (e encryptedConnection) Statistics() Statistics {
  177. return e.conn.Statistics()
  178. }
  179. func encryptFileInfos(files []FileInfo, folderKey *[keySize]byte) {
  180. for i, fi := range files {
  181. files[i] = encryptFileInfo(fi, folderKey)
  182. }
  183. }
  184. // encryptFileInfo encrypts a FileInfo and wraps it into a new fake FileInfo
  185. // with an encrypted name.
  186. func encryptFileInfo(fi FileInfo, folderKey *[keySize]byte) FileInfo {
  187. fileKey := FileKey(fi.Name, folderKey)
  188. // The entire FileInfo is encrypted with a random nonce, and concatenated
  189. // with that nonce.
  190. bs, err := proto.Marshal(&fi)
  191. if err != nil {
  192. panic("impossible serialization mishap: " + err.Error())
  193. }
  194. encryptedFI := encryptBytes(bs, fileKey)
  195. // The vector is set to something that is higher than any other version sent
  196. // previously, assuming people's clocks are correct. We do this because
  197. // there is no way for the insecure device on the other end to do proper
  198. // conflict resolution, so they will simply accept and keep whatever is the
  199. // latest version they see. The secure devices will decrypt the real
  200. // FileInfo, see the real Version, and act appropriately regardless of what
  201. // this fake version happens to be.
  202. version := Vector{
  203. Counters: []Counter{
  204. {
  205. ID: 1,
  206. Value: uint64(time.Now().UnixNano()),
  207. },
  208. },
  209. }
  210. // Construct the fake block list. Each block will be blockOverhead bytes
  211. // larger than the corresponding real one and have an encrypted hash.
  212. // Very small blocks will be padded upwards to minPaddedSize.
  213. //
  214. // The encrypted hash becomes just a "token" for the data -- it doesn't
  215. // help verifying it, but it lets the encrypted device do block level
  216. // diffs and data reuse properly when it gets a new version of a file.
  217. var offset int64
  218. blocks := make([]BlockInfo, len(fi.Blocks))
  219. for i, b := range fi.Blocks {
  220. if b.Size < minPaddedSize {
  221. b.Size = minPaddedSize
  222. }
  223. size := b.Size + blockOverhead
  224. blocks[i] = BlockInfo{
  225. Offset: offset,
  226. Size: size,
  227. Hash: encryptDeterministic(b.Hash, fileKey),
  228. }
  229. offset += int64(size)
  230. }
  231. // Construct the fake FileInfo. This is mostly just a wrapper around the
  232. // encrypted FileInfo and fake block list. We'll represent symlinks as
  233. // directories, because they need some sort of on disk representation
  234. // but have no data outside of the metadata. Deletion and sequence
  235. // numbering are handled as usual.
  236. typ := FileInfoTypeFile
  237. if fi.Type != FileInfoTypeFile {
  238. typ = FileInfoTypeDirectory
  239. }
  240. enc := FileInfo{
  241. Name: encryptName(fi.Name, folderKey),
  242. Type: typ,
  243. Size: offset, // new total file size
  244. Permissions: 0644,
  245. ModifiedS: 1234567890, // Sat Feb 14 00:31:30 CET 2009
  246. Deleted: fi.Deleted,
  247. Version: version,
  248. Sequence: fi.Sequence,
  249. RawBlockSize: fi.RawBlockSize + blockOverhead,
  250. Blocks: blocks,
  251. Encrypted: encryptedFI,
  252. }
  253. return enc
  254. }
  255. func decryptFileInfos(files []FileInfo, folderKey *[keySize]byte) error {
  256. for i, fi := range files {
  257. decFI, err := DecryptFileInfo(fi, folderKey)
  258. if err != nil {
  259. return err
  260. }
  261. files[i] = decFI
  262. }
  263. return nil
  264. }
  265. // DecryptFileInfo extracts the encrypted portion of a FileInfo, decrypts it
  266. // and returns that.
  267. func DecryptFileInfo(fi FileInfo, folderKey *[keySize]byte) (FileInfo, error) {
  268. realName, err := decryptName(fi.Name, folderKey)
  269. if err != nil {
  270. return FileInfo{}, err
  271. }
  272. fileKey := FileKey(realName, folderKey)
  273. dec, err := DecryptBytes(fi.Encrypted, fileKey)
  274. if err != nil {
  275. return FileInfo{}, err
  276. }
  277. var decFI FileInfo
  278. if err := proto.Unmarshal(dec, &decFI); err != nil {
  279. return FileInfo{}, err
  280. }
  281. return decFI, nil
  282. }
  283. // encryptName encrypts the given string in a deterministic manner (the
  284. // result is always the same for any given string) and encodes it in a
  285. // filesystem-friendly manner.
  286. func encryptName(name string, key *[keySize]byte) string {
  287. enc := encryptDeterministic([]byte(name), key)
  288. b32enc := base32.HexEncoding.WithPadding(base32.NoPadding).EncodeToString(enc)
  289. return slashify(b32enc)
  290. }
  291. // decryptName decrypts a string from encryptName
  292. func decryptName(name string, key *[keySize]byte) (string, error) {
  293. name = deslashify(name)
  294. bs, err := base32.HexEncoding.WithPadding(base32.NoPadding).DecodeString(name)
  295. if err != nil {
  296. return "", err
  297. }
  298. dec, err := decryptDeterministic(bs, key)
  299. if err != nil {
  300. return "", err
  301. }
  302. return string(dec), nil
  303. }
  304. // encryptBytes encrypts bytes with a random nonce
  305. func encryptBytes(data []byte, key *[keySize]byte) []byte {
  306. nonce := randomNonce()
  307. return encrypt(data, nonce, key)
  308. }
  309. // encryptDeterministic encrypts bytes using AES-SIV
  310. func encryptDeterministic(data []byte, key *[keySize]byte) []byte {
  311. aead, err := miscreant.NewAEAD(miscreantAlgo, key[:], 0)
  312. if err != nil {
  313. panic("cipher failure: " + err.Error())
  314. }
  315. return aead.Seal(nil, nil, data, nil)
  316. }
  317. // decryptDeterministic decrypts bytes using AES-SIV
  318. func decryptDeterministic(data []byte, key *[keySize]byte) ([]byte, error) {
  319. aead, err := miscreant.NewAEAD(miscreantAlgo, key[:], 0)
  320. if err != nil {
  321. panic("cipher failure: " + err.Error())
  322. }
  323. return aead.Open(nil, nil, data, nil)
  324. }
  325. func encrypt(data []byte, nonce *[nonceSize]byte, key *[keySize]byte) []byte {
  326. aead, err := chacha20poly1305.NewX(key[:])
  327. if err != nil {
  328. // Can only fail if the key is the wrong length
  329. panic("cipher failure: " + err.Error())
  330. }
  331. if aead.NonceSize() != nonceSize || aead.Overhead() != tagSize {
  332. // We want these values to be constant for our type declarations so
  333. // we don't use the values returned by the GCM, but we verify them
  334. // here.
  335. panic("crypto parameter mismatch")
  336. }
  337. // Data is appended to the nonce
  338. return aead.Seal(nonce[:], nonce[:], data, nil)
  339. }
  340. // DecryptBytes returns the decrypted bytes, or an error if decryption
  341. // failed.
  342. func DecryptBytes(data []byte, key *[keySize]byte) ([]byte, error) {
  343. if len(data) < blockOverhead {
  344. return nil, errors.New("data too short")
  345. }
  346. aead, err := chacha20poly1305.NewX(key[:])
  347. if err != nil {
  348. // Can only fail if the key is the wrong length
  349. panic("cipher failure: " + err.Error())
  350. }
  351. if aead.NonceSize() != nonceSize || aead.Overhead() != tagSize {
  352. // We want these values to be constant for our type declarations so
  353. // we don't use the values returned by the GCM, but we verify them
  354. // here.
  355. panic("crypto parameter mismatch")
  356. }
  357. return aead.Open(nil, data[:nonceSize], data[nonceSize:], nil)
  358. }
  359. // randomNonce is a normal, cryptographically random nonce
  360. func randomNonce() *[nonceSize]byte {
  361. var nonce [nonceSize]byte
  362. if _, err := rand.Read(nonce[:]); err != nil {
  363. panic("catastrophic randomness failure: " + err.Error())
  364. }
  365. return &nonce
  366. }
  367. // keysFromPasswords converts a set of folder ID to password into a set of
  368. // folder ID to encryption key, using our key derivation function.
  369. func keysFromPasswords(passwords map[string]string) map[string]*[keySize]byte {
  370. res := make(map[string]*[keySize]byte, len(passwords))
  371. for folder, password := range passwords {
  372. res[folder] = KeyFromPassword(folder, password)
  373. }
  374. return res
  375. }
  376. func knownBytes(folderID string) []byte {
  377. return []byte("syncthing" + folderID)
  378. }
  379. // KeyFromPassword uses key derivation to generate a stronger key from a
  380. // probably weak password.
  381. func KeyFromPassword(folderID, password string) *[keySize]byte {
  382. bs, err := scrypt.Key([]byte(password), knownBytes(folderID), 32768, 8, 1, keySize)
  383. if err != nil {
  384. panic("key derivation failure: " + err.Error())
  385. }
  386. if len(bs) != keySize {
  387. panic("key derivation failure: wrong number of bytes")
  388. }
  389. var key [keySize]byte
  390. copy(key[:], bs)
  391. return &key
  392. }
  393. func FileKey(filename string, folderKey *[keySize]byte) *[keySize]byte {
  394. kdf := hkdf.New(sha256.New, append(folderKey[:], filename...), []byte("syncthing"), nil)
  395. var fileKey [keySize]byte
  396. n, err := io.ReadFull(kdf, fileKey[:])
  397. if err != nil || n != keySize {
  398. panic("hkdf failure")
  399. }
  400. return &fileKey
  401. }
  402. func PasswordToken(folderID, password string) []byte {
  403. return encryptDeterministic(knownBytes(folderID), KeyFromPassword(folderID, password))
  404. }
  405. // slashify inserts slashes (and file extension) in the string to create an
  406. // appropriate tree. ABCDEFGH... => A.syncthing-enc/BC/DEFGH... We can use
  407. // forward slashes here because we're on the outside of native path formats,
  408. // the slash is the wire format.
  409. func slashify(s string) string {
  410. // We somewhat sloppily assume bytes == characters here, but the only
  411. // file names we should deal with are those that come from our base32
  412. // encoding.
  413. comps := make([]string, 0, len(s)/maxPathComponent+3)
  414. comps = append(comps, s[:1]+encryptedDirExtension)
  415. s = s[1:]
  416. comps = append(comps, s[:2])
  417. s = s[2:]
  418. for len(s) > maxPathComponent {
  419. comps = append(comps, s[:maxPathComponent])
  420. s = s[maxPathComponent:]
  421. }
  422. if len(s) > 0 {
  423. comps = append(comps, s)
  424. }
  425. return strings.Join(comps, "/")
  426. }
  427. // deslashify removes slashes and encrypted file extensions from the string.
  428. // This is the inverse of slashify().
  429. func deslashify(s string) string {
  430. s = strings.ReplaceAll(s, encryptedDirExtension, "")
  431. return strings.ReplaceAll(s, "/", "")
  432. }
  433. type rawResponse struct {
  434. data []byte
  435. }
  436. func (r rawResponse) Data() []byte {
  437. return r.data
  438. }
  439. func (r rawResponse) Close() {}
  440. func (r rawResponse) Wait() {}
  441. // IsEncryptedPath returns true if the path points at encrypted data. This is
  442. // determined by checking for a sentinel string in the path.
  443. func IsEncryptedPath(path string) bool {
  444. pathComponents := strings.Split(path, "/")
  445. if len(pathComponents) != 3 {
  446. return false
  447. }
  448. return isEncryptedParentFromComponents(pathComponents[:2])
  449. }
  450. // IsEncryptedParent returns true if the path points at a parent directory of
  451. // encrypted data, i.e. is not a "real" directory. This is determined by
  452. // checking for a sentinel string in the path.
  453. func IsEncryptedParent(path string) bool {
  454. return isEncryptedParentFromComponents(strings.Split(path, "/"))
  455. }
  456. func isEncryptedParentFromComponents(pathComponents []string) bool {
  457. l := len(pathComponents)
  458. if l == 2 && len(pathComponents[1]) != 2 {
  459. return false
  460. } else if l == 0 {
  461. return false
  462. }
  463. if len(pathComponents[0]) == 0 {
  464. return false
  465. }
  466. if pathComponents[0][1:] != encryptedDirExtension {
  467. return false
  468. }
  469. if l < 2 {
  470. return true
  471. }
  472. for _, comp := range pathComponents[2:] {
  473. if len(comp) != maxPathComponent {
  474. return false
  475. }
  476. }
  477. return true
  478. }