encryption.go 20 KB

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