-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecureStore.cs
More file actions
110 lines (96 loc) · 3.78 KB
/
SecureStore.cs
File metadata and controls
110 lines (96 loc) · 3.78 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
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text.Json;
namespace Secure_Store
{
public class Storage
{
public static class SecureStore
{
private static string BasePath
{
get
{
// Use per-session temp directory on all platforms
string sessionDir = Path.Combine(Path.GetTempPath(), "SECURE_STORE" + Environment.UserName);
Directory.CreateDirectory(sessionDir);
return sessionDir;
}
}
private static string GetPath(string key) =>
Path.Combine(BasePath, $"secstr_{key}.dat");
private static void EnsureFolder()
{
if (!Directory.Exists(BasePath))
{
Directory.CreateDirectory(BasePath);
if (OperatingSystem.IsWindows())
{
try
{
var dirInfo = new DirectoryInfo(BasePath);
var dirSecurity = dirInfo.GetAccessControl();
// Remove inheritance & keep only explicit rules
dirSecurity.SetAccessRuleProtection(true, false);
// Give full control to current user only
var currentUser = WindowsIdentity.GetCurrent().User!;
dirSecurity.AddAccessRule(new FileSystemAccessRule(
currentUser,
FileSystemRights.FullControl,
AccessControlType.Allow
));
dirInfo.SetAccessControl(dirSecurity);
// Hide the folder from casual browsing
dirInfo.Attributes |= FileAttributes.Hidden | FileAttributes.System;
}
catch
{
// If ACLs fail, fall back silently; still writable
}
}
}
}
public static void Set<T>(string key, T value)
{
EnsureFolder();
string path = GetPath(key);
string json = JsonSerializer.Serialize(value);
File.WriteAllText(path, json);
if (!OperatingSystem.IsWindows())
{
ApplyUnixPermissions(path);
}
}
public static T? Get<T>(string key)
{
string path = GetPath(key);
if (!File.Exists(path))
return default;
string json = File.ReadAllText(path);
return JsonSerializer.Deserialize<T>(json);
}
private static void ApplyUnixPermissions(string path)
{
try
{
var chmod = new System.Diagnostics.ProcessStartInfo
{
FileName = "/bin/chmod",
Arguments = $"600 \"{path}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var proc = System.Diagnostics.Process.Start(chmod);
proc?.WaitForExit();
}
catch
{
// fallback: hide file (less secure)
File.SetAttributes(path, FileAttributes.Hidden);
}
}
}
}
}