2019-07-03 10:03:01 +00:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
#
|
|
|
|
|
from django.utils import timezone
|
|
|
|
|
from rest_framework import generics
|
2020-06-03 07:05:55 +00:00
|
|
|
|
from rest_framework.fields import DateTimeField
|
2019-07-03 10:03:01 +00:00
|
|
|
|
from rest_framework.response import Response
|
|
|
|
|
|
2023-07-17 12:52:54 +00:00
|
|
|
|
from acls.models import CommandFilterACL, CommandGroup
|
2023-01-16 11:02:09 +00:00
|
|
|
|
from common.api import JMSBulkModelViewSet
|
2023-07-17 12:52:54 +00:00
|
|
|
|
from common.utils import get_logger
|
2023-11-09 06:18:49 +00:00
|
|
|
|
from orgs.utils import current_org
|
2022-10-25 04:57:34 +00:00
|
|
|
|
from terminal.backends import (
|
2023-02-02 14:58:18 +00:00
|
|
|
|
get_command_storage, get_multi_command_storage
|
2019-07-03 10:03:01 +00:00
|
|
|
|
)
|
2023-07-11 04:06:11 +00:00
|
|
|
|
from terminal.const import RiskLevelChoices
|
2023-11-09 06:18:49 +00:00
|
|
|
|
from terminal.exceptions import StorageInvalid
|
|
|
|
|
from terminal.filters import CommandFilter
|
|
|
|
|
from terminal.models import CommandStorage, Session, Command
|
|
|
|
|
from terminal.notifications import CommandAlertMessage, CommandWarningMessage
|
|
|
|
|
from terminal.serializers import (
|
|
|
|
|
SessionCommandSerializer, InsecureCommandAlertSerializer
|
|
|
|
|
)
|
2019-07-03 10:03:01 +00:00
|
|
|
|
|
|
|
|
|
logger = get_logger(__name__)
|
2022-04-13 10:20:29 +00:00
|
|
|
|
__all__ = ['CommandViewSet', 'InsecureCommandAlertAPI']
|
2019-07-03 10:03:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CommandQueryMixin:
|
|
|
|
|
command_store = get_command_storage()
|
2021-01-07 02:53:10 +00:00
|
|
|
|
filterset_fields = [
|
2022-12-05 05:27:51 +00:00
|
|
|
|
"asset", "account", "user", "session",
|
2022-02-24 04:03:40 +00:00
|
|
|
|
"risk_level", "input"
|
2019-07-03 10:03:01 +00:00
|
|
|
|
]
|
|
|
|
|
default_days_ago = 5
|
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def get_org_id():
|
|
|
|
|
if current_org.is_default():
|
|
|
|
|
org_id = ''
|
|
|
|
|
else:
|
|
|
|
|
org_id = current_org.id
|
|
|
|
|
return org_id
|
|
|
|
|
|
|
|
|
|
def get_query_risk_level(self):
|
|
|
|
|
risk_level = self.request.query_params.get('risk_level')
|
|
|
|
|
if risk_level is None:
|
|
|
|
|
return None
|
|
|
|
|
if risk_level.isdigit():
|
|
|
|
|
return int(risk_level)
|
|
|
|
|
return None
|
|
|
|
|
|
2019-07-03 10:03:01 +00:00
|
|
|
|
def get_queryset(self):
|
2019-10-29 09:58:58 +00:00
|
|
|
|
# 解决访问 /docs/ 问题
|
|
|
|
|
if hasattr(self, 'swagger_fake_view'):
|
|
|
|
|
return self.command_store.model.objects.none()
|
2019-07-03 10:03:01 +00:00
|
|
|
|
date_from, date_to = self.get_date_range()
|
2019-07-04 08:28:42 +00:00
|
|
|
|
q = self.request.query_params
|
2019-07-03 10:03:01 +00:00
|
|
|
|
multi_command_storage = get_multi_command_storage()
|
2019-07-04 08:28:42 +00:00
|
|
|
|
queryset = multi_command_storage.filter(
|
2020-07-15 08:55:18 +00:00
|
|
|
|
date_from=date_from, date_to=date_to,
|
2022-12-05 05:27:51 +00:00
|
|
|
|
user=q.get("user"), asset=q.get("asset"), account=q.get("account"),
|
2020-12-15 10:32:40 +00:00
|
|
|
|
input=q.get("input"), session=q.get("session_id", q.get('session')),
|
2020-03-12 08:24:38 +00:00
|
|
|
|
risk_level=self.get_query_risk_level(), org_id=self.get_org_id(),
|
2019-07-04 08:28:42 +00:00
|
|
|
|
)
|
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
|
|
def filter_queryset(self, queryset):
|
2020-07-15 08:55:18 +00:00
|
|
|
|
# 解决es存储命令时,父类根据filter_fields过滤出现异常的问题,返回的queryset类型list
|
2019-07-03 10:03:01 +00:00
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
|
|
def get_date_range(self):
|
|
|
|
|
now = timezone.now()
|
|
|
|
|
days_ago = now - timezone.timedelta(days=self.default_days_ago)
|
2020-06-03 07:05:55 +00:00
|
|
|
|
date_from_st = days_ago.timestamp()
|
|
|
|
|
date_to_st = now.timestamp()
|
|
|
|
|
|
2019-07-03 10:03:01 +00:00
|
|
|
|
query_params = self.request.query_params
|
2020-06-03 07:05:55 +00:00
|
|
|
|
date_from_q = query_params.get("date_from")
|
|
|
|
|
date_to_q = query_params.get("date_to")
|
|
|
|
|
|
|
|
|
|
dt_parser = DateTimeField().to_internal_value
|
|
|
|
|
|
|
|
|
|
if date_from_q:
|
|
|
|
|
date_from_st = dt_parser(date_from_q).timestamp()
|
|
|
|
|
|
|
|
|
|
if date_to_q:
|
|
|
|
|
date_to_st = dt_parser(date_to_q).timestamp()
|
|
|
|
|
return date_from_st, date_to_st
|
2019-07-03 10:03:01 +00:00
|
|
|
|
|
|
|
|
|
|
2021-04-15 12:40:06 +00:00
|
|
|
|
class CommandViewSet(JMSBulkModelViewSet):
|
2019-07-03 10:03:01 +00:00
|
|
|
|
"""接受app发送来的command log, 格式如下
|
|
|
|
|
{
|
|
|
|
|
"user": "admin",
|
|
|
|
|
"asset": "localhost",
|
2022-12-05 05:27:51 +00:00
|
|
|
|
"account": "web",
|
2019-07-03 10:03:01 +00:00
|
|
|
|
"session": "xxxxxx",
|
|
|
|
|
"input": "whoami",
|
|
|
|
|
"output": "d2hvbWFp", # base64.b64encode(s)
|
|
|
|
|
"timestamp": 1485238673.0
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
command_store = get_command_storage()
|
|
|
|
|
serializer_class = SessionCommandSerializer
|
2021-02-22 10:35:53 +00:00
|
|
|
|
filterset_class = CommandFilter
|
2022-02-17 12:13:31 +00:00
|
|
|
|
model = Command
|
2023-02-13 06:44:17 +00:00
|
|
|
|
search_fields = ('input',)
|
|
|
|
|
ordering_fields = ('timestamp', 'risk_level')
|
2021-02-22 10:35:53 +00:00
|
|
|
|
|
2021-03-16 11:42:22 +00:00
|
|
|
|
def merge_all_storage_list(self, request, *args, **kwargs):
|
|
|
|
|
merged_commands = []
|
|
|
|
|
|
|
|
|
|
storages = CommandStorage.objects.all()
|
|
|
|
|
for storage in storages:
|
2021-03-17 07:26:47 +00:00
|
|
|
|
if not storage.is_valid():
|
|
|
|
|
continue
|
|
|
|
|
|
2021-03-16 11:42:22 +00:00
|
|
|
|
qs = storage.get_command_queryset()
|
|
|
|
|
commands = self.filter_queryset(qs)
|
2021-03-17 07:26:47 +00:00
|
|
|
|
merged_commands.extend(commands[:]) # ES 默认只取 10 条数据
|
2021-12-11 14:23:29 +00:00
|
|
|
|
order = self.request.query_params.get('order', None)
|
|
|
|
|
if order == 'timestamp':
|
|
|
|
|
merged_commands.sort(key=lambda command: command.timestamp)
|
|
|
|
|
else:
|
|
|
|
|
merged_commands.sort(key=lambda command: command.timestamp, reverse=True)
|
2021-03-16 11:42:22 +00:00
|
|
|
|
page = self.paginate_queryset(merged_commands)
|
|
|
|
|
if page is not None:
|
|
|
|
|
serializer = self.get_serializer(page, many=True)
|
|
|
|
|
return self.get_paginated_response(serializer.data)
|
|
|
|
|
|
2021-03-17 07:26:47 +00:00
|
|
|
|
serializer = self.get_serializer(merged_commands, many=True)
|
2021-03-16 11:42:22 +00:00
|
|
|
|
return Response(serializer.data)
|
|
|
|
|
|
|
|
|
|
def list(self, request, *args, **kwargs):
|
|
|
|
|
command_storage_id = self.request.query_params.get('command_storage_id')
|
|
|
|
|
session_id = self.request.query_params.get('session_id')
|
|
|
|
|
|
|
|
|
|
if session_id and not command_storage_id:
|
|
|
|
|
# 会话里的命令列表肯定会提供 session_id,这里防止 merge 的时候取全量的数据
|
|
|
|
|
return self.merge_all_storage_list(request, *args, **kwargs)
|
2023-11-09 06:18:49 +00:00
|
|
|
|
queryset = self.get_queryset()
|
|
|
|
|
queryset = self.filter_queryset(queryset)
|
2021-04-13 01:18:29 +00:00
|
|
|
|
|
|
|
|
|
page = self.paginate_queryset(queryset)
|
|
|
|
|
if page is not None:
|
2021-12-24 09:23:09 +00:00
|
|
|
|
page = self.load_remote_addr(page)
|
2021-04-13 01:18:29 +00:00
|
|
|
|
serializer = self.get_serializer(page, many=True)
|
|
|
|
|
return self.get_paginated_response(serializer.data)
|
|
|
|
|
|
2021-04-14 09:24:10 +00:00
|
|
|
|
# 适配像 ES 这种没有指定分页只返回少量数据的情况
|
|
|
|
|
queryset = queryset[:]
|
2021-04-13 01:18:29 +00:00
|
|
|
|
|
2021-12-24 09:23:09 +00:00
|
|
|
|
queryset = self.load_remote_addr(queryset)
|
2021-04-13 01:18:29 +00:00
|
|
|
|
serializer = self.get_serializer(queryset, many=True)
|
|
|
|
|
return Response(serializer.data)
|
2021-03-16 11:42:22 +00:00
|
|
|
|
|
2021-12-24 09:23:09 +00:00
|
|
|
|
def load_remote_addr(self, queryset):
|
|
|
|
|
commands = list(queryset)
|
|
|
|
|
session_ids = {command.session for command in commands}
|
|
|
|
|
sessions = Session.objects.filter(id__in=session_ids).values_list('id', 'remote_addr')
|
|
|
|
|
session_addr_map = {str(i): addr for i, addr in sessions}
|
|
|
|
|
for command in commands:
|
|
|
|
|
command.remote_addr = session_addr_map.get(command.session, '')
|
|
|
|
|
return commands
|
|
|
|
|
|
2021-02-22 10:35:53 +00:00
|
|
|
|
def get_queryset(self):
|
|
|
|
|
command_storage_id = self.request.query_params.get('command_storage_id')
|
2022-02-21 10:51:11 +00:00
|
|
|
|
if not command_storage_id:
|
|
|
|
|
return Command.objects.none()
|
|
|
|
|
|
2021-02-22 10:35:53 +00:00
|
|
|
|
storage = CommandStorage.objects.get(id=command_storage_id)
|
2021-03-17 07:26:47 +00:00
|
|
|
|
if not storage.is_valid():
|
|
|
|
|
raise StorageInvalid
|
|
|
|
|
else:
|
|
|
|
|
qs = storage.get_command_queryset()
|
2021-02-22 10:35:53 +00:00
|
|
|
|
return qs
|
2019-07-03 10:03:01 +00:00
|
|
|
|
|
|
|
|
|
def create(self, request, *args, **kwargs):
|
|
|
|
|
serializer = self.serializer_class(data=request.data, many=True)
|
|
|
|
|
if serializer.is_valid():
|
|
|
|
|
ok = self.command_store.bulk_save(serializer.validated_data)
|
|
|
|
|
if ok:
|
|
|
|
|
return Response("ok", status=201)
|
|
|
|
|
else:
|
|
|
|
|
return Response("Save error", status=500)
|
|
|
|
|
else:
|
|
|
|
|
msg = "Command not valid: {}".format(serializer.errors)
|
|
|
|
|
logger.error(msg)
|
|
|
|
|
return Response({"msg": msg}, status=401)
|
|
|
|
|
|
|
|
|
|
|
2020-10-27 03:35:31 +00:00
|
|
|
|
class InsecureCommandAlertAPI(generics.CreateAPIView):
|
|
|
|
|
serializer_class = InsecureCommandAlertSerializer
|
2022-02-17 12:13:31 +00:00
|
|
|
|
rbac_perms = {
|
|
|
|
|
'POST': 'terminal.add_command'
|
|
|
|
|
}
|
2020-10-27 03:35:31 +00:00
|
|
|
|
|
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
|
|
|
serializer = InsecureCommandAlertSerializer(data=request.data, many=True)
|
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
|
commands = serializer.validated_data
|
2023-07-17 12:52:54 +00:00
|
|
|
|
session_ids, acl_ids, cmd_group_ids = set(), set(), set()
|
|
|
|
|
for command in commands:
|
|
|
|
|
session_ids.add(command.get('session'))
|
|
|
|
|
acl_ids.add(command.get('cmd_filter_acl'))
|
|
|
|
|
cmd_group_ids.add(command.get('cmd_group'))
|
2023-07-11 04:06:11 +00:00
|
|
|
|
|
2023-07-17 12:52:54 +00:00
|
|
|
|
sessions = Session.objects.filter(id__in=session_ids).only(
|
|
|
|
|
'id', 'org_id', 'asset', 'asset_id', 'user', 'user_id', 'account', 'account_id'
|
|
|
|
|
)
|
|
|
|
|
session_mapper = {str(i.id): i for i in sessions}
|
|
|
|
|
acls = CommandFilterACL.objects.filter(id__in=acl_ids).only('id', 'name', 'reviewers')
|
|
|
|
|
acl_mapper = {str(i.id): i for i in acls}
|
|
|
|
|
cmd_groups = CommandGroup.objects.filter(id__in=cmd_group_ids).only('id', 'name')
|
|
|
|
|
cmd_group_mapper = {str(i.id): i for i in cmd_groups}
|
|
|
|
|
|
2023-07-19 03:00:58 +00:00
|
|
|
|
for command in commands:
|
|
|
|
|
cmd_acl = acl_mapper.get(command['cmd_filter_acl'])
|
|
|
|
|
command['_cmd_filter_acl'] = cmd_acl
|
|
|
|
|
cmd_group = cmd_group_mapper.get(command['cmd_group'])
|
|
|
|
|
command['_cmd_group'] = cmd_group
|
|
|
|
|
session = session_mapper.get(command['session'])
|
|
|
|
|
risk_level = command.get('risk_level')
|
|
|
|
|
|
|
|
|
|
if session:
|
|
|
|
|
command.update({
|
|
|
|
|
'_account': session.account,
|
|
|
|
|
'_org_name': session.org.name,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if risk_level in [RiskLevelChoices.reject, RiskLevelChoices.review_reject]:
|
|
|
|
|
CommandAlertMessage(command).publish_async()
|
|
|
|
|
elif risk_level in [RiskLevelChoices.warning]:
|
|
|
|
|
for reviewer in cmd_acl.reviewers.all():
|
|
|
|
|
CommandWarningMessage(reviewer, command).publish_async()
|
|
|
|
|
else:
|
|
|
|
|
logger.info(f'Risk level ignore: {RiskLevelChoices.get_label(risk_level)}({risk_level})')
|
2023-07-11 04:06:11 +00:00
|
|
|
|
|
|
|
|
|
return Response({'msg': 'ok'})
|