2022-11-03 14:39:48 +00:00
|
|
|
import os
|
|
|
|
import time
|
2022-10-14 08:33:24 +00:00
|
|
|
from collections import defaultdict
|
2023-02-16 10:49:42 +00:00
|
|
|
from copy import deepcopy
|
2022-10-14 08:33:24 +00:00
|
|
|
|
2022-11-03 14:39:48 +00:00
|
|
|
from django.conf import settings
|
2023-01-16 11:02:09 +00:00
|
|
|
from django.utils import timezone
|
2023-02-16 10:49:42 +00:00
|
|
|
from openpyxl import Workbook
|
2022-10-13 09:47:29 +00:00
|
|
|
|
2023-02-16 10:49:42 +00:00
|
|
|
from accounts.const import AutomationTypes, SecretType, SSHKeyStrategy, SecretStrategy
|
2023-02-22 03:23:43 +00:00
|
|
|
from accounts.models import ChangeSecretRecord
|
2023-01-16 11:02:09 +00:00
|
|
|
from accounts.notifications import ChangeSecretExecutionTaskMsg
|
|
|
|
from accounts.serializers import ChangeSecretRecordBackUpSerializer
|
2023-02-21 03:36:17 +00:00
|
|
|
from assets.const import HostTypes
|
2023-01-16 11:02:09 +00:00
|
|
|
from common.utils import get_logger, lazyproperty
|
|
|
|
from common.utils.file import encrypt_and_compress_zip_file
|
|
|
|
from common.utils.timezone import local_now_display
|
2023-02-16 10:49:42 +00:00
|
|
|
from users.models import User
|
2023-01-16 11:02:09 +00:00
|
|
|
from ..base.manager import AccountBasePlaybookManager
|
2023-02-16 10:49:42 +00:00
|
|
|
from ...utils import SecretGenerator
|
2022-10-13 09:47:29 +00:00
|
|
|
|
2022-11-03 14:39:48 +00:00
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
2022-10-13 09:47:29 +00:00
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
class ChangeSecretManager(AccountBasePlaybookManager):
|
2023-02-10 06:07:20 +00:00
|
|
|
ansible_account_prefer = ''
|
|
|
|
|
2022-10-13 09:47:29 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.method_hosts_mapper = defaultdict(list)
|
2022-10-21 10:19:09 +00:00
|
|
|
self.secret_type = self.execution.snapshot['secret_type']
|
2023-01-16 11:02:09 +00:00
|
|
|
self.secret_strategy = self.execution.snapshot.get(
|
|
|
|
'secret_strategy', SecretStrategy.custom
|
|
|
|
)
|
|
|
|
self.ssh_key_change_strategy = self.execution.snapshot.get(
|
|
|
|
'ssh_key_change_strategy', SSHKeyStrategy.add
|
|
|
|
)
|
|
|
|
self.snapshot_account_usernames = self.execution.snapshot['accounts']
|
2022-10-13 09:47:29 +00:00
|
|
|
self.name_recorder_mapper = {} # 做个映射,方便后面处理
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def method_type(cls):
|
2022-10-21 10:19:09 +00:00
|
|
|
return AutomationTypes.change_secret
|
2022-10-13 09:47:29 +00:00
|
|
|
|
2022-10-20 12:34:15 +00:00
|
|
|
def get_kwargs(self, account, secret):
|
|
|
|
kwargs = {}
|
2022-11-08 09:54:51 +00:00
|
|
|
if self.secret_type != SecretType.SSH_KEY:
|
2022-10-20 12:34:15 +00:00
|
|
|
return kwargs
|
2023-01-16 11:02:09 +00:00
|
|
|
kwargs['strategy'] = self.ssh_key_change_strategy
|
2022-10-20 12:34:15 +00:00
|
|
|
kwargs['exclusive'] = 'yes' if kwargs['strategy'] == SSHKeyStrategy.set else 'no'
|
|
|
|
|
|
|
|
if kwargs['strategy'] == SSHKeyStrategy.set_jms:
|
|
|
|
kwargs['dest'] = '/home/{}/.ssh/authorized_keys'.format(account.username)
|
|
|
|
kwargs['regexp'] = '.*{}$'.format(secret.split()[2].strip())
|
|
|
|
return kwargs
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
@lazyproperty
|
|
|
|
def secret_generator(self):
|
|
|
|
return SecretGenerator(
|
|
|
|
self.secret_strategy, self.secret_type,
|
|
|
|
self.execution.snapshot.get('password_rules')
|
|
|
|
)
|
|
|
|
|
|
|
|
def get_secret(self):
|
|
|
|
if self.secret_strategy == SecretStrategy.custom:
|
|
|
|
return self.execution.snapshot['secret']
|
|
|
|
else:
|
|
|
|
return self.secret_generator.get_secret()
|
|
|
|
|
2023-01-29 08:25:16 +00:00
|
|
|
def host_callback(
|
|
|
|
self, host, asset=None, account=None,
|
|
|
|
automation=None, path_dir=None, **kwargs
|
|
|
|
):
|
|
|
|
host = super().host_callback(
|
|
|
|
host, asset=asset, account=account, automation=automation,
|
|
|
|
path_dir=path_dir, **kwargs
|
|
|
|
)
|
2022-10-13 09:47:29 +00:00
|
|
|
if host.get('error'):
|
|
|
|
return host
|
|
|
|
|
|
|
|
accounts = asset.accounts.all()
|
|
|
|
if account:
|
2023-01-16 11:02:09 +00:00
|
|
|
accounts = accounts.exclude(username=account.username)
|
2022-10-13 09:47:29 +00:00
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
if '*' not in self.snapshot_account_usernames:
|
|
|
|
accounts = accounts.filter(username__in=self.snapshot_account_usernames)
|
2022-10-21 10:19:09 +00:00
|
|
|
|
|
|
|
accounts = accounts.filter(secret_type=self.secret_type)
|
2023-02-22 03:18:42 +00:00
|
|
|
if not accounts:
|
2023-02-22 07:15:00 +00:00
|
|
|
print('没有发现待改密账号: %s 用户名: %s 类型: %s' % (
|
|
|
|
asset.name, self.snapshot_account_usernames, self.secret_type
|
|
|
|
))
|
2023-02-22 03:18:42 +00:00
|
|
|
return []
|
|
|
|
|
2022-10-13 09:47:29 +00:00
|
|
|
method_attr = getattr(automation, self.method_type() + '_method')
|
|
|
|
method_hosts = self.method_hosts_mapper[method_attr]
|
|
|
|
method_hosts = [h for h in method_hosts if h != host['name']]
|
|
|
|
inventory_hosts = []
|
|
|
|
records = []
|
2022-10-20 12:34:15 +00:00
|
|
|
host['secret_type'] = self.secret_type
|
2023-02-21 03:36:17 +00:00
|
|
|
|
|
|
|
if asset.type == HostTypes.WINDOWS and self.secret_type == SecretType.SSH_KEY:
|
2023-02-22 07:17:44 +00:00
|
|
|
print(f'Windows {asset} does not support ssh key push \n')
|
2023-02-21 03:36:17 +00:00
|
|
|
return inventory_hosts
|
|
|
|
|
2022-10-13 09:47:29 +00:00
|
|
|
for account in accounts:
|
|
|
|
h = deepcopy(host)
|
2023-02-21 05:00:04 +00:00
|
|
|
h['name'] += '(' + account.username + ')'
|
2022-10-20 12:34:15 +00:00
|
|
|
new_secret = self.get_secret()
|
2022-10-13 09:47:29 +00:00
|
|
|
|
|
|
|
recorder = ChangeSecretRecord(
|
2022-11-03 14:39:48 +00:00
|
|
|
asset=asset, account=account, execution=self.execution,
|
2022-10-13 09:47:29 +00:00
|
|
|
old_secret=account.secret, new_secret=new_secret,
|
|
|
|
)
|
|
|
|
records.append(recorder)
|
|
|
|
self.name_recorder_mapper[h['name']] = recorder
|
|
|
|
|
2022-10-20 12:34:15 +00:00
|
|
|
private_key_path = None
|
2022-11-08 09:54:51 +00:00
|
|
|
if self.secret_type == SecretType.SSH_KEY:
|
2022-10-20 12:34:15 +00:00
|
|
|
private_key_path = self.generate_private_key_path(new_secret, path_dir)
|
|
|
|
new_secret = self.generate_public_key(new_secret)
|
|
|
|
|
|
|
|
h['kwargs'] = self.get_kwargs(account, new_secret)
|
2022-10-13 09:47:29 +00:00
|
|
|
h['account'] = {
|
|
|
|
'name': account.name,
|
|
|
|
'username': account.username,
|
|
|
|
'secret_type': account.secret_type,
|
|
|
|
'secret': new_secret,
|
2022-10-20 12:34:15 +00:00
|
|
|
'private_key_path': private_key_path
|
2022-10-13 09:47:29 +00:00
|
|
|
}
|
2022-11-09 10:23:00 +00:00
|
|
|
if asset.platform.type == 'oracle':
|
|
|
|
h['account']['mode'] = 'sysdba' if account.privileged else None
|
2022-10-13 09:47:29 +00:00
|
|
|
inventory_hosts.append(h)
|
|
|
|
method_hosts.append(h['name'])
|
|
|
|
self.method_hosts_mapper[method_attr] = method_hosts
|
|
|
|
ChangeSecretRecord.objects.bulk_create(records)
|
|
|
|
return inventory_hosts
|
|
|
|
|
2022-10-14 08:33:24 +00:00
|
|
|
def on_host_success(self, host, result):
|
|
|
|
recorder = self.name_recorder_mapper.get(host)
|
|
|
|
if not recorder:
|
|
|
|
return
|
2022-11-01 03:52:51 +00:00
|
|
|
recorder.status = 'success'
|
2022-10-14 08:33:24 +00:00
|
|
|
recorder.date_finished = timezone.now()
|
|
|
|
recorder.save()
|
2023-02-22 03:23:43 +00:00
|
|
|
account = recorder.account
|
2023-02-22 03:18:42 +00:00
|
|
|
if not account:
|
2023-02-22 07:13:51 +00:00
|
|
|
print("Account not found, deleted ?")
|
2023-02-22 03:18:42 +00:00
|
|
|
return
|
2022-10-14 08:33:24 +00:00
|
|
|
account.secret = recorder.new_secret
|
2023-02-22 03:23:43 +00:00
|
|
|
account.save(update_fields=['secret'])
|
2022-10-14 08:33:24 +00:00
|
|
|
|
|
|
|
def on_host_error(self, host, error, result):
|
|
|
|
recorder = self.name_recorder_mapper.get(host)
|
|
|
|
if not recorder:
|
|
|
|
return
|
|
|
|
recorder.status = 'failed'
|
|
|
|
recorder.date_finished = timezone.now()
|
|
|
|
recorder.error = error
|
|
|
|
recorder.save()
|
2022-10-13 09:47:29 +00:00
|
|
|
|
|
|
|
def on_runner_failed(self, runner, e):
|
2022-11-03 14:39:48 +00:00
|
|
|
logger.error("Change secret error: ", e)
|
|
|
|
|
2023-02-08 07:36:45 +00:00
|
|
|
def check_secret(self):
|
2023-02-08 05:36:32 +00:00
|
|
|
if self.secret_strategy == SecretStrategy.custom \
|
|
|
|
and not self.execution.snapshot['secret']:
|
|
|
|
print('Custom secret is empty')
|
2023-02-08 07:36:45 +00:00
|
|
|
return False
|
|
|
|
return True
|
2023-02-08 05:36:32 +00:00
|
|
|
|
2023-02-08 07:36:45 +00:00
|
|
|
def run(self, *args, **kwargs):
|
|
|
|
if not self.check_secret():
|
|
|
|
return
|
2022-11-03 14:39:48 +00:00
|
|
|
super().run(*args, **kwargs)
|
|
|
|
recorders = self.name_recorder_mapper.values()
|
|
|
|
recorders = list(recorders)
|
|
|
|
self.send_recorder_mail(recorders)
|
|
|
|
|
|
|
|
def send_recorder_mail(self, recorders):
|
|
|
|
recipients = self.execution.recipients
|
2022-11-04 03:09:56 +00:00
|
|
|
if not recorders or not recipients:
|
2022-11-03 14:39:48 +00:00
|
|
|
return
|
2023-01-16 11:02:09 +00:00
|
|
|
|
|
|
|
recipients = User.objects.filter(id__in=list(recipients.keys()))
|
2022-11-03 14:39:48 +00:00
|
|
|
|
|
|
|
name = self.execution.snapshot['name']
|
|
|
|
path = os.path.join(os.path.dirname(settings.BASE_DIR), 'tmp')
|
|
|
|
filename = os.path.join(path, f'{name}-{local_now_display()}-{time.time()}.xlsx')
|
|
|
|
if not self.create_file(recorders, filename):
|
|
|
|
return
|
|
|
|
|
|
|
|
for user in recipients:
|
|
|
|
attachments = []
|
|
|
|
if user.secret_key:
|
|
|
|
password = user.secret_key.encode('utf8')
|
|
|
|
attachment = os.path.join(path, f'{name}-{local_now_display()}-{time.time()}.zip')
|
|
|
|
encrypt_and_compress_zip_file(attachment, password, [filename])
|
|
|
|
attachments = [attachment]
|
|
|
|
ChangeSecretExecutionTaskMsg(name, user).publish(attachments)
|
|
|
|
os.remove(filename)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def create_file(recorders, filename):
|
|
|
|
serializer_cls = ChangeSecretRecordBackUpSerializer
|
|
|
|
serializer = serializer_cls(recorders, many=True)
|
2023-01-16 11:02:09 +00:00
|
|
|
|
|
|
|
header = [str(v.label) for v in serializer.child.fields.values()]
|
2023-02-24 10:08:22 +00:00
|
|
|
rows = [[str(i) for i in row.values()] for row in serializer.data]
|
2022-11-03 14:39:48 +00:00
|
|
|
if not rows:
|
|
|
|
return False
|
|
|
|
|
|
|
|
rows.insert(0, header)
|
|
|
|
wb = Workbook(filename)
|
|
|
|
ws = wb.create_sheet('Sheet1')
|
|
|
|
for row in rows:
|
|
|
|
ws.append(row)
|
|
|
|
wb.save(filename)
|
|
|
|
return True
|