-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Diceware.cs
363 lines (309 loc) · 10.3 KB
/
Diceware.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
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
KeePassDiceware Plugin
Copyright (C) 2021 cmd <https://github.com/cmdwtf>
Portions Copyright (C) 2014-2021 Mark McGuill. All rights reserved. (Marked with comments.)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using KeePassLib.Cryptography;
using KeePassLib.Cryptography.PasswordGenerator;
namespace KeePassDiceware
{
public class Diceware
{
private static readonly char[] LookalikeCharacters = "I|1lO0".ToCharArray();
// Copyright (C) 2014-2021 Mark McGuill. All rights reserved.
private static readonly Dictionary<char, string> L33tMap = new()
{
{ 'A', "4" },
{ 'B', "|3" },
{ 'C', "(" },
{ 'D', "|)" },
{ 'E', "3" },
{ 'F', "|=" },
{ 'G', "6" },
{ 'H', "|-|" },
{ 'I', "|" },
{ 'J', "9" },
{ 'K', "|<" },
{ 'L', "1" },
{ 'M', "|v|" },
{ 'N', "|/|" },
{ 'O', "0" },
{ 'P', "|*" },
{ 'Q', "0," },
{ 'R', "|2" },
{ 'S', "5" },
{ 'T', "7" },
{ 'U', "|_|" },
{ 'V', "|/" },
{ 'W', "|/|/" },
{ 'X', "><" },
{ 'Y', "`/" },
{ 'Z', "2" },
};
// Copyright (C) 2014-2021 Mark McGuill. All rights reserved.
private static readonly Dictionary<char, string> L3ssl33tMap = new()
{
{ 'A', "4" },
{ 'E', "3" },
{ 'G', "6" },
{ 'I', "|" },
{ 'J', "9" },
{ 'L', "1" },
{ 'O', "0" },
{ 'S', "5" },
{ 'T', "7" },
{ 'Z', "2" },
};
public static string Generate(Options options, PwProfile profile, CryptoRandomStream random)
{
Debug.Assert(options != null);
Debug.Assert(profile != null);
VerifyOptions(options, profile);
// get wordlists to choose words from
string[] wordlist = GetWordList(options.WordLists).ToArray();
if (!wordlist.Any())
{
throw new InvalidOperationException("No word lists were selected, cannot generate password.");
}
// select the requested number of words
string[] selectedWords = (from i in Enumerable.Range(0, options.WordCount)
select wordlist.SelectRandom(random))
.ToArray();
// mutate the words as requested
ApplyWordCasing(selectedWords, options.WordCasing, random);
ApplyL33tSpeak(selectedWords, options.L33tSpeak, random);
ApplySalt(selectedWords, options.Salt, options.SaltSources, options.WordSeparator, random);
ApplyAdvancedSettings(selectedWords, options, profile, random);
// join the mutated words by the selected separator
string joined = string.Join(options.WordSeparator, selectedWords);
// and return the result!
return joined;
}
private static void VerifyOptions(Options options, PwProfile profile)
{
if (profile.NoRepeatingCharacters)
{
throw new NotSupportedException("The 'each character must occur at most once' advanced setting is unsupported for this generator.");
}
if (profile.ExcludeLookAlike || profile.ExcludeCharacters.Length > 0)
{
if (options.AdvancedStrategy == AdvancedStrategy.SubstitueWordSeparator &&
options.WordSeparator.Length == 0)
{
throw new InvalidOperationException("The excluded character strategy selected was to replace excluded characters with the word separator, but no word separator was specified.");
}
if (options.AdvancedStrategy == AdvancedStrategy.SubstitueSalt &&
options.SaltSources.All(s => !s.Enabled))
{
throw new InvalidOperationException("The excluded character strategy selected was to replace excluded characters with salt, but no salt sources were selected.");
}
}
}
private static void ApplyWordCasing(string[] words, WordCasingType wordCasing, CryptoRandomStream random)
{
if (wordCasing == WordCasingType.DoNotChange)
{
return;
}
for (int scan = 0; scan < words.Length; ++scan)
{
switch (wordCasing)
{
case WordCasingType.Lowercase:
words[scan] = words[scan].ToLowerInvariant();
break;
case WordCasingType.Uppercase:
words[scan] = words[scan].ToUpperInvariant();
break;
case WordCasingType.TitleCase:
string first = words[scan][0].ToString().ToUpperInvariant();
words[scan] = $"{first}{words[scan].Substring(1)}";
break;
case WordCasingType.Random:
char[] randomized = (from c in words[scan].ToCharArray()
select (random.CoinToss()
? char.ToUpper(c)
: char.ToLower(c))
)
.ToArray();
words[scan] = new string(randomized);
break;
case WordCasingType.WholeWord:
if (random.CoinToss())
{
words[scan] = words[scan].ToUpperInvariant();
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(wordCasing));
}
}
}
private static void ApplyL33tSpeak(string[] words, L33tSpeakType l33tSpeak, CryptoRandomStream random)
{
if (l33tSpeak == L33tSpeakType.None)
{
return;
}
for (int scan = 0; scan < words.Length; ++scan)
{
bool mutateWord = l33tSpeak.HasFlag(L33tSpeakType.AllWords)
|| random.CoinToss();
if (mutateWord == false)
{
continue;
}
words[scan] = l33tSpeak.HasFlag(L33tSpeakType.Basic)
? ApplyCharRemap(words[scan], L3ssl33tMap)
: ApplyCharRemap(words[scan], L33tMap);
}
}
private static string ApplyCharRemap(string target, Dictionary<char, string> map)
{
var sb = new StringBuilder();
foreach (char c in target)
{
if (map.ContainsKey(c))
{
sb.Append(map[c]);
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
private static void ApplySalt(string[] words, SaltType salt, IEnumerable<SaltSource> sources, string separator, CryptoRandomStream random)
{
if (salt == SaltType.None)
{
return;
}
if (salt == SaltType.Sprinkle)
{
for (int scan = 0; scan < words.Length; ++scan)
{
if (random.CoinToss()) // skip word
{
continue;
}
int insertAt = random.AtMost(words[scan].Length);
words[scan] = words[scan].Insert(insertAt, GenerateSalt(sources, random));
}
return;
}
if (salt == SaltType.BetweenEach)
{
// after each word sans the last, insert a generated salt chunk.
for (int scan = 0; scan < words.Length - 1; ++scan)
{
string generatedSalt = GenerateSalt(sources, random);
words[scan] = $"{words[scan]}{separator}{generatedSalt}";
}
return;
}
string singleSalt = GenerateSalt(sources, random);
switch (salt)
{
case SaltType.Prefix:
words[0] = $"{singleSalt}{separator}{words[0]}";
break;
case SaltType.Suffix:
words[words.Length - 1] = $"{words[words.Length - 1]}{singleSalt}";
break;
case SaltType.SuffixAsWord:
words[words.Length - 1] = $"{words[words.Length - 1]}{separator}{singleSalt}";
break;
case SaltType.BetweenOne:
if (words.Length <= 1)
{
// invalid case: can't insert between a single word.
throw new ArgumentOutOfRangeException(nameof(words.Length), "Salt cannot be inserted between a single word.");
}
// get a random index word after which to place salt
int targetIndex = random.AtMost(words.Length - 2);
words[targetIndex] = $"{words[targetIndex]}{separator}{singleSalt}";
break;
default:
throw new ArgumentOutOfRangeException(nameof(salt));
}
}
private static void ApplyAdvancedSettings(string[] words, Options options, PwProfile profile, CryptoRandomStream random)
{
if (profile.ExcludeLookAlike == false &&
profile.ExcludeCharacters.Length == 0)
{
return;
}
for (int scan = 0; scan < words.Length; ++scan)
{
if (profile.ExcludeLookAlike)
{
foreach (char lookalike in LookalikeCharacters)
{
words[scan] = AdvancedSettingChararacterReplace(words[scan], lookalike, options, random);
}
}
foreach (char excluded in profile.ExcludeCharacters)
{
words[scan] = AdvancedSettingChararacterReplace(words[scan], excluded, options, random);
}
}
string AdvancedSettingChararacterReplace(string password, char exclude, Options options, CryptoRandomStream random)
{
string excludeStr = exclude.ToString();
return options.AdvancedStrategy switch
{
AdvancedStrategy.Drop => password.Replace(excludeStr, string.Empty),
AdvancedStrategy.SubstitueWordSeparator => password.Replace(excludeStr, options.WordSeparator),
AdvancedStrategy.SubstitueSalt => password.Replace(excludeStr, GenerateSalt(options.SaltSources, random)),
_ => throw new InvalidOperationException($"Unhandled {nameof(AdvancedStrategy)}."),
};
}
}
public static string GenerateSalt(IEnumerable<SaltSource> sources, CryptoRandomStream random)
{
StringBuilder result = null;
foreach (SaltSource source in sources)
{
if (!source.Enabled)
{
continue;
}
char[] saltOptions = source.GetCharacterPool();
int length = random.Range(source.MinimumAmount, source.MaximumAmount);
char[] chars = (from i in Enumerable.Range(0, length)
select saltOptions.SelectRandom(random))
.ToArray();
result ??= new StringBuilder();
result.Append(chars);
}
return result?.ToString() ?? string.Empty;
}
public static IEnumerable<string> GetWordList(List<WordList> lists)
{
HashSet<string> joinedWordList = new HashSet<string>();
foreach (WordList list in lists.Where(wl => wl.Enabled))
{
joinedWordList.UnionWith(list.Get());
}
return joinedWordList;
}
}
}