-
Notifications
You must be signed in to change notification settings - Fork 1
/
sha256.c
640 lines (574 loc) · 18.2 KB
/
sha256.c
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
#pragma comment(lib, "bcrypt.lib")
#include "sha256sum.h"
#include "pathcch.h"
#include "shlwapi.h"
#include "strsafe.h"
#include <bcrypt.h>
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
#define STATUS_UNSUCCESSFUL ((NTSTATUS)0xC0000001L)
#define HASH_LENGTH 64
#define LINE_BUFFER_SIZE 1024
typedef struct file_hash_t
{
LPWSTR file;
LPWSTR hash;
struct file_hash_t* next;
} FileHash;
void RemoveBinaryPrefix(LPWSTR str)
{
if (str[0] == L'*')
{
// Shift all characters one position to the left
for (int i = 0; str[i] != L'\0'; ++i)
{
str[i] = str[i + 1];
}
}
}
ErrorCode CalcHash(__in Args* args, __out LPWSTR* file_hash, __in LPWSTR file)
{
ErrorCode status = SUCCESS;
HANDLE hFile;
DWORD dwBytesRead;
BYTE buffer[LINE_BUFFER_SIZE] = { 0 };
BCRYPT_ALG_HANDLE hAlg = NULL;
BCRYPT_HASH_HANDLE hHash = NULL;
NTSTATUS hashStatus = STATUS_UNSUCCESSFUL;
DWORD cbData = 0,
cbHash = 0,
cbHashObject = 0;
PBYTE pbHashObject = NULL;
PBYTE pbHash = NULL;
RemoveBinaryPrefix(file);
// open file
hFile = CreateFileW(file, // File name
GENERIC_READ, // Open for reading
0, // No sharing
NULL, // Default security
OPEN_EXISTING, // Existing file only
FILE_ATTRIBUTE_NORMAL, // Normal file
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
if (!args->status)
{
wchar_t errorMsg[MAX_PATH + 50];
wsprintfW(errorMsg, L"failed to open file '%ls' with error: %lu\r\n", file, GetLastError());
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), errorMsg, lstrlenW(errorMsg), NULL, NULL);
}
status = CALC_HASH_FAILED_TO_OPEN_FILE;
goto Cleanup;
}
// open an algorithm handle
if (!NT_SUCCESS(hashStatus = BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_SHA256_ALGORITHM, NULL, 0)))
{
if (!args->status)
{
printf("open an algorithm handle failed: %ld\n", hashStatus);
}
status = CALC_HASH_FAILED_TO_OPEN_ALG_HANDLE;
goto Cleanup;
}
// calculate the size of the buffer to hold the hash object
if (!NT_SUCCESS(hashStatus = BCryptGetProperty(hAlg, BCRYPT_OBJECT_LENGTH, (PBYTE)&cbHashObject, sizeof(DWORD), &cbData, 0)))
{
if (!args->status)
{
printf("hash buffer size allocation failed, err: %ld\n", hashStatus);
}
status = CALC_HASH_FAILED_TO_ALLOCATE_HASH_BUFFER_SIZE;
goto Cleanup;
}
// allocate the hash object on the heap
pbHashObject = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbHashObject);
if (NULL == pbHashObject)
{
if (!args->status)
{
printf("memory allocation for hash object failed\n");
}
status = CALC_HASH_FAILED_TO_ALLOCATE_HASH_OBJECT;
goto Cleanup;
}
// calculate the length of the hash
if (!NT_SUCCESS(hashStatus = BCryptGetProperty(hAlg, BCRYPT_HASH_LENGTH, (PBYTE)&cbHash, sizeof(DWORD), &cbData, 0)))
{
if (!args->status)
{
printf("hash length calculation failed: %ld\n", hashStatus);
}
status = CALC_HASH_FAILED_TO_CALC_HASH_LENGTH;
goto Cleanup;
}
// allocate the hash buffer on the heap
pbHash = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbHash);
if (NULL == pbHash)
{
if (!args->status)
{
printf("memory allocation for hash buffer failed\n");
}
status = CALC_HASH_FAILED_TO_ALLOCATE_HASH_BUFFER;
goto Cleanup;
}
// create a hash
if (!NT_SUCCESS(hashStatus = BCryptCreateHash(hAlg, &hHash, pbHashObject, cbHashObject, NULL, 0, 0)))
{
if (!args->status)
{
printf("hash creation failed: %ld\n", hashStatus);
}
status = CALC_HASH_FAILED_TO_CREATE_HASH;
goto Cleanup;
}
while (TRUE)
{
if (!ReadFile(hFile, buffer, sizeof(buffer), &dwBytesRead, NULL))
{
if (!args->status)
{
printf("read file failed: %lu\n", GetLastError());
}
status = CALC_HASH_FAILED_TO_READ;
goto Cleanup;
}
if (dwBytesRead == 0)
{
break;
}
// hash some data
if (!NT_SUCCESS(hashStatus = BCryptHashData(hHash, (PBYTE)buffer, dwBytesRead, 0)))
{
if (!args->status)
{
printf("data hashing failed: %ld\n", hashStatus);
}
status = CALC_HASH_FAILED_TO_HASH;
goto Cleanup;
}
}
// close the hash
if (!NT_SUCCESS(hashStatus = BCryptFinishHash(hHash, pbHash, cbHash, 0)))
{
if (!args->status)
{
printf("hash finalization failed: %ld\n", hashStatus);
}
status = CALC_HASH_FAILED_TO_FINISH_HASH;
goto Cleanup;
}
// Output the hash
*file_hash = malloc((cbHash * 2 + 1) * sizeof(WCHAR));
if (*file_hash == NULL)
{
if (!args->status)
{
printf("memory allocation for file hash failed\n");
}
status = CALC_HASH_FAILED_TO_ALLOCATE_FILE_HASH;
goto Cleanup;
}
for (DWORD i = 0; i < cbHash; i++)
{
swprintf_s((*file_hash) + i * 2, 3, L"%02x", pbHash[i]);
}
(*file_hash)[cbHash * 2] = L'\0';
Cleanup:
if (hFile)
{
CloseHandle(hFile);
}
if (hAlg)
{
BCryptCloseAlgorithmProvider(hAlg, 0);
}
if (hHash)
{
BCryptDestroyHash(hHash);
}
if (pbHashObject)
{
HeapFree(GetProcessHeap(), 0, pbHashObject);
}
if (pbHash)
{
HeapFree(GetProcessHeap(), 0, pbHash);
}
if (status != SUCCESS)
{
*file_hash = NULL;
}
return status;
}
//void print(LPWSTR key, LPWSTR value)
//{
// TCHAR msg[MAX_PATH];
// wsprintfW(msg, L"%ls: %ls\n", key, value);
// WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), msg, lstrlenW(msg), NULL, NULL);
//}
TCHAR getPathSeparator(LPWSTR filePath, size_t filePathLen)
{
int lastSlashIndex = -1;
// Find the index of the last slash or backslash
for (int i = 0; i < filePathLen; i++)
{
if (filePath[i] == L'/' || filePath[i] == L'\\')
{
return filePath[i];
}
}
return L'\\'; // return windows default if none found
}
BOOL getPathWithoutFileName(LPWSTR result, size_t resultLen, LPWSTR filePath, size_t filePathLen)
{
int lastSlashIndex = -1;
// Find the index of the last slash or backslash
for (int i = 0; i < filePathLen; i++)
{
if (filePath[i] == L'/' || filePath[i] == L'\\')
{
lastSlashIndex = i;
}
}
// If no path separator was found this function fails
if (lastSlashIndex == -1)
{
return FALSE;
}
else
{
memcpy(result, filePath, (lastSlashIndex + 1) * sizeof(TCHAR));
result[lastSlashIndex] = L'\0';
}
return TRUE;
}
ErrorCode PrintHash(__in Args* args, __in LPWSTR userInputFilePath, __in LPWSTR fileName)
{
// get full path from user input path, remove the file and append fileName so we get
// a clean absolute file path
TCHAR absPath[MAX_PATH];
if (GetFullPathName(userInputFilePath, MAX_PATH, absPath, NULL) == 0 || absPath == NULL)
{
return PARSE_ARGS_ALLOCATE_ERROR; // TODO: add new error
}
PathCchRemoveFileSpec(absPath, MAX_PATH);
TCHAR absFilePath[MAX_PATH];
PathCchCombine(absFilePath, MAX_PATH, absPath, fileName);
// now calculate the file hash using the absolute file path we just constructed
LPWSTR hash = NULL;
ErrorCode ok = CalcHash(args, &hash, absFilePath);
if (hash != NULL && ok == SUCCESS)
{
// depending whether it is a relative or an absolute path the output needs to be different to
// immitade the output of sha256sum from Linux
BOOL isRel = PathIsRelativeW(userInputFilePath);
if (isRel == TRUE)
{
size_t userInputFilePathLen;
StringCchLengthW(userInputFilePath, MAX_PATH, &userInputFilePathLen);
TCHAR inputPath[MAX_PATH];
BOOL containsPath = getPathWithoutFileName(inputPath, MAX_PATH, userInputFilePath, userInputFilePathLen);
// if the user passed a relative file without a .\ or ..\ and other prefixes
if (containsPath == FALSE)
{
wprintf(L"%ls *%ls\n", hash, fileName);
}
// if the user passed a relative file with .\, ..\ and so on, we
// need to concatenate the inputFilePath and the given fileName
else
{
TCHAR inputFilePath[MAX_PATH];
StringCchCopyW(inputFilePath, MAX_PATH, inputPath);
TCHAR separator = getPathSeparator(userInputFilePath, userInputFilePathLen);
if (FAILED(StringCchCatW(inputFilePath, MAX_PATH, &separator)))
{
return PARSE_ARGS_ALLOCATE_ERROR; // TODO: add new error
}
if (FAILED(StringCchCatW(inputFilePath, MAX_PATH, fileName)))
{
return PARSE_ARGS_ALLOCATE_ERROR; // TODO: add new error
}
wprintf(L"%ls *%ls\n", hash, inputFilePath);
}
}
// in case of an absolute path the absolute path shall be used
else
{
wprintf(L"%ls *%ls\n", hash, absFilePath);
}
}
return SUCCESS;
}
ErrorCode ParseLine(__in Args* args, __out FileHash* fh, __in int line_num, __in LPWSTR line)
{
LPWSTR tokContext = NULL;
LPWSTR delim = L" ";
fh->hash = wcstok_s(line, delim, &tokContext);
if (fh->hash == NULL)
{
if (!args->status && args->warn)
{
printf("invalid hash on line %d\n", line_num);
}
return PARSE_LINE_INVALID_HASH_TOKEN;
}
if (wcslen(fh->hash) != HASH_LENGTH)
{
if (!args->status && args->warn)
{
printf("invalid hash on line %d\n", line_num);
}
return PARSE_LINE_INVALID_HASH_LENGTH;
}
fh->file = wcstok_s(NULL, delim, &tokContext);
if (fh->file == NULL)
{
if (!args->status && args->warn)
{
printf("invalid file on line %d\n", line_num);
}
return PARSE_LINE_INAVLID_FILE;
}
return SUCCESS;
}
ErrorCode VerifyChecksums(__in Args* args)
{
ErrorCode status = SUCCESS;
HANDLE hFile = NULL;
CHAR buffer[LINE_BUFFER_SIZE] = { 0 };
CHAR lineBuffer[LINE_BUFFER_SIZE] = { 0 };
DWORD dwBytesRead;
UINT lineIndex = 0;
int lineNum = 1;
FileHash* head = NULL;
FileHash* current = NULL;
// open file
hFile = CreateFileW(args->sumFile, // File name
GENERIC_READ, // Open for reading
0, // No sharing
NULL, // Default security
OPEN_EXISTING, // Existing file only
FILE_ATTRIBUTE_NORMAL, // Normal file
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
if (!args->status)
{
printf("failed to open file: %lu\n", GetLastError());
}
status = CHECK_SUMS_FAILED_TO_OPEN_SUM_FILE;
goto Cleanup;
}
while (ReadFile(hFile, buffer, LINE_BUFFER_SIZE, &dwBytesRead, NULL) && dwBytesRead > 0)
{
for (UINT i = 0; i < dwBytesRead; i++)
{
if (buffer[i] != '\n')
{
if (lineIndex < LINE_BUFFER_SIZE - 1)
{
lineBuffer[lineIndex++] = buffer[i];
}
else
{
if (!args->status)
{
printf("line %d too long, max size: %d\n", lineNum, LINE_BUFFER_SIZE);
}
status = CHECK_SUMS_LINE_TOO_LONG;
goto Cleanup;
}
}
else
{
// check if \r is at the end and replace it with \0
if (lineIndex > 0 && lineBuffer[lineIndex - 1] == '\r')
{
lineBuffer[lineIndex - 1] = '\0';
}
// add \0 in case there was no \r
lineBuffer[lineIndex] = '\0';
int reqSize = MultiByteToWideChar(CP_UTF8, 0, lineBuffer, lineIndex, NULL, 0);
LPWSTR wideBuffer = malloc(sizeof(WCHAR) * (reqSize + 1));
if (wideBuffer == NULL)
{
if (!args->status)
{
printf("failed to allocate memory for wideBuffer1 for line %d\n", lineNum);
}
status = CHECK_SUMS_FAILED_TO_ALLOCATE_WIDE_BUFFER1;
goto Cleanup;
}
MultiByteToWideChar(CP_UTF8, 0, lineBuffer, lineIndex, wideBuffer, reqSize);
wideBuffer[reqSize] = L'\0';
FileHash* fh = malloc(sizeof(FileHash));
if (fh == NULL)
{
if (!args->status)
{
printf("failed to allocate memory for fh1 for line %d\n", lineNum);
}
status = CHECK_SUMS_FAILED_TO_ALLOCATE_FILE_HASH1;
goto Cleanup;
}
fh->next = NULL;
if (reqSize == 0 || wcslen(wideBuffer) == 0)
{
if (!args->status)
{
printf("skip empty line %d\n", lineNum);
}
free(fh);
}
else
{
ErrorCode parseResult = ParseLine(args, fh, lineNum, wideBuffer);
if (parseResult != SUCCESS)
{
free(fh);
status = parseResult;
goto Cleanup;
}
else
{
if (head == NULL)
{
head = fh;
}
else
{
current->next = fh;
}
current = fh;
}
}
lineIndex = 0;
lineNum++;
}
}
}
// last line withtout trailing line break
if (lineIndex > 0)
{
if (lineBuffer[lineIndex - 1] == '\r')
{
lineBuffer[lineIndex - 1] = '\0';
}
lineBuffer[lineIndex] = '\0';
int reqSize = MultiByteToWideChar(CP_UTF8, 0, lineBuffer, lineIndex, NULL, 0);
LPWSTR wideBuffer = malloc(sizeof(WCHAR) * (reqSize + 1));
if (wideBuffer == NULL)
{
if (!args->status)
{
printf("failed to allocate memory for wideBuffer2 for line %d\n", lineNum);
}
status = CHECK_SUMS_FAILED_TO_ALLOCATE_WIDE_BUFFER2;
goto Cleanup;
}
MultiByteToWideChar(CP_UTF8, 0, lineBuffer, lineIndex, wideBuffer, reqSize);
wideBuffer[reqSize] = L'\0';
FileHash* fh = malloc(sizeof(struct file_hash_t));
if (fh == NULL)
{
if (!args->status)
{
printf("failed to allocate memory for fh2 for line %d\n", lineNum);
}
status = CHECK_SUMS_FAILED_TO_ALLOCATE_FILE_HASH2;
goto Cleanup;
}
fh->next = NULL;
if (reqSize == 0 || wcslen(wideBuffer) == 0)
{
if (!args->status)
{
printf("skip empty line %d\n", lineNum);
}
}
else
{
ErrorCode parseResult = ParseLine(args, fh, lineNum, wideBuffer);
if (parseResult != SUCCESS)
{
free(fh);
status = parseResult;
goto Cleanup;
}
else
{
if (head == NULL)
{
head = fh;
}
else
{
current->next = fh;
}
current = fh;
}
}
}
if (GetLastError() != 0)
{
if (!args->status)
{
printf("file read failed: %lu\n", GetLastError());
}
status = CHECK_SUMS_FAILED_TO_READ;
goto Cleanup;
}
current = head;
while (current != NULL)
{
LPWSTR file_hash = NULL;
ErrorCode calcResult = CalcHash(args, &file_hash, current->file);
if (calcResult != SUCCESS)
{
status = calcResult;
goto Cleanup;
}
wchar_t msg[MAX_PATH + 20];
if (wcscmp(current->hash, file_hash) == 0)
{
if (!args->status && !args->quiet)
{
wsprintfW(msg, L"%ls: OK\r\n", current->file);
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), msg, lstrlenW(msg), NULL, NULL);
}
}
else
{
if (!args->status)
{
wsprintfW(msg, L"%ls: FAILED\r\n", current->file);
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), msg, lstrlenW(msg), NULL, NULL);
}
status = CHECK_SUM_CHECKSUM_FAILED;
}
current = current->next;
}
if (!args->status && status == CHECK_SUM_CHECKSUM_FAILED)
{
LPWSTR msg = L"checksum failed\r\n";
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), msg, lstrlenW(msg), NULL, NULL);
}
Cleanup:
if (hFile)
{
CloseHandle(hFile);
}
// clean file_hashes
if (head != NULL)
{
current = head;
FileHash* next = NULL;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
}
return status;
}