-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
FileKeyStore.cs
208 lines (181 loc) · 8.51 KB
/
FileKeyStore.cs
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
using Leosac.KeyManager.Library.Plugin;
using Newtonsoft.Json;
using System.Text;
namespace Leosac.KeyManager.Library.KeyStore.File
{
public class FileKeyStore : KeyStore
{
public static string LeosacKeyFileExtension => ".leok";
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod()?.DeclaringType);
public FileKeyStore()
{
Properties = new FileKeyStoreProperties();
}
public FileKeyStoreProperties GetFileProperties()
{
var p = Properties as FileKeyStoreProperties;
return p ?? throw new KeyStoreException("Missing File key store properties.");
}
public override string Name => "File";
public override bool CanCreateKeyEntries => true;
public override bool CanDeleteKeyEntries => true;
public override IEnumerable<KeyEntryClass> SupportedClasses
{
get => new KeyEntryClass[] { KeyEntryClass.Symmetric, KeyEntryClass.Asymmetric };
}
public override Task Open()
{
log.Info(String.Format("Opening the key store `{0}`...", GetFileProperties().Fullpath));
if (!System.IO.Directory.Exists(GetFileProperties().Fullpath))
{
log.Error(string.Format("Cannot open the key sore `{0}`.", GetFileProperties().Fullpath));
throw new KeyStoreException("Cannot open the key sore.");
}
if (!Attributes.ContainsKey(ATTRIBUTE_NAME))
{
var dirname = System.IO.Path.GetDirectoryName(GetFileProperties().Fullpath);
if (!string.IsNullOrEmpty(dirname))
{
Attributes[ATTRIBUTE_NAME] = dirname;
Attributes[ATTRIBUTE_HEXNAME] = Convert.ToHexString(Encoding.UTF8.GetBytes(dirname));
}
}
log.Info("Key store opened.");
return Task.CompletedTask;
}
public override Task Close()
{
log.Info(string.Format("Closing the key store `{0}`...", GetFileProperties().Fullpath));
log.Info("Key Store closed.");
return Task.CompletedTask;
}
protected string GetKeyEntryFile(KeyEntryId identifier, KeyEntryClass keClass)
{
return System.IO.Path.Combine(GetFileProperties().Fullpath, identifier.Id + "." + keClass + LeosacKeyFileExtension);
}
public override Task<bool> CheckKeyEntryExists(KeyEntryId identifier, KeyEntryClass keClass)
{
if (!string.IsNullOrEmpty(identifier.Label))
{
log.Warn("KeyEntry label specified but such key resolution is not supported by the key store type.");
}
return Task.FromResult(System.IO.File.Exists(GetKeyEntryFile(identifier, keClass)));
}
public override async Task Create(IChangeKeyEntry change)
{
log.Info(string.Format("Creating key entry `{0}`...", change.Identifier));
if (await CheckKeyEntryExists(change.Identifier, change.KClass))
{
log.Error(string.Format("A key entry with the same identifier `{0}` already exists.", change.Identifier));
throw new KeyStoreException("A key entry with the same identifier already exists.");
}
var kefile = GetKeyEntryFile(change.Identifier, change.KClass);
if (change is KeyEntry)
{
var serialized = JsonConvert.SerializeObject(change, typeof(KeyEntry), _jsonSettings);
using var aes = System.Security.Cryptography.Aes.Create();
aes.Key = GetWrappingKey();
var data = aes.EncryptCbc(Encoding.UTF8.GetBytes(serialized), new byte[16], System.Security.Cryptography.PaddingMode.PKCS7);
await System.IO.File.WriteAllBytesAsync(kefile, data);
}
else if (change is KeyEntryCryptogram cryptogram)
{
System.IO.File.WriteAllText(kefile, cryptogram.Value);
}
else
{
throw new KeyStoreException("Unsupported `change` parameter.");
}
log.Info(string.Format("Key entry `{0}` created.", change.Identifier));
}
public override async Task Delete(KeyEntryId identifier, KeyEntryClass keClass, bool ignoreIfMissing)
{
log.Info(string.Format("Deleting key entry `{0}`...", identifier));
var exists = await CheckKeyEntryExists(identifier, keClass);
if (!exists && !ignoreIfMissing)
{
log.Error(string.Format("The key entry `{0}` doesn't exist.", identifier));
throw new KeyStoreException("The key entry doesn't exist.");
}
if (exists)
{
System.IO.File.Delete(GetKeyEntryFile(identifier, keClass));
log.Info(string.Format("Key entry `{0}` deleted.", identifier));
}
}
public override async Task<KeyEntry?> Get(KeyEntryId identifier, KeyEntryClass keClass)
{
log.Info(string.Format("Getting key entry `{0}`...", identifier));
if (!await CheckKeyEntryExists(identifier, keClass))
{
log.Error(string.Format("The key entry `{0}` doesn't exist.", identifier));
throw new KeyStoreException("The key entry doesn't exist.");
}
var encdata = await System.IO.File.ReadAllBytesAsync(GetKeyEntryFile(identifier, keClass));
using var aes = System.Security.Cryptography.Aes.Create();
aes.Key = GetWrappingKey();
var data = aes.DecryptCbc(encdata, new byte[16], System.Security.Cryptography.PaddingMode.PKCS7);
var keyEntry = JsonConvert.DeserializeObject<KeyEntry>(Encoding.UTF8.GetString(data), _jsonSettings);
// Plugin context workaround
if (keyEntry != null)
{
var factory = KeyEntryFactory.GetFactoryFromPropertyType(keyEntry.Properties?.GetType());
if (factory != null)
{
keyEntry.Properties = factory.CreateKeyEntryProperties(JsonConvert.SerializeObject(keyEntry.Properties));
}
}
log.Info(string.Format("Key entry `{0}` retrieved.", identifier));
return keyEntry;
}
private byte[] GetWrappingKey()
{
if (string.IsNullOrEmpty(Properties?.Secret))
{
return new byte[16];
}
var key = Convert.FromHexString(Properties.Secret);
if (key.Length != 16 && key.Length != 32)
{
throw new KeyStoreException("Wrong wrapping key length.");
}
return key;
}
public override Task<IList<KeyEntryId>> GetAll(KeyEntryClass? keClass)
{
log.Info(string.Format("Getting all key entries (class: `{0}`)...", keClass));
IList<KeyEntryId> keyEntries = new List<KeyEntryId>();
var filter = "*";
if (keClass != null)
{
filter += "." + keClass.ToString()!.ToLowerInvariant();
}
filter += LeosacKeyFileExtension;
var files = System.IO.Directory.GetFiles(GetFileProperties().Fullpath, filter);
foreach (var file in files)
{
string identifier = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetFileNameWithoutExtension(file));
keyEntries.Add(new KeyEntryId { Id = identifier });
}
log.Info(string.Format("{0} key entries returned.", keyEntries.Count));
return Task.FromResult(keyEntries);
}
public override async Task Store(IList<IChangeKeyEntry> changes)
{
log.Info(string.Format("Storing `{0}` key entries...", changes.Count));
foreach (var change in changes)
{
await Update(change, true);
}
log.Info("Key Entries storing completed.");
}
public override async Task Update(IChangeKeyEntry change, bool ignoreIfMissing)
{
log.Info(string.Format("Updating key entry `{0}`...", change.Identifier));
await Delete(change.Identifier, change.KClass, ignoreIfMissing);
await Create(change);
OnKeyEntryUpdated(change);
log.Info(string.Format("Key entry `{0}` updated.", change.Identifier));
}
}
}