2022-11-14 06:03:58 +00:00
|
|
|
import base64
|
2022-07-11 10:09:06 +00:00
|
|
|
import json
|
2022-11-14 06:03:58 +00:00
|
|
|
import os
|
2022-07-11 10:09:06 +00:00
|
|
|
import urllib.parse
|
2022-11-14 06:03:58 +00:00
|
|
|
|
2023-05-18 14:08:41 +00:00
|
|
|
from django.conf import settings
|
2021-02-24 07:31:22 +00:00
|
|
|
from django.http import HttpResponse
|
2022-07-11 10:09:06 +00:00
|
|
|
from django.shortcuts import get_object_or_404
|
2022-11-22 13:54:40 +00:00
|
|
|
from django.utils import timezone
|
2023-07-24 03:52:25 +00:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2023-07-13 08:00:24 +00:00
|
|
|
from rest_framework import status, serializers
|
2022-07-11 10:09:06 +00:00
|
|
|
from rest_framework.decorators import action
|
2023-06-27 07:22:18 +00:00
|
|
|
from rest_framework.exceptions import PermissionDenied, ValidationError
|
2021-08-02 08:18:34 +00:00
|
|
|
from rest_framework.request import Request
|
2022-11-14 06:03:58 +00:00
|
|
|
from rest_framework.response import Response
|
2022-07-11 10:09:06 +00:00
|
|
|
|
2023-06-27 07:22:18 +00:00
|
|
|
from accounts.const import AliasAccount
|
2023-10-07 09:41:20 +00:00
|
|
|
from acls.notifications import AssetLoginReminderMsg
|
2023-01-16 11:02:09 +00:00
|
|
|
from common.api import JMSModelViewSet
|
2023-02-03 08:03:34 +00:00
|
|
|
from common.exceptions import JMSException
|
2023-05-29 11:45:55 +00:00
|
|
|
from common.utils import random_string, get_logger, get_request_ip
|
2022-11-29 06:42:04 +00:00
|
|
|
from common.utils.django import get_request_os
|
2023-05-09 05:43:46 +00:00
|
|
|
from common.utils.http import is_true, is_false
|
2022-07-11 10:09:06 +00:00
|
|
|
from orgs.mixins.api import RootOrgViewMixin
|
2022-11-11 07:04:31 +00:00
|
|
|
from perms.models import ActionChoices
|
2022-12-07 07:09:01 +00:00
|
|
|
from terminal.connect_methods import NativeClient, ConnectMethodUtil
|
2023-07-19 10:10:40 +00:00
|
|
|
from terminal.models import EndpointRule, Endpoint
|
2023-09-11 08:22:11 +00:00
|
|
|
from users.const import FileNameConflictResolution
|
|
|
|
from users.models import Preference
|
2023-03-08 02:25:53 +00:00
|
|
|
from ..models import ConnectionToken, date_expired_default
|
2021-02-24 07:31:22 +00:00
|
|
|
from ..serializers import (
|
2022-07-20 05:18:56 +00:00
|
|
|
ConnectionTokenSerializer, ConnectionTokenSecretSerializer,
|
2023-05-09 06:21:14 +00:00
|
|
|
SuperConnectionTokenSerializer, ConnectTokenAppletOptionSerializer,
|
2023-07-13 08:00:24 +00:00
|
|
|
ConnectionTokenReusableSerializer,
|
2022-11-29 13:41:33 +00:00
|
|
|
)
|
2019-02-27 12:55:28 +00:00
|
|
|
|
2022-07-11 10:09:06 +00:00
|
|
|
__all__ = ['ConnectionTokenViewSet', 'SuperConnectionTokenViewSet']
|
2023-02-10 11:40:35 +00:00
|
|
|
logger = get_logger(__name__)
|
2022-02-17 12:13:31 +00:00
|
|
|
|
2022-11-14 06:03:58 +00:00
|
|
|
|
2022-10-31 10:47:12 +00:00
|
|
|
class RDPFileClientProtocolURLMixin:
|
|
|
|
request: Request
|
|
|
|
get_serializer: callable
|
2022-07-11 10:09:06 +00:00
|
|
|
|
|
|
|
def get_rdp_file_info(self, token: ConnectionToken):
|
|
|
|
rdp_options = {
|
2021-02-24 07:31:22 +00:00
|
|
|
'full address:s': '',
|
|
|
|
'username:s': '',
|
2021-07-16 06:15:10 +00:00
|
|
|
'use multimon:i': '0',
|
2021-04-29 06:18:52 +00:00
|
|
|
'session bpp:i': '32',
|
2021-02-24 07:31:22 +00:00
|
|
|
'audiomode:i': '0',
|
|
|
|
'disable wallpaper:i': '0',
|
|
|
|
'disable full window drag:i': '0',
|
|
|
|
'disable menu anims:i': '0',
|
|
|
|
'disable themes:i': '0',
|
|
|
|
'alternate shell:s': '',
|
|
|
|
'shell working directory:s': '',
|
|
|
|
'authentication level:i': '2',
|
|
|
|
'connect to console:i': '0',
|
|
|
|
'disable cursor setting:i': '0',
|
|
|
|
'allow font smoothing:i': '1',
|
|
|
|
'allow desktop composition:i': '1',
|
|
|
|
'redirectprinters:i': '0',
|
|
|
|
'prompt for credentials on client:i': '0',
|
|
|
|
'autoreconnection enabled:i': '1',
|
|
|
|
'bookmarktype:i': '3',
|
|
|
|
'use redirection server name:i': '0',
|
2022-03-25 02:43:48 +00:00
|
|
|
'smart sizing:i': '1',
|
2021-02-24 07:31:22 +00:00
|
|
|
}
|
2023-07-28 10:06:38 +00:00
|
|
|
# 设置多屏显示
|
|
|
|
multi_mon = is_true(self.request.query_params.get('multi_mon'))
|
|
|
|
if multi_mon:
|
|
|
|
rdp_options['use multimon:i'] = '1'
|
2021-02-24 07:31:22 +00:00
|
|
|
|
2023-07-28 09:45:12 +00:00
|
|
|
# 设置多屏显示
|
|
|
|
multi_mon = is_true(self.request.query_params.get('multi_mon'))
|
|
|
|
if multi_mon:
|
|
|
|
rdp_options['use multimon:i'] = '1'
|
|
|
|
|
2021-11-16 03:32:25 +00:00
|
|
|
# 设置磁盘挂载
|
2022-07-11 10:09:06 +00:00
|
|
|
drives_redirect = is_true(self.request.query_params.get('drives_redirect'))
|
2022-02-16 07:48:28 +00:00
|
|
|
if drives_redirect:
|
2022-11-23 08:11:17 +00:00
|
|
|
if ActionChoices.contains(token.actions, ActionChoices.transfer()):
|
2022-07-11 10:09:06 +00:00
|
|
|
rdp_options['drivestoredirect:s'] = '*'
|
2021-10-07 07:30:39 +00:00
|
|
|
|
2022-07-11 10:09:06 +00:00
|
|
|
# 设置全屏
|
|
|
|
full_screen = is_true(self.request.query_params.get('full_screen'))
|
|
|
|
rdp_options['screen mode id:i'] = '2' if full_screen else '1'
|
2021-11-16 03:32:25 +00:00
|
|
|
|
2022-07-11 10:09:06 +00:00
|
|
|
# 设置 RDP Server 地址
|
2023-07-04 09:35:58 +00:00
|
|
|
endpoint = self.get_smart_endpoint(protocol='rdp', asset=token.asset)
|
|
|
|
rdp_options['full address:s'] = f'{endpoint.host}:{endpoint.rdp_port}'
|
2021-11-09 09:10:29 +00:00
|
|
|
|
2022-07-11 10:09:06 +00:00
|
|
|
# 设置用户名
|
|
|
|
rdp_options['username:s'] = '{}|{}'.format(token.user.username, str(token.id))
|
2022-10-27 07:47:05 +00:00
|
|
|
# rdp_options['domain:s'] = token.account_ad_domain
|
2021-11-09 09:10:29 +00:00
|
|
|
|
2022-07-11 10:09:06 +00:00
|
|
|
# 设置宽高
|
|
|
|
height = self.request.query_params.get('height')
|
|
|
|
width = self.request.query_params.get('width')
|
|
|
|
if width and height:
|
|
|
|
rdp_options['desktopwidth:i'] = width
|
|
|
|
rdp_options['desktopheight:i'] = height
|
2023-05-18 11:06:51 +00:00
|
|
|
rdp_options['winposstr:s'] = f'0,1,0,0,{width},{height}'
|
|
|
|
rdp_options['dynamic resolution:i'] = '0'
|
2022-07-11 10:09:06 +00:00
|
|
|
|
|
|
|
# 设置其他选项
|
|
|
|
rdp_options['session bpp:i'] = os.getenv('JUMPSERVER_COLOR_DEPTH', '32')
|
|
|
|
rdp_options['audiomode:i'] = self.parse_env_bool('JUMPSERVER_DISABLE_AUDIO', 'false', '2', '0')
|
|
|
|
|
2022-12-20 03:05:00 +00:00
|
|
|
# 设置远程应用, 不是 Mstsc
|
|
|
|
if token.connect_method != NativeClient.mstsc:
|
|
|
|
remote_app_options = token.get_remote_app_option()
|
|
|
|
rdp_options.update(remote_app_options)
|
2022-11-29 10:36:42 +00:00
|
|
|
|
2023-04-25 06:25:06 +00:00
|
|
|
rdp = token.asset.platform.protocols.filter(name='rdp').first()
|
|
|
|
if rdp and rdp.setting.get('console'):
|
2023-05-18 11:34:26 +00:00
|
|
|
rdp_options['administrative session:i'] = '1'
|
2023-04-25 06:25:06 +00:00
|
|
|
|
2022-11-29 10:36:42 +00:00
|
|
|
# 文件名
|
|
|
|
name = token.asset.name
|
2022-08-10 10:17:59 +00:00
|
|
|
prefix_name = f'{token.user.username}-{name}'
|
|
|
|
filename = self.get_connect_filename(prefix_name)
|
2022-07-11 10:09:06 +00:00
|
|
|
|
2021-09-24 07:31:25 +00:00
|
|
|
content = ''
|
2022-07-11 10:09:06 +00:00
|
|
|
for k, v in rdp_options.items():
|
2021-09-24 07:31:25 +00:00
|
|
|
content += f'{k}:{v}\n'
|
2021-07-27 05:35:25 +00:00
|
|
|
|
2022-07-11 10:09:06 +00:00
|
|
|
return filename, content
|
|
|
|
|
2022-08-10 10:17:59 +00:00
|
|
|
@staticmethod
|
2023-08-09 14:59:53 +00:00
|
|
|
def escape_name(name):
|
|
|
|
name = name.replace('/', '_')
|
|
|
|
name = name.replace('\\', '_')
|
|
|
|
name = name.replace('.', '_')
|
|
|
|
name = urllib.parse.quote(name)
|
|
|
|
return name
|
|
|
|
|
|
|
|
def get_connect_filename(self, prefix_name):
|
2022-08-10 10:17:59 +00:00
|
|
|
filename = f'{prefix_name}-jumpserver'
|
2023-08-09 14:59:53 +00:00
|
|
|
filename = self.escape_name(filename)
|
2022-08-10 10:17:59 +00:00
|
|
|
return filename
|
|
|
|
|
2022-10-31 10:47:12 +00:00
|
|
|
@staticmethod
|
|
|
|
def parse_env_bool(env_key, env_default, true_value, false_value):
|
|
|
|
return true_value if is_true(os.getenv(env_key, env_default)) else false_value
|
|
|
|
|
|
|
|
def get_client_protocol_data(self, token: ConnectionToken):
|
2022-11-29 06:42:04 +00:00
|
|
|
_os = get_request_os(self.request)
|
2022-10-31 10:47:12 +00:00
|
|
|
|
2022-11-29 13:41:33 +00:00
|
|
|
connect_method_name = token.connect_method
|
2022-12-07 07:09:01 +00:00
|
|
|
connect_method_dict = ConnectMethodUtil.get_connect_method(
|
2022-11-29 13:41:33 +00:00
|
|
|
token.connect_method, token.protocol, _os
|
|
|
|
)
|
2023-08-09 14:59:53 +00:00
|
|
|
asset = token.asset
|
2022-11-29 13:41:33 +00:00
|
|
|
if connect_method_dict is None:
|
|
|
|
raise ValueError('Connect method not support: {}'.format(connect_method_name))
|
2022-03-28 11:52:48 +00:00
|
|
|
|
2023-08-09 14:59:53 +00:00
|
|
|
account = token.account or token.input_username
|
|
|
|
datetime = timezone.localtime(timezone.now()).strftime('%Y-%m-%d_%H:%M:%S')
|
|
|
|
name = account + '@' + str(asset) + '[' + datetime + ']'
|
2022-07-11 10:09:06 +00:00
|
|
|
data = {
|
2023-08-09 14:59:53 +00:00
|
|
|
'version': 2,
|
|
|
|
'id': str(token.id), # 兼容老的,未来几个版本删掉
|
|
|
|
'value': token.value, # 兼容老的,未来几个版本删掉
|
|
|
|
'name': self.escape_name(name),
|
2022-11-30 12:02:13 +00:00
|
|
|
'protocol': token.protocol,
|
2023-08-09 14:59:53 +00:00
|
|
|
'token': {
|
|
|
|
'id': str(token.id),
|
|
|
|
'value': token.value,
|
|
|
|
},
|
|
|
|
'file': {},
|
|
|
|
'command': ''
|
2022-03-28 11:52:48 +00:00
|
|
|
}
|
2022-11-29 06:42:04 +00:00
|
|
|
|
2022-12-20 03:05:00 +00:00
|
|
|
if connect_method_name == NativeClient.mstsc or connect_method_dict['type'] == 'applet':
|
2022-11-29 06:42:04 +00:00
|
|
|
filename, content = self.get_rdp_file_info(token)
|
|
|
|
data.update({
|
2022-12-20 03:05:00 +00:00
|
|
|
'protocol': 'rdp',
|
2022-11-29 06:42:04 +00:00
|
|
|
'file': {
|
2022-11-29 06:45:29 +00:00
|
|
|
'name': filename,
|
2022-11-29 06:42:04 +00:00
|
|
|
'content': content,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
else:
|
2023-08-09 14:59:53 +00:00
|
|
|
endpoint = self.get_smart_endpoint(
|
|
|
|
protocol=connect_method_dict['endpoint_protocol'],
|
|
|
|
asset=asset
|
|
|
|
)
|
|
|
|
data.update({
|
|
|
|
'asset': {
|
|
|
|
'id': str(asset.id),
|
|
|
|
'category': asset.category,
|
|
|
|
'type': asset.type,
|
|
|
|
'name': asset.name,
|
|
|
|
'address': asset.address,
|
|
|
|
'info': {
|
|
|
|
**asset.spec_info,
|
|
|
|
}
|
|
|
|
},
|
|
|
|
'endpoint': {
|
|
|
|
'host': endpoint.host,
|
|
|
|
'port': endpoint.get_port(token.asset, token.protocol),
|
|
|
|
}
|
|
|
|
})
|
2022-11-29 06:42:04 +00:00
|
|
|
return data
|
2022-03-28 11:52:48 +00:00
|
|
|
|
2022-10-31 10:47:12 +00:00
|
|
|
def get_smart_endpoint(self, protocol, asset=None):
|
2023-07-19 10:10:40 +00:00
|
|
|
endpoint = Endpoint.match_by_instance_label(asset, protocol)
|
|
|
|
if not endpoint:
|
|
|
|
target_ip = asset.get_target_ip() if asset else ''
|
|
|
|
endpoint = EndpointRule.match_endpoint(
|
|
|
|
target_instance=asset, target_ip=target_ip,
|
|
|
|
protocol=protocol, request=self.request
|
|
|
|
)
|
2022-10-31 10:47:12 +00:00
|
|
|
return endpoint
|
2021-09-24 07:31:25 +00:00
|
|
|
|
2021-11-16 03:32:25 +00:00
|
|
|
|
2022-10-31 10:47:12 +00:00
|
|
|
class ExtraActionApiMixin(RDPFileClientProtocolURLMixin):
|
|
|
|
request: Request
|
|
|
|
get_object: callable
|
|
|
|
get_serializer: callable
|
|
|
|
perform_create: callable
|
2023-03-08 02:25:53 +00:00
|
|
|
validate_exchange_token: callable
|
2022-07-11 10:09:06 +00:00
|
|
|
|
2022-11-28 07:01:16 +00:00
|
|
|
@action(methods=['POST', 'GET'], detail=True, url_path='rdp-file')
|
|
|
|
def get_rdp_file(self, *args, **kwargs):
|
|
|
|
token = self.get_object()
|
2022-11-23 08:11:17 +00:00
|
|
|
token.is_valid()
|
2022-07-11 10:09:06 +00:00
|
|
|
filename, content = self.get_rdp_file_info(token)
|
|
|
|
filename = '{}.rdp'.format(filename)
|
|
|
|
response = HttpResponse(content, content_type='application/octet-stream')
|
2022-04-24 09:00:48 +00:00
|
|
|
response['Content-Disposition'] = 'attachment; filename*=UTF-8\'\'%s' % filename
|
|
|
|
return response
|
|
|
|
|
2022-11-28 07:01:16 +00:00
|
|
|
@action(methods=['POST', 'GET'], detail=True, url_path='client-url')
|
|
|
|
def get_client_protocol_url(self, *args, **kwargs):
|
|
|
|
token = self.get_object()
|
2022-11-23 08:11:17 +00:00
|
|
|
token.is_valid()
|
2021-11-16 03:32:25 +00:00
|
|
|
try:
|
2022-07-11 10:09:06 +00:00
|
|
|
protocol_data = self.get_client_protocol_data(token)
|
2021-11-16 03:32:25 +00:00
|
|
|
except ValueError as e:
|
2022-07-11 10:09:06 +00:00
|
|
|
return Response(data={'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
2021-11-16 03:32:25 +00:00
|
|
|
protocol_data = json.dumps(protocol_data).encode()
|
|
|
|
protocol_data = base64.b64encode(protocol_data).decode()
|
2021-08-02 08:18:34 +00:00
|
|
|
data = {
|
2022-07-11 10:09:06 +00:00
|
|
|
'url': 'jms://{}'.format(protocol_data)
|
2021-08-02 08:18:34 +00:00
|
|
|
}
|
|
|
|
return Response(data=data)
|
|
|
|
|
2022-07-11 10:09:06 +00:00
|
|
|
@action(methods=['PATCH'], detail=True)
|
|
|
|
def expire(self, request, *args, **kwargs):
|
|
|
|
instance = self.get_object()
|
|
|
|
instance.expire()
|
|
|
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
2022-05-31 08:20:33 +00:00
|
|
|
|
2023-07-13 08:00:24 +00:00
|
|
|
@action(methods=['PATCH'], detail=True, url_path='reuse')
|
|
|
|
def reuse(self, request, *args, **kwargs):
|
|
|
|
instance = self.get_object()
|
|
|
|
if not settings.CONNECTION_TOKEN_REUSABLE:
|
2023-07-20 02:41:11 +00:00
|
|
|
error = _('Reusable connection token is not allowed, global setting not enabled')
|
|
|
|
raise serializers.ValidationError(error)
|
2023-07-13 08:00:24 +00:00
|
|
|
serializer = self.get_serializer(instance, data=request.data, partial=True)
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
is_reusable = serializer.validated_data.get('is_reusable', False)
|
|
|
|
instance.set_reusable(is_reusable)
|
|
|
|
return Response(data=serializer.data)
|
|
|
|
|
2023-03-08 02:25:53 +00:00
|
|
|
@action(methods=['POST'], detail=False)
|
|
|
|
def exchange(self, request, *args, **kwargs):
|
|
|
|
pk = request.data.get('id', None) or request.data.get('pk', None)
|
|
|
|
# 只能兑换自己使用的 Token
|
|
|
|
instance = get_object_or_404(ConnectionToken, pk=pk, user=request.user)
|
|
|
|
instance.id = None
|
|
|
|
self.validate_exchange_token(instance)
|
|
|
|
instance.date_expired = date_expired_default()
|
|
|
|
instance.save()
|
|
|
|
serializer = self.get_serializer(instance)
|
|
|
|
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
|
|
|
|
2022-10-31 10:47:12 +00:00
|
|
|
|
|
|
|
class ConnectionTokenViewSet(ExtraActionApiMixin, RootOrgViewMixin, JMSModelViewSet):
|
|
|
|
filterset_fields = (
|
|
|
|
'user_display', 'asset_display'
|
|
|
|
)
|
|
|
|
search_fields = filterset_fields
|
|
|
|
serializer_classes = {
|
|
|
|
'default': ConnectionTokenSerializer,
|
2023-07-13 08:00:24 +00:00
|
|
|
'reuse': ConnectionTokenReusableSerializer,
|
2022-10-31 10:47:12 +00:00
|
|
|
}
|
2023-05-09 05:43:46 +00:00
|
|
|
http_method_names = ['get', 'post', 'patch', 'head', 'options', 'trace']
|
2022-10-31 10:47:12 +00:00
|
|
|
rbac_perms = {
|
2022-11-29 06:42:04 +00:00
|
|
|
'list': 'authentication.view_connectiontoken',
|
2022-10-31 10:47:12 +00:00
|
|
|
'retrieve': 'authentication.view_connectiontoken',
|
|
|
|
'create': 'authentication.add_connectiontoken',
|
2023-03-08 02:25:53 +00:00
|
|
|
'exchange': 'authentication.add_connectiontoken',
|
2023-07-13 08:00:24 +00:00
|
|
|
'reuse': 'authentication.reuse_connectiontoken',
|
|
|
|
'expire': 'authentication.expire_connectiontoken',
|
2022-10-31 10:47:12 +00:00
|
|
|
'get_rdp_file': 'authentication.add_connectiontoken',
|
|
|
|
'get_client_protocol_url': 'authentication.add_connectiontoken',
|
|
|
|
}
|
|
|
|
|
|
|
|
def get_queryset(self):
|
2022-11-29 06:42:04 +00:00
|
|
|
queryset = ConnectionToken.objects \
|
|
|
|
.filter(user=self.request.user) \
|
|
|
|
.filter(date_expired__gt=timezone.now())
|
2022-11-28 14:58:43 +00:00
|
|
|
return queryset
|
2022-10-31 10:47:12 +00:00
|
|
|
|
|
|
|
def get_user(self, serializer):
|
|
|
|
return self.request.user
|
|
|
|
|
|
|
|
def perform_create(self, serializer):
|
2022-11-22 13:54:40 +00:00
|
|
|
self.validate_serializer(serializer)
|
|
|
|
return super().perform_create(serializer)
|
2022-10-31 10:47:12 +00:00
|
|
|
|
2023-09-19 03:09:58 +00:00
|
|
|
def _insert_connect_options(self, data, user):
|
2023-09-11 08:22:11 +00:00
|
|
|
connect_options = data.pop('connect_options', {})
|
2023-10-09 07:40:54 +00:00
|
|
|
default_name_opts = {
|
|
|
|
'file_name_conflict_resolution': FileNameConflictResolution.REPLACE,
|
|
|
|
'terminal_theme_name': 'Default',
|
|
|
|
}
|
|
|
|
preferences_query = Preference.objects.filter(
|
|
|
|
user=user, category='koko', name__in=default_name_opts.keys()
|
|
|
|
).values_list('name', 'value')
|
|
|
|
preferences = dict(preferences_query)
|
|
|
|
for name in default_name_opts.keys():
|
|
|
|
value = preferences.get(name, default_name_opts[name])
|
|
|
|
connect_options[name] = value
|
2023-09-11 08:22:11 +00:00
|
|
|
data['connect_options'] = connect_options
|
|
|
|
|
2022-11-22 13:54:40 +00:00
|
|
|
def validate_serializer(self, serializer):
|
|
|
|
data = serializer.validated_data
|
|
|
|
user = self.get_user(serializer)
|
2023-09-19 03:09:58 +00:00
|
|
|
self._insert_connect_options(data, user)
|
2022-11-22 13:54:40 +00:00
|
|
|
asset = data.get('asset')
|
2022-12-05 04:42:15 +00:00
|
|
|
account_name = data.get('account')
|
2023-03-08 02:25:53 +00:00
|
|
|
_data = self._validate(user, asset, account_name)
|
|
|
|
data.update(_data)
|
|
|
|
return serializer
|
|
|
|
|
|
|
|
def validate_exchange_token(self, token):
|
|
|
|
user = token.user
|
|
|
|
asset = token.asset
|
|
|
|
account_name = token.account
|
|
|
|
_data = self._validate(user, asset, account_name)
|
|
|
|
for k, v in _data.items():
|
|
|
|
setattr(token, k, v)
|
|
|
|
return token
|
|
|
|
|
|
|
|
def _validate(self, user, asset, account_name):
|
|
|
|
data = dict()
|
2022-11-22 13:54:40 +00:00
|
|
|
data['org_id'] = asset.org_id
|
|
|
|
data['user'] = user
|
2022-11-25 15:09:55 +00:00
|
|
|
data['value'] = random_string(16)
|
2023-06-27 07:22:18 +00:00
|
|
|
|
|
|
|
if account_name == AliasAccount.ANON and asset.category not in ['web', 'custom']:
|
|
|
|
raise ValidationError(_('Anonymous account is not supported for this asset'))
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
account = self._validate_perm(user, asset, account_name)
|
|
|
|
if account.has_secret:
|
|
|
|
data['input_secret'] = ''
|
2023-02-10 07:56:47 +00:00
|
|
|
|
2023-06-27 07:22:18 +00:00
|
|
|
if account.username != AliasAccount.INPUT:
|
2023-01-16 11:02:09 +00:00
|
|
|
data['input_username'] = ''
|
|
|
|
ticket = self._validate_acl(user, asset, account)
|
|
|
|
if ticket:
|
|
|
|
data['from_ticket'] = ticket
|
|
|
|
data['is_active'] = False
|
2023-03-08 02:25:53 +00:00
|
|
|
return data
|
2022-11-22 13:54:40 +00:00
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
@staticmethod
|
|
|
|
def _validate_perm(user, asset, account_name):
|
|
|
|
from perms.utils.account import PermAccountUtil
|
|
|
|
account = PermAccountUtil().validate_permission(user, asset, account_name)
|
|
|
|
if not account or not account.actions:
|
|
|
|
msg = _('Account not found')
|
|
|
|
raise JMSException(code='perm_account_invalid', detail=msg)
|
|
|
|
if account.date_expired < timezone.now():
|
2023-02-03 08:03:34 +00:00
|
|
|
msg = _('Permission expired')
|
2023-01-16 11:02:09 +00:00
|
|
|
raise JMSException(code='perm_expired', detail=msg)
|
|
|
|
return account
|
|
|
|
|
2023-10-07 07:50:28 +00:00
|
|
|
@staticmethod
|
|
|
|
def _record_operate_log(acl, asset):
|
|
|
|
from audits.handler import create_or_update_operate_log
|
|
|
|
after = {str(_('Assets')): str(asset)}
|
|
|
|
object_name = acl._meta.object_name
|
|
|
|
resource_type = acl._meta.verbose_name
|
|
|
|
create_or_update_operate_log(
|
|
|
|
acl.action, resource_type, resource=acl,
|
|
|
|
after=after, object_name=object_name
|
|
|
|
)
|
|
|
|
|
2023-01-16 11:02:09 +00:00
|
|
|
def _validate_acl(self, user, asset, account):
|
|
|
|
from acls.models import LoginAssetACL
|
2023-09-21 02:15:10 +00:00
|
|
|
acls = LoginAssetACL.filter_queryset(user=user, asset=asset, account=account)
|
2023-05-29 11:45:55 +00:00
|
|
|
ip = get_request_ip(self.request)
|
|
|
|
acl = LoginAssetACL.get_match_rule_acls(user, ip, acls)
|
2023-01-16 11:02:09 +00:00
|
|
|
if not acl:
|
|
|
|
return
|
|
|
|
if acl.is_action(acl.ActionChoices.accept):
|
2023-10-07 07:50:28 +00:00
|
|
|
self._record_operate_log(acl, asset)
|
2023-01-16 11:02:09 +00:00
|
|
|
return
|
|
|
|
if acl.is_action(acl.ActionChoices.reject):
|
2023-10-07 07:50:28 +00:00
|
|
|
self._record_operate_log(acl, asset)
|
2023-05-25 10:42:54 +00:00
|
|
|
msg = _('ACL action is reject: {}({})'.format(acl.name, acl.id))
|
2023-01-16 11:02:09 +00:00
|
|
|
raise JMSException(code='acl_reject', detail=msg)
|
|
|
|
if acl.is_action(acl.ActionChoices.review):
|
|
|
|
if not self.request.query_params.get('create_ticket'):
|
|
|
|
msg = _('ACL action is review')
|
|
|
|
raise JMSException(code='acl_review', detail=msg)
|
2023-10-07 07:50:28 +00:00
|
|
|
self._record_operate_log(acl, asset)
|
2023-01-16 11:02:09 +00:00
|
|
|
ticket = LoginAssetACL.create_login_asset_review_ticket(
|
|
|
|
user=user, asset=asset, account_username=account.username,
|
|
|
|
assignees=acl.reviewers.all(), org_id=asset.org_id
|
|
|
|
)
|
|
|
|
return ticket
|
2023-10-07 09:41:20 +00:00
|
|
|
if acl.is_action(acl.ActionChoices.notice):
|
|
|
|
reviewers = acl.reviewers.all()
|
2023-10-09 09:16:38 +00:00
|
|
|
if not reviewers:
|
|
|
|
return
|
2023-10-12 12:04:28 +00:00
|
|
|
account_username = account.username
|
2023-10-09 09:16:38 +00:00
|
|
|
self._record_operate_log(acl, asset)
|
2023-10-07 09:41:20 +00:00
|
|
|
for reviewer in reviewers:
|
2023-10-12 12:04:28 +00:00
|
|
|
AssetLoginReminderMsg(reviewer, asset, user, account_username).publish_async()
|
2022-10-31 10:47:12 +00:00
|
|
|
|
|
|
|
|
2022-07-11 10:09:06 +00:00
|
|
|
class SuperConnectionTokenViewSet(ConnectionTokenViewSet):
|
2022-04-24 09:00:48 +00:00
|
|
|
serializer_classes = {
|
|
|
|
'default': SuperConnectionTokenSerializer,
|
2022-12-07 07:09:01 +00:00
|
|
|
'get_secret_detail': ConnectionTokenSecretSerializer,
|
2022-04-24 09:00:48 +00:00
|
|
|
}
|
|
|
|
rbac_perms = {
|
|
|
|
'create': 'authentication.add_superconnectiontoken',
|
2022-12-07 07:09:01 +00:00
|
|
|
'renewal': 'authentication.add_superconnectiontoken',
|
2023-07-13 08:00:24 +00:00
|
|
|
'get_secret_detail': 'authentication.view_superconnectiontokensecret',
|
2022-12-07 07:09:01 +00:00
|
|
|
'get_applet_info': 'authentication.view_superconnectiontoken',
|
|
|
|
'release_applet_account': 'authentication.view_superconnectiontoken',
|
2022-04-24 09:00:48 +00:00
|
|
|
}
|
|
|
|
|
2022-10-31 10:47:12 +00:00
|
|
|
def get_queryset(self):
|
|
|
|
return ConnectionToken.objects.all()
|
|
|
|
|
|
|
|
def get_user(self, serializer):
|
2022-07-20 05:23:43 +00:00
|
|
|
return serializer.validated_data.get('user')
|
|
|
|
|
2022-07-11 10:09:06 +00:00
|
|
|
@action(methods=['PATCH'], detail=False)
|
2022-04-24 09:00:48 +00:00
|
|
|
def renewal(self, request, *args, **kwargs):
|
2022-07-11 10:09:06 +00:00
|
|
|
from common.utils.timezone import as_current_tz
|
|
|
|
|
2022-11-28 14:58:43 +00:00
|
|
|
token_id = request.data.get('id') or ''
|
2022-07-11 10:09:06 +00:00
|
|
|
token = get_object_or_404(ConnectionToken, pk=token_id)
|
|
|
|
date_expired = as_current_tz(token.date_expired)
|
|
|
|
if token.is_expired:
|
|
|
|
raise PermissionDenied('Token is expired at: {}'.format(date_expired))
|
|
|
|
token.renewal()
|
|
|
|
data = {
|
|
|
|
'ok': True,
|
|
|
|
'msg': f'Token is renewed, date expired: {date_expired}'
|
|
|
|
}
|
|
|
|
return Response(data=data, status=status.HTTP_200_OK)
|
2022-12-07 07:09:01 +00:00
|
|
|
|
|
|
|
@action(methods=['POST'], detail=False, url_path='secret')
|
|
|
|
def get_secret_detail(self, request, *args, **kwargs):
|
|
|
|
""" 非常重要的 api, 在逻辑层再判断一下 rbac 权限, 双重保险 """
|
2023-07-13 08:00:24 +00:00
|
|
|
rbac_perm = 'authentication.view_superconnectiontokensecret'
|
2022-12-07 07:09:01 +00:00
|
|
|
if not request.user.has_perm(rbac_perm):
|
|
|
|
raise PermissionDenied('Not allow to view secret')
|
|
|
|
|
|
|
|
token_id = request.data.get('id') or ''
|
|
|
|
token = get_object_or_404(ConnectionToken, pk=token_id)
|
|
|
|
token.is_valid()
|
|
|
|
serializer = self.get_serializer(instance=token)
|
2023-02-08 03:28:44 +00:00
|
|
|
|
2023-05-09 05:43:46 +00:00
|
|
|
expire_now = request.data.get('expire_now', None)
|
|
|
|
asset_type = token.asset.type
|
|
|
|
# 设置默认值
|
|
|
|
if expire_now is None:
|
|
|
|
# TODO 暂时特殊处理 k8s 不过期
|
|
|
|
if asset_type in ['k8s', 'kubernetes']:
|
|
|
|
expire_now = False
|
|
|
|
else:
|
2023-05-18 14:08:41 +00:00
|
|
|
expire_now = not settings.CONNECTION_TOKEN_REUSABLE
|
2023-05-09 05:43:46 +00:00
|
|
|
|
2023-05-18 14:08:41 +00:00
|
|
|
if is_false(expire_now):
|
|
|
|
logger.debug('Api specified, now expire now')
|
|
|
|
elif token.is_reusable and settings.CONNECTION_TOKEN_REUSABLE:
|
|
|
|
logger.debug('Token is reusable, not expire now')
|
2023-05-09 05:43:46 +00:00
|
|
|
else:
|
2022-12-07 07:09:01 +00:00
|
|
|
token.expire()
|
2023-05-09 05:43:46 +00:00
|
|
|
|
2022-12-07 07:09:01 +00:00
|
|
|
return Response(serializer.data, status=status.HTTP_200_OK)
|
|
|
|
|
|
|
|
@action(methods=['POST'], detail=False, url_path='applet-option')
|
|
|
|
def get_applet_info(self, *args, **kwargs):
|
|
|
|
token_id = self.request.data.get('id')
|
|
|
|
token = get_object_or_404(ConnectionToken, pk=token_id)
|
|
|
|
if token.is_expired:
|
|
|
|
return Response({'error': 'Token expired'}, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
data = token.get_applet_option()
|
|
|
|
serializer = ConnectTokenAppletOptionSerializer(data)
|
|
|
|
return Response(serializer.data)
|
|
|
|
|
|
|
|
@action(methods=['DELETE', 'POST'], detail=False, url_path='applet-account/release')
|
|
|
|
def release_applet_account(self, *args, **kwargs):
|
|
|
|
account_id = self.request.data.get('id')
|
2023-02-10 11:40:35 +00:00
|
|
|
released = ConnectionToken.release_applet_account(account_id)
|
|
|
|
|
|
|
|
if released:
|
|
|
|
logger.debug('Release applet account success: {}'.format(account_id))
|
|
|
|
return Response({'msg': 'released'})
|
|
|
|
else:
|
|
|
|
logger.error('Release applet account error: {}'.format(account_id))
|
|
|
|
return Response({'error': 'not found or expired'}, status=400)
|