encryption.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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. Size: offset, // new total file size
  271. Permissions: 0644,
  272. ModifiedS: 1234567890, // Sat Feb 14 00:31:30 CET 2009
  273. Deleted: fi.Deleted,
  274. RawInvalid: fi.IsInvalid(),
  275. Version: version,
  276. Sequence: fi.Sequence,
  277. RawBlockSize: fi.RawBlockSize + blockOverhead,
  278. Blocks: blocks,
  279. Encrypted: encryptedFI,
  280. }
  281. return enc
  282. }
  283. func decryptFileInfos(files []FileInfo, folderKey *[keySize]byte) error {
  284. for i, fi := range files {
  285. decFI, err := DecryptFileInfo(fi, folderKey)
  286. if err != nil {
  287. return err
  288. }
  289. files[i] = decFI
  290. }
  291. return nil
  292. }
  293. // DecryptFileInfo extracts the encrypted portion of a FileInfo, decrypts it
  294. // and returns that.
  295. func DecryptFileInfo(fi FileInfo, folderKey *[keySize]byte) (FileInfo, error) {
  296. realName, err := decryptName(fi.Name, folderKey)
  297. if err != nil {
  298. return FileInfo{}, err
  299. }
  300. fileKey := FileKey(realName, folderKey)
  301. dec, err := DecryptBytes(fi.Encrypted, fileKey)
  302. if err != nil {
  303. return FileInfo{}, err
  304. }
  305. var decFI FileInfo
  306. if err := proto.Unmarshal(dec, &decFI); err != nil {
  307. return FileInfo{}, err
  308. }
  309. return decFI, nil
  310. }
  311. var base32Hex = base32.HexEncoding.WithPadding(base32.NoPadding)
  312. // encryptName encrypts the given string in a deterministic manner (the
  313. // result is always the same for any given string) and encodes it in a
  314. // filesystem-friendly manner.
  315. func encryptName(name string, key *[keySize]byte) string {
  316. enc := encryptDeterministic([]byte(name), key, nil)
  317. return slashify(base32Hex.EncodeToString(enc))
  318. }
  319. // decryptName decrypts a string from encryptName
  320. func decryptName(name string, key *[keySize]byte) (string, error) {
  321. name, err := deslashify(name)
  322. if err != nil {
  323. return "", err
  324. }
  325. bs, err := base32Hex.DecodeString(name)
  326. if err != nil {
  327. return "", err
  328. }
  329. dec, err := decryptDeterministic(bs, key, nil)
  330. if err != nil {
  331. return "", err
  332. }
  333. return string(dec), nil
  334. }
  335. // encryptBytes encrypts bytes with a random nonce
  336. func encryptBytes(data []byte, key *[keySize]byte) []byte {
  337. nonce := randomNonce()
  338. return encrypt(data, nonce, key)
  339. }
  340. // encryptDeterministic encrypts bytes using AES-SIV
  341. func encryptDeterministic(data []byte, key *[keySize]byte, additionalData []byte) []byte {
  342. aead, err := miscreant.NewAEAD(miscreantAlgo, key[:], 0)
  343. if err != nil {
  344. panic("cipher failure: " + err.Error())
  345. }
  346. return aead.Seal(nil, nil, data, additionalData)
  347. }
  348. // decryptDeterministic decrypts bytes using AES-SIV
  349. func decryptDeterministic(data []byte, key *[keySize]byte, additionalData []byte) ([]byte, error) {
  350. aead, err := miscreant.NewAEAD(miscreantAlgo, key[:], 0)
  351. if err != nil {
  352. panic("cipher failure: " + err.Error())
  353. }
  354. return aead.Open(nil, nil, data, additionalData)
  355. }
  356. func encrypt(data []byte, nonce *[nonceSize]byte, key *[keySize]byte) []byte {
  357. aead, err := chacha20poly1305.NewX(key[:])
  358. if err != nil {
  359. // Can only fail if the key is the wrong length
  360. panic("cipher failure: " + err.Error())
  361. }
  362. if aead.NonceSize() != nonceSize || aead.Overhead() != tagSize {
  363. // We want these values to be constant for our type declarations so
  364. // we don't use the values returned by the GCM, but we verify them
  365. // here.
  366. panic("crypto parameter mismatch")
  367. }
  368. // Data is appended to the nonce
  369. return aead.Seal(nonce[:], nonce[:], data, nil)
  370. }
  371. // DecryptBytes returns the decrypted bytes, or an error if decryption
  372. // failed.
  373. func DecryptBytes(data []byte, key *[keySize]byte) ([]byte, error) {
  374. if len(data) < blockOverhead {
  375. return nil, errors.New("data too short")
  376. }
  377. aead, err := chacha20poly1305.NewX(key[:])
  378. if err != nil {
  379. // Can only fail if the key is the wrong length
  380. panic("cipher failure: " + err.Error())
  381. }
  382. if aead.NonceSize() != nonceSize || aead.Overhead() != tagSize {
  383. // We want these values to be constant for our type declarations so
  384. // we don't use the values returned by the GCM, but we verify them
  385. // here.
  386. panic("crypto parameter mismatch")
  387. }
  388. return aead.Open(nil, data[:nonceSize], data[nonceSize:], nil)
  389. }
  390. // randomNonce is a normal, cryptographically random nonce
  391. func randomNonce() *[nonceSize]byte {
  392. var nonce [nonceSize]byte
  393. if _, err := rand.Read(nonce[:]); err != nil {
  394. panic("catastrophic randomness failure: " + err.Error())
  395. }
  396. return &nonce
  397. }
  398. // keysFromPasswords converts a set of folder ID to password into a set of
  399. // folder ID to encryption key, using our key derivation function.
  400. func keysFromPasswords(passwords map[string]string) map[string]*[keySize]byte {
  401. res := make(map[string]*[keySize]byte, len(passwords))
  402. for folder, password := range passwords {
  403. res[folder] = KeyFromPassword(folder, password)
  404. }
  405. return res
  406. }
  407. func knownBytes(folderID string) []byte {
  408. return []byte("syncthing" + folderID)
  409. }
  410. // KeyFromPassword uses key derivation to generate a stronger key from a
  411. // probably weak password.
  412. func KeyFromPassword(folderID, password string) *[keySize]byte {
  413. bs, err := scrypt.Key([]byte(password), knownBytes(folderID), 32768, 8, 1, keySize)
  414. if err != nil {
  415. panic("key derivation failure: " + err.Error())
  416. }
  417. if len(bs) != keySize {
  418. panic("key derivation failure: wrong number of bytes")
  419. }
  420. var key [keySize]byte
  421. copy(key[:], bs)
  422. return &key
  423. }
  424. var hkdfSalt = []byte("syncthing")
  425. func FileKey(filename string, folderKey *[keySize]byte) *[keySize]byte {
  426. kdf := hkdf.New(sha256.New, append(folderKey[:], filename...), hkdfSalt, nil)
  427. var fileKey [keySize]byte
  428. n, err := io.ReadFull(kdf, fileKey[:])
  429. if err != nil || n != keySize {
  430. panic("hkdf failure")
  431. }
  432. return &fileKey
  433. }
  434. func PasswordToken(folderID, password string) []byte {
  435. return encryptDeterministic(knownBytes(folderID), KeyFromPassword(folderID, password), nil)
  436. }
  437. // slashify inserts slashes (and file extension) in the string to create an
  438. // appropriate tree. ABCDEFGH... => A.syncthing-enc/BC/DEFGH... We can use
  439. // forward slashes here because we're on the outside of native path formats,
  440. // the slash is the wire format.
  441. func slashify(s string) string {
  442. // We somewhat sloppily assume bytes == characters here, but the only
  443. // file names we should deal with are those that come from our base32
  444. // encoding.
  445. comps := make([]string, 0, len(s)/maxPathComponent+3)
  446. comps = append(comps, s[:1]+encryptedDirExtension)
  447. s = s[1:]
  448. comps = append(comps, s[:2])
  449. s = s[2:]
  450. for len(s) > maxPathComponent {
  451. comps = append(comps, s[:maxPathComponent])
  452. s = s[maxPathComponent:]
  453. }
  454. if len(s) > 0 {
  455. comps = append(comps, s)
  456. }
  457. return strings.Join(comps, "/")
  458. }
  459. // deslashify removes slashes and encrypted file extensions from the string.
  460. // This is the inverse of slashify().
  461. func deslashify(s string) (string, error) {
  462. if len(s) == 0 || !strings.HasPrefix(s[1:], encryptedDirExtension) {
  463. return "", fmt.Errorf("invalid encrypted path: %q", s)
  464. }
  465. s = s[:1] + s[1+len(encryptedDirExtension):]
  466. return strings.ReplaceAll(s, "/", ""), nil
  467. }
  468. type rawResponse struct {
  469. data []byte
  470. }
  471. func (r rawResponse) Data() []byte {
  472. return r.data
  473. }
  474. func (r rawResponse) Close() {}
  475. func (r rawResponse) Wait() {}
  476. // IsEncryptedParent returns true if the path points at a parent directory of
  477. // encrypted data, i.e. is not a "real" directory. This is determined by
  478. // checking for a sentinel string in the path.
  479. func IsEncryptedParent(pathComponents []string) bool {
  480. l := len(pathComponents)
  481. if l == 2 && len(pathComponents[1]) != 2 {
  482. return false
  483. } else if l == 0 {
  484. return false
  485. }
  486. if len(pathComponents[0]) == 0 {
  487. return false
  488. }
  489. if pathComponents[0][1:] != encryptedDirExtension {
  490. return false
  491. }
  492. if l < 2 {
  493. return true
  494. }
  495. for _, comp := range pathComponents[2:] {
  496. if len(comp) != maxPathComponent {
  497. return false
  498. }
  499. }
  500. return true
  501. }
  502. type folderKeyRegistry struct {
  503. keys map[string]*[keySize]byte // folder ID -> key
  504. mut sync.RWMutex
  505. }
  506. func newFolderKeyRegistry(passwords map[string]string) *folderKeyRegistry {
  507. return &folderKeyRegistry{
  508. keys: keysFromPasswords(passwords),
  509. }
  510. }
  511. func (r *folderKeyRegistry) get(folder string) (*[keySize]byte, bool) {
  512. r.mut.RLock()
  513. key, ok := r.keys[folder]
  514. r.mut.RUnlock()
  515. return key, ok
  516. }
  517. func (r *folderKeyRegistry) setPasswords(passwords map[string]string) {
  518. r.mut.Lock()
  519. r.keys = keysFromPasswords(passwords)
  520. r.mut.Unlock()
  521. }