encryption.go 20 KB

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