0 votes
by (120 points)

I was looking at if it would be possible to hook the transfer and output file streams to perform some operations on the stream (Specifically write the file encrypted). I thought it may be possible by implementing the abstract class ReadWriteFileSystemProvider but while I can gain access to the stream of the file I can't see any method of gaining access to the network stream and don't see any method of handling the write operation myself.

Thank you for any advice.

Applies to: Rebex SFTP

1 Answer

0 votes
by (148k points)

The custom file system provider is not writing to a network stream because unlike FTP, the SFTP protocol is a remote file system protocol with request/response architecture. It's not stream-based, and it allows random access, so read/write requests are not even guaranteed to be sequential.

When the SFTP client is about to transfer a file, it opens the file, issues a series of read or write requests and closes the file. ReadWriteFileSystemProvider's GetContent method is called when the client opens the file, and it can be customized to return a custom Stream. Then, when the client reads a block of data, the stream's Read method will be called to retrieve this data. And when the client writes a block of data, the stream's Write method will be called to save the new data.

This means that you can implement encryption in the Write method and decryption in the Read method, but you have to take the random-access nature of the SFTP protocol into account. That makes simple stream-based encryption schemes unsuitable (at least unless you severely limit the amount of actions SFTP clients can perform). However, there are encryption methods designed with this in mind, such as XTS-AES implemented by Rebex Security.

by (120 points)
Lukas,

Thanks for the feedback. I was able to get it to work by giving a memory stream in the getcontent and then encrypting that to a file but that is not a practical solution because some files may be large. Does the suggested library allow for encrypting the stream without the unencrypted file ever being at rest and does it support asymmetric keys?

Thanks for the help
by (148k points)
Yes, solutions based on memory streams are only suitable for small files, unfortunately.
Rebex Security supports asymmetric RSA keys: https://www.rebex.net/security.net/features/xts-aes.aspx#rsa-keys
by (120 points)
Lukas,

That's good to hear so that solution could be used to stream directly to the file encrypted without having the decrypted version of the file ever remaining at rest on desk?

Again thank you for your help.
by (148k points)
Yes, no decrypted would get saved to disk if all writes/reads are done via XtsStream.
...