encryption.go 20 KB

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