-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFolderLocker.cs
More file actions
260 lines (216 loc) · 11.7 KB
/
FolderLocker.cs
File metadata and controls
260 lines (216 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
using System.IO;
using System.IO.Compression;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
namespace WinFolderLock
{
internal static class FolderLocker
{
// File format:
// [8 bytes] magic = "WFLCKV1\0"
// [4 bytes] int protectedKeyLength (little-endian)
// [protectedKeyLength bytes] protected AES key (DPAPI LocalMachine)
// [12 bytes] nonce
// [16 bytes] tag
// [remaining bytes] ciphertext
private static readonly byte[] Magic = Encoding.ASCII.GetBytes("WFLCKV1\0");
public static void LockFolder(string folderPath, string lockedFilePath, bool overwriteExisting = false)
{
if (string.IsNullOrWhiteSpace(folderPath)) throw new ArgumentNullException(nameof(folderPath));
if (string.IsNullOrWhiteSpace(lockedFilePath)) throw new ArgumentNullException(nameof(lockedFilePath));
if (!Directory.Exists(folderPath)) throw new DirectoryNotFoundException(folderPath);
string sessionDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WinFolderLock", "Sessions", Path.GetRandomFileName());
Directory.CreateDirectory(sessionDir);
var tempZip = Path.Combine(sessionDir, Path.GetRandomFileName() + ".zip");
try
{
ZipFile.CreateFromDirectory(folderPath, tempZip, CompressionLevel.Optimal, includeBaseDirectory: false);
var plaintext = File.ReadAllBytes(tempZip);
var key = new byte[32];
RandomNumberGenerator.Fill(key);
var protectedKey = ProtectedData.Protect(key, null, DataProtectionScope.CurrentUser);
var nonce = new byte[12];
RandomNumberGenerator.Fill(nonce);
var tag = new byte[16];
var ciphertext = new byte[plaintext.Length];
using (var aesgcm = new AesGcm(key, 16))
{
aesgcm.Encrypt(nonce, plaintext, ciphertext, tag, null);
}
var fileMode = overwriteExisting ? FileMode.Create : FileMode.CreateNew;
using (var fs = new FileStream(lockedFilePath, fileMode, FileAccess.Write, FileShare.None))
using (var bw = new BinaryWriter(fs))
{
bw.Write(Magic);
bw.Write(protectedKey.Length);
bw.Write(protectedKey);
bw.Write(nonce);
bw.Write(tag);
bw.Write(ciphertext);
}
var attributes = File.GetAttributes(lockedFilePath) & ~FileAttributes.Hidden & ~FileAttributes.System;
File.SetAttributes(lockedFilePath, attributes | FileAttributes.Archive);
SetAdminOnlyAcl(lockedFilePath);
Directory.Delete(folderPath, recursive: true);
}
finally
{
try { if (File.Exists(tempZip)) File.Delete(tempZip); } catch (Exception ex) { Helper.LogError(ex); }
try { if (Directory.Exists(sessionDir)) Directory.Delete(sessionDir, recursive: true); } catch (Exception ex) { Helper.LogError(ex); }
}
}
public static void UnlockFolder(string lockedFilePath, string destinationFolderPath, bool deleteLockedFile = false)
{
if (string.IsNullOrWhiteSpace(lockedFilePath)) throw new ArgumentNullException(nameof(lockedFilePath));
if (string.IsNullOrWhiteSpace(destinationFolderPath)) throw new ArgumentNullException(nameof(destinationFolderPath));
if (!File.Exists(lockedFilePath)) throw new FileNotFoundException(lockedFilePath);
if (Directory.Exists(destinationFolderPath)) throw new IOException("Destination folder already exists: " + destinationFolderPath);
byte[] protectedKey;
byte[] nonce = new byte[12];
byte[] tag = new byte[16];
byte[] ciphertext;
using (var fs = new FileStream(lockedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var br = new BinaryReader(fs))
{
var magicBytes = br.ReadBytes(Magic.Length);
if (!IsMagicValid(magicBytes))
throw new InvalidDataException("File is not a valid .wflck file.");
var protectedKeyLength = br.ReadInt32();
if (protectedKeyLength <= 0 || protectedKeyLength > 10_000)
throw new InvalidDataException("Invalid protected key length in .wflck file.");
protectedKey = br.ReadBytes(protectedKeyLength);
if (protectedKey.Length != protectedKeyLength) throw new EndOfStreamException();
if (br.Read(nonce, 0, nonce.Length) != nonce.Length) throw new EndOfStreamException();
if (br.Read(tag, 0, tag.Length) != tag.Length) throw new EndOfStreamException();
var remaining = (int)(fs.Length - fs.Position);
ciphertext = br.ReadBytes(remaining);
if (ciphertext.Length != remaining) throw new EndOfStreamException();
}
var key = ProtectedData.Unprotect(protectedKey, null, DataProtectionScope.CurrentUser);
var plaintext = new byte[ciphertext.Length];
using (var aesgcm = new AesGcm(key, 16))
{
aesgcm.Decrypt(nonce, ciphertext, tag, plaintext, null);
}
var tempZip = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".zip");
try
{
File.WriteAllBytes(tempZip, plaintext);
// Ensure destination folder exists before extracting
Directory.CreateDirectory(destinationFolderPath);
ZipFile.ExtractToDirectory(tempZip, destinationFolderPath);
if (deleteLockedFile)
{
try { File.SetAttributes(lockedFilePath, FileAttributes.Normal); } catch { }
File.Delete(lockedFilePath);
}
}
finally
{
try { if (File.Exists(tempZip)) File.Delete(tempZip); } catch (Exception ex) { Helper.LogError(ex); }
Array.Clear(key, 0, key.Length);
Array.Clear(plaintext, 0, plaintext.Length);
}
}
public static bool IsLockedFile(string filePath)
{
if (!File.Exists(filePath)) return false;
try
{
using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var header = new byte[Magic.Length];
var read = fs.Read(header, 0, header.Length);
return read == header.Length && IsMagicValid(header);
}
catch (Exception ex)
{
Helper.LogError(ex);
return false;
}
}
private static bool IsMagicValid(byte[] header)
{
return header.SequenceEqual(Magic);
}
private static void SetAdminOnlyAcl(string path)
{
var fileInfo = new FileInfo(path);
try
{
// Best-effort: add explicit allow rules for the creating user, Users group (read), Administrators and SYSTEM.
// Do not change ownership or toggle inheritance to avoid requiring elevated privileges.
var security = fileInfo.GetAccessControl();
var currentUserSid = WindowsIdentity.GetCurrent()?.User;
if (currentUserSid != null)
{
security.AddAccessRule(new FileSystemAccessRule(currentUserSid, FileSystemRights.FullControl, AccessControlType.Allow));
}
var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
security.AddAccessRule(new FileSystemAccessRule(users, FileSystemRights.ReadAndExecute | FileSystemRights.ReadAttributes | FileSystemRights.ReadData, AccessControlType.Allow));
var system = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
security.AddAccessRule(new FileSystemAccessRule(system, FileSystemRights.FullControl, AccessControlType.Allow));
var admins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
security.AddAccessRule(new FileSystemAccessRule(admins, FileSystemRights.FullControl, AccessControlType.Allow));
fileInfo.SetAccessControl(security);
}
catch (Exception ex)
{
Helper.LogError(ex);
// If ACL updates fail (permission issues), continue without failing the lock operation.
}
}
public static string UnlockFolderToTemp(string lockedFilePath)
{
if (string.IsNullOrWhiteSpace(lockedFilePath)) throw new ArgumentNullException(nameof(lockedFilePath));
if (!File.Exists(lockedFilePath)) throw new FileNotFoundException(lockedFilePath);
byte[] protectedKey;
byte[] nonce = new byte[12];
byte[] tag = new byte[16];
byte[] ciphertext;
using (var fs = new FileStream(lockedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var br = new BinaryReader(fs))
{
var magicBytes = br.ReadBytes(Magic.Length);
if (magicBytes.Length != Magic.Length || !IsMagicValid(magicBytes))
throw new InvalidDataException("File is not a valid .wflck file.");
var protectedKeyLength = br.ReadInt32();
if (protectedKeyLength <= 0 || protectedKeyLength > 10_000)
throw new InvalidDataException("Invalid protected key length in .wflck file.");
protectedKey = br.ReadBytes(protectedKeyLength);
if (protectedKey.Length != protectedKeyLength) throw new EndOfStreamException();
var read = br.Read(nonce, 0, nonce.Length);
if (read != nonce.Length) throw new EndOfStreamException();
read = br.Read(tag, 0, tag.Length);
if (read != tag.Length) throw new EndOfStreamException();
var remaining = (int)(fs.Length - fs.Position);
ciphertext = br.ReadBytes(remaining);
if (ciphertext.Length != remaining) throw new EndOfStreamException();
}
var key = ProtectedData.Unprotect(protectedKey, null, DataProtectionScope.CurrentUser);
var plaintext = new byte[ciphertext.Length];
using (var aesgcm = new AesGcm(key, 16))
{
aesgcm.Decrypt(nonce, ciphertext, tag, plaintext, null);
}
string sessionDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WinFolderLock", "Sessions", Path.GetRandomFileName());
Directory.CreateDirectory(sessionDir);
var tempZip = Path.Combine(sessionDir, Path.GetRandomFileName() + ".zip");
var tempExtractPath = Path.Combine(sessionDir, "extracted");
try
{
File.WriteAllBytes(tempZip, plaintext);
Directory.CreateDirectory(tempExtractPath);
ZipFile.ExtractToDirectory(tempZip, tempExtractPath);
return tempExtractPath;
}
finally
{
try { if (File.Exists(tempZip)) File.Delete(tempZip); } catch (Exception ex) { Helper.LogError(ex); }
Array.Clear(key, 0, key.Length);
Array.Clear(plaintext, 0, plaintext.Length);
}
}
}
}