encryption.go 20 KB

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