encryption.go 18 KB

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