2018-09-03 03:24:25 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2022-11-04 06:22:38 +00:00
|
|
|
import uuid
|
2022-06-08 11:32:50 +00:00
|
|
|
|
2021-09-13 08:50:53 +00:00
|
|
|
from django.db.models.signals import (
|
2022-11-04 06:22:38 +00:00
|
|
|
post_save, m2m_changed, pre_delete, pre_save
|
2021-09-13 08:50:53 +00:00
|
|
|
)
|
2018-09-03 03:24:25 +00:00
|
|
|
from django.dispatch import receiver
|
2021-02-26 09:33:11 +00:00
|
|
|
from django.conf import settings
|
2018-09-03 03:24:25 +00:00
|
|
|
from django.db import transaction
|
2019-11-05 10:46:29 +00:00
|
|
|
from django.utils import timezone
|
2021-02-26 09:33:11 +00:00
|
|
|
from django.utils.functional import LazyObject
|
2020-12-09 10:43:13 +00:00
|
|
|
from django.contrib.auth import BACKEND_SESSION_KEY
|
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2022-01-18 04:25:28 +00:00
|
|
|
from django.utils import translation
|
2019-08-21 12:27:21 +00:00
|
|
|
from rest_framework.renderers import JSONRenderer
|
2019-11-05 10:46:29 +00:00
|
|
|
from rest_framework.request import Request
|
2018-09-03 03:24:25 +00:00
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
from users.models import User
|
|
|
|
from assets.models import Asset, SystemUser, CommandFilter
|
|
|
|
from terminal.models import Session, Command
|
|
|
|
from perms.models import AssetPermission, ApplicationPermission
|
|
|
|
from rbac.models import Role
|
|
|
|
|
|
|
|
from audits.utils import model_to_dict_for_operate_log as model_to_dict
|
|
|
|
from audits.handler import (
|
|
|
|
get_instance_current_with_cache_diff, cache_instance_before_data,
|
|
|
|
create_or_update_operate_log, get_instance_dict_from_cache
|
|
|
|
)
|
2021-09-27 11:06:26 +00:00
|
|
|
from authentication.signals import post_auth_failed, post_auth_success
|
2021-11-08 07:12:12 +00:00
|
|
|
from authentication.utils import check_different_city_login_if_need
|
2018-09-03 03:24:25 +00:00
|
|
|
from jumpserver.utils import current_request
|
2019-12-16 08:53:29 +00:00
|
|
|
from users.signals import post_user_change_password
|
2022-11-04 06:22:38 +00:00
|
|
|
from .utils import write_login_log
|
2022-02-08 10:58:56 +00:00
|
|
|
from . import models, serializers
|
2021-07-22 11:53:14 +00:00
|
|
|
from .models import OperateLog
|
2022-11-04 06:22:38 +00:00
|
|
|
from .const import MODELS_NEED_RECORD
|
2022-02-08 10:58:56 +00:00
|
|
|
from terminal.backends.command.serializers import SessionCommandSerializer
|
|
|
|
from terminal.serializers import SessionSerializer
|
2022-11-04 06:22:38 +00:00
|
|
|
from common.const.signals import POST_ADD, POST_REMOVE, POST_CLEAR, SKIP_SIGNAL
|
2021-09-27 11:06:26 +00:00
|
|
|
from common.utils import get_request_ip, get_logger, get_syslogger
|
2022-02-08 10:58:56 +00:00
|
|
|
from common.utils.encode import data_to_json
|
2018-09-03 03:24:25 +00:00
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
|
2019-02-21 11:22:23 +00:00
|
|
|
logger = get_logger(__name__)
|
2019-12-16 08:53:29 +00:00
|
|
|
sys_logger = get_syslogger(__name__)
|
2019-08-21 12:27:21 +00:00
|
|
|
json_render = JSONRenderer()
|
2019-02-21 11:22:23 +00:00
|
|
|
|
2018-09-03 03:24:25 +00:00
|
|
|
|
2021-02-26 09:33:11 +00:00
|
|
|
class AuthBackendLabelMapping(LazyObject):
|
|
|
|
@staticmethod
|
|
|
|
def get_login_backends():
|
|
|
|
backend_label_mapping = {}
|
|
|
|
for source, backends in User.SOURCE_BACKEND_MAPPING.items():
|
|
|
|
for backend in backends:
|
|
|
|
backend_label_mapping[backend] = source.label
|
|
|
|
backend_label_mapping[settings.AUTH_BACKEND_PUBKEY] = _('SSH Key')
|
|
|
|
backend_label_mapping[settings.AUTH_BACKEND_MODEL] = _('Password')
|
2021-04-12 04:32:15 +00:00
|
|
|
backend_label_mapping[settings.AUTH_BACKEND_SSO] = _('SSO')
|
2021-06-10 10:02:55 +00:00
|
|
|
backend_label_mapping[settings.AUTH_BACKEND_AUTH_TOKEN] = _('Auth Token')
|
2021-03-24 11:01:35 +00:00
|
|
|
backend_label_mapping[settings.AUTH_BACKEND_WECOM] = _('WeCom')
|
2022-07-12 09:36:40 +00:00
|
|
|
backend_label_mapping[settings.AUTH_BACKEND_FEISHU] = _('FeiShu')
|
2021-03-24 11:01:35 +00:00
|
|
|
backend_label_mapping[settings.AUTH_BACKEND_DINGTALK] = _('DingTalk')
|
2022-04-13 12:24:56 +00:00
|
|
|
backend_label_mapping[settings.AUTH_BACKEND_TEMP_TOKEN] = _('Temporary token')
|
2021-02-26 09:33:11 +00:00
|
|
|
return backend_label_mapping
|
|
|
|
|
|
|
|
def _setup(self):
|
|
|
|
self._wrapped = self.get_login_backends()
|
|
|
|
|
|
|
|
|
|
|
|
AUTH_BACKEND_LABEL_MAPPING = AuthBackendLabelMapping()
|
2020-12-09 10:43:13 +00:00
|
|
|
|
2021-07-22 11:53:14 +00:00
|
|
|
M2M_ACTION = {
|
2022-02-14 02:57:52 +00:00
|
|
|
POST_ADD: OperateLog.ACTION_CREATE,
|
|
|
|
POST_REMOVE: OperateLog.ACTION_DELETE,
|
|
|
|
POST_CLEAR: OperateLog.ACTION_DELETE,
|
2021-07-22 11:53:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@receiver(m2m_changed)
|
|
|
|
def on_m2m_changed(sender, action, instance, reverse, model, pk_set, **kwargs):
|
|
|
|
if action not in M2M_ACTION:
|
|
|
|
return
|
2022-11-04 06:22:38 +00:00
|
|
|
if not instance:
|
2021-07-22 11:53:14 +00:00
|
|
|
return
|
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
resource_type = instance._meta.verbose_name
|
|
|
|
current_instance = model_to_dict(instance, include_model_fields=False)
|
2021-07-22 11:53:14 +00:00
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
instance_id = current_instance.get('id')
|
|
|
|
log_id, before_instance = get_instance_dict_from_cache(instance_id)
|
2021-07-22 11:53:14 +00:00
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
field_name = str(model._meta.verbose_name)
|
|
|
|
objs = model.objects.filter(pk__in=pk_set)
|
|
|
|
objs_display = [str(o) for o in objs]
|
|
|
|
action = M2M_ACTION[action]
|
|
|
|
changed_field = current_instance.get(field_name, [])
|
2021-07-22 11:53:14 +00:00
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
after, before, before_value = None, None, None
|
|
|
|
if action == OperateLog.ACTION_CREATE:
|
|
|
|
before_value = list(set(changed_field) - set(objs_display))
|
|
|
|
elif action == OperateLog.ACTION_DELETE:
|
|
|
|
before_value = list(
|
|
|
|
set(changed_field).symmetric_difference(set(objs_display))
|
|
|
|
)
|
2021-07-22 11:53:14 +00:00
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
if changed_field:
|
|
|
|
after = {field_name: changed_field}
|
|
|
|
if before_value:
|
|
|
|
before = {field_name: before_value}
|
2021-07-22 11:53:14 +00:00
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
if sorted(str(before)) == sorted(str(after)):
|
|
|
|
return
|
2021-07-22 11:53:14 +00:00
|
|
|
|
2022-11-04 06:22:38 +00:00
|
|
|
create_or_update_operate_log(
|
|
|
|
OperateLog.ACTION_UPDATE, resource_type,
|
|
|
|
resource=instance, log_id=log_id, before=before, after=after
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def signal_of_operate_log_whether_continue(sender, instance, created, update_fields=None):
|
|
|
|
condition = True
|
|
|
|
if not instance:
|
|
|
|
condition = False
|
|
|
|
if instance and getattr(instance, SKIP_SIGNAL, False):
|
|
|
|
condition = False
|
|
|
|
# 终端模型的 create 事件由系统产生,不记录
|
|
|
|
if instance._meta.object_name == 'Terminal' and created:
|
|
|
|
condition = False
|
2021-02-26 09:33:11 +00:00
|
|
|
# last_login 改变是最后登录日期, 每次登录都会改变
|
2019-12-05 07:09:25 +00:00
|
|
|
if instance._meta.object_name == 'User' and \
|
|
|
|
update_fields and 'last_login' in update_fields:
|
2022-11-04 06:22:38 +00:00
|
|
|
condition = False
|
|
|
|
# 不在记录白名单中,跳过
|
|
|
|
if sender._meta.object_name not in MODELS_NEED_RECORD:
|
|
|
|
condition = False
|
|
|
|
return condition
|
|
|
|
|
|
|
|
|
|
|
|
@receiver(pre_save)
|
|
|
|
def on_object_pre_create_or_update(sender, instance=None, raw=False, using=None, update_fields=None, **kwargs):
|
|
|
|
ok = signal_of_operate_log_whether_continue(
|
|
|
|
sender, instance, False, update_fields
|
|
|
|
)
|
|
|
|
if not ok:
|
2019-12-05 07:09:25 +00:00
|
|
|
return
|
2022-11-04 06:22:38 +00:00
|
|
|
instance_before_data = {'id': instance.id}
|
|
|
|
raw_instance = type(instance).objects.filter(pk=instance.id).first()
|
|
|
|
if raw_instance:
|
|
|
|
instance_before_data = model_to_dict(raw_instance)
|
|
|
|
operate_log_id = str(uuid.uuid4())
|
|
|
|
instance_before_data['operate_log_id'] = operate_log_id
|
|
|
|
setattr(instance, 'operate_log_id', operate_log_id)
|
|
|
|
cache_instance_before_data(instance_before_data)
|
|
|
|
|
|
|
|
|
|
|
|
@receiver(post_save)
|
|
|
|
def on_object_created_or_update(sender, instance=None, created=False, update_fields=None, **kwargs):
|
|
|
|
ok = signal_of_operate_log_whether_continue(
|
|
|
|
sender, instance, created, update_fields
|
|
|
|
)
|
|
|
|
if not ok:
|
|
|
|
return
|
|
|
|
|
|
|
|
log_id, before, after = None, None, None
|
2018-09-03 03:24:25 +00:00
|
|
|
if created:
|
2019-08-21 12:27:21 +00:00
|
|
|
action = models.OperateLog.ACTION_CREATE
|
2022-11-04 06:22:38 +00:00
|
|
|
after = model_to_dict(instance)
|
|
|
|
log_id = getattr(instance, 'operate_log_id', None)
|
2018-09-03 03:24:25 +00:00
|
|
|
else:
|
2019-08-21 12:27:21 +00:00
|
|
|
action = models.OperateLog.ACTION_UPDATE
|
2022-11-04 06:22:38 +00:00
|
|
|
current_instance = model_to_dict(instance)
|
|
|
|
log_id, before, after = get_instance_current_with_cache_diff(current_instance)
|
|
|
|
|
|
|
|
resource_type = sender._meta.verbose_name
|
|
|
|
create_or_update_operate_log(
|
|
|
|
action, resource_type, resource=instance,
|
|
|
|
log_id=log_id, before=before, after=after
|
|
|
|
)
|
2018-09-03 03:24:25 +00:00
|
|
|
|
|
|
|
|
2021-09-13 08:50:53 +00:00
|
|
|
@receiver(pre_delete)
|
2018-09-03 03:24:25 +00:00
|
|
|
def on_object_delete(sender, instance=None, **kwargs):
|
2022-11-04 06:22:38 +00:00
|
|
|
ok = signal_of_operate_log_whether_continue(sender, instance, False)
|
|
|
|
if not ok:
|
|
|
|
return
|
|
|
|
|
|
|
|
resource_type = sender._meta.verbose_name
|
|
|
|
create_or_update_operate_log(
|
|
|
|
models.OperateLog.ACTION_DELETE, resource_type,
|
|
|
|
resource=instance, before=model_to_dict(instance)
|
|
|
|
)
|
2018-09-03 03:24:25 +00:00
|
|
|
|
|
|
|
|
2019-12-16 08:53:29 +00:00
|
|
|
@receiver(post_user_change_password, sender=User)
|
|
|
|
def on_user_change_password(sender, user=None, **kwargs):
|
|
|
|
if not current_request:
|
|
|
|
remote_addr = '127.0.0.1'
|
|
|
|
change_by = 'System'
|
|
|
|
else:
|
|
|
|
remote_addr = get_request_ip(current_request)
|
|
|
|
if not current_request.user.is_authenticated:
|
|
|
|
change_by = str(user)
|
|
|
|
else:
|
|
|
|
change_by = str(current_request.user)
|
|
|
|
with transaction.atomic():
|
|
|
|
models.PasswordChangeLog.objects.create(
|
|
|
|
user=str(user), change_by=change_by,
|
|
|
|
remote_addr=remote_addr,
|
|
|
|
)
|
2019-08-21 12:27:21 +00:00
|
|
|
|
|
|
|
|
|
|
|
def on_audits_log_create(sender, instance=None, **kwargs):
|
|
|
|
if sender == models.UserLoginLog:
|
|
|
|
category = "login_log"
|
2022-02-08 10:58:56 +00:00
|
|
|
serializer_cls = serializers.UserLoginLogSerializer
|
2019-08-21 12:27:21 +00:00
|
|
|
elif sender == models.FTPLog:
|
|
|
|
category = "ftp_log"
|
2022-02-08 10:58:56 +00:00
|
|
|
serializer_cls = serializers.FTPLogSerializer
|
2019-08-21 12:27:21 +00:00
|
|
|
elif sender == models.OperateLog:
|
|
|
|
category = "operation_log"
|
2022-02-08 10:58:56 +00:00
|
|
|
serializer_cls = serializers.OperateLogSerializer
|
2019-08-21 12:27:21 +00:00
|
|
|
elif sender == models.PasswordChangeLog:
|
|
|
|
category = "password_change_log"
|
2022-02-08 10:58:56 +00:00
|
|
|
serializer_cls = serializers.PasswordChangeLogSerializer
|
2019-08-21 12:27:21 +00:00
|
|
|
elif sender == Session:
|
|
|
|
category = "host_session_log"
|
2022-02-08 10:58:56 +00:00
|
|
|
serializer_cls = SessionSerializer
|
2019-09-25 08:31:58 +00:00
|
|
|
elif sender == Command:
|
|
|
|
category = "session_command_log"
|
2022-02-08 10:58:56 +00:00
|
|
|
serializer_cls = SessionCommandSerializer
|
2019-08-21 12:27:21 +00:00
|
|
|
else:
|
|
|
|
return
|
|
|
|
|
2022-02-08 10:58:56 +00:00
|
|
|
serializer = serializer_cls(instance)
|
|
|
|
data = data_to_json(serializer.data, indent=None)
|
2019-08-21 12:27:21 +00:00
|
|
|
msg = "{} - {}".format(category, data)
|
|
|
|
sys_logger.info(msg)
|
2019-11-05 10:46:29 +00:00
|
|
|
|
|
|
|
|
2020-12-09 10:43:13 +00:00
|
|
|
def get_login_backend(request):
|
2021-02-26 09:33:11 +00:00
|
|
|
backend = request.session.get('auth_backend', '') or \
|
|
|
|
request.session.get(BACKEND_SESSION_KEY, '')
|
2021-01-20 10:56:12 +00:00
|
|
|
|
2021-02-26 09:33:11 +00:00
|
|
|
backend_label = AUTH_BACKEND_LABEL_MAPPING.get(backend, None)
|
|
|
|
if backend_label is None:
|
|
|
|
backend_label = ''
|
|
|
|
return backend_label
|
2020-12-09 10:43:13 +00:00
|
|
|
|
|
|
|
|
2021-06-10 10:02:55 +00:00
|
|
|
def generate_data(username, request, login_type=None):
|
2019-11-05 10:46:29 +00:00
|
|
|
user_agent = request.META.get('HTTP_USER_AGENT', '')
|
2020-01-19 04:13:42 +00:00
|
|
|
login_ip = get_request_ip(request) or '0.0.0.0'
|
2021-06-10 10:02:55 +00:00
|
|
|
|
|
|
|
if login_type is None and isinstance(request, Request):
|
2021-04-14 06:45:15 +00:00
|
|
|
login_type = request.META.get('HTTP_X_JMS_LOGIN_TYPE', 'U')
|
2021-06-10 10:02:55 +00:00
|
|
|
if login_type is None:
|
2019-11-05 10:46:29 +00:00
|
|
|
login_type = 'W'
|
|
|
|
|
2022-01-18 04:25:28 +00:00
|
|
|
with translation.override('en'):
|
|
|
|
backend = str(get_login_backend(request))
|
|
|
|
|
2019-11-05 10:46:29 +00:00
|
|
|
data = {
|
|
|
|
'username': username,
|
|
|
|
'ip': login_ip,
|
|
|
|
'type': login_type,
|
2021-04-08 08:51:44 +00:00
|
|
|
'user_agent': user_agent[0:254],
|
2020-12-09 10:43:13 +00:00
|
|
|
'datetime': timezone.now(),
|
2022-01-18 04:25:28 +00:00
|
|
|
'backend': backend,
|
2019-11-05 10:46:29 +00:00
|
|
|
}
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
|
|
@receiver(post_auth_success)
|
2021-06-10 10:02:55 +00:00
|
|
|
def on_user_auth_success(sender, user, request, login_type=None, **kwargs):
|
2019-11-05 10:46:29 +00:00
|
|
|
logger.debug('User login success: {}'.format(user.username))
|
2021-11-08 07:12:12 +00:00
|
|
|
check_different_city_login_if_need(user, request)
|
2021-06-10 10:02:55 +00:00
|
|
|
data = generate_data(user.username, request, login_type=login_type)
|
2022-06-07 11:26:07 +00:00
|
|
|
request.session['login_time'] = data['datetime'].strftime("%Y-%m-%d %H:%M:%S")
|
2019-11-18 08:30:26 +00:00
|
|
|
data.update({'mfa': int(user.mfa_enabled), 'status': True})
|
2019-12-27 08:00:32 +00:00
|
|
|
write_login_log(**data)
|
2019-11-05 10:46:29 +00:00
|
|
|
|
|
|
|
|
|
|
|
@receiver(post_auth_failed)
|
2020-04-28 13:00:22 +00:00
|
|
|
def on_user_auth_failed(sender, username, request, reason='', **kwargs):
|
2019-11-05 10:46:29 +00:00
|
|
|
logger.debug('User login failed: {}'.format(username))
|
|
|
|
data = generate_data(username, request)
|
2020-04-28 13:00:22 +00:00
|
|
|
data.update({'reason': reason[:128], 'status': False})
|
2019-12-27 08:00:32 +00:00
|
|
|
write_login_log(**data)
|