-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathhandle.py
More file actions
2597 lines (2225 loc) · 141 KB
/
handle.py
File metadata and controls
2597 lines (2225 loc) · 141 KB
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/env python
#
# Azure Disk Encryption For Linux extension
#
# Copyright 2016 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import filecmp
import json
import os
import os.path
import re
import subprocess
import sys
import time
import tempfile
import traceback
import uuid
import shutil
from distutils.version import LooseVersion
from Utils import HandlerUtil
from Common import CommonVariables, CryptItem
from ExtensionParameter import ExtensionParameter
from DiskUtil import DiskUtil
from CryptMountConfigUtil import CryptMountConfigUtil
from ResourceDiskUtil import ResourceDiskUtil
from BackupLogger import BackupLogger
from EncryptionSettingsUtil import EncryptionSettingsUtil
from EncryptionConfig import EncryptionConfig
from IMDSUtil import IMDSUtil,IMDSStoredResults
from patch import GetDistroPatcher
from BekUtil import BekUtil
from AbstractBekUtilImpl import BekMissingException
from check_util import CheckUtil
from DecryptionMarkConfig import DecryptionMarkConfig
from EncryptionMarkConfig import EncryptionMarkConfig
from EncryptionEnvironment import EncryptionEnvironment
from OnGoingItemConfig import OnGoingItemConfig
from ProcessLock import ProcessLock
from CommandExecutor import CommandExecutor, ProcessCommunicator
from OnlineEncryptionHandler import OnlineEncryptionHandler
from VolumeNotificationService import VolumeNotificationService
from io import open
def install():
hutil.do_parse_context('Install')
hutil.do_exit(0, 'Install', CommonVariables.extension_success_status, str(CommonVariables.success), 'Install Succeeded')
def disable():
hutil.do_parse_context('Disable')
# archiving old configs during disable rather than uninstall will allow subsequent versions
# to restore these configs in their update step rather than their install step once all
# released versions of the extension are at this version or above
hutil.archive_old_configs()
if security_Type == CommonVariables.ConfidentialVM:
vns_service = VolumeNotificationService(logger=logger)
vns_service.stop()
#mask the service, to avoid spontaneous service start.
vns_service.mask()
hutil.do_exit(0, 'Disable', CommonVariables.extension_success_status, '0', 'Disable succeeded')
def uninstall():
hutil.do_parse_context('Uninstall')
if security_Type == CommonVariables.ConfidentialVM:
vns_service = VolumeNotificationService(logger=logger)
vns_service.stop()
vns_service.disable()
vns_service.unregister()#deleting service file.
vns_service.unmask() #to make sure service will be removed from /etc/ location - sucessfully unregistered.
hutil.do_exit(0, 'Uninstall', CommonVariables.extension_success_status, '0', 'Uninstall succeeded')
def disable_encryption():
hutil.do_parse_context('DisableEncryption')
logger.log('Disabling encryption')
decryption_marker = DecryptionMarkConfig(logger, encryption_environment)
exit_status = {
'operation': 'DisableEncryption',
'status': CommonVariables.extension_success_status,
'status_code': str(CommonVariables.success),
'message': 'Decryption completed'
}
if not vns_call:
hutil.exit_if_same_seq(exit_status)
hutil.save_seq()
try:
extension_parameter = ExtensionParameter(hutil, logger, DistroPatcher, encryption_environment, get_protected_settings(), get_public_settings())
disk_util = DiskUtil(hutil=hutil, patching=DistroPatcher, logger=logger, encryption_environment=encryption_environment)
crypt_mount_config_util = CryptMountConfigUtil(logger=logger, encryption_environment=encryption_environment, disk_util=disk_util)
encryption_status = json.loads(disk_util.get_encryption_status())
if encryption_status["os"] != "NotEncrypted":
raise Exception("Disabling encryption is not supported when OS volume is encrypted")
bek_util = BekUtil(disk_util, logger,encryption_environment)
encryption_config = EncryptionConfig(encryption_environment, logger)
bek_passphrase_file = bek_util.get_bek_passphrase_file(encryption_config)
crypt_mount_config_util.consolidate_azure_crypt_mount(bek_passphrase_file)
crypt_items = crypt_mount_config_util.get_crypt_items()
logger.log('Found {0} items to decrypt'.format(len(crypt_items)))
for crypt_item in crypt_items:
disk_util.create_cleartext_key(crypt_item.mapper_name)
add_result = disk_util.luks_add_cleartext_key(bek_passphrase_file,
crypt_item.dev_path,
crypt_item.mapper_name,
crypt_item.luks_header_path)
if add_result != CommonVariables.process_success:
if disk_util.is_luks_device(crypt_item.dev_path, crypt_item.luks_header_path):
raise Exception("luksAdd failed with return code {0}".format(add_result))
else:
logger.log("luksAdd failed with return code {0}".format(add_result))
logger.log("Ignoring for now, as device ({0}) does not seem to be a luks device".format(crypt_item.dev_path))
if crypt_item.dev_path.startswith("/dev/sd"):
logger.log('Updating crypt item entry to use mapper name')
logger.log('Device name before update: {0}'.format(crypt_item.dev_path))
crypt_item.dev_path = disk_util.get_persistent_path_by_sdx_path(crypt_item.dev_path)
logger.log('Device name after update: {0}'.format(crypt_item.dev_path))
crypt_item.uses_cleartext_key = True
crypt_mount_config_util.update_crypt_item(crypt_item)
logger.log('Added cleartext key for {0}'.format(crypt_item))
decryption_marker.command = extension_parameter.command
decryption_marker.volume_type = extension_parameter.VolumeType
decryption_marker.commit()
settings_util = EncryptionSettingsUtil(logger)
settings_util.clear_encryption_settings(disk_util)
hutil.do_status_report(operation='DisableEncryption',
status=CommonVariables.extension_success_status,
status_code=str(CommonVariables.success),
message='Encryption settings cleared')
bek_util.store_bek_passphrase(encryption_config, b'')
bek_util.delete_bek_passphrase_file(encryption_config)
if decryption_marker.config_file_exists():
logger.log(msg="decryption is marked, starting daemon.", level=CommonVariables.InfoLevel)
start_daemon('DisableEncryption')
hutil.do_exit(exit_code=0,
operation='DisableEncryption',
status=CommonVariables.extension_success_status,
code=str(CommonVariables.success),
message='Decryption started')
except Exception as e:
message = "Failed to disable the extension with error: {0}, stack trace: {1}".format(e, traceback.format_exc())
logger.log(msg=message, level=CommonVariables.ErrorLevel)
hutil.do_exit(exit_code=CommonVariables.unknown_error,
operation='DisableEncryption',
status=CommonVariables.extension_error_status,
code=str(CommonVariables.unknown_error),
message=message)
def stamp_disks_with_settings(items_to_encrypt, encryption_config, encryption_marker=None):
if security_Type == CommonVariables.ConfidentialVM:
logger.log(msg="Do not send vm setting to host for stamping.",level=CommonVariables.InfoLevel)
return
disk_util = DiskUtil(hutil=hutil, patching=DistroPatcher, logger=logger, encryption_environment=encryption_environment)
crypt_mount_config_util = CryptMountConfigUtil(logger=logger, encryption_environment=encryption_environment, disk_util=disk_util)
bek_util = BekUtil(disk_util, logger,encryption_environment)
current_passphrase_file = bek_util.get_bek_passphrase_file(encryption_config)
public_settings = get_public_settings()
extension_parameter = ExtensionParameter(hutil, logger, DistroPatcher, encryption_environment, get_protected_settings(), public_settings)
has_keystore_flag = CommonVariables.KeyStoreTypeKey in public_settings
# post new encryption settings via wire server protocol
settings = EncryptionSettingsUtil(logger)
new_protector_name = settings.get_new_protector_name()
settings.create_protector_file(current_passphrase_file, new_protector_name)
data = settings.get_settings_data(
protector_name=new_protector_name,
kv_url=extension_parameter.KeyVaultURL,
kv_id=extension_parameter.KeyVaultResourceId,
kek_url=extension_parameter.KeyEncryptionKeyURL,
kek_kv_id=extension_parameter.KekVaultResourceId,
kek_algorithm=extension_parameter.KeyEncryptionAlgorithm,
extra_device_items=items_to_encrypt,
disk_util=disk_util,
crypt_mount_config_util=crypt_mount_config_util,
key_store_type=extension_parameter.KeyStoreType,
keystoretype_flag_exists=has_keystore_flag)
settings.post_to_wireserver(data)
# exit transitioning state by issuing a status report indicating
# that the necessary encryption settings are stamped successfully
# For online encryption transistioning phase will not be exited at this point.
# It will be exited after the online encryption is setup.
status = CommonVariables.extension_success_status
if encryption_marker is not None and encryption_marker.get_encryption_mode() == CommonVariables.EncryptionModeOnline:
status = CommonVariables.extension_transitioning_status
hutil.do_status_report(operation='StartEncryption',
status=status,
status_code=str(CommonVariables.success),
message='Encryption settings stamped')
filenames = []
for disk in data.get("Disks", []):
for volume in disk.get("Volumes", []):
for tag in volume.get("SecretTags", []):
if tag.get("Name") == 'DiskEncryptionKeyFileName':
if tag.get("Value") is not None:
filenames.append(str(tag["Value"]))
for filename in filenames:
filepath = os.path.join(CommonVariables.encryption_key_mount_point, filename)
if filepath != current_passphrase_file:
shutil.copyfile(current_passphrase_file, filepath)
settings.remove_protector_file(new_protector_name)
encryption_config.passphrase_file_name = extension_parameter.DiskEncryptionKeyFileName
encryption_config.volume_type = extension_parameter.VolumeType
encryption_config.secret_id = new_protector_name
encryption_config.secret_seq_num = hutil.get_current_seq()
encryption_config.commit()
extension_parameter.commit()
def are_disks_stamped_with_current_config(encryption_config):
return encryption_config.get_secret_seq_num() == str(hutil.get_current_seq())
def get_public_settings():
public_settings_str = hutil._context._config['runtimeSettings'][0]['handlerSettings'].get('publicSettings')
if isinstance(public_settings_str, str):
return json.loads(public_settings_str)
else:
return public_settings_str
def get_protected_settings():
protected_settings_str = hutil._context._config['runtimeSettings'][0]['handlerSettings'].get('protectedSettings')
if isinstance(protected_settings_str, str):
return json.loads(protected_settings_str)
else:
return protected_settings_str
def update_encryption_settings(extra_items_to_encrypt=[]):
hutil.do_parse_context('UpdateEncryptionSettings')
logger.log('Updating encryption settings')
# ensure cryptsetup package is still available in case it was for some reason removed after enable
try:
DistroPatcher.install_cryptsetup()
except Exception as e:
hutil.save_seq()
message = "Failed to update encryption settings with error: {0}, stack trace: {1}".format(e, traceback.format_exc())
hutil.do_exit(exit_code=CommonVariables.missing_dependency,
operation='UpdateEncryptionSettings',
status=CommonVariables.extension_error_status,
code=str(CommonVariables.missing_dependency),
message=message)
encryption_config = EncryptionConfig(encryption_environment, logger)
config_secret_seq = encryption_config.get_secret_seq_num()
if not config_secret_seq:
current_secret_seq_num = -1
else:
current_secret_seq_num = int(config_secret_seq)
update_call_seq_num = hutil.get_current_seq()
logger.log("Current secret was created in operation #{0}".format(current_secret_seq_num))
logger.log("The update call is operation #{0}".format(update_call_seq_num))
executor = CommandExecutor(logger)
executor.Execute("mount /boot")
settings_stamped = False
updated_crypt_items = []
old_passphrase = None
try:
extension_parameter = ExtensionParameter(hutil, logger, DistroPatcher, encryption_environment, get_protected_settings(), get_public_settings())
disk_util = DiskUtil(hutil=hutil, patching=DistroPatcher, logger=logger, encryption_environment=encryption_environment)
crypt_mount_config_util = CryptMountConfigUtil(logger=logger, encryption_environment=encryption_environment, disk_util=disk_util)
bek_util = BekUtil(disk_util, logger,encryption_environment)
existing_passphrase_file = bek_util.get_bek_passphrase_file(encryption_config)
if not existing_passphrase_file:
hutil.save_seq()
message = "Cannot find current passphrase file. This could happen if BEK volume is not mounted or LinuxPassPhrase file is missing from BEK volume."
hutil.do_exit(exit_code=CommonVariables.configuration_error,
operation='UpdateEncryptionSettings',
status=CommonVariables.extension_error_status,
code=str(CommonVariables.configuration_error),
message=message)
with open(existing_passphrase_file, 'r') as f:
old_passphrase = f.read()
if current_secret_seq_num < update_call_seq_num:
if extension_parameter.passphrase is None or extension_parameter.passphrase == "":
extension_parameter.passphrase = bek_util.generate_passphrase()
logger.log('Recreating secret to store in the KeyVault')
temp_keyfile = tempfile.NamedTemporaryFile(delete=False)
temp_keyfile.write(extension_parameter.passphrase)
temp_keyfile.close()
crypt_mount_config_util.consolidate_azure_crypt_mount(existing_passphrase_file)
for crypt_item in crypt_mount_config_util.get_crypt_items():
if not crypt_item:
continue
before_keyslots = disk_util.luks_dump_keyslots(crypt_item.dev_path, crypt_item.luks_header_path)
logger.log("Before key addition, keyslots for {0}: {1}".format(crypt_item.dev_path, before_keyslots))
logger.log("Adding new key for {0}".format(crypt_item.dev_path))
luks_add_result = disk_util.luks_add_key(passphrase_file=existing_passphrase_file,
dev_path=crypt_item.dev_path,
mapper_name=crypt_item.mapper_name,
header_file=crypt_item.luks_header_path,
new_key_path=temp_keyfile.name)
logger.log("luks add result is {0}".format(luks_add_result))
after_keyslots = disk_util.luks_dump_keyslots(crypt_item.dev_path, crypt_item.luks_header_path)
logger.log("After key addition, keyslots for {0}: {1}".format(crypt_item.dev_path, after_keyslots))
new_keyslot = list([x[0] != x[1] for x in zip(before_keyslots, after_keyslots)]).index(True)
logger.log("New key was added in keyslot {0}".format(new_keyslot))
updated_crypt_items.append(crypt_item)
logger.log("New key successfully added to all encrypted devices")
if DistroPatcher.distro_info[0] == "Ubuntu":
executor.Execute("update-initramfs -u -k all", True)
if DistroPatcher.distro_info[0] == "redhat" or DistroPatcher.distro_info[0] == "centos":
distro_version = DistroPatcher.distro_info[1]
if distro_version.startswith('7.'):
executor.ExecuteInBash("/usr/sbin/dracut -f -v --kver `grubby --default-kernel | sed 's|/boot/vmlinuz-||g'`", True)
logger.log("Update initrd image with new osluksheader.")
os.unlink(temp_keyfile.name)
# store new passphrase and overwrite old encryption key file
bek_util.store_bek_passphrase(encryption_config, extension_parameter.passphrase)
stamp_disks_with_settings(items_to_encrypt=extra_items_to_encrypt, encryption_config=encryption_config)
settings_stamped = True
existing_passphrase_file = bek_util.get_bek_passphrase_file(encryption_config)
logger.log('Secret has already been updated')
disk_util.log_lsblk_output()
if extension_parameter.passphrase and extension_parameter.passphrase.decode("utf-8") != open(existing_passphrase_file,'r').read():
logger.log("The new passphrase has not been placed in BEK volume yet")
logger.log("Skipping removal of old passphrase")
exit_without_status_report()
logger.log('Removing old passphrase')
temp_oldkeyfile = tempfile.NamedTemporaryFile(delete=False)
temp_oldkeyfile.write(old_passphrase.encode("utf-8"))
temp_oldkeyfile.close()
for crypt_item in crypt_mount_config_util.get_crypt_items():
if not crypt_item:
continue
if filecmp.cmp(existing_passphrase_file, temp_oldkeyfile.name):
logger.log('Current BEK and backup are the same, skipping removal')
continue
logger.log('Removing old passphrase from {0}'.format(crypt_item.dev_path))
keyslots = disk_util.luks_dump_keyslots(crypt_item.dev_path, crypt_item.luks_header_path)
logger.log("Keyslots before removal: {0}".format(keyslots))
luks_remove_result = disk_util.luks_remove_key(passphrase_file=temp_oldkeyfile.name,
dev_path=crypt_item.dev_path,
header_file=crypt_item.luks_header_path)
logger.log("luks remove result is {0}".format(luks_remove_result))
keyslots = disk_util.luks_dump_keyslots(crypt_item.dev_path, crypt_item.luks_header_path)
logger.log("Keyslots after removal: {0}".format(keyslots))
logger.log("Old key successfully removed from all encrypted devices")
hutil.save_seq()
extension_parameter.commit()
os.unlink(temp_oldkeyfile.name)
bek_util.umount_azure_passhprase(encryption_config)
if len(extra_items_to_encrypt) > 0:
hutil.do_status_report(operation='UpdateEncryptionSettings',
status=CommonVariables.extension_success_status,
status_code=str(CommonVariables.success),
message='Encryption settings updated')
else:
hutil.do_exit(exit_code=0,
operation='UpdateEncryptionSettings',
status=CommonVariables.extension_success_status,
code=str(CommonVariables.success),
message='Encryption settings updated')
except Exception as e:
hutil.save_seq()
if not settings_stamped:
clear_new_luks_keys(disk_util, old_passphrase, extension_parameter.passphrase, bek_util, encryption_config, updated_crypt_items)
message = "Failed to update encryption settings with error: {0}, stack trace: {1}".format(e, traceback.format_exc())
logger.log(msg=message, level=CommonVariables.ErrorLevel)
bek_util.umount_azure_passhprase(encryption_config)
hutil.do_exit(exit_code=CommonVariables.unknown_error,
operation='UpdateEncryptionSettings',
status=CommonVariables.extension_error_status,
code=str(CommonVariables.unknown_error),
message=message)
def clear_new_luks_keys(disk_util, old_passphrase, new_passphrase, bek_util, encryption_config, updated_crypt_items):
try:
if not old_passphrase:
logger.log("Old passphrase does not exist. Nothing to revert.")
return
if not new_passphrase:
logger.log("New passphrase does not exist. Nothing to clear.")
return
temp_keyfile = tempfile.NamedTemporaryFile(delete=False)
temp_keyfile.write(new_passphrase)
temp_keyfile.close()
executor = CommandExecutor(logger)
for crypt_item in updated_crypt_items:
if not crypt_item:
continue
logger.log('Removing new passphrase from {0}'.format(crypt_item.dev_path))
before_keyslots = disk_util.luks_dump_keyslots(crypt_item.dev_path, crypt_item.luks_header_path)
logger.log("Keyslots before removal: {0}".format(before_keyslots))
luks_remove_result = disk_util.luks_remove_key(passphrase_file=temp_keyfile.name,
dev_path=crypt_item.dev_path,
header_file=crypt_item.luks_header_path)
logger.log("luks remove result is {0}".format(luks_remove_result))
after_keyslots = disk_util.luks_dump_keyslots(crypt_item.dev_path, crypt_item.luks_header_path)
logger.log("Keyslots after removal: {0}".format(after_keyslots))
if DistroPatcher.distro_info[0] == "Ubuntu":
executor.Execute("update-initramfs -u -k all", True)
if DistroPatcher.distro_info[0] == "redhat" or DistroPatcher.distro_info[0] == "centos":
distro_version = DistroPatcher.distro_info[1]
if distro_version.startswith('7.'):
executor.ExecuteInBash("/usr/sbin/dracut -f -v --kver `grubby --default-kernel | sed 's|/boot/vmlinuz-||g'`", True)
logger.log("Update initrd image with new osluksheader.")
bek_util.store_bek_passphrase(encryption_config, old_passphrase)
os.unlink(temp_keyfile.name)
logger.log("Cleared new luks keys.")
except Exception as e:
msg = "Failed to clear new luks key with error: {0}, stack trace: {1}".format(e, traceback.format_exc())
logger.log(msg=msg, level=CommonVariables.WarningLevel)
def update():
# The extension update handshake is [old:disable][new:update][old:uninstall][new:install]
# this method is called when updating an older version of the extension to a newer version
hutil.do_parse_context('Update')
logger.log("Installing pre-requisites")
DistroPatcher.install_extras()
DistroPatcher.update_prereq()
hutil.do_exit(0, 'Update', CommonVariables.extension_success_status, '0', 'Update Succeeded')
def exit_without_status_report():
sys.exit(0)
def not_support_header_option_distro(patching):
if patching.distro_info[0].lower() == "centos" and patching.distro_info[1].startswith('6.'):
return True
if patching.distro_info[0].lower() == "redhat" and patching.distro_info[1].startswith('6.'):
return True
if patching.distro_info[0].lower() == "suse" and patching.distro_info[1].startswith('11'):
return True
return False
def none_or_empty(obj):
if obj is None or obj == "":
return True
else:
return False
def toggle_se_linux_for_centos7(disable):
if DistroPatcher.distro_info[0].lower() == 'centos' and DistroPatcher.distro_info[1].startswith('7.0'):
if disable:
se_linux_status = encryption_environment.get_se_linux()
if se_linux_status.lower() == 'enforcing':
encryption_environment.disable_se_linux()
return True
else:
encryption_environment.enable_se_linux()
return False
def mount_encrypted_disks(disk_util, crypt_mount_config_util, bek_util, passphrase_file, encryption_config):
# mount encrypted resource disk
retain_mountpoint = False
if security_Type == CommonVariables.ConfidentialVM:
logger.log("retaining the mountpoint.")
retain_mountpoint = True
resource_disk_util = ResourceDiskUtil(logger, disk_util, crypt_mount_config_util, passphrase_file, get_public_settings(), DistroPatcher.distro_info,retain_mountpoint)
if encryption_config.config_file_exists():
volume_type = encryption_config.get_volume_type().lower()
if volume_type == CommonVariables.VolumeTypeData.lower() or volume_type == CommonVariables.VolumeTypeAll.lower():
if security_Type != CommonVariables.ConfidentialVM:
resource_disk_util.automount()
else:
logger.log("Format resource disk if unusable. security type {0}".format(security_Type))
resource_disk_util.automount(True)
logger.log("mounted resource disk")
else:
# Probably a re-image scenario: Just do a best effort
if resource_disk_util.try_remount():
logger.log("mounted resource disk")
# add walkaround for the centos 7.0
se_linux_status = None
if DistroPatcher.distro_info[0].lower() == 'centos' and DistroPatcher.distro_info[1].startswith('7.0'):
se_linux_status = encryption_environment.get_se_linux()
if se_linux_status.lower() == 'enforcing':
encryption_environment.disable_se_linux()
# mount any data disks - make sure the azure disk config path exists.
for crypt_item in crypt_mount_config_util.get_crypt_items():
if not crypt_item:
continue
if not os.path.exists(os.path.join(CommonVariables.dev_mapper_root, crypt_item.mapper_name)):
luks_open_result = disk_util.luks_open(passphrase_file=passphrase_file,
dev_path=crypt_item.dev_path,
mapper_name=crypt_item.mapper_name,
header_file=crypt_item.luks_header_path,
uses_cleartext_key=crypt_item.uses_cleartext_key)
logger.log("luks open result is {0}".format(luks_open_result))
disk_util.mount_crypt_item(crypt_item, passphrase_file)
if DistroPatcher.distro_info[0].lower() == 'centos' and DistroPatcher.distro_info[1].startswith('7.0'):
if se_linux_status is not None and se_linux_status.lower() == 'enforcing':
encryption_environment.enable_se_linux()
def is_vns_call():
for a in sys.argv[1:]:
if re.match("^([-/]*)(vnscall)", a):
return True
return False
def main():
global hutil, DistroPatcher, logger, encryption_environment, security_Type, vns_call
HandlerUtil.waagent.Log("{0} started to handle.".format(CommonVariables.extension_name))
hutil = HandlerUtil.HandlerUtility(HandlerUtil.waagent.Log, HandlerUtil.waagent.Error, CommonVariables.extension_name)
logger = BackupLogger(hutil)
DistroPatcher = GetDistroPatcher(logger)
hutil.patching = DistroPatcher
encryption_environment = EncryptionEnvironment(patching=DistroPatcher, logger=logger)
#reading the stored IMDS results.
security_Type = None
imds_Stored_Results=IMDSStoredResults(logger=logger,encryption_environment=encryption_environment)
if imds_Stored_Results.config_file_exists():
security_Type = imds_Stored_Results.get_security_type()
else:
#TODO: read from IMDS. subject to clarification.
pass
disk_util = DiskUtil(hutil=hutil, patching=DistroPatcher, logger=logger, encryption_environment=encryption_environment)
hutil.disk_util = disk_util
vns_call = is_vns_call()
for a in sys.argv[1:]:
if re.match("^([-/]*)(disable)", a):
disable()
elif re.match("^([-/]*)(uninstall)", a):
uninstall()
elif re.match("^([-/]*)(install)", a):
install()
elif re.match("^([-/]*)(enable)", a):
if DistroPatcher is None:
hutil.do_exit(exit_code=CommonVariables.os_not_supported,
operation='Enable',
status=CommonVariables.extension_error_status,
code=(CommonVariables.os_not_supported),
message='Enable failed: OS distribution is not supported')
else:
enable()
elif re.match("^([-/]*)(update)", a):
update()
elif re.match("^([-/]*)(daemon)", a):
daemon()
def mark_encryption(command, volume_type, disk_format_query, encryption_mode=None, encryption_phase=None):
encryption_marker = EncryptionMarkConfig(logger, encryption_environment)
encryption_marker.command = command
encryption_marker.volume_type = volume_type
encryption_marker.diskFormatQuery = disk_format_query
update_status = False
if encryption_mode is not None and encryption_mode == CommonVariables.EncryptionModeOnline:
logger.log("Disks will be encrypted with online mode")
encryption_marker.encryption_mode = encryption_mode
if encryption_phase is not None and encryption_phase == CommonVariables.EncryptionPhaseResume:
logger.log("Marking Online encryption resume phase.")
encryption_marker.encryption_phase = encryption_phase
update_status = True
encryption_marker.commit()
if update_status:
hutil.do_status_report(operation='StartEncryption',
status=CommonVariables.extension_success_status,
status_code=str(CommonVariables.success),
message='Online Encryption initialized.')
return encryption_marker
def should_perform_online_encryption(disk_util, encryption_command, volume_type):
if security_Type != CommonVariables.ConfidentialVM and not DistroPatcher.support_online_encryption:
return False
if security_Type == CommonVariables.ConfidentialVM and not DistroPatcher.validate_online_encryption_support():
return False
DistroPatcher.install_cryptsetup()
if disk_util.get_luks_header_size() != CommonVariables.luks_header_size_v2:
return False
if encryption_command == CommonVariables.EnableEncryptionFormatAll:
if volume_type.lower() == CommonVariables.VolumeTypeAll.lower():
return True
else:
return False
if encryption_command != CommonVariables.EnableEncryption:
return False
return True
def is_resume_phase(encryption_phase):
if encryption_phase is not None and encryption_phase == CommonVariables.EncryptionPhaseResume:
return True
return False
def is_daemon_running():
handler_path = os.path.join(os.getcwd(), __file__).encode('utf-8')
daemon_arg = b'-daemon'
psproc = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
pslist, _ = psproc.communicate()
for line in pslist.split(b'\n'):
if handler_path in line and daemon_arg in line:
return True
return False
def enable():
lock = ProcessLock(logger=logger, lock_file_path=encryption_environment.enable_lock_file_path)
if not lock.try_lock():
logger.log("there's another enable running, please wait it to exit.", level=CommonVariables.WarningLevel)
return
logger.log('enable process lock, PID {0}'.format(os.getpid()))
try:
hutil.do_parse_context('Enable')
logger.log('Enabling extension')
public_settings = get_public_settings()
logger.log('Public settings:\n{0}'.format(json.dumps(public_settings, sort_keys=True, indent=4)))
check_Util = CheckUtil(logger)
imds_Stored_Results=IMDSStoredResults(logger=logger,encryption_environment=encryption_environment)
imds_Util = IMDSUtil(logger)
try:
check_Util.pre_Initialization_Check(imdsStoredResults=imds_Stored_Results,iMDSUtil=imds_Util,public_settings=public_settings,continueADEOnIMDSFailure=True)
except Exception as ex:
hutil.do_exit(exit_code=CommonVariables.configuration_error,
operation='pre_Initialization_Check',
status=CommonVariables.extension_error_status,
code=str(CommonVariables.configuration_error),
message=str(ex))
#reading security type from IMDS stored results. update to global variable.
global security_Type
security_Type = imds_Stored_Results.get_security_type()
logger.log('security type stored result {0}'.format(security_Type))
#register/enable vns service for CVM
if not vns_call and security_Type == CommonVariables.ConfidentialVM:
vns_service = VolumeNotificationService(logger=logger)
if not vns_service.is_enabled():
handler_env = hutil.get_handler_env()
log_dir = handler_env['handlerEnvironment']['logFolder']
ret = vns_service.register(log_dir)
if ret:
logger.log('Volume notification service registartion is successful!')
else:
logger.log('Volume notification service registration is unsuccessful!.',level=CommonVariables.ErrorLevel)
#making sure that azguestattestation package is installed for SKR.
DistroPatcher.install_azguestattestation()
# Mount already encrypted disks before running fatal prechecks
disk_util = DiskUtil(hutil=hutil, patching=DistroPatcher, logger=logger, encryption_environment=encryption_environment)
crypt_mount_config_util = CryptMountConfigUtil(logger=logger, encryption_environment=encryption_environment, disk_util=disk_util)
bek_util = BekUtil(disk_util, logger,encryption_environment)
existing_passphrase_file = None
existing_volume_type = None
encryption_config = EncryptionConfig(encryption_environment=encryption_environment, logger=logger)
if encryption_config.config_file_exists():
existing_volume_type = encryption_config.get_volume_type()
#log to capture lsblk before encryption view.
disk_util.log_lsblk_output()
if public_settings.get(CommonVariables.EncryptionEncryptionOperationKey) == CommonVariables.EnableEncryptionFormatAll:
#in case of stop start unmount /mnt to avoid resource disk encryption issues.
disk_util.umount('/mnt')
is_migrate_operation = False
if CommonVariables.MigrateKey in public_settings:
if public_settings.get(CommonVariables.MigrateKey) == CommonVariables.MigrateValue:
is_migrate_operation = True
existing_passphrase_file = bek_util.get_bek_passphrase_file(encryption_config)
if existing_passphrase_file is not None:
crypt_mount_config_util.consolidate_azure_crypt_mount(existing_passphrase_file)
mount_encrypted_disks(disk_util=disk_util,
crypt_mount_config_util=crypt_mount_config_util,
bek_util=bek_util,
encryption_config=encryption_config,
passphrase_file=existing_passphrase_file)
# Migrate to early unlock if using crypt mount
if crypt_mount_config_util.should_use_azure_crypt_mount():
crypt_mount_config_util.migrate_crypt_items()
elif ResourceDiskUtil.RD_MAPPER_NAME in [ci.mapper_name for ci in crypt_mount_config_util.get_crypt_items()]:
# If there are crypt items but no passphrase file. This might be a RD-Only scenario
# Generate password but don't push it
# Do a mount_all_disks
generated_passphrase = bek_util.generate_passphrase()
bek_util.store_bek_passphrase(encryption_config, generated_passphrase)
generated_passphrase_file = bek_util.get_bek_passphrase_file(encryption_config)
mount_encrypted_disks(disk_util=disk_util,
crypt_mount_config_util=crypt_mount_config_util,
bek_util=bek_util,
encryption_config=encryption_config,
passphrase_file=generated_passphrase_file)
if security_Type == CommonVariables.ConfidentialVM:
crypt_mount_config_util.device_unlock_using_luks2_header()
encryption_status = json.loads(disk_util.get_encryption_status())
logger.log('Data Disks Status: {0}'.format(encryption_status['data']))
logger.log('OS Disk Status: {0}'.format(encryption_status['os']))
encryption_operation = public_settings.get(CommonVariables.EncryptionEncryptionOperationKey)
check_release_rsa_or_ec_key = False
if security_Type == CommonVariables.ConfidentialVM:
check_release_rsa_or_ec_key = True
# run fatal prechecks, report error if exceptions are caught
try:
if not is_migrate_operation:
check_Util.precheck_for_fatal_failures(public_settings, encryption_status, DistroPatcher, existing_volume_type,check_release_rsa_or_ec_key)
except Exception as e:
logger.log("PRECHECK: Fatal Exception thrown during precheck")
logger.log(traceback.format_exc())
# Reject settings if fatal exception occurs while a daemon is running
if is_daemon_running():
hutil.reject_settings()
msg = str(traceback.format_exc())
hutil.do_exit(exit_code=CommonVariables.configuration_error,
operation='Enable',
status=CommonVariables.extension_error_status,
code=(CommonVariables.configuration_error),
message=msg)
hutil.disk_util.log_lsblk_output()
# run prechecks and log any failures detected
try:
if check_Util.is_non_fatal_precheck_failure():
logger.log("PRECHECK: Precheck failure, incompatible environment suspected")
else:
logger.log("PRECHECK: Prechecks successful")
except Exception as e:
logger.log("PRECHECK: Exception thrown during precheck")
logger.log(traceback.format_exc())
if encryption_operation in [CommonVariables.EnableEncryption, CommonVariables.EnableEncryptionFormat, CommonVariables.EnableEncryptionFormatAll]:
#for CVM if not called from VNS-> unmask, enable and start the VNS service.
if not vns_call and security_Type == CommonVariables.ConfidentialVM and not vns_service.is_active():
vns_service.unmask()
vns_service.enable()
vns_service.start()
if vns_service.is_active():
logger.log("VNS service is started sucessfully!")
if is_migrate_operation:
perform_migration(encryption_config, crypt_mount_config_util)
return # Control should not reach here but added return just to be safe
logger.log("handle.py found enable encryption operation")
is_continue_encryption = True
volume_type = None
if security_Type == CommonVariables.ConfidentialVM:
if encryption_status['os'] != 'Encrypted':
msg = "ADE encryption supported to CVM only if OS is encrypted."
logger.log(level=CommonVariables.ErrorLevel,msg=msg)
is_continue_encryption = False
volume_type = public_settings.get(CommonVariables.VolumeTypeKey)
if is_continue_encryption and volume_type == CommonVariables.VolumeTypeOS:
is_continue_encryption = False
if is_continue_encryption:
handle_encryption(public_settings, encryption_status, disk_util, bek_util, encryption_operation)
else:
msg = 'Encryption operation {2} is not supported to {0}, volume type: {1}, OS encryption status: {2}'\
.format(security_Type,volume_type,encryption_operation, encryption_status['os'])
logger.log(msg)
hutil.do_exit(exit_code=CommonVariables.configuration_error,
operation='Enable',
status=CommonVariables.extension_error_status,
code=(CommonVariables.configuration_error),
message=msg)
elif encryption_operation == CommonVariables.DisableEncryption:
logger.log("handle.py found disable encryption operation")
#for CVM if not called from VNS-> stop and mask the VNS service.
if not vns_call and security_Type ==CommonVariables.ConfidentialVM and vns_service.is_active():
vns_service.stop()
vns_service.mask()
if not vns_service.is_active():
logger.log("VNS service is stopped sucessfully!")
disable_encryption()
else:
msg = "Encryption operation {0} is not supported".format(encryption_operation)
logger.log(msg)
hutil.do_exit(exit_code=CommonVariables.configuration_error,
operation='Enable',
status=CommonVariables.extension_error_status,
code=(CommonVariables.configuration_error),
message=msg)
except BekMissingException as e:
hutil.do_exit(exit_code=CommonVariables.missing_dependency,
operation='Enable',
status=CommonVariables.extension_error_status,
code=str(CommonVariables.missing_dependency),
message=str(e))
except Exception as e:
msg = "Unexpected Error during enable: {0}".format(traceback.format_exc())
logger.log(msg)
hutil.do_exit(exit_code=CommonVariables.unknown_error,
operation='Enable',
status=CommonVariables.extension_error_status,
code=str(CommonVariables.unknown_error),
message=msg)
finally:
lock.release_lock()
logger.log("exiting enable lock, PID {0}".format(os.getpid()))
def are_required_devices_encrypted(volume_type, encryption_status, disk_util, bek_util, encryption_operation):
are_data_disk_encrypted = True if encryption_status['data'] == 'Encrypted' else False
is_os_disk_encrypted = True if encryption_status['os'] == 'Encrypted' else False
items_to_encrypt = []
if volume_type.lower() == CommonVariables.VolumeTypeData.lower():
if are_data_disk_encrypted:
logger.log('All data drives are encrypted.')
return True, items_to_encrypt
else:
logger.log('Not all data drives are encrypted.')
items_to_encrypt = find_all_devices_to_encrypt(None, disk_util, bek_util, volume_type, encryption_operation)
return False, items_to_encrypt
elif volume_type.lower() == CommonVariables.VolumeTypeOS.lower():
if is_os_disk_encrypted:
logger.log('OS drive is encrypted.')
return True, items_to_encrypt
else:
logger.log('OS Drive is not encrypted.')
items_to_encrypt = os_device_to_encrypt(disk_util)
return False, items_to_encrypt
elif volume_type.lower() == CommonVariables.VolumeTypeAll.lower():
if are_data_disk_encrypted and is_os_disk_encrypted:
logger.log('Both OS and Data drives are encrypted.')
return True, items_to_encrypt
else:
if not are_data_disk_encrypted:
items_to_encrypt = find_all_devices_to_encrypt(None, disk_util, bek_util, volume_type, encryption_operation)
if not is_os_disk_encrypted:
items_to_encrypt = items_to_encrypt + os_device_to_encrypt(disk_util)
return False, items_to_encrypt
def handle_encryption(public_settings, encryption_status, disk_util, bek_util, encryption_operation):
extension_parameter = ExtensionParameter(hutil, logger, DistroPatcher, encryption_environment, get_protected_settings(), public_settings)
volume_type = public_settings.get(CommonVariables.VolumeTypeKey)
if extension_parameter.config_file_exists() and extension_parameter.config_changed():
logger.log("Config has changed, updating encryption settings")
if not vns_call:
hutil.exit_if_same_seq()
# If a daemon is already running reject and exit an update encryption settings request
if is_daemon_running():
logger.log("An operation already running. Cannot accept an update settings request.")
hutil.reject_settings()
are_devices_encrypted, items_to_encrypt = are_required_devices_encrypted(volume_type, encryption_status, disk_util, bek_util, encryption_operation)
if not are_devices_encrypted:
logger.log('Required devices not encrypted for volume type {0}. Calling update to stamp encryption settings.'.format(volume_type))
update_encryption_settings(items_to_encrypt)
logger.log('Encryption Settings stamped. Calling enable to encrypt new devices.')
enable_encryption()
else:
logger.log('Calling Update Encryption Setting.')
update_encryption_settings()
else:
logger.log("Config did not change or first call, enabling encryption")
encryption_marker = EncryptionMarkConfig(logger, encryption_environment)
if encryption_marker.config_file_exists():
logger.log('Encryption marker exists. Calling Enable')
enable_encryption()
else:
if not vns_call:
hutil.exit_if_same_seq()
are_devices_encrypted, items_to_encrypt = are_required_devices_encrypted(volume_type, encryption_status, disk_util, bek_util, encryption_operation)
if are_devices_encrypted:
hutil.do_exit(exit_code=CommonVariables.success,
operation='EnableEncryption',
status=CommonVariables.extension_success_status,
code=str(CommonVariables.success),
message=CommonVariables.SuccessMessage[volume_type.lower()])
else:
logger.log('Calling enable for volume type {0}.'.format(volume_type))
enable_encryption()
def enable_encryption():
hutil.do_parse_context('EnableEncryption')
# we need to start another subprocess to do it, because the initial process
# would be killed by the wala in 5 minutes.
logger.log('Enabling encryption')
"""
trying to mount the crypted items.
"""
disk_util = DiskUtil(hutil=hutil, patching=DistroPatcher, logger=logger, encryption_environment=encryption_environment)
bek_util = BekUtil(disk_util, logger,encryption_environment)
existing_passphrase_file = None
encryption_config = EncryptionConfig(encryption_environment=encryption_environment, logger=logger)
config_path_result = disk_util.make_sure_path_exists(encryption_environment.encryption_config_path)
if config_path_result != CommonVariables.process_success:
logger.log(msg="azure encryption path creation failed.",
level=CommonVariables.ErrorLevel)
existing_passphrase_file = bek_util.get_bek_passphrase_file(encryption_config)
if existing_passphrase_file is None and encryption_config.config_file_exists():
msg = "EncryptionConfig is present, but could not get the key file."
try:
hutil.redo_last_status()
logger.log(msg=msg, level=CommonVariables.WarningLevel)
exit_without_status_report()
except Exception: