encryption.go 20 KB

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