-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathdiskmodule.pas
executable file
·2025 lines (1843 loc) · 79 KB
/
diskmodule.pas
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
unit diskmodule;
// this unit enables QuickHash to hash disk drives.
{$mode objfpc}{$H+} // {$H+} ensures strings are of unlimited size
interface
uses
{$ifdef UNIX}
process,
{$IFDEF UseCThreads}
cthreads,
{$ENDIF}
{$endif}
{$ifdef Windows}
Process, Windows, ActiveX, ComObj, Variants, comserv,
win32proc, GPTMBR, uGPT,
{$endif}
diskspecification, uProgress, Classes, SysUtils, FileUtil,
Forms, Controls, Graphics, LazUTF8, strutils,
Dialogs, StdCtrls, ComCtrls, ExtCtrls, Menus, DateTimePicker,
// New as of v2.8.0 - HashLib4Pascal Unit, superseeds DCPCrypt and part of Lazarus package system.
// Cryptographic algorithms
HlpHashFactory,
HlpIHash,
HlpIHashResult,
// Non-Cryptographic algorithms (new to v3.3.4)
HlpCRC;
type
{ TfrmDiskHashingModule }
TfrmDiskHashingModule = class(TForm)
btnRefreshDiskList: TButton;
btnStartHashing: TButton;
cbdisks: TComboBox;
cbLogFile: TCheckBox;
lblDiskHashSchedulerStatus: TLabel;
lblschedulertickboxDiskModule: TCheckBox;
comboHashChoice: TComboBox;
ledtComputedHash: TLabeledEdit;
GroupBox1: TGroupBox;
ImageList1: TImageList;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
ledtSelectedItem: TLabeledEdit;
lt: TLabel;
ls: TLabel;
lm: TLabel;
lv: TLabel;
menShowDiskManager: TMenuItem;
menShowDiskTechData: TMenuItem;
menHashDisk: TMenuItem;
PopupMenu1: TPopupMenu;
sdLogFile: TSaveDialog;
DiskHashingTimer: TTimer;
TreeView1: TTreeView;
DateTimePickerDiskModule: TDateTimePicker;
procedure btnAbortHashingClick(Sender: TObject);
procedure btnRefreshDiskListClick(Sender: TObject);
procedure btnStartHashingClick(Sender: TObject);
procedure cbLogFileChange(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure lblschedulertickboxDiskModuleChange(Sender: TObject);
procedure ledtSelectedItemChange(Sender: TObject);
procedure menHashDiskClick(Sender: TObject);
procedure menShowDiskManagerClick(Sender: TObject);
procedure TreeView1SelectionChanged(Sender: TObject);
function InitialiseHashChoice(Sender : TObject) : Integer;
procedure cbdisksChange(Sender: TObject);
function GetDiskTechnicalSpecs(Sender: TObject) : Integer;
procedure GetDiskTechnicalSpecsLinux(Sender: TObject);
procedure InvokeDiskHashScheduler (Sender : TObject);
procedure CheckSchedule(DesiredStartTime : TDateTime);
private
{ private declarations }
public
BytesPerSector : integer;
StartHashing : boolean;
NullStrictConvert : boolean;
{ public declarations }
end;
var
frmDiskHashingModule: TfrmDiskHashingModule;
PhyDiskNode, PartitionNoNode, DriveLetterNode : TTreeNode;
HashChoice, ExecutionCount : integer;
slOffsetsOfHits : TStringList;
Stop : boolean;
{$ifdef Windows}
// These few functions are needed for traversing the attached disks in Windows.
// Much of the disk and partitions data is derived for display purposes from
// Credit to https://github.com/RRUZ/delphi-wmi-class-generator
// For the actual hashing functions, direct Windows API calls are used.
function ListDrives : boolean;
function GetWin32_DiskPartitionInfo() : boolean;
function GetWin32_PhysicalDiskInfo() : boolean;
function DriveTypeStr(DriveType:integer): string;
function VarStrNull(const V:OleVariant):string;
function GetWMIObject(const objectName: String): IDispatch;
function VarArrayToStr(const vArray: variant): string;
function RemoveLogicalVolPrefix(strPath : string; LongPathOverrideVal : string) : string;
procedure RtlGetNtVersionNumbers(out MajorVersion : DWORD;
out MinorVersion : DWORD;
out Build : DWORD);
stdcall; external 'ntdll.dll';
// Formatting functions
function GetDiskLengthInBytes(hSelectedDisk : THandle) : Int64;
function GetSectorSizeInBytes(hSelectedDisk : THandle) : Int64;
function GetJustDriveLetter(str : widestring) : string;
function GetDriveIDFromLetter(str : string) : Byte;
function GetOSName() : string;
// function GetVolumeName(DriveLetter: Char): string; DEPRECATED as of v3.3.0
{$endif}
{$ifdef Unix}
// These are Linux specific functions
procedure ListDrivesLinux();
function GetOSNameLinux() : string;
function GetBlockCountLinux(s : string) : string;
function GetBlockSizeLinux(DiskDevName : string) : Integer;
function GetDiskLabels(DiskDevName : string) : string;
function GetByteCountLinux(DiskDevName : string) : QWord;
{$endif}
function HashDisk(hDiskHandle : THandle; DiskSize : Int64; HashChoice : Integer) : Int64;
function FormatByteSize(const bytes: QWord): string;
function ExtractNumbers(s: string): string;
implementation
{$R *.lfm}
{ TfrmDiskHashingModule }
// Enable or disable elements depending on the OS hosting the application
procedure TfrmDiskHashingModule.FormCreate(Sender: TObject);
begin
Stop := false;
ExecutionCount := 0;
ledtComputedHash.Enabled := false;
{$ifdef CPU64}
comboHashChoice.Items.Strings[6] := 'xxHash64';
{$else if CPU32}
comboHashChoice.Items.Strings[6] := 'xxHash32';
{$endif}
ledtComputedHash.Enabled := false; // Blake 3
{$ifdef Windows}
// These are the Linux centric elements, so disable them on Windows
cbdisks.Enabled := false;
cbdisks.Visible := false;
Label1.Enabled := false;
Label1.Visible := false;
Label2.Enabled := false;
Label2.Visible := false;
Label3.Enabled := false;
Label3.Visible := false;
Label4.Enabled := false;
Label4.Visible := false;
Label5.Enabled := false;
Label5.Visible := false;
lv.Enabled := false;
lv.Visible := false;
lm.Enabled := false;
lm.Visible := false;
ls.Enabled := false;
ls.Visible := false;
lt.Enabled := false;
lt.Visible := false;
{$endif}
end;
procedure TfrmDiskHashingModule.lblschedulertickboxDiskModuleChange(
Sender: TObject);
begin
if lblschedulertickboxDiskModule.Checked then
begin
DateTimePickerDiskModule.Enabled := true;
DateTimePickerDiskModule.Visible := true;
end
else
begin
DateTimePickerDiskModule.Enabled := false;
DateTimePickerDiskModule.Visible := false;
end;
end;
procedure TfrmDiskHashingModule.ledtSelectedItemChange(Sender: TObject);
begin
end;
procedure TfrmDiskHashingModule.btnRefreshDiskListClick(Sender: TObject);
begin
NullStrictConvert := False; // Hopefully avoid "could not convert variant of type (Null) into type Int64" errors
{$ifdef Windows}
try
TreeView1.Items.Clear;
ListDrives;
finally
end;
{$endif}
{$ifdef UNIX}
try
Treeview1.Items.Clear;
ListDrivesLinux;
finally
end;
{$endif}
end;
procedure TfrmDiskHashingModule.btnStartHashingClick(Sender: TObject);
begin
diskmodule.Stop := false; // if a hash was previously run and aborted, the flag needs to be reset for run 2
if lblschedulertickboxDiskModule.Checked then
begin
InvokeDiskHashScheduler(self);
end;
menHashDiskClick(Sender);
end;
// Checks if the desired start date and time has arrived yet by starting timer
// If it has, disable timer. Otherwise, keep it going.
procedure TfrmDiskHashingModule.CheckSchedule(DesiredStartTime : TDateTime);
begin
if Now >= DesiredStartTime then
begin
DiskHashingTimer.Enabled := false;
StartHashing := true;
end
else
begin
DiskHashingTimer.Enabled := true;
StartHashing := false;
end;
end;
procedure TfrmDiskHashingModule.InvokeDiskHashScheduler (Sender : TObject);
var
scheduleStartTime : TDateTime;
begin
if DateTimePickerDiskModule.DateTime < Now then
begin
ShowMessage('Scheduled start time is in the past. Correct it.');
exit;
end
else begin
StartHashing := false;
scheduleStartTime := DateTimePickerDiskModule.DateTime;
lblDiskHashSchedulerStatus.Caption := 'Waiting....scheduled for a start time of ' + FormatDateTime('YY/MM/DD HH:MM', schedulestarttime);
// Set the interval as the milliseconds remaining until the future start time
DiskHashingTimer.Interval:= trunc((schedulestarttime - Now) * 24 * 60 * 60 * 1000);
// and then enable the timer
DiskHashingTimer.Enabled := true;
// and then check if current date and time is equal to desired scheduled date and time
repeat
Application.ProcessMessages;
CheckSchedule(scheduleStartTime);
until (StartHashing = true);
end;
end;
procedure TfrmDiskHashingModule.cbLogFileChange(Sender: TObject);
begin
if cbLogFile.Checked then cbLogFile.Caption:= 'Create and save a log file';
if not cbLogFile.Checked then cbLogFile.Caption:= 'No log file required.';
end;
procedure TfrmDiskHashingModule.btnAbortHashingClick(Sender: TObject);
begin
Stop := true;
if Stop = TRUE then
begin
ledtComputedHash.Text := 'Process aborted.';
Abort;
end;
end;
procedure TfrmDiskHashingModule.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
end;
// Gets various disk properties like model, manufacturer etc, for Linux usage
// Returns a concatanated string for display in the Treeview
function GetDiskLabels(DiskDevName : string) : string;
const
smodel = 'ID_MODEL=';
sserial = 'ID_SERIAL_SHORT=';
stype = 'ID_TYPE=';
svendor = 'ID_VENDOR=';
var
DiskInfoProcess : TProcess;
diskinfo : TStringList;
i : Integer;
stmp, strModel, strVendor, strType, strSerial : String;
begin
strModel := '';
strVendor := '';
strType := '';
strSerial := '';
// Probe all attached disks and populate the interface
DiskInfoProcess:=TProcess.Create(nil);
DiskInfoProcess.Options:=[poWaitOnExit, poUsePipes];
DiskInfoProcess.CommandLine:='/sbin/udevadm info --query=property --name='+DiskDevName; //get info about selected disk
DiskInfoProcess.Execute;
diskinfo:=TStringList.Create;
diskinfo.LoadFromStream(DiskInfoProcess.Output);
for i:=0 to diskinfo.Count-1 do
begin
if pos(smodel, diskinfo.Strings[i])>0 then
begin
stmp:=diskinfo.Strings[i];
Delete(stmp, 1, Length(smodel));
if pos('_', stmp)>0 then
begin
strModel:=Copy(stmp, 1, pos('_', stmp)-1);
Delete(stmp, 1, pos('_', stmp));
strModel :=stmp;
if Length(strModel) = 0 then strModel := 'No Value';
end
else
strModel:=stmp;
end
else if pos(sserial, diskinfo.Strings[i])>0 then
begin
strSerial := Copy(diskinfo.Strings[i], Length(sserial)+1, Length(diskinfo.Strings[i])-Length(sserial));
if Length(strSerial) = 0 then strSerial := 'No Value';
end
else if pos(stype, diskinfo.Strings[i])>0 then
begin
strType := Copy(diskinfo.Strings[i], Length(stype)+1, Length(diskinfo.Strings[i])-Length(stype));
if Length(strType) = 0 then strType := 'No Value';
end
else if pos(svendor, diskinfo.Strings[i])>0 then
begin
strVendor := Copy(diskinfo.Strings[i], Length(svendor)+1, Length(diskinfo.Strings[i])-Length(svendor));
if Length(strVendor) = 0 then strVendor := 'No Value';
end;
end;
result := '(Model: ' + strModel + ', Serial No: ' + strSerial + ', Type: ' + strType + ', Vendor: ' + strVendor + ')';
end;
// Delete this eventually, once youre sure the Combo box is redundant
procedure TfrmDiskHashingModule.cbdisksChange(Sender: TObject);
const
smodel = 'ID_MODEL=';
sserial = 'ID_SERIAL_SHORT=';
stype = 'ID_TYPE=';
svendor = 'ID_VENDOR=';
var
DiskInfoProcess : TProcess;
DiskInfoProcessUDISKS : TProcess;
diskinfo, diskinfoUDISKS : TStringList;
i : Integer;
stmp : String;
begin
if cbdisks.ItemIndex<0 then
exit;
lv.Caption:='';
lm.Caption:='';
ls.Caption:='';
lt.Caption:='';
// Probe all attached disks and populate the interface
DiskInfoProcess:=TProcess.Create(nil);
DiskInfoProcess.Options:=[poWaitOnExit, poUsePipes];
DiskInfoProcess.CommandLine:='/sbin/udevadm info --query=property --name='+cbdisks.Text; //get info about selected disk
DiskInfoProcess.Execute;
diskinfo:=TStringList.Create;
diskinfo.LoadFromStream(DiskInfoProcess.Output);
for i:=0 to diskinfo.Count-1 do
begin
if pos(smodel, diskinfo.Strings[i])>0 then
begin
stmp:=diskinfo.Strings[i];
Delete(stmp, 1, Length(smodel));
if pos('_', stmp)>0 then
begin
lv.Caption:=Copy(stmp, 1, pos('_', stmp)-1);
Delete(stmp, 1, pos('_', stmp));
lm.Caption:=stmp;
end
else
lm.Caption:=stmp;
end
else if pos(sserial, diskinfo.Strings[i])>0 then
ls.Caption:=Copy(diskinfo.Strings[i], Length(sserial)+1, Length(diskinfo.Strings[i])-Length(sserial))
else if pos(stype, diskinfo.Strings[i])>0 then
lt.Caption:=Copy(diskinfo.Strings[i], Length(stype)+1, Length(diskinfo.Strings[i])-Length(stype))
else if pos(svendor, diskinfo.Strings[i])>0 then
begin
lm.Caption:=lv.Caption+' '+lm.Caption;
lv.Caption:=Copy(diskinfo.Strings[i], Length(svendor)+1, Length(diskinfo.Strings[i])-Length(svendor));
end;
end;
// Get all technical specifications about a user selected disk and save it
DiskInfoProcessUDISKS := TProcess.Create(nil);
DiskInfoProcessUDISKS.Options := [poWaitOnExit, poUsePipes];
DiskInfoProcessUDISKS.CommandLine := 'udisksctl info -b /dev/' + cbdisks.Text;
DiskInfoProcessUDISKS.Execute;
diskinfoUDISKS := TStringList.Create;
diskinfoUDISKS.LoadFromStream(diskinfoProcessUDISKS.Output);
diskinfoUDISKS.SaveToFile('TechnicalDiskDetails.txt');
// Free everything
diskinfo.Free;
diskinfoUDISKS.Free;
DiskInfoProcess.Free;
DiskInfoProcessUDISKS.Free;
end;
{$ifdef UNIX}
procedure ListDrivesLinux();
var
DisksProcess: TProcess;
i: Integer;
intPhysDiskSize, intLogDiskSize : QWord;
slDisklist: TSTringList;
PhyDiskNode, DriveLetterNode : TTreeNode;
strPhysDiskSize, strLogDiskSize, DiskDevName, DiskLabels, dmCryptDiscovered : string;
begin
intPhysDiskSize := 0;
DisksProcess:=TProcess.Create(nil);
DisksProcess.Options:=[poWaitOnExit, poUsePipes];
DisksProcess.CommandLine:='cat /proc/partitions'; //get all disks/partitions list
DisksProcess.Execute;
slDisklist:=TStringList.Create;
slDisklist.LoadFromStream(DisksProcess.Output);
slDisklist.Delete(0); //delete columns name line
slDisklist.Delete(0); //delete separator line
//cbdisks.Items.Clear;
frmDiskHashingModule.Treeview1.Images := frmDiskHashingModule.ImageList1;
PhyDiskNode := frmDiskHashingModule.TreeView1.Items.Add(nil,'Physical Disk') ;
PhyDiskNode.ImageIndex := 0;
DriveLetterNode := frmDiskHashingModule.TreeView1.Items.Add(nil,'Logical Volume') ;
DriveLetterNode.ImageIndex := 1;
// List physical disks, e.g. sda, sdb, hda, hdb etc
for i:=0 to slDisklist.Count-1 do
begin
if Length(Copy(slDisklist.Strings[i], 26, Length(slDisklist.Strings[i])-25))=3 then
begin
DiskDevName := '/dev/' + Trim(RightStr(slDisklist.Strings[i], 3));
DiskLabels := GetDiskLabels(DiskDevName);
intPhysDiskSize := GetByteCountLinux(DiskDevName);
strPhysDiskSize := FormatByteSize(intPhysDiskSize);
frmDiskHashingModule.TreeView1.Items.AddChild(PhyDiskNode, DiskDevName + ' | ' + strPhysDiskSize + ' ('+IntToStr(intPhysDiskSize)+' bytes) ' + DiskLabels);
end;
end;
// List Logical drives (partitions), e.g. sda1, sdb2, hda1, hdb2 etc
for i:=0 to slDisklist.Count-1 do
begin
dmCryptDiscovered := '';
if Length(Copy(slDisklist.Strings[i], 26, Length(slDisklist.Strings[i])-25))=4 then
begin
DiskDevName := '/dev/' + Trim(RightStr(slDisklist.Strings[i], 4));
DiskLabels := GetDiskLabels(DiskDevName);
if Pos('/dm', DiskDevName) > 0 then
begin
dmCryptDiscovered := '*** mounted dmCrypt drive! ***';
end;
intLogDiskSize := GetByteCountLinux(DiskDevName);
strLogDiskSize := FormatByteSize(intLogDiskSize);
frmDiskHashingModule.TreeView1.Items.AddChild(DriveLetterNode, DiskDevName + ' | ' + strLogDiskSize + ' ('+IntToStr(intLogDiskSize)+' bytes)' + dmCryptDiscovered +' ' + DiskLabels);
end;
end;
frmDiskHashingModule.Treeview1.AlphaSort;
slDisklist.Free;
DisksProcess.Free;
end;
// Returns a string holding the disk block COUNT (not size) as extracted from the string from
// /proc/partitions. e.g. : 8 0 312571224 sda
function GetBlockCountLinux(s : string) : string;
var
strBlockCount : string;
StartPos, EndPos : integer;
begin
strBlockCount := '';
StartPos := 0;
EndPos := 0;
EndPos := RPos(Chr($20), s);
StartPos := RPosEx(Chr($20), s, EndPos-1);
strBlockCount := Copy(s, StartPos, EndPos-StartPos);
result := strBlockCount;
end;
function GetBlockSizeLinux(DiskDevName : string) : Integer;
var
DiskProcess: TProcess;
i : Integer;
slDevDisk: TSTringList;
strBlockSize : string;
begin
result := 0;
DiskProcess:=TProcess.Create(nil);
DiskProcess.Options:=[poWaitOnExit, poUsePipes];
DiskProcess.CommandLine:='udisksctl info -b ' + DiskDevName; //get all disks/partitions list
DiskProcess.Execute;
slDevDisk := TStringList.Create;
slDevDisk.LoadFromStream(DiskProcess.Output);
for i := 0 to slDevDisk.Count -1 do
begin
if pos('block size:', slDevDisk.Strings[i]) > 0 then
begin
strBlockSize := RightStr(slDevDisk.Strings[i], 4);
if Length(strBlockSize) > 0 then result := StrToInt(strBlockSize);
end;
end;
end;
// Extracts the byte value "Size: " from the output of udisksctl info -b /dev/sdX
function GetByteCountLinux(DiskDevName : string) : QWord;
var
DiskProcess : TProcess;
i : Integer;
slDevDisk : TSTringList;
strByteCount : string;
ScanDiskData : boolean;
intByteCount : QWord;
begin
ScanDiskData := false;
result := 0;
intByteCount := 0;
strByteCount := '';
DiskProcess:=TProcess.Create(nil);
DiskProcess.Options:=[poWaitOnExit, poUsePipes];
DiskProcess.CommandLine:='udisksctl info -b ' + DiskDevName; //get all disks/partitions list
DiskProcess.Execute;
slDevDisk := TStringList.Create;
slDevDisk.LoadFromStream(DiskProcess.Output);
for i := 0 to slDevDisk.Count -1 do
begin
// Search for 'Size:' in the output, but note there are two values.
// This function only wants the first value, so abort once it's found
if (pos('Size:', slDevDisk.Strings[i]) > 0) and (ScanDiskData = false) then
begin
ScanDiskData := true;
strByteCount := ExtractNumbers(slDevDisk.Strings[i]);
if Length(strByteCount) > 0 then
begin
intByteCount := StrToQWord(strByteCount);
result := intByteCount;
end;
end;
end;
slDevDisk.free;
end;
{$endif}
// For extracting the disk size value from the output of udisksctl (from udisk2 package) on Linux
function ExtractNumbers(s: string): string;
var
i: Integer ;
begin
Result := '' ;
for i := 1 to length(s) do
begin
if s[i] in ['0'..'9'] then
Result := Result + s[i];
end;
end;
// Returns the exact disk size for BOTH physical disks and logical drives as
// reported by the Windows API and is used during the reading stage
function GetDiskLengthInBytes(hSelectedDisk : THandle) : Int64;
{$ifdef Windows}
const
// These are defined at the MSDN.Microsoft.com website for DeviceIOControl
// and https://forum.tuts4you.com/topic/22361-deviceiocontrol-ioctl-codes/
{
IOCTL_DISK_GET_DRIVE_GEOMETRY = $0070000
IOCTL_DISK_GET_PARTITION_INFO = $0074004
IOCTL_DISK_SET_PARTITION_INFO = $007C008
IOCTL_DISK_GET_DRIVE_LAYOUT = $007400C
IOCTL_DISK_SET_DRIVE_LAYOUT = $007C010
IOCTL_DISK_VERIFY = $0070014
IOCTL_DISK_FORMAT_TRACKS = $007C018
IOCTL_DISK_REASSIGN_BLOCKS = $007C01C
IOCTL_DISK_PERFORMANCE = $0070020
IOCTL_DISK_IS_WRITABLE = $0070024
IOCTL_DISK_LOGGING = $0070028
IOCTL_DISK_FORMAT_TRACKS_EX = $007C02C
IOCTL_DISK_HISTOGRAM_STRUCTURE = $0070030
IOCTL_DISK_HISTOGRAM_DATA = $0070034
IOCTL_DISK_HISTOGRAM_RESET = $0070038
IOCTL_DISK_REQUEST_STRUCTURE = $007003C
IOCTL_DISK_REQUEST_DATA = $0070040
IOCTL_DISK_CONTROLLER_NUMBER = $0070044
IOCTL_DISK_GET_PARTITION_INFO_EX = $0070048
IOCTL_DISK_SET_PARTITION_INFO_EX = $007C04C
IOCTL_DISK_GET_DRIVE_LAYOUT_EX = $0070050
IOCTL_DISK_SET_DRIVE_LAYOUT_EX = $007C054
IOCTL_DISK_CREATE_DISK = $007C058
IOCTL_DISK_GET_LENGTH_INFO = $007405C // Our constant...
SMART_GET_VERSION = $0074080
SMART_SEND_DRIVE_COMMAND = $007C084
SMART_RCV_DRIVE_DATA = $007C088
IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = $00700A0
IOCTL_DISK_UPDATE_DRIVE_SIZE = $007C0C8
IOCTL_DISK_GROW_PARTITION = $007C0D0
IOCTL_DISK_GET_CACHE_INFORMATION = $00740D4
IOCTL_DISK_SET_CACHE_INFORMATION = $007C0D8
IOCTL_DISK_GET_WRITE_CACHE_STATE = $00740DC
IOCTL_DISK_DELETE_DRIVE_LAYOUT = $007C100
IOCTL_DISK_UPDATE_PROPERTIES = $0070140
IOCTL_DISK_FORMAT_DRIVE = $007C3CC
IOCTL_DISK_SENSE_DEVICE = $00703E0
IOCTL_DISK_INTERNAL_SET_VERIFY = $0070403
IOCTL_DISK_INTERNAL_CLEAR_VERIFY = $0070407
IOCTL_DISK_INTERNAL_SET_NOTIFY = $0070408
IOCTL_DISK_CHECK_VERIFY = $0074800
IOCTL_DISK_MEDIA_REMOVAL = $0074804
IOCTL_DISK_EJECT_MEDIA = $0074808
IOCTL_DISK_LOAD_MEDIA = $007480C
IOCTL_DISK_RESERVE = $0074810
IOCTL_DISK_RELEASE = $0074814
IOCTL_DISK_FIND_NEW_DEVICES = $0074818
IOCTL_DISK_GET_MEDIA_TYPES = $0070C00
}
// For physical disk access
IOCTL_DISK_GET_LENGTH_INFO = $0007405C;
type
TDiskLength = packed record
Length : Int64;
end;
var
ByteSize: int64;
BytesReturned: DWORD;
DLength: TDiskLength;
{$endif}
begin
result := 0;
{$ifdef Windows}
ByteSize := 0;
BytesReturned := 0;
DLength := Default(TDiskLength);
// https://msdn.microsoft.com/en-us/library/aa365178%28v=vs.85%29.aspx
if not DeviceIOControl(hSelectedDisk,
IOCTL_DISK_GET_LENGTH_INFO,
nil,
0,
@DLength,
SizeOf(TDiskLength),
BytesReturned,
nil)
then raise Exception.Create('Unable to initiate IOCTL_DISK_GET_LENGTH_INFO.');
if DLength.Length > 0 then ByteSize := DLength.Length;
result := ByteSize;
{$endif}
{$ifdef UNIX}
// TODO : How to get physical disk size in Linux
{$endif}
end;
// Obtains the name of the host OS for embedding into the E01 image
// http://free-pascal-lazarus.989080.n3.nabble.com/Lazarus-WindowsVersion-td4032307.html
function GetOSNameLinux() : string;
var
OSVersion : string;
begin
// TODO : add an lsb_release parser for Linux distro specifics
OSVersion := 'Linux ';
result := OSVersion;
end;
// Returns a human readable view of the number of bytes as Mb, Gb Tb, etc
function FormatByteSize(const bytes: QWord): string;
var
B: byte;
KB: word;
MB: QWord;
GB: QWord;
TB: QWord;
begin
B := 1; //byte
KB := 1024 * B; //kilobyte
MB := 1024 * KB; //megabyte
GB := 1024 * MB; //gigabyte
TB := 1024 * GB; //terabyte
if bytes > TB then
result := FormatFloat('#.## TiB', bytes / TB)
else
if bytes > GB then
result := FormatFloat('#.## GiB', bytes / GB)
else
if bytes > MB then
result := FormatFloat('#.## MiB', bytes / MB)
else
if bytes > KB then
result := FormatFloat('#.## KiB', bytes / KB)
else
if bytes > B then
result := FormatFloat('#.## bytes', bytes)
else
if bytes = 0 then
result := '0 bytes';
end;
procedure TfrmDiskHashingModule.TreeView1SelectionChanged(Sender: TObject);
var
strDriveLetter, strPhysicalDiskID : string;
begin
if (Sender is TTreeView) and Assigned(TTreeview(Sender).Selected) then
begin
if (TTreeView(Sender).Selected.Text = 'Physical Disk')
or (TTreeView(Sender).Selected.Text = 'Logical Volume') then
ledtSelectedItem.Text := '...'
else
// If the user Chooses "Drive E:", adjust the selection to "E:" for the Thandle initiation
// We just copy the characters following "Drive ".
if Pos('Drive', TTreeView(Sender).Selected.Text) > 0 then
begin
strDriveLetter := '\\?\'+Trim(Copy(TTreeView(Sender).Selected.Text, 6, 3));
ledtSelectedItem.Text := strDriveLetter;
end
// If the user chooses a physical disk, adjust the friendly displayed version
// to an actual low level name the OS can initiate a handle to
else if Pos('\\.\PHYSICALDRIVE', TTreeView(Sender).Selected.Text) > 0 then
begin
// "\\.\PHYSICALDRIVE" = 17 chars, and up to '25' disks allocated so a further
// 2 chars for that, so 19 chars ibn total.
strPhysicalDiskID := Trim(Copy(TTreeView(Sender).Selected.Text, 0, 19));
ledtSelectedItem.Text := strPhysicalDiskID;
end
// This is a simple Linux only 'else if' that will catch physical and logical
else if (Pos('/dev/sd', TTreeView(Sender).Selected.Text) > 0) or (Pos('/dev/hd', TTreeView(Sender).Selected.Text) > 0) then
begin
// "/dev/sd" = 7 chars, and up to '25' disks allocated so a further
// 2 chars for that, s 9 chars in total.
strPhysicalDiskID := Trim(Copy(TTreeView(Sender).Selected.Text, 0, 9));
ledtSelectedItem.Text := strPhysicalDiskID;
end;
end;
end;
// Assigns numeric value to hash algorithm choice to make if else statements used later, faster
function TfrmDiskHashingModule.InitialiseHashChoice(Sender : TObject) : Integer;
begin
result := -1;
if comboHashChoice.Text = 'MD5' then
begin
result := 1;
end
else if comboHashChoice.Text = 'SHA-1' then
begin
result := 2;
end
else if comboHashChoice.Text = 'MD5 & SHA-1' then
begin
result := 3;
end
else if comboHashChoice.Text = 'SHA256' then
begin
result := 4;
end
else if comboHashChoice.Text = 'SHA512' then
begin
result := 5;
end
else if comboHashChoice.Text = 'SHA-1 & SHA256' then
begin
result := 6;
end
else if (comboHashChoice.Text = 'xxHash32') or (comboHashChoice.Text = 'xxHash64') then
begin
result := 7;
end
else if comboHashChoice.Text = 'Blake3' then
begin
result := 8;
end
else if comboHashChoice.Text = 'CRC32' then
begin
result := 9;
end
else result := 10;
end;
// Get the technical disk data for a specifically selected disk. Returns 1 on success
// -1 otherwise
function TfrmDiskHashingModule.GetDiskTechnicalSpecs(Sender : TObject) : integer;
{
https://msdn.microsoft.com/en-us/library/aa394132%28v=vs.85%29.aspx
uint32 BytesPerSector;
uint64 DefaultBlockSize;
string Description;
datetime InstallDate;
string InterfaceType;
uint32 LastErrorCode;
string Model;
uint32 Partitions;
uint32 SectorsPerTrack;
string SerialNumber;
uint32 Signature;
uint64 Size;
string Status;
uint64 TotalCylinders;
uint32 TotalHeads;
uint64 TotalSectors;
uint64 TotalTracks;
uint32 TracksPerCylinder;
}
{$ifdef Windows}
var
FSWbemLocator : Variant;
objWMIService : Variant;
colDiskDrivesWin32DiskDrive : Variant;
oEnumDiskDrive : IEnumvariant;
// http://forum.lazarus.freepascal.org/index.php?topic=24490.0
objdiskDrive : OLEVariant; // Changed from variant to OLE Variant for FPC 3.0.
nrValue : LongWord; // Added to replace nil pointer for FPC 3.0
nr : LongWord absolute nrValue; // FPC 3.0 requires IEnumvariant.next to supply a longword variable for # returned values
ReportedSectors, DefaultBlockSize, Size, TotalCylinders, TotalTracks : Int64;
Partitions, SectorsPerTrack,
WinDiskSignature, TotalHeads, TracksPerCylinder : integer;
Description, InterfaceType, Model, SerialNumber,
Status, DiskName, WinDiskSignatureHex, MBRorGPT, GPTData: ansistring;
SelectedDisk : widestring;
slDiskSpecs : TStringList;
{$endif}
begin
result := -1;
{$ifdef Unix}
GetDiskTechnicalSpecsLinux(Sender);
{$endif}
{$ifdef Windows}
DiskName := '';
Size := 0;
TotalHeads := 0;
TotalCylinders := 0;
BytesPerSector := 0;
WinDiskSignature := 0;
TotalHeads := 0;
TotalTracks := 0;
TotalCylinders := 0;
TracksPerCylinder:= 0;
DefaultBlockSize := 0;
Status := '';
Model := '';
Description := '';
InterfaceType := '';
SerialNumber := '';
SelectedDisk := '';
Partitions := 0;
GPTData := '';
frmTechSpecs.Memo1.Clear;
if Pos('\\.\PHYSICALDRIVE', TreeView1.Selected.Text) > 0 then
begin
// "\\.\PHYSICALDRIVE" = 17 chars, and up to '25' disks allocated so a further
// 2 chars for that, so 19 chars ibn total.
SelectedDisk := Trim(Copy(TreeView1.Selected.Text, 0, 19));
// Determine if it a MBR or GPT partitioned disk. Call GPTMBR and uGPT units...
MBRorGPT := MBR_or_GPT(SelectedDisk);
if Pos('GPT', MBRorGPT) > 0 then
begin
GPTData := QueryGPT(SelectedDisk);
end;
// Now ensure the disk string is suitable for WMI and and so on
SelectedDisk := ANSIToUTF8(Trim(StringReplace(SelectedDisk,'\','\\',[rfReplaceAll])));
// Years from now, when this makes no sense, just remember that WMI wants a widestring!!!!
// Dont spend hours of your life again trying to work that undocumented aspect out.
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
objWMIService := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
colDiskDrivesWin32DiskDrive := objWMIService.ExecQuery('SELECT * FROM Win32_DiskDrive WHERE DeviceID="'+SelectedDisk+'"', 'WQL');
oEnumDiskDrive := IUnknown(colDiskDrivesWin32DiskDrive._NewEnum) as IEnumVariant;
// Parse the Win32_Diskdrive WMI.
while oEnumDiskDrive.Next(1, objdiskDrive, nr) = 0 do
begin
// Using VarIsNull ensures null values are just not parsed rather than errors being generated.
if not VarIsNull(objdiskDrive.TotalSectors) then ReportedSectors := objdiskDrive.TotalSectors;
if not VarIsNull(objdiskDrive.BytesPerSector) then BytesPerSector := objdiskDrive.BytesPerSector;
if not VarIsNull(objdiskDrive.Description) then Description := objdiskDrive.Description;
if not VarIsNull(objdiskDrive.InterfaceType) then InterfaceType := objdiskDrive.InterfaceType;
if not VarIsNull(objdiskDrive.Model) then Model := objdiskDrive.Model;
if not VarIsNull(objdiskDrive.Name) then DiskName := objdiskDrive.Name;
if not VarIsNull(objdiskDrive.Partitions) then Partitions := objdiskDrive.Partitions;
if not VarIsNull(objdiskDrive.SectorsPerTrack) then SectorsPerTrack := objdiskDrive.SectorsPerTrack;
if not VarIsNull(objdiskDrive.Signature) then WinDiskSignature:= objdiskDrive.Signature; // also returned by MBR_or_GPT function
if not VarIsNull(objdiskDrive.Size) then Size := objdiskDrive.Size;
if not VarIsNull(objdiskDrive.Status) then Status := objdiskDrive.Status;
if not VarIsNull(objdiskDrive.TotalCylinders) then TotalCylinders := objdiskDrive.TotalCylinders;
if not VarIsNull(objdiskDrive.TotalHeads) then TotalHeads := objdiskDrive.TotalHeads;
if not VarIsNull(objdiskDrive.TotalTracks) then TotalTracks := objdiskDrive.TotalTracks;
if not VarIsNull(objdiskDrive.TracksPerCylinder) then TracksPerCylinder:= objdiskDrive.TracksPerCylinder;
if not VarIsNull(objdiskDrive.DefaultBlockSize) then DefaultBlockSize:= objdiskDrive.DefaultBlockSize;
//if not VarIsNull(objdiskDrive.Manufacturer) then Manufacturer := objdiskDrive.Manufacturer; WMI just reports "Standard Disk Drives"
if not VarIsNull(objdiskDrive.SerialNumber) then SerialNumber := objdiskDrive.SerialNumber;
WinDiskSignatureHex := IntToHex(SwapEndian(WinDiskSignature), 8);
if Size > 0 then
begin
slDiskSpecs := TStringList.Create;
slDiskSpecs.Add('Disk ID: ' + DiskName);
slDiskSpecs.Add('Bytes per Sector: ' + IntToStr(BytesPerSector));
slDiskSpecs.Add('Description: ' + Description);
slDiskSpecs.Add('Interface type: ' + InterfaceType);
slDiskSpecs.Add('Model: ' + Model);
//slDiskSpecs.Add('Manufacturer: ' + Manufacturer);
slDiskSpecs.Add('MBR or GPT? ' + MBRorGPT);
slDiskSpecs.Add('No of Partitions: ' + IntToStr(Partitions));
slDiskSpecs.Add('Serial Number: ' + SerialNumber);
slDiskSpecs.Add('Windows Disk Signature (from offset 440d): ' + WinDiskSignatureHex);
slDiskSpecs.Add('Size: ' + IntToStr(Size) + ' bytes (' + FormatByteSize(Size) + ').');
slDiskSpecs.Add('Status: ' + Status);
slDiskSpecs.Add('Cylinders: ' + IntToStr(TotalCylinders));
slDiskSpecs.Add('Heads: ' + IntToStr(TotalHeads));
slDiskSpecs.Add('Reported Sectors: ' + IntToStr(ReportedSectors));
slDiskSpecs.Add('Tracks: ' + IntToStr(TotalTracks));
slDiskSpecs.Add('Sectors per Track: ' + IntToStr(SectorsPerTrack));
slDiskSpecs.Add('Tracks per Cylinder: ' + IntToStr(TracksPerCylinder));
slDiskSpecs.Add('Default Block Size: ' + IntToStr(DefaultBlockSize));
slDiskSpecs.Add('= = = = = = = = = = = = = = = = = = =');
// Only add GPT related data if GPT partitioning was detected earlier
if Pos('GPT', MBRorGPT) > 0 then
begin
slDiskSpecs.Add('GPT Partition Data (if found) : ');
slDiskSpecs.Add(' ');
slDiskSpecs.Add(GPTData);
end;
result := 1;
frmTechSpecs.Memo1.Lines.AddText(slDiskSpecs.Text);
frmTechSpecs.Show;
slDiskSpecs.Free;
end
else result := -1;
end;
objdiskDrive:=Unassigned;
end; // end of if PHYSICAL DRIVEX
// If the user tries to generate such data for a logical volume, tell him he can't yet.
// TODO : Add detailed offset parameters for partitions and such
if Pos('Drive', TreeView1.Selected.Text) > 0 then
begin
ShowMessage('Logical volume details are not available yet. Maybe in the future. ');
end;
{$endif}
end;