-
Notifications
You must be signed in to change notification settings - Fork 5
/
cryptsidian.mjs
435 lines (356 loc) · 12.9 KB
/
cryptsidian.mjs
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/* Cryptsidian
* By: triumphantomato
* https://github.com/triumphantomato
*/
/*
************************
************************
* Architecture Overview
************************
************************
// created with asciiflow.com
┌──────────────┐ ┌───────────────────┐ ┌────────────────────────┐
│ │◄────────────┤ │ │ │
│ Obsidian API │ │ API Functions ├──────►│ Backend Functions │
│ ├────────────►│ │ │ │ ▲ │
│ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │
│ │ │ │ │ ▼ │
│ │ │ │ │ ┌─────────────────┐ │
│ │ └───────────────────┘ │ │ Encrypt/Decrypt │ │
│ │ │ │ Files │ │
│ │ │ │ │ │
│ │ │ │ │ │
│ │ │ │ │ │
│ │ │ │ │ │
│ │ │ └─────────────────┘ │
│ │ │ │
│ │ └────────────────────────┘
│ │
└──────────────┘
*/
/*
* libraries
*/
import * as path from 'path';
import * as fs from 'fs';
import * as crypto from 'crypto';
/*
* crypto primitives
*/
export const ALGORITHM = 'aes-256-ctr';
export const SALT = Buffer.alloc(32, '3170ebab43b9ccaaacbbb0ee72285a21c39fa324315db3ddcc11da1e3ff816e5', 'hex');
//salt used in scrypt PBKDF, derived from crypto.randomBytes(32) - you can replace with your own, but will need to keep track
//of this to decrypt your files in the future if you change it. Recommendation: leave it alone.
/*
* keywords
*/
export const ENCRYPT = 'ENCRYPT';
export const DECRYPT = 'DECRYPT';
export const KEY_LENGTH = 32; // length in bytes
/*
* global variables
*/
let secretKey; //will be derived from user input later
/**
************************
************************
* API Functions
************************
************************
**/
/* all of these are implemented in the main.ts file, in onOpen() on class CryptoModal
* Registering Cryptsidian with the Obsidian Plugin API
* Prompting the user to enter their password for encryption/decryption.
* Retrieving the path to the user's Obsidian vault
*/
/**
************************
************************
* Backend Functions
************************
************************
**/
/**
************************
* Backend: passwords
************************
**/
/**
* Takes a user-supplied string and checks for safety.
* @param {string} input - user supplied string
* @return {false|string} - false when input fails checks or string of user input if it passes.
**/
export function stringSanitizer( input ){
if (typeof(input) !== 'string'){
throw new Error("Password must be a string, received " + typeof(input) + " instead\n");
}
//deal with accents - normalize Unicode
input = input.normalize('NFC');
//validate entropy
if (hasEnoughEntropy(input)){
return input;
}
return false;
}
/**
* Takes a string and checks for sufficient entropy.
* If a user's password has all character types (number, lower and uppercase, special chars), it will require 13 characters minimum at level=80.
* @param {string} input - input string
* @param {number} [level = 80] - entropy level in bits. 64 - okay but iffy, 80 - okay, 112 - recommended, 256 - probably quantum secure. Take these guidelines with a grain of salt and consult a cryptographer for your application.
* @return {bool} judgment - true if sufficient, false if not
**/
export function hasEnoughEntropy( input, level=80 ){
if (level < 64){
throw new Error('Function hasEnoughEntropy() called with < 64 bits of entropy. This is unsafe, aborting.\n');
}
let charspace = 0;
let minlength = Math.ceil(level/Math.log2(10+26+26+32));
if (level >= 64){
//test entropy (via minlength)
if (input.length < minlength){
throw{
name: "PasswordError",
message: "Your password is not long enough. It must be " + minlength + " characters or longer.\n"
}
}
//test entropy (via explicit entropy calculation)
if (/\d+/g.test(input)) charspace += 10; //digits in charspace
if (/[a-z]/g.test(input)) charspace += 26; //lowercase in charspace
if (/[A-Z]/g.test(input)) charspace += 26; //uppercase in charspace
if (/[`~!@#$%^&*()-=_+\[\]{};':"\\|,.<>\/?]/g.test(input)) charspace += 32; //special chars in charspace
let entropy = input.length * Math.log2(charspace);
if (entropy < level){
throw{
name: "PasswordError",
message: "Your password is not strong enough. Try adding different kinds of characters, like numbers, special characters, or uppercase letters.\n"
}
}
else if (entropy >= level){
return true;
}
return false;
}
return false;
}
/**
************************
* Backend: keys
************************
**/
/**
* Takes a user password and sets the secretKey global variable by calling keyDeriver(password).
* Is the isolation boundary between backend and frontend.
* @param {string} password - user password to derive encryption key from
* @returns <void>
**/
export function setUserSecretKey( password ){
secretKey = Buffer.alloc(KEY_LENGTH); //zero-fills secretKey to be a buffer of length KEY_LENGTH
secretKey = keyDeriver(password);
return;
}
/**
* Takes an input string and returns a secret key of length key_length (default is value of constant KEY_LENGTH).
* @param {string} input
* @param {number} [key_length = KEY_LENGTH]
* @return {Buffer} secretKey
**/
export function keyDeriver( input, key_length=KEY_LENGTH ){
if(input == null || typeof(input) !== 'string'){
throw new Error("Function keyDeriver received bad input. Expected a non-null string.");
}
let password = stringSanitizer(input);
if (password){
secretKey = crypto.scryptSync(password, SALT, KEY_LENGTH);
return secretKey;
}
}
/**
* Checks to ensure secretKey is correctly set and then returns it. Accessing secretKey outside of this function is unsafe.
* @returns {Buffer} secretKey
**/
function getSecretKey( ){
if (secretKey == null){ // (== null) checks null and undefined
throw{
name: "KeyError",
message: "secretKey is null or undefined. Uh-oh.\n"
}
}
if (secretKey.length !== KEY_LENGTH){
throw{
name: "KeyError",
message: "secretKey is not the right length. Got: " + secretKey.length + " bytes, but expected: " + KEY_LENGTH + " bytes"
}
}
return secretKey;
}
/**
**************************
* Backend: encrypt/decrypt
**************************
**/
/**
* Overwrites an encrypted version of the file to disk
* @param {string} file_path - location of file to encrypt
* @returns <void>
**/
export function encryptFile( file_path ){
//get data and file descriptor
let data = getFileBuffer(file_path);
let fd = openFile(file_path);
//generate IV
let iv = crypto.randomBytes(16);
//validate secretKey not empty
let key = getSecretKey();
//make a ciphertext
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
const encrypted_data = Buffer.concat([cipher.update(data), cipher.final()]);
//cipher.final() not necessary for aes-256-ctr but this construciton should also
//work with other algorithms
//prepend IV and write encrypted data back to file
fs.writeSync(fd, iv, 0, iv.length, 0);
fs.writeSync(fd, encrypted_data, 0, encrypted_data.length, iv.length);
//cleanup
fs.close(fd, (err) => {
if (err){
console.error("failed to close file descriptor when attempting to encrypt file: \n" + file_path + "\n in function encryptFile()\n");
throw new Error(err);
}
});
}
/**
* Decrypts a file and writes it to disk, in place
* @param {string} file_path - file to decrypt
* @returns <void>
**/
export function decryptFile( file_path ){
//get this to calculate cipher_data_length later
let stats = fs.statSync(file_path); //must be done before opening the fd or it errors
//get secretKey
let key = getSecretKey();
//get file descriptor
let fd = openFile(file_path);
//calculate cipher_data_length
let cipher_data_length = (stats.size - 16); //in bytes, minus the 16-byte IV
//we'll walk through the file to extract IV and then content instead of using getFileBuffer() helper function
//read first 16 bytes for the IV
let iv = Buffer.alloc(16);
try{
fs.readSync(fd, iv, 0, 16, null); //should advance file position to 16 bytes in
}
catch (err){
console.error("Error using fs.readSync(fd, iv, 0, 16, null) to get the IV back");
throw new Error(err);
}
//read the rest for the data
let cipher_data = Buffer.alloc(cipher_data_length);
fs.readSync(fd, cipher_data, 0, cipher_data_length, null); //should start the read from 16 bytes in
//now make a decipher object and decrypt the file
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
const decrypted_data = Buffer.concat([decipher.update(cipher_data), decipher.final()]);
//write the cleartext data back to file
fs.writeSync(fd, decrypted_data, 0, decrypted_data.length, 0);
//truncate the remaining crypto bytes from the overwritten file
try{
fs.ftruncateSync(fd, cipher_data_length);
}
catch (err){
console.error("Error truncating file after decryption in decryptFile(), for file: \n" + file_path);
throw new Error(err);
}
//cleanup
fs.close(fd, (err) => {
if (err){
console.error("failed to close file descriptor when attempting to decrypt file: \n" + file_path + "\n in function decryptFile()\n");
throw new Error(err);
}
});
}
/**
************************
* Backend: files
************************
**/
/**
* Returns an fd or error for a file.
* @param {string} file_path
* @returns {number} fd
**/
export function openFile( file_path ){
let fd;
try{
fd = fs.openSync(file_path, 'r+');
}
catch (err){
throw new Error(err);
}
return fd;
}
/**
* Returns the contents of a file as a buffer.
* @param {string} file_path - a single file path to read
* @return {Buffer} buf - buffer of an individual file
**/
export function getFileBuffer( file_path ){
file_path = path.normalize(file_path);
let buf;
try{
buf = fs.readFileSync(file_path);
}
catch (err){
console.error("failed calling getFileBuffer() on file_path: " + file_path);
throw new Error(err);
}
return buf;
}
/**
* Takes an array of filepaths and encrypts or decrypts them depending on operation.
* @param {Array}<string> file_array
* @param {string} operation
**/
export function fileProcessor( file_array, operation ){
if (operation === 'ENCRYPT'){
for (const file of file_array){
encryptFile(file);
}
return;
}
if (operation === 'DECRYPT'){
for (const file of file_array){
decryptFile(file);
}
return;
}
else throw new Error("fileProcessor(file_array, operation) called with invalid operation argument. \n Got " + operation + ". Must be ENCRYPT or DECRYPT.");
}
/**
* Returns array of all files with absolute paths in Vault dir and all sub-dirs
* @param {string} vault - absolute path to the user's Obsidian vault
* @return {Array}<string> vault_files
**/
export function getVaultFiles( vault ){
vault = path.normalize(vault);
let vault_files = [];
let files = [];
try {
files = fs.readdirSync(vault, {withFileTypes: true});
}
catch (err) {
console.error('failed calling fsreaddirSync(vault, {withFileTypes: true} on this directory: \'' + vault + '\'\n');
throw new Error(err);
}
for (const file of files){
if (file.name[0] === '.') continue; //skip dotfiles -- do i need to change this to be Windows compatible?
if (file.isFile()){
let absolutePath = path.resolve(vault, file.name);
vault_files.push(absolutePath);
}
else if (file.isDirectory()){
vault_files.push(...getVaultFiles(path.resolve(vault, file.name)));
//... is spread syntax unpacking the returned vault_files array from the recursed call
}
}
return vault_files;
//todo: make vault_files a TS array of only strings
}