Skip to content

Implement encrypted devices - #6214

Closed
calmh wants to merge 47 commits into
syncthing:masterfrom
calmh:encryption
Closed

calmh wants to merge 47 commits into
syncthing:masterfrom
calmh:encryption

Conversation

@calmh

@calmh calmh commented Dec 5, 2019 •

Copy link
Copy Markdown
Member

Since it came up again, here's a fairly lightweight attempt at encrypted devices. It's early days and lots of user friendlyness lacking, but the basics work for me. I can sync files back and forth to an encrypted device. In principle it works like this:

  • The encryption is added as a shim at the protocol layer, transforming Index(Updated)/Request/Response messages. There is no new folder type or such.
  • Only the sending (encrypting) side needs to know that encryption is enabled; the other side doesn't need to know or care.
  • Both sides need to be upgraded to this version though, because there is a new field in the FileInfo that needs to be sent over the wire and retained in the database on encrypted devices.
  • The encryption is enabled by setting an encryption password config on a given device+folder.
  • The encryption hides everything except file sizes which are derivable from but not identical to the original (some per-block overhead). We could easily pad this to further obfuscate file sizes, but splitting up completely might be more difficult. I think we're fine here as long as we're similar to the level of encfs etc.
  • All items in an encrypted folder get encrypted names, with slashes inserted to follow max path component lengths.

Protocol wise, it's like this:

  • Encryption is AES-GCM.
  • Key derivation is scrypt, with fixed salt (we need to generate the same key on two different but equivalently configured devices).
  • Nonces for block hashes and file names are based on the content, passed through pbkdf2 (we need the encrypted strings to match for two different devices doing the same encryption).
  • Nonces for data are random; we don't need the actual encrypted data blocks to look the same for two different devices.
  • FileInfos get encrypted and packed into a new field in a "wrapping" FileInfo. This FileInfo has an encrypted name, other attributes are essentially empty or static except for the block list. The block list gets rewritten to have the same number of blocks but each being a little bit larger to account for encryption overhead. There are some comments in encryption.go to explain the transformation.
  • Requests/Responses get tweaked to account for the changed size on the wire compared to on disk.

That's pretty much it.

On the encrypted side, the folder type should be receive only and don't do any scans... Changes to the stuff on the encrypted side will predictable break things.

Other code changes are mostly to account for hashes being nil on encrypted files, so they cannot be verified, and to propagate the block number being pulled. This latter simplifies calculating the correct offset for a block, as we know how many block overheads to add or remove...

Comment thread lib/protocol/encryption.go Resolved
Comment thread lib/protocol/encryption.go Resolved
Comment thread lib/connections/service.go Resolved
Comment thread lib/model/folder_sendrecv.go Resolved
Comment thread lib/protocol/encryption.go Resolved
Comment thread lib/protocol/encryption.go Resolved
Comment thread lib/protocol/encryption.go Resolved
@AudriusButkevicius

Copy link
Copy Markdown
Member

In a Christmas party totally drunk but

@AudriusButkevicius AudriusButkevicius left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this potentially cuts in in the wrong place and abuses the existing protocol to try and wedge it in.

I've though about this multiple times and these are my thoughts:

There are a few different aspects on what users want from this. First, they want the data to be encrypted, fine, but they also want that encrypted data to be sent forward. I am not sure, but I guess this is covered by this implementation. Second things users want, is for a device to be able to receive and decrypt data, yet not be able to send any new data to the cluster, hence I think what we need is separate concept for encryption and a separate concept for signing. Keys for both of these things can be derived from the same master key, or the user can share the decryption only key, or decryption + signing. I am not sure, but I think with decryption key, we can still have the data, receive it, and pass it on to others, including the index entries we've received and stored ourselves would still be signed (I don't think device having a file updates the clocks in anyway) and forwardable. We can have a simillar scheme like btsync where we have three different keys, master key (signing key priv, encryption key), read (validate signatures with signing key pub), read decrypt (validate signatures signing key pub, and decrypt)

I think this might be a better approach (which I think echoes your early day proposal):

  1. Add signature and nonce fields to a file info
  2. In scanner, produce fileinfos with encrypted names (each path component encrypted individually, to still have a structure, and a healthy fs index), file size of encrypted file, real hashes of encrypted content, nonce and signature.
  3. In request handler, check if we have a key, decrypt filename, read content, encrypt content, do hash validation, send. (Maybe some signing?)
  4. In index handler check signatures of index before accepting them.
  5. Add a flag to cluster config to signify you expect signed indexes, do not start index sender if we don't have a signing key and the other side expects signed indexes.
  6. Store hash of the keys (or absence of them) in the database. When adding the folder, validate it matches, if it does not, drop the index and rescan.
  7. Break protocol as much as we need to not to have a hacked/wedged functionality.

Comment thread lib/protocol/encryption.go Outdated
bs := pbkdf2.Key(append(data, (*key)[:]...), nonceSalt[:], 4096, 24, sha256.New)
var nonce [24]byte
copy(nonce[:], bs)
return &nonce

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure this is kosher from crypto perspective. The point of the nonces is that they should be random

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I've done some reading and thinking on this. Nonces don't have to be random but any given nonce must only be used once for any given key + data. Having the nonce be the hash of data is something I've seen elsewhere and I'm 99% sure it's fine as long as the key is not varied. Mixing it with the key like this makes it so that you can't guess the original data and check the hash, and makes it safe to re-encrypt the same data with another key.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't fully understood the code yet, so the following may be incorrect, but:

As I understand this, there is a single (per-device-per-folder-doesn't-matter) key used in all encryption and decryption processes [assuming only 1 encrypted device & 1 encrypted folder]. This key is pretty static, as in it's not automatically changed/rotated. The static key is used in this function, together with the hash of a single plaintext-block in order to create a deterministic nonce.

If the above is true, two identical plaintext blocks will result in the same nonce (since the key is static). Since the nonce isn't hidden in any way, this enables an attacker to immediatly detect if two blocks contain the same plaintext. This information can be used by an attacker to perform statistical analysis on the ciphertext, if the plaintext contains repeating patterns. In a worst case scenario, data is repeating in intervalls multiple of the block size so that lots of blocks are identical, giving a lot of attack surface - if a single plaintext block can be guessed, all other identical blocks are known. This is basically the "standard attack on ECB".

Again, all of this holds only if my assumptions above are true.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a safety-net is to use a SIV or RIV cipher-mode.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The above is probably true, but note that deterministic nonces are not used for the actual data blocks -- it's used for encrypting file names and hashes. I'm not sure if this makes it better or worse. It's still possible to recognize a repeated block of plaintext by the encrypted hash; Syncthing needs to do this recognition or any change to a file will always require transferring all the blocks. Unless this does break the security of the key (I'll look into SIV & RIV) I think that's a valid tradeoff to retain Syncthing-typical behavior even with encrypted files.

@calmh calmh Dec 18, 2019 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, the last block of the file can be arbitrarily small though, down to a single byte. If this is a problem we could pad it up to a full block size without too much pain I think. That'll mean potentially a lot of lost space, if you have a million 1 KiB files that becomes a million 128 KiB files...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added padding up to a kilobyte for small blocks, just to see how it looks. Not clear to me if this is a real security gain or not?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't fully understood the proposal (mainly because my Go-fu is lacking) and AFAICS, you're intending to use SIV on blocks (or chunks, parts, whatever your lingo is). So you need to have a protocol on top to tie several blocks back to a full piece.
Let me ask this silly question: Can truncations be a problem? I.e. the attacker strips a suffix (e.g. the last block). Can this be detected? Will this have an adverse effect?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not using SIV for the blocks, those are standard AES-GCM with a random nonce. If the untrusted device (potential attacker) returns bad data it will fail to decrypt, as AES-GCM (and SIV I think?) authenticates before decryption. Even if it didn't, it would fail at the next step as the data wouldn't match the expected cleartext length & hash, which is verified as part of the pulling process for every block, regardless of whether it was encrypted or not on the other side.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, the last block of the file can be arbitrarily small though, down to a single byte. If this is a problem we could pad it up to a full block size without too much pain I think. That'll mean potentially a lot of lost space, if you have a million 1 KiB files that becomes a million 128 KiB files...

If the size of a block isn't hidden, very small blocks make guessing a bit easier - worst case, I have lot's of one-byte files. If the attacker has some sort of side-channel that allows verification if a guess was correct, it's trivially easy to decrypt even a million one-byte files. The effect increases further when blocks exist more than once.

But this scenario even works if file size was fully protected/unknown, because an attacker could assume that every file is very small. Even further, the theoretical attack could even work entirely without syncthing. So the main point is that leaking the file size assists in guessing, but not leaking it doesn't prevent anything.

I don't want to lean myself too much out of the window, but I say small blocks in itself are not the issue. I don't believe small block padding adds much value, altough I may have missed something in my considerations. In any case, padding has no value if the true plaintext size is known to the untrusted device.

Comment thread lib/protocol/encryption.go Resolved
@calmh

calmh commented Dec 6, 2019 •

Copy link
Copy Markdown
Member Author

I hear you about there being more flexible ways of doing it, but I think there is value in not breaking everything and rebuilding from start. I'm super open to considering alternatives, but pragmatically we haven't been able to implement this for many years and this is the simplest approach I could imagine actually working.

As is, this can be forwarded and chained: A <-encrypted-> B <-normal-> C <-encrypted-> D works fine with just A and D having the password and with B and C seeing just nonsense data.

Not accepting new data from B or C is kind of already in this - non-encrypted FileInfos will cause a decryption failure and drop the connection. :) And there is no way for B or C to create properly encrypted FileInfos without the key. Perhaps you meant the ability to prevent that without running with a fully encrypted device -- i.e., just untrusted but not encrypted.

Certainly there should/will be some negotiation in the ClusterConfig, the message should also be cleaned from mentioning other devices and such.

@calmh

calmh commented Dec 6, 2019

Copy link
Copy Markdown
Member Author

I created https://forum.syncthing.net/t/lates-encrypted-devices-proposal-what-how/14164 for the more general "does this even do what we want?" discussion as that will get unwieldy here. Actual code review to stay here of course, if we get to the point where that's relevant.

@AudriusButkevicius

Copy link
Copy Markdown
Member

Right, let me try to build up the will power and take a stab at this as well. I guess we can continue iron this one out, just in case I flop and never get to doing it.

We're making a somewhat breaking protocol changes here anyway, we might as well do it right.

@calmh

calmh commented Dec 6, 2019

Copy link
Copy Markdown
Member Author

Please do. :) There’s nothing breaking here though. Yeah, encrypted devices will only work with the new version, but nothing existing breaks. It’s not like a 2.0-and-force-everyone-to-upgrade.

* master:
  lib/db, lib/protocol: Compact FileInfo and BlockInfo alignment (syncthing#6215)
@AudriusButkevicius

AudriusButkevicius commented Dec 9, 2019 •

Copy link
Copy Markdown
Member

The more I look into this, the more I think this is probably the path of least resistance.
I'd extend the protocol in any way necessary not to need blob in a blob stuff (add salt/nonce whatever is necessary to the file decrypt stuff on the file, don't just munge it into a random blob field and set everything else to garbage).

I found https://godoc.org/github.com/capitalone/fpe/ff1 which can be used for encrypting integers, path components, while still being ok in terms of security, which we might find interesting.

Ideally we'd extend this to support signing, and clearly this needs per-folder "refuse-unsigned indexes and let other side know" support.

@calmh

calmh commented Dec 10, 2019 •

Copy link
Copy Markdown
Member Author

So about the blob. I can see the blob being "ugly", but it has a cleanliness advantage too. No device is interested in a mix of encrypted and cleartext attributes -- either you're working with the real FileInfo, or the real data is hidden from you. So I see no real advantage in treating all the attributes individually and having branching in places further out -- "should I look at the real mtime? or the encrypted mtime?". Doing the translation earlier and switching out the entire FileInfo makes sure that the handling is consistent regardless.

As for paths & names... I think it's a feature that the directory structure is hidden. There is no advantage in exposing to the untrusted device which files belong together in a directory and it makes correlation of what kind of data it is easier. The (potentially) too-long names are still a problem that needs solving though... I think just splitting at intervals and having the destination device know that it's OK to create the intermediate directories for encrypted files could be enough. Or we could decouple the storage path from the name in the FileInfo. We need the name in the FileInfo to be reversible to the real name, but the on-disk file could live in sha256(encrypted-filename) or such. We don't need to be able to go from on-disk encrypted file to FileInfo, because no changes to these files should ever be scanned.

And of course it should be per-folder, yes.

@AudriusButkevicius

Copy link
Copy Markdown
Member

I don't think there is much difference in whether we store stuff in an encrypted blob or in the actual field. If anything the latter is less alienating for consumers of the protocol. The fact you bodge fields now to some static values and get it from the encrypted blob is no different from the values being generally encrypted and pointing to year 3000 and decryption just converting year 3000 to 2019.

@calmh

calmh commented Dec 10, 2019

Copy link
Copy Markdown
Member Author

I think I'm not understanding your actual point then. :)

@AudriusButkevicius

Copy link
Copy Markdown
Member

What I mean is that you currently have in clear text:

FileInfo{
   Mtime: <real mtime>
   EncryptedBlob: nil
}

after encryption that becomes

FileInfo{
   Mtime: <static garbage>
   EncryptedBlob: enc(<real mtime>)
}

Instead, I think we should do:

FileInfo{
   Mtime: enc(<real mtime>)
   Nonce/Salt/Pepper/WhateverIsNeededtoDecodeStuff: <stuff needed to turn encrypted mtime into real one>
}

so this are what they are (regardless what form they are in).

Comment thread lib/protocol/encryption.go Resolved
Comment thread lib/protocol/encryption.go Resolved
Comment thread lib/protocol/encryption.go Resolved
* master:
  golangci: Skip godox
  build(deps): bump github.com/mattn/go-isatty from 0.0.10 to 0.0.11 (syncthing#6231)
  lib/upgrade: Let Mac load .zip archives (syncthing#6230)
  lib/api: Prevent leaks in tests (syncthing#6227)
  lib/syncthing: Expose backend instead of lowlevel (syncthing#6224)
  gui: Prevent spurious api call (fixes syncthing#6222) (syncthing#6223)
  gui: Fix a typo in a class name (syncthing#6220)
  gui: Allow to degrade 'Automatic upgrades' option to 'No upgrades' (fixes syncthing#6044) (syncthing#6168)

@imsodin imsodin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cool - thanks for giving me a reason to engage a bit with crypto :)

// Very small blocks will be padded upwards to minPaddedSize.
//
// The encrypted hash becomes just a "token" for the data -- it doesn't
// help verifying it, but it lets the encrypted device to block level

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// help verifying it, but it lets the encrypted device to block level
// help verifying it, but it lets the encrypted device do block level

Comment thread lib/protocol/encryption.go Resolved
Comment thread lib/protocol/protocol.go Resolved
Comment thread lib/scanner/walk.go
}

// If the directory is an encrypted data container it can't currently be
// scanned. (Special handling here in the future?)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As your mentioning future: To not require such hacks and for a nice UI representation I'd add an explicit new folder type, activated by some indication in the BEP (or just act on any "side-effect" like non-AES hashes or the presence of the Encrypted field in a file-info). Then we can disable scanning (and FS watching) all-together and adjust the controls in the UI too.

* master: (32 commits)
  gui, man, authors: Update docs, translations, and contributors
  lib/config, lib/model: Limit concurrent pulls (fixes syncthing#5914) (syncthing#6290)
  lib/db: Fixup last commit with better key name
  lib/db: Configurable block GC time (syncthing#6295)
  lib/db: Deduplicate block lists in database (fixes syncthing#5898) (syncthing#6283)
  lib/relays: Fix incorrect timeout, bring back logging (ref syncthing#6289) (syncthing#6291)
  gui, man, authors: Update docs, translations, and contributors
  all: Transactionalize db.FileSet (fixes syncthing#5952) (syncthing#6239)
  lib/model: Handle progress emitter zero interval (fixes syncthing#6281) (syncthing#6282)
  build(deps): bump github.com/pkg/errors from 0.9.0 to 0.9.1 (syncthing#6279)
  cmd/syncthing: Always use monitor process (fixes syncthing#4774, fixes syncthing#5786) (syncthing#6278)
  lib/syncthing: Wait for actual termination on Stop() (syncthing#6277)
  lib/model: Remove legacy handling of symlinks (syncthing#6276)
  lib/model: Return paused summary instead of error on paused folders (syncthing#6272)
  lib/config: Add some info to the folder marker missing (ref syncthing#5207) (syncthing#6270)
  assets, gui: Losslessly compress all JPG, PNG, and PDF images (syncthing#6265)
  cmd/strelaypoolsrv: Serve gzip compressed responses
  gui, man, authors: Update docs, translations, and contributors
  gui, man, authors: Update docs, translations, and contributors
  build: go mod tidy
  ...
@imsodin

imsodin commented Feb 5, 2020 •

Copy link
Copy Markdown
Member

calmh added 3 commits March 7, 2020 11:15
* master: (64 commits)
  lib/db: Be more lenient during migration (fixes syncthing#6397) (syncthing#6398)
  lib/db: Be more lenient during migration (fixes syncthing#6397) (syncthing#6398)
  cmd/ursrv: Analytics for Synology dist
  build: Build image should use Go 1.13 for now
  gui, lib/api: Remove CPU & RAM measurements (fixes syncthing#6249) (syncthing#6393)
  gui, man, authors: Update docs, translations, and contributors
  all: Tweak error creation (syncthing#6391)
  authors: Cleanup on request
  build: We can now use Go 1.13
  lib/db: Prevent GC concurrently with migration (fixes syncthing#6389) (syncthing#6390)
  lib/db: Prevent GC concurrently with migration (fixes syncthing#6389) (syncthing#6390)
  build: Fix syso creation (fixes syncthing#6386) (syncthing#6387)
  build: Fix syso creation (fixes syncthing#6386) (syncthing#6387)
  lib/db: Correct metadata recalculation (fixes syncthing#6381) (syncthing#6382)
  lib/db: Correct metadata recalculation (fixes syncthing#6381) (syncthing#6382)
  lib/db: Remove reference to env var that never existed
  lib/db: Slightly improve indirection (ref syncthing#6372) (syncthing#6373)
  lib/db: Remove reference to env var that never existed
  lib/db: Slightly improve indirection (ref syncthing#6372) (syncthing#6373)
  build: Forked github.com/spaolacci/murmur3 for unsafe (ref syncthing#6371)
  ...
* master:
  lib/protocol: Zero pad index ID strings
  lib/db: Don't ignore failures unmarshaling version lists (syncthing#6411)
  lib/db: Use need func in withNeed and simplify (syncthing#6412)
  cmd/syncthing: Do auto-upgrade before startup (fixes syncthing#6384) (syncthing#6385)
  lib/db: Extend set test with second remote (syncthing#6402)
  gui, man, authors: Update docs, translations, and contributors
  lib/protocol: Use BlocksHash to compare block lists when available (syncthing#6401)
  lib/api: Ignore that one file that always shows up in git status
@imsodin

imsodin commented May 5, 2020 •

Copy link
Copy Markdown
Member

To reduce the length of this PR conversation and focus on just code here I posted plans/questions on UX on the companion forum thread, please weigh in there. There's also a bit about protocol/crypto.
https://forum.syncthing.net/t/latest-encrypted-devices-proposal-what-how/14164/49

@imsodin

imsodin commented May 19, 2020 •

Copy link
Copy Markdown
Member

I get why the new BEP block_no field in requests is required for encryption, however I think the currently handling is a bit half-baked: We always set it but ignore it unless it's an encrypted device, because it's redundant with size and offset. In addition it essentially elevates the current SHOULD, that the requested data range is equivalent to a single block, to a MUST.
I think it would be cleaner if we make this explicitly an alternative/extension to the current request format: You can instead of requesting by size and offset request a specific block number, using block_no and an additional new field block_size. Meaning both pairs of arguments are still valid, but not meant to be used together in a single request.
Does that make any sense?

@calmh

calmh commented May 19, 2020

Copy link
Copy Markdown
Member Author

Downside with that is that it doesn't work well for the last block which non-block-sized... I mean, sure, you can get whatever they happen to have lying around and the if the hash matches it's the same data... but it's a bit weird?

@calmh

calmh commented May 19, 2020

Copy link
Copy Markdown
Member Author

Adding just block_size might do as well

@imsodin

imsodin commented May 19, 2020

Copy link
Copy Markdown
Member

Why weird? I'd consider it perfectly normal to get e.g. 5kB of data when requesting block 7 with a blocksize of 10kB for a file of size 75kB.

@calmh

calmh commented May 19, 2020 •

Copy link
Copy Markdown
Member Author

Okay. We'd have to stat the file to figure out the size of buffer we need to do the read. Or do a database get. As is, it's explicit in the request.

@calmh calmh closed this Jun 15, 2020
@calmh
calmh deleted the encryption branch November 11, 2020 18:39
@st-review st-review added the frozen-due-to-age Issues closed and untouched for a long time, together with being locked for discussion label Jun 16, 2021
@syncthing syncthing locked and limited conversation to collaborators Jun 16, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

frozen-due-to-age Issues closed and untouched for a long time, together with being locked for discussion

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants