-
Notifications
You must be signed in to change notification settings - Fork 0
/
wiper.py
executable file
·1205 lines (1121 loc) · 49.7 KB
/
wiper.py
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
#!/usr/bin/python3
#
# , _ ,
# ( o o ) Optimized
# /'` ' `'\ Wipe &
# |'''''''| Logging
# |\\'''//|
# """
#
# OWL - Optimized Wiping and Logging
# thanks to Hasan Eray Dogan for the name
#
# forensic drive wiper program for Corvus Forensics LLC
# designed to wipe, verify, gather stats, update database, notify admin of results
##
import os, sys, argparse, time, datetime, math, re
import json
from blkinfo import BlkDiskInfo
import configparser
import requests
import urllib.parse
import subprocess
# pip3 install pySMART
# apt install python3-pymongo
# pip3 install blkinfo
# pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
# todo program in options for:
# target device
# block size
# hash method for paranoid types?
# full overwrite and verify all blocks
# double overwrite and verify all blocks (stress test)
# stats about number of bytes overwritten
config = configparser.RawConfigParser()
configured=False
# TODO - compile this and move to /usr/local/sbin
# TODO - add to BH but with the database option omitted?
# compile with pyinstaller -F to make a standalone version
# build a search array where local config will override the more global
searcharray = []
searcharray.append(os.curdir)
searcharray.append(os.path.expanduser("~"))
searcharray.append("/usr/local/etc/")
searcharray.append("/etc/")
for loc in searcharray:
try:
with open(os.path.join(loc,'wiper.conf')) as source:
config.read_file(source)
configured=True
except IOError:
pass
#config.read('wiper.conf')
if configured:
# mongo databse config
if config.get('mongo', 'enabled') == "1":
mongohost = config.get('mongo', 'host')
mongoport = config.get('mongo', 'port')
mongodatabase = config.get('mongo', 'database')
mongocollection = config.get('mongo', 'collection')
from pymongo import MongoClient
client = MongoClient(mongohost, int(mongoport))
db = client[mongodatabase]
collection = db[mongocollection]
else:
mongohost="0"
# mail server config
if config.get('smtp', 'enabled') == "1":
mailactive="1"
mailserver = config.get('smtp', 'server')
maillogin = config.get('smtp', 'login')
mailpassword = config.get('smtp', 'password')
mailto = config.get('smtp', 'to')
mailfrom = config.get('smtp', 'from')
import smtplib
else:
mailactive="0"
# asset management API config
if config.get('amapi', 'enabled') == "1":
assman = config.get('amapi', 'enabled')
asssvr = config.get('amapi', 'server')
asstok = config.get('amapi', 'token')
else:
assman="0"
# chat SPI for notifications
if config.get('chatapi', 'enabled') == "1":
chatty = config.get('chatapi', 'enabled')
chatendp = config.get('chatapi', 'endpoint')
chatauth = config.get('chatapi', 'authorization')
chathead = config.get('chatapi', 'headers')
chatmeth = config.get('chatapi', 'method')
else:
chatty="0"
else:
print("Configuration file wiper.conf not found.")
mailactive="0"
mongohost="0"
assman="0"
global devsize
global devpos
global nullbytes
global onesbytes
global blocksize, origblocksize
starttime = time.time()
# parse arguments
# TODO add args to specify different wiping options:
# drivemap - don't wipe, just verify
# checkblock - the default wiping loop to check and wipe non-zero sectors
# singlepass - single wiping pass across the entire drive all sectors
# fulltest - Media certification: write 0xFF, verify, 0x00, verify.
# This block of code can move all the way to the bottom by the main func calls
arghelpdesc = 'Health check, sterilization, verification, and logging for data storage devices.'
parser = argparse.ArgumentParser(description=arghelpdesc)
parser.add_argument("target", help="Path to block device", nargs=1)
# TODO - if target not provided, list possible targets to wipe
parser.add_argument("-f", "--full", help="Full double wipe and verify [default]", action="store_true")
parser.add_argument("-s", "--smart", help="Perform smart wipe", action="store_true")
parser.add_argument("-z", "--zero", help="Single pass of null bytes", action="store_true")
parser.add_argument("-c", "--check", help="verify media contains only nulls", action="store_true")
parser.add_argument("-i", "--inventory", help="add media inventory number to record")
parser.add_argument("-b", "--blocksize", help="override default working blocksize")
parser.add_argument("--ataerase", help="Perform ATA Erase", action="store_true")
parser.add_argument("--atasecure", help="Perform ATA Secure Erase", action="store_true")
args = parser.parse_args()
# print(args.fname[0])
devname = os.path.abspath(args.target[0])
#print(target)
if not os.path.exists(devname):
print("ERROR: Target device ", devname, "not found.")
sys.exit(1)
try:
inventory = args.inventory
except:
inventory = ""
# Set the color bits we need for outputting to the terminal
trmred = "\x1B[1m\x1B[31m" # Bold Red (ANSI) - malware
trmgrn = "\x1B[0m\x1B[32m" # Normal Green (ANSI) - clean
trmcyn = "\x1B[1m\x1B[36m" # Bold Cyan (ANSI)
trmyel = "\x1B[0m\x1B[33m" # Normal Yellow (ANSI) - unknown
trmmag = "\x1B[35m" # Magenta (ANSI)
trmbmag = "\x1B[1m\x1B[35m" # Bold Magenta (ANSI) - errors
trmnorm = "\x1B[0m" # Normal (ANSI) - normal
print(trmyel + " , _ ,")
print(" ( o o )")
print("/'` ' `'\\")
print("|'''''''|")
print("|\\\\'''//|")
print(" \"\"\"" + trmnorm)
print('O.W.L. - Optimized Wipe and Logging - Forensic Media Sterilization Utility')
print("Device:", devname)
# devstat = os.stat(devname)
# direct access to disk to bypass cache, sync writes
block = os.open(devname, os.O_RDWR|os.O_SYNC)
# figure out the total size of the target
devsize = os.lseek(block, 0, os.SEEK_END)
# seek back to the beginning
devpos = os.lseek(block, 0, os.SEEK_SET)
# print("Position:", devpos)
print("Device size:", ('{:,}'.format(devsize)), "bytes")
# set blocksize to 1MB = 4096*256
blocksize = 4096 * 256
origblocksize = blocksize
print("Block size set to", ('{:,}'.format(blocksize)), "bytes")
#sys.exit(0)
# define null4k block
nullbytes = bytes(blocksize)
# define 4k block of FF for the full overwrite tests
onesbytes = nullbytes.replace(b'\x00', b'\xff')
# byteshash = hashlib.md5(null4k).hexdigest()
# bytescrc = crc16.crc16xmodem(null4k)
# print("null md5:", byteshash, "- null crc16:", bytescrc)
# bytesin = os.read(block,4096)
# byteshash = hashlib.md5(bytesin).hexdigest()
# print("md5:" , byteshash , "- crc16:" , crc16.crc16xmodem(bytesin))
# os.lseek(dev,0,os.SEEK_SET)
def checkblock():
# ideal for flash media where we want to limit writes
# override blocksize to be nice to flash media - assume 4k native
if args.blocksize:
# TODO - should I force this to fit in a normal secotor size? 4096/512?
blocksize=int(args.blocksize)
else:
blocksize = 4096
origblocksize = blocksize
nullbytes = bytes(blocksize)
print("Block size set to", ('{:,}'.format(blocksize)), "bytes")
flushcaches()
os.lseek(block, 0, os.SEEK_SET)
# loop this whole process
starttime = time.time() # reset the clock
blockwrites = 0
for xx in range(0, (devsize), blocksize):
# seek 4k from current position - loop this part while less than devsize
devpos = os.lseek(block, 0, os.SEEK_CUR)
if devpos+blocksize > (devsize):
# taking care of the last block if it's past the end
blocksize = (devsize)-devpos
nullbytes = bytes(blocksize)
##if devpos == devsize:
## print("\n")
## sys.exit(0)
bytesin = os.read(block,blocksize)
# byteshash = hashlib.md5(bytesin).hexdigest()
# todo - might be even faster to simply compare the strings of nulls and provide feedback visually 0/1
# todo - also guaranteed to be accurate with no math issues
# bytescrc = crc16.crc16xmodem(bytesin)
# testing - remove hashing functions when checking simple bstring comparison
percentdone = ("%6.3f" % (((devpos+blocksize) / devsize) * 100))
# calc runtime
runtime = (time.time() - starttime)
# calc average speed
avgspd = ("%0.2f" % ((devpos+blocksize) / runtime / 1024 / 1024))
# calc time remaining
if runtime > 0 and devpos > 0:
etasec = math.floor((devsize - devpos) / (devpos / runtime))
etatime = str(datetime.timedelta(seconds=etasec))
else:
etatime = "-:--:--"
if bytesin == nullbytes:
# calculate percentage complete
status = "Position: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmgrn + "O " + \
trmnorm + " TTC: " + etatime + " @ " + avgspd + " MBps \r"
sys.stdout.write(status)
else:
## double hashes note where I took out syncing for speed - sync at end for speed follow by verify
## if no sectors were overwritten, there is no need to verify since we just did.
#if bytescrc > 0:
# rewind 4k and write
devpos = os.lseek(block, -blocksize, os.SEEK_CUR)
# print("Position:", devpos)
# write 4k nulls and sync
os.write(block, nullbytes)
blockwrites += 1
##os.sync()
# back up 4k and recheck
##devpos = os.lseek(block, -4096, os.SEEK_CUR)
##bytesin = os.read(block,4096)
# byteshash = hashlib.md5(bytesin).hexdigest()
#bytescrc = crc16.crc16xmodem(bytesin)
# calculate percentage complete
status = "Position: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmred + "X " + \
trmnorm + " TTC: " + etatime + " @ " + avgspd + " MBps ("+ ('{:,}'.format(blockwrites)) +" blocks written) \r"
sys.stdout.write(status)
##if bytesin != nullbytes:
# this write failed - throw an error and stop
## wipefail(devpos)
# sync all writes
sys.stdout.write("\n Syncing...\r")
os.sync()
# flush the cache
flushcaches()
# at the end gof the write pass show the elapsed time on the command line
runtime = (time.time() - starttime)
runtimesec = math.floor(runtime)
runtimefmt = str(datetime.timedelta(seconds=runtimesec))
status = "Checked: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmgrn + "- " + \
trmnorm + " RT: " + runtimefmt + " @ " + avgspd + " MBps ("+ str(blockwrites) +" blocks written) \r"
return "clean", "Single pass overwriting non-clean sectors with nulls. Not verified."
def flushcaches():
# flush cache so we read from disk rather than buffer
with open('/proc/sys/vm/drop_caches', 'w') as f:
f.write("1\n")
return
def wipefail(block, position, blocksize, pattern):
# this will get called when the write fails
print("\nWrite failed at position", position, "- attempting rewrite")
# attempt rewipe the failed block
if pattern == "00":
bytepattern = nullbytes
else:
bytepattern = onesbytes
os.lseek(block, position, os.SEEK_SET)
os.write(block, bytepattern)
os.sync()
# flush the cache
flushcaches()
# recheck
os.lseek(block, position, os.SEEK_SET)
bytesin = os.read(block,blocksize)
if bytesin != bytepattern:
print("\nRe-Write attempt failed at position", position, "\n")
# TODO email notify of failure
sys.exit(1)
else:
return
def healthcheck(passno):
# TODO : add option to continue wiping even if SMART fails for final destruction pass
# get drive info and health status using smartmontools via pySMART
# https://github.com/freenas/py-SMART/blob/master/pySMART/device.py
from pySMART import Device
smart = Device(devname)
if smart.model == None:
# usb drives can be problematic - switch interface type
smart = Device(devname, interface='scsi')
# blkinfo to get more data that smart might miss
blk = BlkDiskInfo()
filters = { 'name' : smart.name } # shortname 'sda'
blkdata = blk.get_disks(filters)[0]
# add data to smart json and fix empty fields
smart.lsblk = blkdata
if smart.model == None:
smart['model'] = blkdata['model']
if smart.serial == None:
smart.serial = blkdata['serial']
#import pprint
#pprint.pprint(smart.__dict__)
print("Device: " + str(smart.name))
print("Model: " + str(smart.model))
print("Serial: " + str(smart.serial))
print("SMART health check: " + str(smart.assessment))
# mountcheck! On some systems the response is_mounted does not appear to be there
# TODO - write more detailed mount check to include add'l types, lvm, dm...
try:
mountcheck = blk.get_disks({ 'name' : smart.name, 'is_mounted' : True })
if mountcheck:
print( trmred + devname + " has mounted partitions. Exiting." + trmnorm )
showcursor()
sys.exit(0)
except:
pass
#print(smart)
# <NVME device on /dev/nvme0n1 mod:SAMSUNG MZVLB512HBJQ-00A00 sn:S5EGNE0MC08271>
#print(smart.assessment)
if str(smart.assessment) == "FAIL":
print("SMART check *FAILED* for " + str(devname))
if passno == 1:
smartfail = input("SMART detects drive as failing. Continue? (y/n) ")
if smartfail.lower() != "y":
sys.exit(0)
# Reallocated Sectors Count - not reported in nvme drives
try:
RSC = re.search('(\\d+)$', str(smart.attributes[5])).group(1)
if RSC != "0" and str(smart.attributes[5]) != "None":
print("Reallocated Sectors Count: " + RSC)
if passno == 1:
smartfail = input("SMART reports drive issues. Continue? (y/n) ")
if smartfail.lower() != "y":
sys.exit(0)
except:
pass
# Reported Uncorrectable Errors
try:
RUE = re.search('(\\d+)$', str(smart.attributes[187])).group(1)
if RUE != "0" and str(smart.attributes[187]) != "None":
print("Reported Uncorrectable Errors: " + RUE)
if passno == 1:
smartfail = input("SMART reports drive issues. Continue? (y/n) ")
if smartfail.lower() != "y":
sys.exit(0)
except:
pass
# Command Timeout
try:
SCT = re.search('(\\d+)$', str(smart.attributes[188])).group(1)
if SCT != "0" and str(smart.attributes[188]) != "None":
print("SMART Command Timeout: " + SCT)
if passno == 1:
smartfail = input("SMART reports drive issues. Continue? (y/n) ")
if smartfail.lower() != "y":
sys.exit(0)
except:
pass
# Current Pending Sector Count
try:
CPSC = re.search('(\\d+)$', str(smart.attributes[197])).group(1)
if CPSC != "0" and str(smart.attributes[197]) != "None":
print("Current Pending Sector Count: " + CPSC)
smartfail = input("SMART reports drive issues. Continue? (y/n) ")
if passno == 1:
if smartfail.lower() != "y":
sys.exit(0)
except:
pass
# Uncorrectable Sector Count
try:
USC = re.search('(\\d+)$', str(smart.attributes[198])).group(1)
if USC != "0" and str(smart.attributes[198]) != "None":
print("Uncorrectable Sector Count: " + USC)
if passno == 1:
smartfail = input("SMART reports drive issues. Continue? (y/n) ")
if smartfail.lower() != "y":
sys.exit(0)
except:
pass
# Power On Hours - informational
try:
POH = re.search('(\\d+)$', str(smart.attributes[9])).group(1)
print("Power On Hours: " + POH)
except:
pass
#print(smart.attributes[9])
#print(smart.all_attributes())
#print(smart.tests[0])
#print(smart.all_selftests())
# some devices do not support SMART attributes - so that will need to be handled
#print(smart.name)
#print(smart.model)
#print(smart.serial)
#print(smart.smart_capable)
#print(smart.smart_enabled)
#print(smart.messages)
#print(dir(smart))
smartdict = smart.__dict__
try:
if smartdict['diagnostics']:
smartdict['diagnostics'] = smart.diagnostics.__dict__
except:
pass
try:
if smartdict['smartctl']:
smartdict['smartctl'] = smart.smartctl.__dict__
except:
pass
try:
if smartdict['tests']:
# loop through the array and replace
for i in smart.tests:
smartdict['tests'][int(i.num)-1] = smart.tests[int(i.num)-1].__dict__
except:
pass
#print(dir(smart.attributes))
# TODO - this breaks with pySMART v1.3.0
for i in smart.attributes:
if i:
smartdict['attributes'][int(i.num)] = i.__dict__
#import pprint
#pprint.pprint(smartdict)
#print()
return smartdict
def drivemap():
# quick mapping of the data on the drive for stats
global blocksize
global nullbytes
cleancount = 0
dirtycount = 0
os.lseek(block, 0, os.SEEK_SET)
flushcaches()
starttime = time.time() # reset the clock
for devpos in range(0, (devsize), blocksize):
if devpos+blocksize > (devsize):
# taking care of the last block if it's past the end
blocksize = (devsize)-devpos
nullbytes = bytes(blocksize)
# resize nullbytes accordingly
nullbytes = bytes(blocksize)
bytesin = os.read(block,blocksize)
if bytesin == nullbytes:
cleancount = cleancount + blocksize
else:
dirtycount = dirtycount + blocksize
percentdone = ("%6.3f" % (((devpos+blocksize) / devsize) * 100))
# calc runtime
runtime = (time.time() - starttime)
# calc average speed
# avgspd = ("%0.2f" % (devpos / runtime / 1024 / 1024))
# calc time remaining
#if runtime > 0 and devpos > 0:
# etasec = math.floor((devsize - devpos) / (devpos / runtime))
# etatime = str(datetime.timedelta(seconds=etasec))
#else:
# etatime = "-:--:--"
# calc percent dirty / clean
cleanpct = ("%3.3f" % ((cleancount / devsize) * 100))
dirtypct = ("%3.3f" % ((dirtycount / devsize) * 100))
status = "Mapping: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) Dirty: " + trmred + \
dirtypct + "% " + trmnorm + " Clean: " + trmgrn + cleanpct + "%" + trmnorm + "\r"
sys.stdout.write(status)
sys.stdout.write("\n")
if dirtycount == 0:
print(trmgrn + "Drive is sterile and only contains 0x00." + trmnorm)
return "clean","Drive mapped. Drive is sterile and only contains 0x00."
else:
print(trmred + "Drive is not sterile." + trmnorm)
return "dirty","Drive mapped. Drive is dirty and contains non-nulled data. " + cleanpct + "% clean and " + dirtypct + "% dirty (" + str(dirtycount) + " blocks)."
def command_line(cmd, cmdtimeout=None):
try:
s = subprocess.run(cmd, capture_output=True, timeout=cmdtimeout)
s = s.stdout
return s.strip()
except subprocess.CalledProcessError:
return b''
except subprocess.TimeoutExpired:
return b'Timeout'
def atasecure():
# call hdparm and ATA Secure-Erase the drive
'''
hdparm -I <device>
hdparm --user-master user --security-set-pass pass <device>
hdparm --user-master user --security-erase-enhanced pass <device>
- or if enhanced is not supported -
hdparm --user-master user --security-erase pass <device>
- afterwards, remove passwords from drive -
hdparm --user-master user --security-disable pass <device>
hdparm --user-master user --security-set-pass NULL <device>
'''
hdpcheck = command_line(['which','hdparm'])
if hdpcheck == b'':
sys.exit("ERROR: hdparm utility not found. Exiting.")
# get current drive status
hdpi = command_line(['hdparm','-I', devname]).decode()
if not re.search('supported: enhanced erase', hdpi):
sys.exit("ERROR: ATA Secure Erase not supported for this device. Exiting.")
## TODO - confirm entry for "ordinary" erase in hdparm
if not re.search('(not\tfrozen)', hdpi):
sys.exit("ERROR: Drive is currently frozen. Exiting.")
if not re.search('(not\tlocked)', hdpi):
sys.exit("ERROR: Drive is currently locked. Exiting.")
# get time to secure-erase drive
setime = re.search('([0-9]+min for ENHANCED SECURITY ERASE)', hdpi).group(1)
print('Drive reports ' + setime)
# enable security
setpass = command_line(['hdparm', '--user-master', 'user', '--security-set-pass', 'pass', devname]).decode()
seterase = command_line(['hdparm', '--user-master', 'user', '--security-erase-enhanced', 'pass', devname]).decode()
disablepass = command_line(['hdparm', '--user-master', 'user', '--security-set-pass', 'NULL', devname]).decode()
disablesec = command_line(['hdparm', '--user-master', 'user', '--security-disable', 'NULL', devname]).decode()
print("ATA Secure Erase completed.")
# we can't call this 'clean' or 'clear' because it may not be zeroes
return "erased", "ATA Secure Erase Completed"
def ataerase():
# call hdparm and ATA Erase (null) the drive
# TODO switch to sg_sanitize and similar commands?
hdpcheck = command_line(['which','hdparm'])
if hdpcheck == b'':
sys.exit("ERROR: hdparm utility not found. Exiting.")
# get current drive status
hdpi = command_line(['hdparm','-I', devname]).decode()
if not re.search('supported: enhanced erase', hdpi):
sys.exit("ERROR: ATA Secure Erase not supported for this device. Exiting.")
## TODO - confirm entry for "ordinary" erase in hdparm
if not re.search('(not\tfrozen)', hdpi):
sys.exit("ERROR: Drive is currently frozen. Exiting.")
if not re.search('(not\tlocked)', hdpi):
sys.exit("ERROR: Drive is currently locked. Exiting.")
# get time to secure-erase drive
setime = re.search('([0-9]+min for SECURITY ERASE)', hdpi).group(1)
print('Drive reports ' + setime)
# enable security
setpass = command_line(['hdparm', '--user-master', 'user', '--security-set-pass', 'pass', devname]).decode()
seterase = command_line(['hdparm', '--user-master', 'user', '--security-erase', 'pass', devname]).decode()
disablepass = command_line(['hdparm', '--user-master', 'user', '--security-set-pass', 'NULL', devname]).decode()
disablesec = command_line(['hdparm', '--user-master', 'user', '--security-disable', 'NULL', devname]).decode()
print("ATA Secure Erase completed.")
# we can't call this 'clean' or 'clear' because it may not be zeroes
return "erased", "ATA Erase Completed"
def fulltest():
global blocksize
# this will run the media through a full wipe and verify test FF,verify,00,verify - designed for full drive
# testing or first-time wipe and verify of new media or hunting for stuck bits
#devsize = 1073741824 # DEBUG override 1GB
origblocksize=blocksize
nullbytes = bytes(blocksize)
onesbytes = nullbytes.replace(b'\x00', b'\xff')
os.lseek(block, 0, os.SEEK_SET)
starttime = time.time() # reset the clock
for devpos in range(0, (devsize), blocksize):
if devpos+blocksize > (devsize):
# taking care of the last block if it's past the end
blocksize = (devsize)-devpos
nullbytes = bytes(blocksize)
onesbytes = nullbytes.replace(b'\x00', b'\xff')
#print(devpos, devsize)
#if devpos == devsize:
# print("\n")
# exit()
percentdone = ("%6.3f" % (((devpos+blocksize) / devsize) * 100))
# calc runtime
runtime = (time.time() - starttime)
# calc average speed
avgspd = ("%0.2f" % ((devpos+blocksize) / runtime / 1024 / 1024))
# calc time remaining
if runtime > 0 and devpos > 0:
etasec = math.floor((devsize - devpos) / ((devpos+blocksize) / runtime))
etatime = str(datetime.timedelta(seconds=etasec))
else:
etatime = "-:--:--"
#writing ones
os.write(block, onesbytes)
# sync can wait for the end
#os.sync()
status = "Writing 0xFF: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmred + "FF " + \
trmnorm + " TTC: " + etatime + " @ " + avgspd + " MBps \r"
sys.stdout.write(status)
# at the end gof the write pass show the elapsed time on the command line
runtimesec = math.floor(runtime)
runtimefmt = str(datetime.timedelta(seconds=runtimesec))
status = "Wrote 0xFF: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmgrn + "-- " + \
trmnorm + " ET: " + runtimefmt + " @ " + avgspd + " MBps \r"
# sync all writes
sys.stdout.write("\nSyncing...\r")
os.sync()
ffwriteruntime = (time.time() - starttime)
# flush the cache
flushcaches()
# Then read back every block and verify - if there are any mismatches, die.
os.lseek(block, 0, os.SEEK_SET)
blocksize = origblocksize
nullbytes = bytes(blocksize)
onesbytes = nullbytes.replace(b'\x00', b'\xff')
starttime = time.time()
for devpos in range(0, (devsize), blocksize):
if devpos+blocksize > (devsize):
# taking care of the last block if it's past the end
blocksize = (devsize)-devpos
nullbytes = bytes(blocksize)
onesbytes = nullbytes.replace(b'\x00', b'\xff')
#print(devpos, devsize)
percentdone = ("%6.3f" % (((devpos+blocksize) / devsize) * 100))
# calc runtime
runtime = (time.time() - starttime)
# calc average speed
avgspd = ("%0.2f" % ((devpos+blocksize) / runtime / 1024 / 1024))
# calc time remaining
if runtime > 0 and devpos > 0:
etasec = math.floor((devsize - devpos) / (devpos / runtime))
etatime = str(datetime.timedelta(seconds=etasec))
else:
etatime = "-:--:--"
#reading ones
bytesin = os.read(block, blocksize)
if bytesin != onesbytes:
# this write failed - throw an error and stop
wipefail(block, devpos, blocksize, "FF")
# sync can wait for the end
#os.sync()
status = "Verifying 0xFF: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmgrn + "-- " + \
trmnorm + " TTC: " + etatime + " @ " + avgspd + " MBps \r"
sys.stdout.write(status)
ffverifyruntime = (time.time() - starttime)
print()
# Now repeat for x00 across the whole drive
os.lseek(block, 0, os.SEEK_SET)
blocksize = origblocksize
nullbytes = bytes(blocksize)
onesbytes = nullbytes.replace(b'\x00', b'\xff')
starttime = time.time()
for devpos in range(0, (devsize), blocksize):
if devpos+blocksize > (devsize):
# taking care of the last block if it's past the end
blocksize = (devsize)-devpos
nullbytes = bytes(blocksize)
onesbytes = nullbytes.replace(b'\x00', b'\xff')
#print(xx, devsize)
percentdone = ("%6.3f" % (((devpos+blocksize) / devsize) * 100))
# calc runtime
runtime = (time.time() - starttime)
# calc average speed
avgspd = ("%0.2f" % ((devpos+blocksize) / runtime / 1024 / 1024))
# calc time remaining
if runtime > 0 and devpos > 0:
etasec = math.floor((devsize - devpos) / (devpos / runtime))
etatime = str(datetime.timedelta(seconds=etasec))
else:
etatime = "-:--:--"
# writing zeroes
os.write(block, nullbytes)
# sync can wait for the end
#os.sync()
status = "Writing 0x00: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmred + "00 " + \
trmnorm + " TTC: " + etatime + " @ " + avgspd + " MBps \r"
sys.stdout.write(status)
# at the end gof the write pass show the elapsed time on the command line
runtimesec = math.floor(runtime)
runtimefmt = str(datetime.timedelta(seconds=runtimesec))
status = "Wrote 0x00: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmgrn + "-- " + \
trmnorm + " ET: " + runtimefmt + " @ " + avgspd + " MBps \r"
# sync all writes
sys.stdout.write("\nSyncing...\r")
os.sync()
zzwriteruntime = (time.time() - starttime)
# flush the cache
flushcaches()
# Then read back every block and verify - if there are any mismatches, die.
os.lseek(block, 0, os.SEEK_SET)
starttime = time.time()
blocksize = origblocksize
nullbytes = bytes(blocksize)
onesbytes = nullbytes.replace(b'\x00', b'\xff')
for devpos in range(0, (devsize), blocksize):
if devpos+blocksize > (devsize):
# taking care of the last block if it's past the end
blocksize = (devsize)-devpos
nullbytes = bytes(blocksize)
onesbytes = nullbytes.replace(b'\x00', b'\xff')
#print(xx, devsize)
percentdone = ("%6.3f" % (((devpos+blocksize) / devsize) * 100))
# calc runtime
runtime = (time.time() - starttime)
# calc average speed
avgspd = ("%0.2f" % ((devpos+blocksize) / runtime / 1024 / 1024))
# calc time remaining
if runtime > 0 and devpos > 0:
etasec = math.floor((devsize - devpos) / (devpos / runtime))
etatime = str(datetime.timedelta(seconds=etasec))
else:
etatime = "-:--:--"
#reading ones
bytesin = os.read(block, blocksize)
if bytesin != nullbytes:
# this write failed - throw an error and stop
wipefail(block, devpos, blocksize, "00")
# sync can wait for the end
#os.sync()
status = "Verifying 0x00: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmgrn + "00 " + \
trmnorm + " TTC: " + etatime + " @ " + avgspd + " MBps \r"
sys.stdout.write(status)
# at the end gof the write pass show the elapsed time on the command line
runtimesec = math.floor(runtime)
runtimefmt = str(datetime.timedelta(seconds=runtimesec))
status = "Verified 0x00: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmgrn + "00 " + \
trmnorm + " ET: " + runtimefmt + " @ " + avgspd + " MBps \r"
zzverifyruntime = (time.time() - starttime)
print()
mailsubject = "[wiper] Double wipe and verification completed"
mailbody = "Device " + str(devname) + " has completed and is sterile.\n\n"
# drivedict variables are available to fill in more details
if inventory != "":
mailbody += "Inventory No: " + str(inventory) + "\n"
mailbody += "Model: " + str(drivedict['model']) + "\n"
mailbody += "Serial: " + str(drivedict['serial']) + "\n"
mailbody += "SMART health check: " + str(drivedict['assessment']) + "\n"
mailbody += "Device size: " + ('{:,}'.format(devsize)) + " bytes\n"
mailbody += "Block size: " + str(blocksize) + "\n"
ffwritespeed = ("%0.2f" % (devsize / ffwriteruntime / 1024 / 1024))
mailbody += "FF Writes: " + str(datetime.timedelta(seconds=int(ffwriteruntime))) + " @ " + ffwritespeed + " MBps\n"
ffverifyspeed = ("%0.2f" % (devsize / ffverifyruntime / 1024 / 1024))
mailbody += "FF Vertfy: " + str(datetime.timedelta(seconds=int(ffverifyruntime))) + " @ " + ffverifyspeed + " MBps\n"
zzwritespeed = ("%0.2f" % (devsize / zzwriteruntime / 1024 / 1024))
mailbody += "00 Writes: " + str(datetime.timedelta(seconds=int(zzwriteruntime))) + " @ " + zzwritespeed + " MBps\n"
zzverifyspeed = ("%0.2f" % (devsize / zzverifyruntime / 1024 / 1024))
mailbody += "00 Vertfy: " + str(datetime.timedelta(seconds=int(zzverifyruntime))) + " @ " + zzverifyspeed + " MBps\n"
totalruntime = ffwriteruntime + ffverifyruntime + zzwriteruntime + zzverifyruntime
mailbody += "Total run: " + str(datetime.timedelta(seconds=totalruntime)) + "\n"
averagewrite = ("%0.2f" % ((devsize*2) / (ffwriteruntime + zzwriteruntime) / 1024 / 1024))
averageread = ("%0.2f" % ((devsize*2) / (ffverifyruntime + zzverifyruntime) / 1024 / 1024))
mailbody += "Average R/W speed: " + str(averageread) + " / " + str(averagewrite) + " MBps\n"
if mailactive != "0":
email_notify(mailactive, mailserver, maillogin, mailpassword, mailfrom, mailto, mailsubject, mailbody)
return "verified", "Double wiped and fully verified."
def singlepass():
global blocksize
# this will run the media through a full wipe and verify test FF,verify,00,verify - designed for full drive
# testing or first-time wipe and verify of new media or hunting for stuck bits
os.lseek(block, 0, os.SEEK_SET)
starttime = time.time() # reset the clock
nullbytes = bytes(blocksize)
for devpos in range(0, (devsize), blocksize):
if devpos+blocksize > (devsize):
# taking care of the last block if it's past the end
blocksize = (devsize)-devpos
nullbytes = bytes(blocksize)
#print(devpos, devsize)
#if devpos == devsize:
# print("\n")
# exit()
percentdone = ("%6.3f" % (((devpos+blocksize) / devsize) * 100))
# calc runtime
runtime = (time.time() - starttime)
# calc average speed
avgspd = ("%0.2f" % ((devpos+blocksize) / runtime / 1024 / 1024))
# calc time remaining
if runtime > 0 and devpos > 0:
etasec = math.floor((devsize - devpos) / (devpos / runtime))
etatime = str(datetime.timedelta(seconds=etasec))
else:
etatime = "-:--:--"
#writing zeroes
#wrtstart = time.time()
os.write(block, nullbytes)
#wrtend = time.time()
#realspd = ("%0.2f" % ((blocksize/1024/1024) / ( wrtend-wrtstart)))
# the time of this syncd write could give us real-time write speed
# sync can wait for the end
#os.sync()
status = "Writing 0x00: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmred + "00 " + \
trmnorm + " TTC: " + etatime + " @ " + avgspd + " MBps \r"
sys.stdout.write(status)
# at the end gof the write pass show the elapsed time on the command line
runtimesec = math.floor(runtime)
runtimefmt = str(datetime.timedelta(seconds=runtimesec))
status = "Wrote 0x00: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmgrn + "-- " + \
trmnorm + " ET: " + runtimefmt + " @ " + avgspd + " MBps \r"
# sync all writes
sys.stdout.write("\nSyncing...\r")
os.sync()
# Then read back every block and verify - if there are any mismatches, die.
# flush the cache
flushcaches()
os.lseek(block, 0, os.SEEK_SET)
blocksize = origblocksize # reset
starttime = time.time() # reset the clock
for devpos in range(0, (devsize), blocksize):
if devpos+blocksize > (devsize):
# taking care of the last block if it's past the end
blocksize = (devsize)-devpos
nullbytes = bytes(blocksize)
#print(devpos, devsize)
percentdone = ("%6.3f" % (((devpos+blocksize) / devsize) * 100))
# calc runtime
runtime = (time.time() - starttime)
# calc average speed
avgspd = ("%0.2f" % ((devpos+blocksize) / runtime / 1024 / 1024))
# calc time remaining
if runtime > 0 and devpos > 0:
etasec = math.floor((devsize - devpos) / (devpos / runtime))
etatime = str(datetime.timedelta(seconds=etasec))
else:
etatime = "-:--:--"
#reading ones
bytesin = os.read(block, blocksize)
if bytesin != nullbytes:
# this write failed - throw an error and stop
wipefail(block, devpos, blocksize, "00")
# sync can wait for the end
#os.sync()
status = "Verifying 0x00: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmgrn + "00 " + \
trmnorm + " TTC: " + etatime + " @ " + avgspd + " MBps \r"
sys.stdout.write(status)
# at the end gof the write pass show the elapsed time on the command line
runtimesec = math.floor(runtime)
runtimefmt = str(datetime.timedelta(seconds=runtimesec))
status = "Verified 0x00: " + ('{:,}'.format(devpos+blocksize)) + " (" + percentdone + "%) State: " + trmgrn + "00 " + \
trmnorm + " ET: " + runtimefmt + " @ " + avgspd + " MBps \r"
print()
return "clean", "Single pass with nulls. Verified clean."
def hidecursor():
sys.stdout.write("\033[?25l")
sys.stdout.flush()
def showcursor():
sys.stdout.write("\033[?25h")
sys.stdout.flush()
def rootcheck():
# make sure we are running as root
if os.getuid() != 0:
print("Error: This program must be run as root. Exiting.")
showcursor()
sys.exit(1)
return
def rewipe():
# sometimes a sector fails to wipe correctly and needs a little help
# call this when a verification on a sector fails
# TODO
# get: sector, blocksize, pattern
# seek to sector, write pattern of blocksize, os.sync() ...
# re-seek to sector, check blocksize for pattern
# return if it checks out, die if it fails again.
# this will require some interesting logging and testing
return
def dbcheck(client):
# see if the database is online and set a var for the updater
print("Checking database connection...")
try:
serverinfo = client.server_info()
except:
nodb = input("Database unreachable. Continue? (y/n) ")
if nodb.lower() == "y":
return False
else:
sys.exit(1)
return True
def dbupdate(collection, drivedict):
if mongohost != "0":
print("Updating database...")
collection.insert_one(drivedict)
return
else:
return
def email_notify(mailactive, mailserver, maillogin, mailpassword, mailfrom, mailto, mailsubject, mailbody):
if mailactive != "1":
return
# Prepare message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (mailfrom, mailto, mailsubject, mailbody)
try:
server = smtplib.SMTP(mailserver)
server.starttls()
server.login(maillogin, mailpassword)
server.sendmail(mailfrom, mailto, message)
server.quit()
return
except:
print("Failed sending email message")
return
def cleanup():
# things we need to do on exit
showcursor()
# TODO - consolidate API functions for asset management
def insertass(assdata):
# update asset management system - add maintainence record at end
assreq = asssvr + 'hardware'
asshed = { 'Authorization' : 'Bearer ' + asstok , 'accept' : 'application/json', 'content-type' : 'application/json' }
response = requests.post(assreq, headers=asshed, json=assdata)
if response.status_code == 200:
pass
elif response.status_code == 404:
sys.exit('Error: Asset server endpoint ' + asssvr + ' not found. ' + response.text )
elif response.status_code == 401:
sys.exit('Error: Asset server authorization failed. Check your API token. ' + response.text )
else:
sys.exit('Unexpected response from API: ' + str(response.status_code) + ' ' + response.text )
respdict = response.json()
if 'status' in respdict.keys():
if respdict['status'] == 'error':
sys.exit('Asset server error: ' + json.dumps(respdict['messages']))
print("Asset management skeleton record inserted. Please review.")
return respdict['payload']['id'] #int
def assupdate(assdata):
# update asset management system - add maintainence record at end
assreq = asssvr + 'maintenances'
asshed = { 'Authorization' : 'Bearer ' + asstok , 'accept' : 'application/json', 'content-type' : 'application/json' }
response = requests.post(assreq, headers=asshed, json=assdata)
if response.status_code == 200:
pass
elif response.status_code == 404:
sys.exit('Error: Asset server endpoint ' + asssvr + ' not found. ' + response.text )
elif response.status_code == 401:
sys.exit('Error: Asset server authorization failed. Check your API token. ' + response.text )
else:
sys.exit('Unexpected response from API: ' + str(response.status_code) + ' ' + response.text )
respdict = response.json()
if 'status' in respdict.keys():
if respdict['status'] == 'error':
sys.exit('Asset server error: ' + json.dumps(respdict['messages']))
print("Asset management records updated.")
return
def chatnotify(message):
# internal corvus spreed server - I expect you will need to adjust to suit your needs to send notifications
print("Notifying via chat.")
chathed = json.loads(chathead)
messageenc = urllib.parse.quote(message)
chatreq = chatendp + messageenc
if chatmeth == "POST":
response = requests.post(chatreq, headers=chathed)
elif chatmeth == "GET":
response = requests.get(chatreq, headers=chathed)