encryption.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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/rand"
  10. "crypto/sha256"
  11. "encoding/base32"
  12. "encoding/binary"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "strings"
  17. "time"
  18. "github.com/gogo/protobuf/proto"
  19. "github.com/miscreant/miscreant.go"
  20. "golang.org/x/crypto/chacha20poly1305"
  21. "golang.org/x/crypto/hkdf"
  22. "golang.org/x/crypto/scrypt"
  23. )
  24. const (
  25. nonceSize = 24 // chacha20poly1305.NonceSizeX
  26. tagSize = 16 // chacha20poly1305.Overhead()
  27. keySize = 32 // fits both chacha20poly1305 and AES-SIV
  28. minPaddedSize = 1024 // smallest block we'll allow
  29. blockOverhead = tagSize + nonceSize
  30. maxPathComponent = 200 // characters
  31. encryptedDirExtension = ".syncthing-enc" // for top level dirs
  32. miscreantAlgo = "AES-SIV"
  33. )
  34. // The encryptedModel sits between the encrypted device and the model. It
  35. // receives encrypted metadata and requests from the untrusted device, so it
  36. // must decrypt those and answer requests by encrypting the data.
  37. type encryptedModel struct {
  38. model Model
  39. folderKeys map[string]*[keySize]byte // folder ID -> key
  40. }
  41. func (e encryptedModel) Index(deviceID DeviceID, folder string, files []FileInfo) error {
  42. if folderKey, ok := e.folderKeys[folder]; ok {
  43. // incoming index data to be decrypted
  44. if err := decryptFileInfos(files, folderKey); err != nil {
  45. return err
  46. }
  47. }
  48. return e.model.Index(deviceID, folder, files)
  49. }
  50. func (e encryptedModel) IndexUpdate(deviceID DeviceID, folder string, files []FileInfo) error {
  51. if folderKey, ok := e.folderKeys[folder]; ok {
  52. // incoming index data to be decrypted
  53. if err := decryptFileInfos(files, folderKey); err != nil {
  54. return err
  55. }
  56. }
  57. return e.model.IndexUpdate(deviceID, folder, files)
  58. }
  59. func (e encryptedModel) Request(deviceID DeviceID, folder, name string, blockNo, size int32, offset int64, hash []byte, weakHash uint32, fromTemporary bool) (RequestResponse, error) {
  60. folderKey, ok := e.folderKeys[folder]
  61. if !ok {
  62. return e.model.Request(deviceID, folder, name, blockNo, size, offset, hash, weakHash, fromTemporary)
  63. }
  64. // Figure out the real file name, offset and size from the encrypted /
  65. // tweaked values.
  66. realName, err := decryptName(name, folderKey)
  67. if err != nil {
  68. return nil, fmt.Errorf("decrypting name: %w", err)
  69. }
  70. realSize := size - blockOverhead
  71. realOffset := offset - int64(blockNo*blockOverhead)
  72. if size < minPaddedSize {
  73. return nil, errors.New("short request")
  74. }
  75. // Decrypt the block hash.
  76. fileKey := FileKey(realName, folderKey)
  77. var additional [8]byte
  78. binary.BigEndian.PutUint64(additional[:], uint64(realOffset))
  79. realHash, err := decryptDeterministic(hash, fileKey, additional[:])
  80. if err != nil {
  81. // "Legacy", no offset additional data?
  82. realHash, err = decryptDeterministic(hash, fileKey, nil)
  83. }
  84. if err != nil {
  85. return nil, fmt.Errorf("decrypting block hash: %w", err)
  86. }
  87. // Perform that request and grab the data.
  88. resp, err := e.model.Request(deviceID, folder, realName, blockNo, realSize, realOffset, realHash, 0, false)
  89. if err != nil {
  90. return nil, err
  91. }
  92. // Encrypt the response. Blocks smaller than minPaddedSize are padded
  93. // with random data.
  94. data := resp.Data()
  95. if len(data) < minPaddedSize {
  96. nd := make([]byte, minPaddedSize)
  97. copy(nd, data)
  98. if _, err := rand.Read(nd[len(data):]); err != nil {
  99. panic("catastrophic randomness failure")
  100. }
  101. data = nd
  102. }
  103. enc := encryptBytes(data, fileKey)
  104. resp.Close()
  105. return rawResponse{enc}, nil
  106. }
  107. func (e encryptedModel) DownloadProgress(deviceID DeviceID, folder string, updates []FileDownloadProgressUpdate) error {
  108. if _, ok := e.folderKeys[folder]; !ok {
  109. return e.model.DownloadProgress(deviceID, folder, updates)
  110. }
  111. // Encrypted devices shouldn't send these - ignore them.
  112. return nil
  113. }
  114. func (e encryptedModel) ClusterConfig(deviceID DeviceID, config ClusterConfig) error {
  115. return e.model.ClusterConfig(deviceID, config)
  116. }
  117. func (e encryptedModel) Closed(conn Connection, err error) {
  118. e.model.Closed(conn, err)
  119. }
  120. // The encryptedConnection sits between the model and the encrypted device. It
  121. // encrypts outgoing metadata and decrypts incoming responses.
  122. type encryptedConnection struct {
  123. ConnectionInfo
  124. conn Connection
  125. folderKeys map[string]*[keySize]byte // folder ID -> key
  126. }
  127. func (e encryptedConnection) Start() {
  128. e.conn.Start()
  129. }
  130. func (e encryptedConnection) ID() DeviceID {
  131. return e.conn.ID()
  132. }
  133. func (e encryptedConnection) Index(ctx context.Context, folder string, files []FileInfo) error {
  134. if folderKey, ok := e.folderKeys[folder]; ok {
  135. encryptFileInfos(files, folderKey)
  136. }
  137. return e.conn.Index(ctx, folder, files)
  138. }
  139. func (e encryptedConnection) IndexUpdate(ctx context.Context, folder string, files []FileInfo) error {
  140. if folderKey, ok := e.folderKeys[folder]; ok {
  141. encryptFileInfos(files, folderKey)
  142. }
  143. return e.conn.IndexUpdate(ctx, folder, files)
  144. }
  145. 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) {
  146. folderKey, ok := e.folderKeys[folder]
  147. if !ok {
  148. return e.conn.Request(ctx, folder, name, blockNo, offset, size, hash, weakHash, fromTemporary)
  149. }
  150. // Encrypt / adjust the request parameters.
  151. origSize := size
  152. if size < minPaddedSize {
  153. // Make a request for minPaddedSize data instead of the smaller
  154. // block. We'll chop of the extra data later.
  155. size = minPaddedSize
  156. }
  157. encName := encryptName(name, folderKey)
  158. encOffset := offset + int64(blockNo*blockOverhead)
  159. encSize := size + blockOverhead
  160. // Perform that request, getting back and encrypted block.
  161. bs, err := e.conn.Request(ctx, folder, encName, blockNo, encOffset, encSize, nil, 0, false)
  162. if err != nil {
  163. return nil, err
  164. }
  165. // Return the decrypted block (or an error if it fails decryption)
  166. fileKey := FileKey(name, folderKey)
  167. bs, err = DecryptBytes(bs, fileKey)
  168. if err != nil {
  169. return nil, err
  170. }
  171. return bs[:origSize], nil
  172. }
  173. func (e encryptedConnection) DownloadProgress(ctx context.Context, folder string, updates []FileDownloadProgressUpdate) {
  174. if _, ok := e.folderKeys[folder]; !ok {
  175. e.conn.DownloadProgress(ctx, folder, updates)
  176. }
  177. // No need to send these
  178. }
  179. func (e encryptedConnection) ClusterConfig(config ClusterConfig) {
  180. e.conn.ClusterConfig(config)
  181. }
  182. func (e encryptedConnection) Close(err error) {
  183. e.conn.Close(err)
  184. }
  185. func (e encryptedConnection) Closed() bool {
  186. return e.conn.Closed()
  187. }
  188. func (e encryptedConnection) Statistics() Statistics {
  189. return e.conn.Statistics()
  190. }
  191. func encryptFileInfos(files []FileInfo, folderKey *[keySize]byte) {
  192. for i, fi := range files {
  193. files[i] = encryptFileInfo(fi, folderKey)
  194. }
  195. }
  196. // encryptFileInfo encrypts a FileInfo and wraps it into a new fake FileInfo
  197. // with an encrypted name.
  198. func encryptFileInfo(fi FileInfo, folderKey *[keySize]byte) FileInfo {
  199. fileKey := FileKey(fi.Name, folderKey)
  200. // The entire FileInfo is encrypted with a random nonce, and concatenated
  201. // with that nonce.
  202. bs, err := proto.Marshal(&fi)
  203. if err != nil {
  204. panic("impossible serialization mishap: " + err.Error())
  205. }
  206. encryptedFI := encryptBytes(bs, fileKey)
  207. // The vector is set to something that is higher than any other version sent
  208. // previously, assuming people's clocks are correct. We do this because
  209. // there is no way for the insecure device on the other end to do proper
  210. // conflict resolution, so they will simply accept and keep whatever is the
  211. // latest version they see. The secure devices will decrypt the real
  212. // FileInfo, see the real Version, and act appropriately regardless of what
  213. // this fake version happens to be.
  214. version := Vector{
  215. Counters: []Counter{
  216. {
  217. ID: 1,
  218. Value: uint64(time.Now().UnixNano()),
  219. },
  220. },
  221. }
  222. // Construct the fake block list. Each block will be blockOverhead bytes
  223. // larger than the corresponding real one and have an encrypted hash.
  224. // Very small blocks will be padded upwards to minPaddedSize.
  225. //
  226. // The encrypted hash becomes just a "token" for the data -- it doesn't
  227. // help verifying it, but it lets the encrypted device do block level
  228. // diffs and data reuse properly when it gets a new version of a file.
  229. var offset int64
  230. blocks := make([]BlockInfo, len(fi.Blocks))
  231. for i, b := range fi.Blocks {
  232. if b.Size < minPaddedSize {
  233. b.Size = minPaddedSize
  234. }
  235. size := b.Size + blockOverhead
  236. // The offset goes into the encrypted block hash as additional data,
  237. // essentially mixing in with the nonce. This means a block hash
  238. // remains stable for the same data at the same offset, but doesn't
  239. // reveal the existence of identical data blocks at other offsets.
  240. var additional [8]byte
  241. binary.BigEndian.PutUint64(additional[:], uint64(b.Offset))
  242. hash := encryptDeterministic(b.Hash, fileKey, additional[:])
  243. blocks[i] = BlockInfo{
  244. Hash: hash,
  245. Offset: offset,
  246. Size: size,
  247. }
  248. offset += int64(size)
  249. }
  250. // Construct the fake FileInfo. This is mostly just a wrapper around the
  251. // encrypted FileInfo and fake block list. We'll represent symlinks as
  252. // directories, because they need some sort of on disk representation
  253. // but have no data outside of the metadata. Deletion and sequence
  254. // numbering are handled as usual.
  255. typ := FileInfoTypeFile
  256. if fi.Type != FileInfoTypeFile {
  257. typ = FileInfoTypeDirectory
  258. }
  259. enc := FileInfo{
  260. Name: encryptName(fi.Name, folderKey),
  261. Type: typ,
  262. Size: offset, // new total file size
  263. Permissions: 0644,
  264. ModifiedS: 1234567890, // Sat Feb 14 00:31:30 CET 2009
  265. Deleted: fi.Deleted,
  266. Version: version,
  267. Sequence: fi.Sequence,
  268. RawBlockSize: fi.RawBlockSize + blockOverhead,
  269. Blocks: blocks,
  270. Encrypted: encryptedFI,
  271. }
  272. return enc
  273. }
  274. func decryptFileInfos(files []FileInfo, folderKey *[keySize]byte) error {
  275. for i, fi := range files {
  276. decFI, err := DecryptFileInfo(fi, folderKey)
  277. if err != nil {
  278. return err
  279. }
  280. files[i] = decFI
  281. }
  282. return nil
  283. }
  284. // DecryptFileInfo extracts the encrypted portion of a FileInfo, decrypts it
  285. // and returns that.
  286. func DecryptFileInfo(fi FileInfo, folderKey *[keySize]byte) (FileInfo, error) {
  287. realName, err := decryptName(fi.Name, folderKey)
  288. if err != nil {
  289. return FileInfo{}, err
  290. }
  291. fileKey := FileKey(realName, folderKey)
  292. dec, err := DecryptBytes(fi.Encrypted, fileKey)
  293. if err != nil {
  294. return FileInfo{}, err
  295. }
  296. var decFI FileInfo
  297. if err := proto.Unmarshal(dec, &decFI); err != nil {
  298. return FileInfo{}, err
  299. }
  300. return decFI, nil
  301. }
  302. // encryptName encrypts the given string in a deterministic manner (the
  303. // result is always the same for any given string) and encodes it in a
  304. // filesystem-friendly manner.
  305. func encryptName(name string, key *[keySize]byte) string {
  306. enc := encryptDeterministic([]byte(name), key, nil)
  307. b32enc := base32.HexEncoding.WithPadding(base32.NoPadding).EncodeToString(enc)
  308. return slashify(b32enc)
  309. }
  310. // decryptName decrypts a string from encryptName
  311. func decryptName(name string, key *[keySize]byte) (string, error) {
  312. name = deslashify(name)
  313. bs, err := base32.HexEncoding.WithPadding(base32.NoPadding).DecodeString(name)
  314. if err != nil {
  315. return "", err
  316. }
  317. dec, err := decryptDeterministic(bs, key, nil)
  318. if err != nil {
  319. return "", err
  320. }
  321. return string(dec), nil
  322. }
  323. // encryptBytes encrypts bytes with a random nonce
  324. func encryptBytes(data []byte, key *[keySize]byte) []byte {
  325. nonce := randomNonce()
  326. return encrypt(data, nonce, key)
  327. }
  328. // encryptDeterministic encrypts bytes using AES-SIV
  329. func encryptDeterministic(data []byte, key *[keySize]byte, additionalData []byte) []byte {
  330. aead, err := miscreant.NewAEAD(miscreantAlgo, key[:], 0)
  331. if err != nil {
  332. panic("cipher failure: " + err.Error())
  333. }
  334. return aead.Seal(nil, nil, data, additionalData)
  335. }
  336. // decryptDeterministic decrypts bytes using AES-SIV
  337. func decryptDeterministic(data []byte, key *[keySize]byte, additionalData []byte) ([]byte, error) {
  338. aead, err := miscreant.NewAEAD(miscreantAlgo, key[:], 0)
  339. if err != nil {
  340. panic("cipher failure: " + err.Error())
  341. }
  342. return aead.Open(nil, nil, data, additionalData)
  343. }
  344. func encrypt(data []byte, nonce *[nonceSize]byte, key *[keySize]byte) []byte {
  345. aead, err := chacha20poly1305.NewX(key[:])
  346. if err != nil {
  347. // Can only fail if the key is the wrong length
  348. panic("cipher failure: " + err.Error())
  349. }
  350. if aead.NonceSize() != nonceSize || aead.Overhead() != tagSize {
  351. // We want these values to be constant for our type declarations so
  352. // we don't use the values returned by the GCM, but we verify them
  353. // here.
  354. panic("crypto parameter mismatch")
  355. }
  356. // Data is appended to the nonce
  357. return aead.Seal(nonce[:], nonce[:], data, nil)
  358. }
  359. // DecryptBytes returns the decrypted bytes, or an error if decryption
  360. // failed.
  361. func DecryptBytes(data []byte, key *[keySize]byte) ([]byte, error) {
  362. if len(data) < blockOverhead {
  363. return nil, errors.New("data too short")
  364. }
  365. aead, err := chacha20poly1305.NewX(key[:])
  366. if err != nil {
  367. // Can only fail if the key is the wrong length
  368. panic("cipher failure: " + err.Error())
  369. }
  370. if aead.NonceSize() != nonceSize || aead.Overhead() != tagSize {
  371. // We want these values to be constant for our type declarations so
  372. // we don't use the values returned by the GCM, but we verify them
  373. // here.
  374. panic("crypto parameter mismatch")
  375. }
  376. return aead.Open(nil, data[:nonceSize], data[nonceSize:], nil)
  377. }
  378. // randomNonce is a normal, cryptographically random nonce
  379. func randomNonce() *[nonceSize]byte {
  380. var nonce [nonceSize]byte
  381. if _, err := rand.Read(nonce[:]); err != nil {
  382. panic("catastrophic randomness failure: " + err.Error())
  383. }
  384. return &nonce
  385. }
  386. // keysFromPasswords converts a set of folder ID to password into a set of
  387. // folder ID to encryption key, using our key derivation function.
  388. func keysFromPasswords(passwords map[string]string) map[string]*[keySize]byte {
  389. res := make(map[string]*[keySize]byte, len(passwords))
  390. for folder, password := range passwords {
  391. res[folder] = KeyFromPassword(folder, password)
  392. }
  393. return res
  394. }
  395. func knownBytes(folderID string) []byte {
  396. return []byte("syncthing" + folderID)
  397. }
  398. // KeyFromPassword uses key derivation to generate a stronger key from a
  399. // probably weak password.
  400. func KeyFromPassword(folderID, password string) *[keySize]byte {
  401. bs, err := scrypt.Key([]byte(password), knownBytes(folderID), 32768, 8, 1, keySize)
  402. if err != nil {
  403. panic("key derivation failure: " + err.Error())
  404. }
  405. if len(bs) != keySize {
  406. panic("key derivation failure: wrong number of bytes")
  407. }
  408. var key [keySize]byte
  409. copy(key[:], bs)
  410. return &key
  411. }
  412. func FileKey(filename string, folderKey *[keySize]byte) *[keySize]byte {
  413. kdf := hkdf.New(sha256.New, append(folderKey[:], filename...), []byte("syncthing"), nil)
  414. var fileKey [keySize]byte
  415. n, err := io.ReadFull(kdf, fileKey[:])
  416. if err != nil || n != keySize {
  417. panic("hkdf failure")
  418. }
  419. return &fileKey
  420. }
  421. func PasswordToken(folderID, password string) []byte {
  422. return encryptDeterministic(knownBytes(folderID), KeyFromPassword(folderID, password), nil)
  423. }
  424. // slashify inserts slashes (and file extension) in the string to create an
  425. // appropriate tree. ABCDEFGH... => A.syncthing-enc/BC/DEFGH... We can use
  426. // forward slashes here because we're on the outside of native path formats,
  427. // the slash is the wire format.
  428. func slashify(s string) string {
  429. // We somewhat sloppily assume bytes == characters here, but the only
  430. // file names we should deal with are those that come from our base32
  431. // encoding.
  432. comps := make([]string, 0, len(s)/maxPathComponent+3)
  433. comps = append(comps, s[:1]+encryptedDirExtension)
  434. s = s[1:]
  435. comps = append(comps, s[:2])
  436. s = s[2:]
  437. for len(s) > maxPathComponent {
  438. comps = append(comps, s[:maxPathComponent])
  439. s = s[maxPathComponent:]
  440. }
  441. if len(s) > 0 {
  442. comps = append(comps, s)
  443. }
  444. return strings.Join(comps, "/")
  445. }
  446. // deslashify removes slashes and encrypted file extensions from the string.
  447. // This is the inverse of slashify().
  448. func deslashify(s string) string {
  449. s = strings.ReplaceAll(s, encryptedDirExtension, "")
  450. return strings.ReplaceAll(s, "/", "")
  451. }
  452. type rawResponse struct {
  453. data []byte
  454. }
  455. func (r rawResponse) Data() []byte {
  456. return r.data
  457. }
  458. func (r rawResponse) Close() {}
  459. func (r rawResponse) Wait() {}
  460. // IsEncryptedPath returns true if the path points at encrypted data. This is
  461. // determined by checking for a sentinel string in the path.
  462. func IsEncryptedPath(path string) bool {
  463. pathComponents := strings.Split(path, "/")
  464. if len(pathComponents) != 3 {
  465. return false
  466. }
  467. return isEncryptedParentFromComponents(pathComponents[:2])
  468. }
  469. // IsEncryptedParent returns true if the path points at a parent directory of
  470. // encrypted data, i.e. is not a "real" directory. This is determined by
  471. // checking for a sentinel string in the path.
  472. func IsEncryptedParent(path string) bool {
  473. return isEncryptedParentFromComponents(strings.Split(path, "/"))
  474. }
  475. func isEncryptedParentFromComponents(pathComponents []string) bool {
  476. l := len(pathComponents)
  477. if l == 2 && len(pathComponents[1]) != 2 {
  478. return false
  479. } else if l == 0 {
  480. return false
  481. }
  482. if len(pathComponents[0]) == 0 {
  483. return false
  484. }
  485. if pathComponents[0][1:] != encryptedDirExtension {
  486. return false
  487. }
  488. if l < 2 {
  489. return true
  490. }
  491. for _, comp := range pathComponents[2:] {
  492. if len(comp) != maxPathComponent {
  493. return false
  494. }
  495. }
  496. return true
  497. }