encryption.go 16 KB

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