forked from markpizz/HashSum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HashSum.c
1012 lines (947 loc) · 35 KB
/
HashSum.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Compute and validate checksums of files.
*
* Copyright (C) 2017 Mark Pizzolato.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Written by Mark Pizzolato <[email protected]>
*
* All of the ideas implemented here are derived from the *nix programs:
* md5sum, sha1sum, sha256sum, sha512sum, etc. and are intended to provide
* equivalent funcdtionality to these programs on a Windows platform.
*
*/
/* Written by Mark Pizzolato <[email protected]>. */
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <Windows.h>
#include <bcrypt.h>
#include <Winternl.h>
#pragma comment(lib, "bcrypt.lib")
#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS ERROR_SUCCESS
#endif
#define VERSION "1.0"
#define FLG_CHECK 1
#define FLG_QUIET 2
#define FLG_STATUS 4
#define FLG_WARN 8
#define FLG_STRICT 16
#define FLG_BINARY 32
#define FLG_BSDTAG 64
#define FLG_IGNORE 128
const char *
GetErrorText(DWORD dwError)
{
static char szMsgBuffer[2048];
DWORD dwStatus;
dwStatus = FormatMessageA (FORMAT_MESSAGE_FROM_SYSTEM|
FORMAT_MESSAGE_IGNORE_INSERTS, // __in DWORD dwFlags,
NULL, // __in_opt LPCVOID lpSource,
dwError, // __in DWORD dwMessageId,
0, // __in DWORD dwLanguageId,
szMsgBuffer, // __out LPTSTR lpBuffer,
sizeof (szMsgBuffer) -1, // __in DWORD nSize,
NULL); // __in_opt va_list *Arguments
if (0 == dwStatus)
{
typedef DWORD (__stdcall *_func)();
_func func_ptr = (_func)GetProcAddress(GetModuleHandleA("Ntdll.dll"), "RtlNtStatusToDosError");
dwStatus = FormatMessageA (FORMAT_MESSAGE_FROM_SYSTEM|
FORMAT_MESSAGE_IGNORE_INSERTS, // __in DWORD dwFlags,
NULL, // __in_opt LPCVOID lpSource,
func_ptr(dwError), // __in DWORD dwMessageId,
0, // __in DWORD dwLanguageId,
szMsgBuffer, // __out LPTSTR lpBuffer,
sizeof (szMsgBuffer) -1, // __in DWORD nSize,
NULL); // __in_opt va_list *Arguments
if (0 == dwStatus)
_snprintf(szMsgBuffer, sizeof(szMsgBuffer) - 1, "Error Code: 0x%lX", dwError);
}
while (isspace (szMsgBuffer[strlen (szMsgBuffer)-1]))
szMsgBuffer[strlen (szMsgBuffer) - 1] = '\0';
return szMsgBuffer;
}
const char *
GetProgramBaseName()
{
char FullName[MAX_PATH + 1];
static char BaseName[_MAX_FNAME + 1];
if (GetModuleFileNameA(NULL, FullName, sizeof(FullName)) >= sizeof(FullName))
return "";
if (_splitpath_s(FullName, NULL, 0, NULL, 0, BaseName, sizeof(BaseName), NULL, 0))
return "";
return BaseName;
}
SSIZE_T
GetLine(char **pBuf, size_t *pBufSize, FILE *file)
{
char chunk[1024];
size_t chunk_size;
size_t buf_used = 0;
if (pBuf == NULL)
{
errno = EINVAL;
return -1;
}
if (ferror(file) || feof(file))
return -1;
do {
if (chunk != fgets(chunk, sizeof(chunk), file))
strcpy(chunk, "");
chunk_size = strlen(chunk);
if (*pBufSize < chunk_size + 1)
{
char *newbuf = (char *)realloc(*pBuf, *pBufSize + chunk_size + 1);
if (newbuf == NULL)
return -1;
*pBuf = newbuf;
*pBufSize += chunk_size + 1;
}
memcpy(*pBuf + buf_used, chunk, chunk_size + 1);
buf_used += chunk_size;
} while ((chunk_size != 0) && (chunk[chunk_size - 1] != '\n'));
return buf_used;
}
void
CloseHashAlgorithmProvider(BCRYPT_ALG_HANDLE hAlg)
{
if (hAlg != INVALID_HANDLE_VALUE)
BCryptCloseAlgorithmProvider(hAlg, 0);
}
BCRYPT_ALG_HANDLE
OpenHashAlgorithmProvider(const char *Algorithm)
{
BCRYPT_ALG_HANDLE hAlg = INVALID_HANDLE_VALUE;
NTSTATUS result;
wchar_t AlgorithmW[65];
DWORD cbHash, cbData;
size_t i;
memset(AlgorithmW, 0, sizeof(AlgorithmW));
for (i=0; (i<64) && (Algorithm[i] != '\0'); i++)
AlgorithmW[i] = Algorithm[i];
result = BCryptOpenAlgorithmProvider(&hAlg, // algorithm handle
AlgorithmW,// hashing algorithm ID
NULL, // use default provider
0); // default flags
if (STATUS_SUCCESS != result)
{
fprintf(stderr, "Can't load '%s' cryptographic algorithm provider: %s\n", Algorithm, GetErrorText(result));
hAlg = INVALID_HANDLE_VALUE;
}
else
{
result = BCryptGetProperty(hAlg,
BCRYPT_HASH_LENGTH,
(PBYTE)&cbHash,
sizeof(cbHash),
&cbData,
0);
if (STATUS_SUCCESS != result)
{
fprintf(stderr, "cryptographic algorithm provider '%s' does not provide hash functionality\n", Algorithm, GetErrorText(result));
CloseHashAlgorithmProvider(hAlg);
hAlg = INVALID_HANDLE_VALUE;
}
}
return hAlg;
}
#if 0
/* TexInfo description */
`-b'
`--binary'
Treat each input file as binary, by reading it in binary mode and
outputting a `*' flag. This is the inverse of `--text'. On
systems like GNU that do not distinguish between binary and text
files, this option merely flags each input mode as binary: the MD5
checksum is unaffected. This option is the default on Windows
systems since they distinguish between binary and text files, except
for reading standard input when standard input is a terminal.
`-c'
`--check'
Read file names and checksum information (not data) from each FILE
(or from stdin if no FILE was specified) and report whether the
checksums match the contents of the named files. The input to
this mode of the program is usually the output of a prior,
checksum-generating run of the program. Each valid line of input
consists of an checksum, a binary/text flag, and then a file
name. Binary mode is indicated with `*', text with ` ' (space).
For each such line, the program reads the named file and computes its
checksum. Then, if the computed message digest does not match
the one on the line with the file name, the file is noted as having
failed the test. Otherwise, the file passes the test. By
default, for each valid line, one line is written to standard
output indicating whether the named file passed the test. After
all checks have been performed, if there were any failures, a
warning is issued to standard error. Use the `--status' option to
inhibit that output. If any listed file cannot be opened or read,
if any valid line has a checksum inconsistent with the associated
file, or if no valid line is found, the program exits with
nonzero status. Otherwise, it exits successfully.
`--quiet'
This option is useful only when verifying checksums. When
verifying checksums, don't generate an 'OK' message per
successfully checked file. Files that fail the verification are
reported in the default one-line-per-file format. If there is any
checksum mismatch, print a warning summarizing the failures to
standard error.
`--status'
This option is useful only when verifying checksums. When
verifying checksums, don't generate the default one-line-per-file
diagnostic and don't output the warning summarizing any failures.
Failures to open or read a file still evoke individual diagnostics
to standard error. If all listed files are readable and are
consistent with the associated MD5 checksums, exit successfully.
Otherwise exit with a status code indicating there was a failure.
`--tag'
Output BSD style checksums, which indicate the checksum algorithm
used. As a GNU extension, file names with problematic characters
are escaped as described above, with the same escaping indicator
of `\' at the start of the line, being used. The `--tag' option
implies binary mode, and is disallowed with `--text' mode as
supporting that would unnecessarily complicate the output format,
while providing little benefit.
`-t'
`--text'
Treat each input file as text, by reading it in text mode and
outputting a ` ' flag. This is the inverse of `--binary'. This
option is the default on systems like GNU that do not distinguish
between binary and text files. On other systems, it is the
default for reading standard input when standard input is a
terminal. This mode is never defaulted to if `--tag' is used.
`-w'
`--warn'
When verifying checksums, warn about improperly formatted
checksum lines. This option is useful only if all but a few lines
in the checked input are valid.
`--strict'
When verifying checksums, if one or more input line is invalid,
exit nonzero after all warnings have been issued.
An exit status of zero indicates success, and a nonzero value
indicates failure.
SHA1,SHA256,SHA384,SHA512 "FIPS-180-4"
MD5 "RFC 1321"
MD4 "RFC 1320"
MD2 "RFC 1319"
AES-GMAC "RFC 4543"
AES-CMAC "RFC 4493"
#endif
void
Usage (const char *AlgorithmName)
{
size_t i;
char CommandString[MAX_PATH+1];
char *Algorithms = NULL;
DWORD cbHash, cbData, cbAlgCount;
BCRYPT_ALGORITHM_IDENTIFIER *pAlgList = NULL;
NTSTATUS result;
BCRYPT_ALG_HANDLE hAlg = OpenHashAlgorithmProvider(AlgorithmName);
if (!strcmp("hashsum", GetProgramBaseName()))
_snprintf(CommandString, sizeof(CommandString)-1, "%s -a:%s", GetProgramBaseName(), AlgorithmName);
else
strncpy(CommandString, GetProgramBaseName(), sizeof(CommandString)-1);
if (hAlg != INVALID_HANDLE_VALUE)
{
BCryptGetProperty(hAlg,
BCRYPT_HASH_LENGTH,
(PBYTE)&cbHash,
sizeof(cbHash),
&cbData,
0);
CloseHashAlgorithmProvider(hAlg);
}
if (hAlg == INVALID_HANDLE_VALUE)
{
result = BCryptEnumAlgorithms(BCRYPT_HASH_OPERATION,
&cbAlgCount,
&pAlgList,
0);
if (STATUS_SUCCESS == result)
{
for (i=0; i<cbAlgCount; i++)
{
char AlgorithmName[64];
size_t j;
memset(AlgorithmName, 0, sizeof(AlgorithmName));
for (j=0; (j<sizeof(AlgorithmName)) && (pAlgList[i].pszName[j]); j++)
AlgorithmName[j] = (char)pAlgList[i].pszName[j];
hAlg = OpenHashAlgorithmProvider(AlgorithmName);
if (hAlg != INVALID_HANDLE_VALUE)
{
size_t old_size = (Algorithms) ? strlen(Algorithms) : 0;
Algorithms = (char *)realloc(Algorithms, old_size + strlen(AlgorithmName) + 2);
sprintf(&Algorithms[old_size], "%s,", AlgorithmName);
CloseHashAlgorithmProvider(hAlg);
}
}
Algorithms[strlen(Algorithms)-1] = '\0';
}
}
fprintf(stderr, "\n");
fprintf(stderr,
"%s(1) User Commands %s(1)\n"
"\n"
"NAME\n"
" %s - compute and check %s message digests\n"
"\n",
GetProgramBaseName(), GetProgramBaseName(), CommandString, AlgorithmName);
fprintf(stderr,
"SYNOPSIS\n"
" %s [OPTION]... [FILE]...\n"
"\n"
"DESCRIPTION\n"
" Print or check %s (%u-bit) checksums. With no FILE, or when FILE\n",
CommandString, AlgorithmName, cbHash*8);
fprintf(stderr,
" is -, read standard input.\n"
"\n"
" -b, --binary\n"
" read in binary mode\n"
"\n"
" -c, --check\n"
" read checksums from the FILEs and check them\n"
"\n"
" --tag create a BSD-style checksum\n"
"\n"
" -t, --text\n"
" read in text mode\n"
"\n",
GetProgramBaseName());
if (Algorithms)
fprintf(stderr,
" -a:HASH\n"
" where HASH is one of these algorithms:\n"
" %s\n", Algorithms);
fprintf(stderr,
"\n"
" The following three options are useful only when verifying checksums:\n"
" --quiet\n"
" don't print OK for each successfully verified file\n"
"\n"
" --status\n"
" don't output anything, status code shows success\n"
"\n"
" -w, --warn\n"
" warn about improperly formatted checksum lines\n"
"\n"
" --strict\n"
" with --check, exit non-zero for any invalid input\n"
"\n"
" --help display this help and exit\n"
"\n"
" --version\n"
" output version information and exit\n"
"\n"
" The available checksum algorithms are computed as described in:\n"
" SHA1,SHA256,SHA384,SHA512(FIPS-180-4)\n"
" MD5(RFC 1321)\n"
" MD4(RFC 1320)\n"
" MD2(RFC 1319)\n"
" AES-GMAC(RFC 4543)\n"
" AES-CMAC(RFC 4493)\n"
" When checking, the input should be a former output of this program or\n"
" one of the *nix programs: md5sum, sha1sum, sha256sum, sha384sum or\n"
" sha512sum. The default mode is to print a line with checksum, a\n"
" character indicating input mode ('*' for binary, space for text),\n"
" and name for each FILE.\n"
"\n"
"AUTHOR\n"
" Written by Mark Pizzolato.\n"
"\n"
"REPORTING BUGS\n"
" Report %s bugs to [email protected]\n"
"\n"
"COPYRIGHT\n"
" Copyright (c) 2017 Mark Pizzolato. All Rights Reserved.\n"
" There is NO WARRANTY, to the extent permitted by law.\n"
"\n"
"\n",
GetProgramBaseName());
fprintf(stderr,
"Usage: %s [OPTION]... [FILE]...\n",
CommandString);
if (cbHash)
fprintf(stderr,
"Print or check %s (%u-bit) checksums.\n",
AlgorithmName, cbHash*8);
else
fprintf(stderr,
"Print or check checksums.\n");
fprintf(stderr,
"With no FILE, or when FILE is -, read standard input.\n"
"\n"
" -b, --binary read in binary mode\n"
" -c, --check read checksums from the FILEs and check them\n"
" --tag create a BSD-style checksum\n"
" -t, --text read in text mode\n");
if (Algorithms)
fprintf(stderr,
" -a:HASH where HASH is one of these algorithms:\n"
" %s\n", Algorithms);
fprintf(stderr,
"\n"
"The following five options are useful only when verifying checksums:\n"
" --ignore-missing don't fail or report status for missing files\n"
" --quiet don't print OK for each successfully verified file\n"
" --status don't output anything, status code shows success\n"
" --strict with --check, exit non-zero for any invalid input\n"
" -w, --warn warn about improperly formatted checksum lines\n"
"\n"
" --help display this help and exit\n"
" --version output version information and exit\n"
"\n"
"When checking, the input should be a former output of this program or one\n"
"of the *nix programs: md5sum, sha1sum, sha256sum, sha384sum, sha512sum.\n"
"The available checksum algorithms are computed as described in:\n"
" SHA1,SHA256,SHA384,SHA512(FIPS-180-4)\n"
" MD5(RFC 1321)\n"
" MD4(RFC 1320)\n"
" MD2(RFC 1319)\n"
" AES-GMAC(RFC 4543)\n"
" AES-CMAC(RFC 4493)\n"
"The default mode is to print a line with checksum, a character indicating\n"
"input mode ('*' for binary, space for text), and name for each FILE.\n"
"\n"
"Report %s bugs to [email protected]\n", GetProgramBaseName());
free(Algorithms);
exit(EXIT_FAILURE);
}
int
GetFileHash(BCRYPT_ALG_HANDLE hAlg, FILE *file, char **hash)
{
NTSTATUS result;
BCRYPT_HASH_HANDLE hHash = NULL;
DWORD cbData, cbHashObject, cbHash, i;
PBYTE pbHashObject = NULL;
PBYTE pbHash = NULL;
const char HexDigits[] = "0123456789abcdef";
char FileBuf[32768];
*hash = NULL;
result = BCryptGetProperty(hAlg,
BCRYPT_OBJECT_LENGTH,
(PBYTE)&cbHashObject,
sizeof(cbHashObject),
&cbData,
0);
if (STATUS_SUCCESS != result)
{
fprintf(stderr, "**** Error BCryptGetProperty Returned: %s\n", GetErrorText(result));
goto Cleanup;
}
//allocate the hash object on the heap
pbHashObject = (PBYTE)malloc(cbHashObject);
if(NULL == pbHashObject)
{
fprintf(stderr, "**** memory allocation failed\n");
goto Cleanup;
}
//calculate the length of the hash
result = BCryptGetProperty(hAlg,
BCRYPT_HASH_LENGTH,
(PBYTE)&cbHash,
sizeof(cbHash),
&cbData,
0);
if (STATUS_SUCCESS != result)
{
fprintf(stderr, "**** Error BCryptGetProperty Returned: %s\n", GetErrorText(result));
goto Cleanup;
}
//allocate the hash buffer on the heap
pbHash = (PBYTE)malloc(cbHash);
if(NULL == pbHash)
{
fprintf(stderr, "**** memory allocation failed\n");
goto Cleanup;
}
//create a hash
result = BCryptCreateHash(hAlg,
&hHash,
pbHashObject,
cbHashObject,
NULL,
0,
0);
if (STATUS_SUCCESS != result)
{
fprintf(stderr, "**** Error BCryptCreateHash Returned: %s\n", GetErrorText(result));
goto Cleanup;
}
//hash file data
while (!feof(file))
{
size_t bytes = fread(FileBuf, 1, sizeof(FileBuf), file);
if (bytes == 0)
break;
result = BCryptHashData(hHash,
(PBYTE)FileBuf,
bytes,
0);
if (STATUS_SUCCESS != result)
{
fprintf(stderr, "**** Error BCryptHashData Returned: %s\n", GetErrorText(result));
goto Cleanup;
}
}
//close the hash
result = BCryptFinishHash(hHash,
pbHash,
cbHash,
0);
if (STATUS_SUCCESS != result)
{
fprintf(stderr, "**** Error BCryptFinishHash Returned: %s\n", GetErrorText(result));
goto Cleanup;
}
if (feof(file) && (!ferror(file)))
{
*hash = (char *)calloc(2*cbHash+1, sizeof(*hash));
for (i=0; i<cbHash; i++)
{
(*hash)[2*i] = HexDigits[pbHash[i]&0xF];
(*hash)[2*i+1] = HexDigits[(pbHash[i]>>4)&0xF];
}
}
Cleanup:
if (hHash)
BCryptDestroyHash(hHash);
if (pbHashObject)
free(pbHashObject);
if (pbHash)
free(pbHash);
return (*hash == NULL) ? EXIT_FAILURE : EXIT_SUCCESS;
}
int
ParseSumLine(char *line, size_t size, char **hash, char **file, char **open_mode, char **algo)
{
char *c;
size_t file_len;
char *rparen = strstr(line, ") = ");
char *lparen = strstr(line, " (");
static const char HashChars[] = "0123456789abcdefABCDEF\r\n";
size_t i;
if (lparen && rparen && (lparen < rparen))
{
/* Validate hash data as all hex */
c = rparen + 4;
for (i=0; i<strlen(c); i++)
if (NULL == strchr(HashChars, c[i]))
break;
if (i == strlen(c))
{
*algo = line;
*file = lparen + 2;
*hash = rparen + 4;
*lparen = *rparen = '\0';
*open_mode = "rb";
/* Remove trailing newline from hash string */
if ((*hash)[strlen(*hash)-1] == '\n')
{
(*hash)[strlen(*hash)-1] = '\0';
if ((*hash)[strlen(*hash)-1] == '\r')
(*hash)[strlen(*hash)-1] = '\0';
}
/* Make sure hash hex text is lower case */
for (i=0; i<strlen(*hash); i++)
if (isupper(c[i]))
c[i] = tolower(c[i]);
return EXIT_SUCCESS;
}
}
*hash = line;
if (NULL == (c = strchr(line, ' ')))
return EXIT_FAILURE;
*c++ = '\0';
/* Make sure hash hex text is lower case */
for (i=0; i<strlen(*hash); i++)
{
if (NULL == strchr(HashChars, line[i]))
return EXIT_FAILURE;
if (isupper(line[i]))
line[i] = tolower(line[i]);
}
if ((*c != '*') && (*c != ' '))
return EXIT_FAILURE;
*open_mode = (*c++ == '*') ? "rb" : "rt";
*file = c;
/* Remove trailing newline from filename */
file_len = strlen(*file);
if ((file_len) && (c[file_len-1] == '\n'))
c[--file_len] = '\0';
if ((file_len) && (c[file_len-1] == '\r'))
c[--file_len] = '\0';
*algo = NULL;
return EXIT_SUCCESS;
}
int
ProcessFile(BCRYPT_ALG_HANDLE hAlg, const char *file, int flags)
{
int status;
FILE *f;
char *open_mode = (flags&FLG_BINARY) ? "rb" : "rt";
char *hash = NULL;
wchar_t AlgorithmNameW[32];
char AlgorithmName[sizeof(AlgorithmNameW)];
size_t i;
struct stat statb;
DWORD cbData;
if (strcmp("-", file))
{
if (stat(file, &statb))
{
fprintf(stderr, "Can't stat '%s': %s\n", file, strerror(errno));
return EXIT_FAILURE;
}
if (statb.st_mode&_S_IFDIR)
{
fprintf(stderr, "%s: %s: Is a directory\n", GetProgramBaseName(), file);
return EXIT_FAILURE;
}
}
memset(AlgorithmNameW, 0, sizeof(AlgorithmNameW));
BCryptGetProperty(hAlg,
BCRYPT_ALGORITHM_NAME,
(PBYTE)AlgorithmNameW,
sizeof(AlgorithmNameW),
&cbData,
0);
for (i=0; i<sizeof(AlgorithmNameW); i++)
AlgorithmName[i] = (char)AlgorithmNameW[i];
if (!strcmp("-", file))
{
DWORD Mode;
if ((GetStdHandle (STD_INPUT_HANDLE)) &&
(GetStdHandle (STD_INPUT_HANDLE) != INVALID_HANDLE_VALUE) &&
GetConsoleMode (GetStdHandle (STD_INPUT_HANDLE), &Mode))
flags &= ~FLG_BINARY;
else
flags |= FLG_BINARY;
fprintf(stderr, "%s mode _setmode for stdin\n", (flags&FLG_BINARY) ? "Binary" : "Text");
_setmode(fileno(stdin), (flags&FLG_BINARY) ? _O_BINARY : _O_TEXT);
f = stdin;
}
else
f = fopen(file, open_mode);
if (NULL == f)
{
fprintf(stderr, "Error Opening '%s': %s\n", file, strerror(errno));
return EXIT_FAILURE;
}
if (flags&FLG_CHECK)
{
char *line_buf = NULL;
size_t line_buf_size = 0;
SSIZE_T line_size;
size_t line_number = 0;
int mis_matches = 0;
int matches = 0;
int bad_lines = 0;
int open_or_io_errors = 0;
BCRYPT_ALG_HANDLE hCheckAlg = INVALID_HANDLE_VALUE;
while (0 < (line_size = GetLine(&line_buf, &line_buf_size, f)))
{
char *file_hash;
char *hash;
char *file;
char *algo;
char *open_mode;
int line_stat;
FILE *check;
++line_number;
line_stat = ParseSumLine(line_buf, line_size, &hash, &file, &open_mode, &algo);
if (line_stat != EXIT_SUCCESS)
{
++bad_lines;
status = line_stat;
continue;
}
if (!strcmp("-", file))
{
DWORD Mode;
_setmode(fileno(stdin), ((GetStdHandle (STD_INPUT_HANDLE)) &&
(GetStdHandle (STD_INPUT_HANDLE) != INVALID_HANDLE_VALUE) &&
GetConsoleMode (GetStdHandle (STD_INPUT_HANDLE), &Mode)) ? _O_TEXT : _O_BINARY);
check = stdin;
}
else
{
if (NULL == (check = fopen(file, open_mode)))
{
if ((flags&FLG_IGNORE) && (errno == ENOENT))
continue;
++open_or_io_errors;
fprintf(stderr, "%s: Error Opening '%s': %s\n", GetProgramBaseName(), file, strerror(errno));
continue;
}
}
if (algo && (strcmp(algo, AlgorithmName)))
{
hCheckAlg = OpenHashAlgorithmProvider(algo);
if (hCheckAlg == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "%s: Unknown Algorithm Type: %s, can't check %s\n", GetProgramBaseName(), algo, file);
fclose(check);
status = EXIT_FAILURE;
continue;
}
}
line_stat = GetFileHash((algo && (hCheckAlg != INVALID_HANDLE_VALUE)) ? hCheckAlg : hAlg, check, &file_hash);
if (check != stdin)
fclose(check);
if (hCheckAlg != INVALID_HANDLE_VALUE)
{
CloseHashAlgorithmProvider(hCheckAlg);
hCheckAlg = INVALID_HANDLE_VALUE;
}
if (line_stat != EXIT_SUCCESS)
{
++open_or_io_errors;
status = line_stat;
free(file_hash);
continue;
}
if (strcmp(file_hash, hash))
{
status = EXIT_FAILURE;
++mis_matches;
if (!(flags&FLG_QUIET))
fprintf(stdout, "%s: FAILED\n", file);
free(file_hash);
continue;
}
++matches;
if (!(flags&FLG_QUIET))
fprintf(stdout, "%s: OK\n", file);
free(file_hash);
}
if (!(flags&FLG_STATUS))
{
if (bad_lines)
fprintf(stderr, "%s: WARNING: %d line% improperly formatted\n", GetProgramBaseName(), bad_lines, (bad_lines == 1) ? " is" : "s are");
if (open_or_io_errors)
fprintf(stderr, "%s: WARNING: %d listed file%s could not be read\n", GetProgramBaseName(), open_or_io_errors, (open_or_io_errors == 1) ? "" : "s");
if (mis_matches)
fprintf(stderr, "%s: WARNING: %d computed checksum%s did NOT match\n", GetProgramBaseName(), mis_matches, (mis_matches == 1) ? "" : "s");
if ((mis_matches + matches) == 0)
fprintf(stderr, "%s: %s: no file was verified\n", GetProgramBaseName(), file);
}
free(line_buf);
}
else
{
status = GetFileHash(hAlg, f, &hash);
if (hash)
{
if (flags&FLG_BSDTAG)
{
fprintf(stdout, "%s (", AlgorithmName);
if (f == stdin)
fprintf(stdout, "-");
else
{
size_t i;
for (i=0; i<strlen(file); i++)
fprintf(stdout, "%c", (file[i] == '\\') ? '/' : file[i]);
}
fprintf(stdout, ") = %s", hash);
}
else
{
fprintf(stdout, "%s %s", hash, (flags&FLG_BINARY) ? "*" : " ", file);
if (f == stdin)
fprintf(stdout, "-");
else
{
size_t i;
for (i=0; i<strlen(file); i++)
fprintf(stdout, "%c", (file[i] == '\\') ? '/' : file[i]);
}
}
fprintf(stdout, "\n");
free(hash);
hash = NULL;
}
}
if (f != stdin)
fclose(f);
return status;
}
wchar_t *
CharToWideChar(const char *string)
{
wchar_t *buf = (wchar_t *)calloc(1+strlen(string), sizeof(*buf));
size_t i;
for (i=0; i<strlen(string); i++)
buf[i] = string[i];
return buf;
}
char *
GetAlgorithm (int argc, char **argv)
{
char *file;
char *alg;
size_t i;
file = (char *)malloc(1+strlen(GetProgramBaseName()));
strcpy(file, GetProgramBaseName());
if ((strlen(file) > 3) &&
(!stricmp("SUM", &file[strlen(file) - 3])))
file[strlen(file) - 3] = '\0';
if (!stricmp("HASH", file))
{
while (argc > 1)
{
if (!strncmp("-a:", argv[1], 3))
{
file = (char *)realloc(file, 1+strlen(&argv[1][3]));
strcpy(file, &argv[1][3]);
break;
}
--argc;
++argv;
}
}
alg = (char *)calloc(1+strlen(file), sizeof(*alg));
for (i=0; i<strlen(file); i++)
alg[i] = islower(file[i]) ? toupper(file[i]) : file[i];
free(file);
return alg;
}
void main(int argc,
__in_ecount(argc) char **argv)
{
BCRYPT_ALG_HANDLE hAlg = INVALID_HANDLE_VALUE;
char *algorithm = GetAlgorithm(argc, argv);
int files_processed = 0;
int flags = FLG_BINARY;
int status, exit_status = EXIT_SUCCESS;
while (argc > 1)
{
--argc;
++argv;
if (!strncmp("-a:", argv[0], 3))
{
size_t i;
CloseHashAlgorithmProvider(hAlg);
free(algorithm);
algorithm = (char *)calloc(1+strlen(&argv[0][3]), sizeof(*algorithm));
for (i=0; i<strlen(&argv[0][3]); i++)
algorithm[i] = islower(argv[0][3+i]) ? toupper(argv[0][3+i]) : argv[0][3+i];
hAlg = OpenHashAlgorithmProvider(algorithm);
if (hAlg == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "Unknown Algorithm Type: %s\n", algorithm);
exit(EXIT_FAILURE);
}
continue;
}
if ((!strcmp("-b", argv[0])) ||
(!strcmp("--binary", argv[0])))
{
flags |= FLG_BINARY;
continue;
}
if ((!strcmp("-c", argv[0])) ||
(!strcmp("--check", argv[0])))
{
flags |= FLG_CHECK;
continue;
}
if (!strcmp("--tag", argv[0]))
{
flags |= FLG_BSDTAG;
flags |= FLG_BINARY;
continue;
}
if ((!strcmp("-t", argv[0])) ||
(!strcmp("--text", argv[0])))
{
flags &= ~FLG_BINARY;
continue;
}
if (!strcmp("--ignore-missing", argv[0]))
{
flags |= FLG_IGNORE;
continue;
}
if (!strcmp("--quiet", argv[0]))
{
flags |= FLG_QUIET;
continue;
}
if (!strcmp("--status", argv[0]))
{
flags |= FLG_STATUS;
continue;
}
if ((!strcmp("-w", argv[0])) ||
(!strcmp("--warn", argv[0])))
{
flags |= FLG_WARN;
continue;
}
if (!strcmp("--strict", argv[0]))
{
flags |= FLG_STRICT;
continue;
}
if (!strcmp("--help", argv[0]))
Usage(algorithm);
if (!strcmp("--version", argv[0]))
{
fprintf(stdout, "%s Version %s", GetProgramBaseName(), VERSION);
exit(EXIT_SUCCESS);
}
if ((argv[0][0] == '-') &&
(strcmp("-", argv[0])))
{
fprintf(stderr, "%s: invalid option -- '%s'\n", GetProgramBaseName(), &argv[0][1]);
fprintf(stderr, "try '%s --help' for more information\n", GetProgramBaseName());
exit(EXIT_FAILURE);
}
if (hAlg == INVALID_HANDLE_VALUE)
{
hAlg = OpenHashAlgorithmProvider(algorithm);
if (hAlg == INVALID_HANDLE_VALUE)
{
status = EXIT_FAILURE;
break;
}
}
status = ProcessFile(hAlg, argv[0], flags);
if (status)
exit_status = status;
++files_processed;
}
if (files_processed == 0)
{
if (hAlg == INVALID_HANDLE_VALUE)