r/AskProgramming • • 2d ago

C# filestream writing to bitlocker drive binary files are corrupt, any ideas?

I wrote a program in c# that stores multiple files in a single file similar to zip or tar. That program just uses filestream writing, nothing fancy. I recently got a new computer, so I copied my compressed file onto the computer and was able to extract files from it.

After using my program, I used bitlocker on the ssd. Bitlocker gives you two options, use the old aes-cbc or new xts-aes cypher and if you want to do the entire drive or just existing files. I took the default of new xts-aes and only existing files. Let it run until the drive was encrypted and rebooted.

First thing I did after reboot was try to extract more files using my program and it found the input file corrupted. That shouldn't happen, but I just reloaded the file from a backup and things seemed to be working again. However, when I extracted to the encrypted ssd, text files were ok but media files like images and videos were corrupted. I used a diff tool and confirmed every single text was ok and every other file corrupted. Extracting from the same file on the encrypted ssd to a flash drive worked perfectly and nothing was corrupted. So only writing to the encrypted ssd from my app was having issues. Copying from the extracted files on the flash drive to the ssd also did not corrupt the files.

My understanding is bitlocker shouldn't care about the file type and it should be completely transparent to the application, yet thats not the behavior I was getting.

I then turned bitlocker off on the ssd, let it decrypt the drive and rebooted. The file on the ssd was not corrupted by the decrypt and extracts from the same file to the ssd now worked for all file types.

I turned bitlocker back on for the ssd and used the older aes-cbc and told it to encrypt everything including free space. After it completed and I rebooted, my program now correctly extracts files to the ssd.

So clearly other applications like the windows file copy didn't have issues with the bitlocker ssd and only my applcation did. I'm not able to come up with a theory as to how this could happen. I could see if everything was corrupted but the fact that text files are all ok is even more confusing. I used crystaldiskinfo to confirm there were no read or write failures on the ssd and the event logs don't show any errors reading or writing files to the ssd or bitlocker issues.

I guess my next step would be to decrypt the drive again and try the original bitlocker options to see if the problem returns. Any ideas what could be going on? Everything I've been able to read says bitlocker shouldn't care about the file type and bitlocker presence should be transparent to filestream writing in c#.

Edit: including relevent code

        public void Extract(string pFileName, long pSize)
        {
            byte[] vIV = ReadIV();
            CryptoStream cryptoStream = new(
               oFileStream,
               oAes.CreateDecryptor(oAes.Key, vIV),
               CryptoStreamMode.Read, true);
            {
                long vSize = pSize;
                int n = 0;
                using (FileStream vOutputFileStream = new FileStream(pFileName, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    do
                    {
                        n = MAXBUFFER;
                        if (vSize < n)
                            n = (int)vSize;
                        cryptoStream.ReadExactly(oBytes, 0, n);
                        vOutputFileStream.Write(oBytes, 0, n);
                        vSize -= n;
                    }
                    while (vSize > 0);
                    vOutputFileStream.Close();
                }
            }
        }
4 Upvotes

14 comments sorted by

3

u/PLBjt 2d ago

Text fine and binary broken smells like the code assumes Read fills the whole buffer. Stream.Read can return fewer bytes than you asked for, and the encrypted volume changes the I/O pattern enough that short reads start happening. Check that every Read uses the returned count (or ReadExactly on .NET 7+) and that you only write that many bytes back out. Also make sure nothing in the extract path goes through a StreamReader/StreamWriter or text-mode API, since an encoding pass leaves plain text intact and mangles everything else. Quick test: diff a broken file against the original and see if the first bad byte lands on a multiple of your buffer size.

1

u/XRay2212xray 2d ago

I do use readexactly. The file size is known and passed as a parameter to the code that extracts the data and the file that is produced is the exact right number of bytes. I'm going to have to try to reproduce and start looking thru the actual bytes to see where it goes wrong. I had been considering the text files might just all be smaller then something like the block size and the image and video larger. Since I knew the file size, I'm ultimately just reading that number of bytes. I know .read in older .net versions could return less then the full buffer but my understanding is readexactly would always read the complete number of bytes requested unless it hit eof. Its been working for years on my old computer but that was migrated from win 10 which was using the aes-cbc so maybe the newer encryption is throwing off the i/o patterns. Its published as a self contained single file exe with net9.0-windows10.0.26100.0 as the target framework. Added the code to the original post.

2

u/PLBjt 1d ago

Fair point, ReadExactly rules out the short-read theory. Since the sizes match, I'd compare the output against the source with a binary diff and look at where the first differing byte sits. If it's at a clean multiple of 4096 or your buffer size, suspect a buffer being reused or flushed before it's fully filled. If it's random, look at whether anything else touches the stream, like a second writer or a text-mode call. Also try the same extract to a non-BitLocker drive on the new machine so you know if the volume is even involved.

1

u/XRay2212xray 1d ago

Thanks. Ive got the write loop within a using block and ending with a close so thats pretty straight forward. I didn't do a flush before close, but my understanding is close should take care of the flush and the output file sizes were the exact right number of bytes.

As for exporting to other drives, thats how I started to suspect bitlocker is somehow interacting in an unexpected way. Export from the same file on the bitlocker drive to multiple flash and external usb hdd's worked completely. Also when I turned bitlocker off, it then worked on the ssd. I then tried different bitlocker settings and it worked. Last night I went back to the original bitlocker settings and now it seems to work there too. I guess I'll just leave it and if the problem starts occuring again save the corrupted files and hexdump them and see exactly where and what the differences are.

Thanks for your help. I appreciate your taking the time.

2

u/Good_Construction190 2d ago

Are you flushing and closing streams?

1

u/XRay2212xray 2d ago

I added the code to the post. The output is wrapped in a using and I do call close but not flush. My understanding is that close will handle the flushing. I guess if all else fails I could explicitly add the flush.

1

u/Good_Construction190 2d ago

You shouldn't have to

1

u/phirzcolru 2d ago

If the person writing the code takes the wandering bits into consideration

7

u/dodexahedron 2d ago

Bitlocker is completely transparent to applications. File contents are never exposed encrypted and, in fact, unless you have unlocked the volume in tje first place, you wouldn't even be able to enumerate the contents of it and open the file at all.

So no. Bitlocker is not involved.
This is a program bug or an invocation or environment difference (or multiple of the above).

First, attempt to reproduce the problem. I suspect you will not be able to, and that your problem was simply around how it was invoked or some other potentially tiny difference between the failed and successful runs. This could include threading issues, as well, or anything else causing non-deterministic behavior of your deserializer code.

If you do manage to reproduce it, show us the code for your program, the way you invoked it, and an example data file that reproduces the problem.

Otherwise, IO on composed streams with a FileStream at the bottom will work just fine so long as the writer and the reader use exactly the same composition, and the data on disk will be whatever results from applying the transformations of each stream, in sequence, from top to bottom of the stack of streams. And then you can read it back with the same stack, which does the same stuff in reverse for you already.

Oh also...

.net version may matter, depending on what the data itself is and its encoding at each layer of that stream stack. A recompilation, especially after a reboot, may have changed the environment due to an update, for example.

No matter what, the answer to the question is that no, Bitlocker doesnt have anything at all to do with this and you would have a lot more problems, a lot earlier, if it did.

5

u/DamienTheUnbeliever 2d ago

Almost certainly there's one or more race conditions in *your code* that are being exposed because the IO to the bitlocker drive takes *slightly longer* and uses a bit more CPU.

1

u/chrisvenus 1d ago

Looking at the code I see oBytes being used but not declared locally. I wonder if it's a shared variable and as you say multiple things using it at the same time is causing a race.

3

u/henke37 2d ago

Post code.

2

u/Away_Ranger_6458 1d ago

BitLocker operates at the block/volume level below the filesystem, so a normal FileStream shouldn't see ciphertext or care whether XTSBitLocker operates at the block/volume level below the filesystem, so a normal FileStream shouldn't see ciphertext or care whether XTS-AES is enabled. If corruption only started after encrypting, I'd suspect either an incomplete flush/dispose in your C# writer (using block or Flush(true)) or a subtle SSD/driver issue under load. Try computing a SHA-256 hash right after writing and again after rebooting to isolate whether it's a write-buffering bug or disk corruption.-AES is enabled. If corruption only started after encrypting, I'd suspect

1

u/ih-shah-may-ehl 2d ago

Absolutely 100% guaranteed the problem is your code, not bitlocker