2018-11-23 02:25:35 +00:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
#
|
2020-06-10 09:34:56 +00:00
|
|
|
|
import os
|
|
|
|
|
import tarfile
|
2023-06-13 10:25:03 +00:00
|
|
|
|
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from django.core.files.storage import default_storage
|
2022-07-01 11:07:42 +00:00
|
|
|
|
from django.db.models import F
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from django.http import FileResponse
|
2020-03-12 08:24:38 +00:00
|
|
|
|
from django.shortcuts import get_object_or_404, reverse
|
2020-06-10 09:34:56 +00:00
|
|
|
|
from django.utils.encoding import escape_uri_path
|
2023-08-29 06:21:06 +00:00
|
|
|
|
from django.utils.translation import gettext_noop, gettext as _
|
2023-02-15 06:30:57 +00:00
|
|
|
|
from django_filters import rest_framework as filters
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from rest_framework import generics
|
2020-04-07 04:26:47 +00:00
|
|
|
|
from rest_framework import viewsets, views
|
2020-06-10 09:34:56 +00:00
|
|
|
|
from rest_framework.decorators import action
|
2021-12-13 02:50:10 +00:00
|
|
|
|
from rest_framework.permissions import IsAuthenticated
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from rest_framework.response import Response
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2023-08-29 06:21:06 +00:00
|
|
|
|
from audits.const import ActionChoices
|
2023-06-13 10:25:03 +00:00
|
|
|
|
from common.api import AsyncApiMixin
|
2020-06-10 09:34:56 +00:00
|
|
|
|
from common.const.http import GET
|
2023-06-13 10:25:03 +00:00
|
|
|
|
from common.drf.filters import BaseFilterSet
|
2023-08-28 07:43:45 +00:00
|
|
|
|
from common.drf.filters import DatetimeRangeFilterBackend
|
2020-06-10 09:34:56 +00:00
|
|
|
|
from common.drf.renders import PassthroughRenderer
|
2023-06-13 10:25:03 +00:00
|
|
|
|
from common.storage.replay import ReplayStorageHandler
|
2023-08-29 06:21:06 +00:00
|
|
|
|
from common.utils import data_to_json, is_uuid, i18n_fmt
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from common.utils import get_logger, get_object_or_none
|
2023-08-29 06:21:06 +00:00
|
|
|
|
from common.views.mixins import RecordViewLogMixin
|
2019-08-21 12:27:21 +00:00
|
|
|
|
from orgs.mixins.api import OrgBulkModelViewSet
|
2020-04-07 04:26:47 +00:00
|
|
|
|
from orgs.utils import tmp_to_root_org, tmp_to_org
|
2023-06-13 10:25:03 +00:00
|
|
|
|
from rbac.permissions import RBACPermission
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from terminal import serializers
|
2023-06-13 10:25:03 +00:00
|
|
|
|
from terminal.const import TerminalType
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from terminal.models import Session
|
2023-02-20 07:08:06 +00:00
|
|
|
|
from terminal.permissions import IsSessionAssignee
|
2023-06-13 10:25:03 +00:00
|
|
|
|
from terminal.utils import is_session_approver
|
2022-12-04 09:39:48 +00:00
|
|
|
|
from users.models import User
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2020-04-07 04:26:47 +00:00
|
|
|
|
__all__ = [
|
2022-10-25 04:57:34 +00:00
|
|
|
|
'SessionViewSet', 'SessionReplayViewSet',
|
2023-09-13 08:52:11 +00:00
|
|
|
|
'SessionJoinValidateAPI', 'MySessionAPIView'
|
2020-04-07 04:26:47 +00:00
|
|
|
|
]
|
2021-12-29 12:07:56 +00:00
|
|
|
|
|
2019-07-03 10:03:01 +00:00
|
|
|
|
logger = get_logger(__name__)
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2023-08-29 07:16:02 +00:00
|
|
|
|
REPLAY_OP = gettext_noop('User %s %s session %s replay')
|
|
|
|
|
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2021-12-13 02:50:10 +00:00
|
|
|
|
class MySessionAPIView(generics.ListAPIView):
|
2022-12-04 09:39:48 +00:00
|
|
|
|
permission_classes = (IsAuthenticated,)
|
2021-12-13 02:50:10 +00:00
|
|
|
|
serializer_class = serializers.SessionSerializer
|
|
|
|
|
|
|
|
|
|
def get_queryset(self):
|
2022-04-12 06:25:49 +00:00
|
|
|
|
user = self.request.user
|
|
|
|
|
qs = Session.objects.filter(user_id=user.id)
|
|
|
|
|
return qs
|
2021-12-13 02:50:10 +00:00
|
|
|
|
|
|
|
|
|
|
2023-02-15 06:30:57 +00:00
|
|
|
|
class SessionFilterSet(BaseFilterSet):
|
|
|
|
|
terminal = filters.CharFilter(method='filter_terminal')
|
|
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
model = Session
|
|
|
|
|
fields = [
|
|
|
|
|
"user", "asset", "account", "remote_addr",
|
|
|
|
|
"protocol", "is_finished", 'login_from', 'terminal'
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def filter_terminal(queryset, name, value):
|
|
|
|
|
if is_uuid(value):
|
|
|
|
|
return queryset.filter(terminal__id=value)
|
|
|
|
|
else:
|
|
|
|
|
return queryset.filter(terminal__name=value)
|
|
|
|
|
|
|
|
|
|
|
2023-08-29 06:21:06 +00:00
|
|
|
|
class SessionViewSet(RecordViewLogMixin, OrgBulkModelViewSet):
|
2019-10-18 07:05:45 +00:00
|
|
|
|
model = Session
|
2020-03-12 08:24:38 +00:00
|
|
|
|
serializer_classes = {
|
|
|
|
|
'default': serializers.SessionSerializer,
|
|
|
|
|
'display': serializers.SessionDisplaySerializer,
|
|
|
|
|
}
|
2021-02-03 03:51:02 +00:00
|
|
|
|
search_fields = [
|
2022-08-24 08:14:32 +00:00
|
|
|
|
"user", "asset", "account", "remote_addr",
|
2022-02-17 12:13:31 +00:00
|
|
|
|
"protocol", "is_finished", 'login_from',
|
2019-07-03 14:28:20 +00:00
|
|
|
|
]
|
2023-02-15 06:30:57 +00:00
|
|
|
|
filterset_class = SessionFilterSet
|
2019-07-03 14:28:20 +00:00
|
|
|
|
date_range_filter_fields = [
|
|
|
|
|
('date_start', ('date_from', 'date_to'))
|
|
|
|
|
]
|
2023-08-28 07:43:45 +00:00
|
|
|
|
extra_filter_backends = [DatetimeRangeFilterBackend]
|
2022-02-17 12:13:31 +00:00
|
|
|
|
rbac_perms = {
|
2023-08-31 09:00:03 +00:00
|
|
|
|
'download': ['terminal.download_sessionreplay'],
|
2022-02-17 12:13:31 +00:00
|
|
|
|
}
|
2023-10-07 06:47:17 +00:00
|
|
|
|
permission_classes = [RBACPermission]
|
|
|
|
|
|
|
|
|
|
def get_permissions(self):
|
|
|
|
|
if self.action == 'retrieve':
|
|
|
|
|
self.permission_classes = [RBACPermission | IsSessionAssignee]
|
|
|
|
|
return super().get_permissions()
|
2019-07-03 08:29:39 +00:00
|
|
|
|
|
2020-06-10 09:34:56 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def prepare_offline_file(session, local_path):
|
|
|
|
|
replay_path = default_storage.path(local_path)
|
|
|
|
|
current_dir = os.getcwd()
|
|
|
|
|
dir_path = os.path.dirname(replay_path)
|
|
|
|
|
replay_filename = os.path.basename(replay_path)
|
|
|
|
|
meta_filename = '{}.json'.format(session.id)
|
|
|
|
|
offline_filename = '{}.tar'.format(session.id)
|
|
|
|
|
os.chdir(dir_path)
|
|
|
|
|
|
|
|
|
|
with open(meta_filename, 'wt') as f:
|
2022-02-08 10:58:56 +00:00
|
|
|
|
serializer = serializers.SessionDisplaySerializer(session)
|
|
|
|
|
data = data_to_json(serializer.data)
|
|
|
|
|
f.write(data)
|
2020-06-10 09:34:56 +00:00
|
|
|
|
|
|
|
|
|
with tarfile.open(offline_filename, 'w') as f:
|
|
|
|
|
f.add(replay_filename)
|
|
|
|
|
f.add(meta_filename)
|
|
|
|
|
file = open(offline_filename, 'rb')
|
|
|
|
|
os.chdir(current_dir)
|
|
|
|
|
return file
|
|
|
|
|
|
2023-06-08 10:04:07 +00:00
|
|
|
|
def get_storage(self):
|
|
|
|
|
return ReplayStorageHandler(self.get_object())
|
|
|
|
|
|
2021-12-08 07:35:22 +00:00
|
|
|
|
@action(methods=[GET], detail=True, renderer_classes=(PassthroughRenderer,), url_path='replay/download',
|
|
|
|
|
url_name='replay-download')
|
2020-06-10 09:34:56 +00:00
|
|
|
|
def download(self, request, *args, **kwargs):
|
2023-06-08 10:04:07 +00:00
|
|
|
|
storage = self.get_storage()
|
2023-06-13 03:33:08 +00:00
|
|
|
|
local_path, url = storage.get_file_path_url()
|
2020-06-10 09:34:56 +00:00
|
|
|
|
if local_path is None:
|
2023-06-13 03:33:08 +00:00
|
|
|
|
# url => error message
|
|
|
|
|
return Response({'error': url}, status=404)
|
2020-06-10 09:34:56 +00:00
|
|
|
|
|
2023-06-08 10:04:07 +00:00
|
|
|
|
file = self.prepare_offline_file(storage.obj, local_path)
|
2020-06-10 09:34:56 +00:00
|
|
|
|
response = FileResponse(file)
|
|
|
|
|
response['Content-Type'] = 'application/octet-stream'
|
|
|
|
|
# 这里要注意哦,网上查到的方法都是response['Content-Disposition']='attachment;filename="filename.py"',
|
|
|
|
|
# 但是如果文件名是英文名没问题,如果文件名包含中文,下载下来的文件名会被改为url中的path。
|
2023-06-08 10:04:07 +00:00
|
|
|
|
filename = escape_uri_path('{}.tar'.format(storage.obj.id))
|
2020-06-10 09:34:56 +00:00
|
|
|
|
disposition = "attachment; filename*=UTF-8''{}".format(filename)
|
|
|
|
|
response["Content-Disposition"] = disposition
|
2023-08-29 06:21:06 +00:00
|
|
|
|
|
|
|
|
|
detail = i18n_fmt(
|
2023-08-29 07:16:02 +00:00
|
|
|
|
REPLAY_OP, self.request.user, _('Download'), str(storage.obj)
|
2023-08-29 06:21:06 +00:00
|
|
|
|
)
|
|
|
|
|
self.record_logs(
|
|
|
|
|
[storage.obj.asset_id], ActionChoices.download, detail,
|
|
|
|
|
model=Session, resource_display=str(storage.obj)
|
|
|
|
|
)
|
2020-06-10 09:34:56 +00:00
|
|
|
|
return response
|
|
|
|
|
|
2023-08-31 09:00:03 +00:00
|
|
|
|
@action(methods=[GET], detail=False, permission_classes=[IsAuthenticated], url_path='online-info', )
|
|
|
|
|
def online_info(self, request, *args, **kwargs):
|
|
|
|
|
asset = self.request.query_params.get('asset_id')
|
|
|
|
|
account = self.request.query_params.get('account')
|
|
|
|
|
if asset is None or account is None:
|
|
|
|
|
return Response({'count': None})
|
|
|
|
|
|
2023-08-31 09:42:21 +00:00
|
|
|
|
queryset = Session.objects.filter(is_finished=False) \
|
2023-08-31 09:00:03 +00:00
|
|
|
|
.filter(asset_id=asset) \
|
|
|
|
|
.filter(protocol='rdp') # 当前只统计 rdp 协议的会话
|
|
|
|
|
if '(' in account and ')' in account:
|
|
|
|
|
queryset = queryset.filter(account=account)
|
|
|
|
|
else:
|
|
|
|
|
queryset = queryset.filter(account__endswith='({})'.format(account))
|
|
|
|
|
count = queryset.count()
|
|
|
|
|
return Response({'count': count})
|
|
|
|
|
|
2022-07-01 11:07:42 +00:00
|
|
|
|
def get_queryset(self):
|
2023-08-31 09:00:03 +00:00
|
|
|
|
queryset = super().get_queryset() \
|
|
|
|
|
.prefetch_related('terminal') \
|
2022-07-01 11:07:42 +00:00
|
|
|
|
.annotate(terminal_display=F('terminal__name'))
|
|
|
|
|
return queryset
|
|
|
|
|
|
2019-07-04 09:09:36 +00:00
|
|
|
|
def filter_queryset(self, queryset):
|
|
|
|
|
queryset = super().filter_queryset(queryset)
|
2021-05-17 06:46:40 +00:00
|
|
|
|
# 解决guacamole更新session时并发导致幽灵会话的问题,暂不处理
|
2019-07-04 09:09:36 +00:00
|
|
|
|
if self.request.method in ('PATCH',):
|
|
|
|
|
queryset = queryset.select_for_update()
|
2019-01-15 02:23:30 +00:00
|
|
|
|
return queryset
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
|
|
def perform_create(self, serializer):
|
|
|
|
|
if hasattr(self.request.user, 'terminal'):
|
|
|
|
|
serializer.validated_data["terminal"] = self.request.user.terminal
|
|
|
|
|
return super().perform_create(serializer)
|
|
|
|
|
|
|
|
|
|
|
2023-08-29 06:21:06 +00:00
|
|
|
|
class SessionReplayViewSet(AsyncApiMixin, RecordViewLogMixin, viewsets.ViewSet):
|
2018-11-23 02:25:35 +00:00
|
|
|
|
serializer_class = serializers.ReplaySerializer
|
2020-03-12 08:24:38 +00:00
|
|
|
|
download_cache_key = "SESSION_REPLAY_DOWNLOAD_{}"
|
2022-02-17 12:13:31 +00:00
|
|
|
|
session = None
|
|
|
|
|
rbac_perms = {
|
2022-02-23 07:47:12 +00:00
|
|
|
|
'create': 'terminal.upload_sessionreplay',
|
2022-03-15 03:33:38 +00:00
|
|
|
|
'retrieve': 'terminal.view_sessionreplay',
|
2022-02-17 12:13:31 +00:00
|
|
|
|
}
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
|
|
|
|
def create(self, request, *args, **kwargs):
|
|
|
|
|
session_id = kwargs.get('pk')
|
2018-12-18 03:29:21 +00:00
|
|
|
|
session = get_object_or_404(Session, id=session_id)
|
2018-11-23 02:25:35 +00:00
|
|
|
|
serializer = self.serializer_class(data=request.data)
|
|
|
|
|
|
|
|
|
|
if serializer.is_valid():
|
|
|
|
|
file = serializer.validated_data['file']
|
2021-12-08 07:35:22 +00:00
|
|
|
|
# 兼容旧版本 API 未指定 version 为 2 的情况
|
|
|
|
|
version = serializer.validated_data.get('version', 2)
|
|
|
|
|
name, err = session.save_replay_to_storage_with_version(file, version)
|
2018-11-23 02:25:35 +00:00
|
|
|
|
if not name:
|
|
|
|
|
msg = "Failed save replay `{}`: {}".format(session_id, err)
|
|
|
|
|
logger.error(msg)
|
|
|
|
|
return Response({'msg': str(err)}, status=400)
|
|
|
|
|
url = default_storage.url(name)
|
|
|
|
|
return Response({'url': url}, status=201)
|
|
|
|
|
else:
|
|
|
|
|
msg = 'Upload data invalid: {}'.format(serializer.errors)
|
|
|
|
|
logger.error(msg)
|
|
|
|
|
return Response({'msg': serializer.errors}, status=401)
|
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
def get_replay_data(session, url):
|
2023-06-13 10:25:03 +00:00
|
|
|
|
all_guacamole_types = (
|
|
|
|
|
TerminalType.lion, TerminalType.guacamole,
|
|
|
|
|
TerminalType.razor, TerminalType.xrdp
|
|
|
|
|
)
|
|
|
|
|
|
2021-12-08 07:35:22 +00:00
|
|
|
|
if url.endswith('.cast.gz'):
|
|
|
|
|
tp = 'asciicast'
|
2023-06-13 10:25:03 +00:00
|
|
|
|
elif url.endswith('.replay.mp4'):
|
2023-04-27 11:31:58 +00:00
|
|
|
|
tp = 'mp4'
|
2023-06-13 10:25:03 +00:00
|
|
|
|
elif (getattr(session.terminal, 'type', None) in all_guacamole_types) or \
|
|
|
|
|
(session.protocol in ('rdp', 'vnc')):
|
|
|
|
|
tp = 'guacamole'
|
|
|
|
|
else:
|
|
|
|
|
tp = 'json'
|
2018-12-19 11:55:41 +00:00
|
|
|
|
|
2020-06-10 09:34:56 +00:00
|
|
|
|
download_url = reverse('api-terminal:session-replay-download', kwargs={'pk': session.id})
|
2020-03-12 08:24:38 +00:00
|
|
|
|
data = {
|
|
|
|
|
'type': tp, 'src': url,
|
|
|
|
|
'user': session.user, 'asset': session.asset,
|
2023-02-20 03:20:02 +00:00
|
|
|
|
'account': session.account,
|
2020-03-12 08:24:38 +00:00
|
|
|
|
'date_start': session.date_start,
|
|
|
|
|
'date_end': session.date_end,
|
|
|
|
|
'download_url': download_url,
|
2019-12-06 03:36:36 +00:00
|
|
|
|
}
|
2020-03-12 08:24:38 +00:00
|
|
|
|
return data
|
2018-11-23 02:25:35 +00:00
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
def is_need_async(self):
|
|
|
|
|
if self.action != 'retrieve':
|
|
|
|
|
return False
|
|
|
|
|
return True
|
|
|
|
|
|
2023-08-29 06:21:06 +00:00
|
|
|
|
def async_callback(self, *args, **kwargs):
|
|
|
|
|
session_id = kwargs.get('pk')
|
|
|
|
|
session = get_object_or_404(Session, id=session_id)
|
|
|
|
|
detail = i18n_fmt(
|
2023-08-29 07:16:02 +00:00
|
|
|
|
REPLAY_OP, self.request.user, _('View'), str(session)
|
2023-08-29 06:21:06 +00:00
|
|
|
|
)
|
|
|
|
|
self.record_logs(
|
|
|
|
|
[session.asset_id], ActionChoices.download, detail,
|
|
|
|
|
model=Session, resource_display=str(session)
|
|
|
|
|
)
|
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
def retrieve(self, request, *args, **kwargs):
|
|
|
|
|
session_id = kwargs.get('pk')
|
|
|
|
|
session = get_object_or_404(Session, id=session_id)
|
|
|
|
|
|
2023-06-08 10:04:07 +00:00
|
|
|
|
storage = ReplayStorageHandler(session)
|
2023-06-13 03:33:08 +00:00
|
|
|
|
local_path, url = storage.get_file_path_url()
|
2023-06-12 07:35:39 +00:00
|
|
|
|
if local_path is None:
|
2023-06-13 03:33:08 +00:00
|
|
|
|
# url => error message
|
|
|
|
|
return Response({"error": url}, status=404)
|
|
|
|
|
data = self.get_replay_data(session, url)
|
2020-03-12 08:24:38 +00:00
|
|
|
|
return Response(data)
|
2020-04-07 04:26:47 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SessionJoinValidateAPI(views.APIView):
|
2022-02-17 12:13:31 +00:00
|
|
|
|
"""
|
|
|
|
|
监控用
|
|
|
|
|
"""
|
2020-04-07 04:26:47 +00:00
|
|
|
|
serializer_class = serializers.SessionJoinValidateSerializer
|
2022-02-17 12:13:31 +00:00
|
|
|
|
rbac_perms = {
|
|
|
|
|
'POST': 'terminal.validate_sessionactionperm'
|
|
|
|
|
}
|
2020-04-07 04:26:47 +00:00
|
|
|
|
|
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
|
|
|
serializer = self.serializer_class(data=request.data)
|
|
|
|
|
if not serializer.is_valid():
|
|
|
|
|
msg = str(serializer.errors)
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
|
|
|
|
user_id = serializer.validated_data['user_id']
|
|
|
|
|
session_id = serializer.validated_data['session_id']
|
|
|
|
|
|
|
|
|
|
with tmp_to_root_org():
|
|
|
|
|
session = get_object_or_none(Session, pk=session_id)
|
|
|
|
|
if not session:
|
|
|
|
|
msg = _('Session does not exist: {}'.format(session_id))
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
2020-04-14 08:12:24 +00:00
|
|
|
|
if not session.can_join:
|
2020-04-07 04:26:47 +00:00
|
|
|
|
msg = _('Session is finished or the protocol not supported')
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
|
|
|
|
|
|
|
|
|
user = get_object_or_none(User, pk=user_id)
|
|
|
|
|
if not user:
|
|
|
|
|
msg = _('User does not exist: {}'.format(user_id))
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
2022-02-17 12:13:31 +00:00
|
|
|
|
|
2020-04-07 04:26:47 +00:00
|
|
|
|
with tmp_to_org(session.org):
|
2021-12-29 12:07:56 +00:00
|
|
|
|
if is_session_approver(session_id, user_id):
|
|
|
|
|
return Response({'ok': True, 'msg': ''}, status=200)
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
if not user.has_perm('terminal.monitor_session'):
|
2020-04-07 04:26:47 +00:00
|
|
|
|
msg = _('User does not have permission')
|
|
|
|
|
return Response({'ok': False, 'msg': msg}, status=401)
|
|
|
|
|
|
|
|
|
|
return Response({'ok': True, 'msg': ''}, status=200)
|