encryption.go 20 KB

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