encryption.go 18 KB

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