2019-02-27 12:55:28 +00:00
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
#
|
2021-04-20 08:17:18 +00:00
|
|
|
|
import urllib.parse
|
2021-08-02 08:18:34 +00:00
|
|
|
|
import json
|
|
|
|
|
from typing import Callable
|
2021-11-09 09:10:29 +00:00
|
|
|
|
import os
|
2021-09-24 07:31:25 +00:00
|
|
|
|
import base64
|
|
|
|
|
import ctypes
|
2021-04-20 08:17:18 +00:00
|
|
|
|
|
2021-01-21 05:50:29 +00:00
|
|
|
|
from django.conf import settings
|
2019-02-27 12:55:28 +00:00
|
|
|
|
from django.core.cache import cache
|
2021-02-23 06:37:42 +00:00
|
|
|
|
from django.shortcuts import get_object_or_404
|
2021-02-24 07:31:22 +00:00
|
|
|
|
from django.http import HttpResponse
|
2022-02-14 09:38:30 +00:00
|
|
|
|
from django.utils import timezone
|
2021-06-10 10:02:55 +00:00
|
|
|
|
from django.utils.translation import ugettext as _
|
2019-02-27 12:55:28 +00:00
|
|
|
|
from rest_framework.response import Response
|
2021-08-02 08:18:34 +00:00
|
|
|
|
from rest_framework.request import Request
|
2021-02-23 06:37:42 +00:00
|
|
|
|
from rest_framework.viewsets import GenericViewSet
|
|
|
|
|
from rest_framework.decorators import action
|
|
|
|
|
from rest_framework.exceptions import PermissionDenied
|
2021-06-09 02:39:03 +00:00
|
|
|
|
from rest_framework import serializers
|
2021-02-23 06:37:42 +00:00
|
|
|
|
|
2021-09-24 07:31:25 +00:00
|
|
|
|
from applications.models import Application
|
2022-02-16 07:48:28 +00:00
|
|
|
|
from authentication.signals import post_auth_failed
|
2021-02-23 06:37:42 +00:00
|
|
|
|
from common.utils import get_logger, random_string
|
2021-10-21 10:34:12 +00:00
|
|
|
|
from common.mixins.api import SerializerMixin
|
2021-09-24 07:31:25 +00:00
|
|
|
|
from common.utils.common import get_file_by_arch
|
2019-08-21 12:27:21 +00:00
|
|
|
|
from orgs.mixins.api import RootOrgViewMixin
|
2021-08-03 02:57:57 +00:00
|
|
|
|
from common.http import is_true
|
2021-12-22 09:35:32 +00:00
|
|
|
|
from perms.models.base import Action
|
2022-02-16 07:48:28 +00:00
|
|
|
|
from perms.utils.application.permission import get_application_actions
|
|
|
|
|
from perms.utils.asset.permission import get_asset_actions
|
2022-03-30 03:08:50 +00:00
|
|
|
|
from common.const.http import PATCH
|
2022-04-12 09:45:10 +00:00
|
|
|
|
from terminal.models import EndpointRule
|
2021-02-24 07:31:22 +00:00
|
|
|
|
from ..serializers import (
|
|
|
|
|
ConnectionTokenSerializer, ConnectionTokenSecretSerializer,
|
|
|
|
|
)
|
2019-02-27 12:55:28 +00:00
|
|
|
|
|
|
|
|
|
logger = get_logger(__name__)
|
2022-04-12 09:45:10 +00:00
|
|
|
|
__all__ = ['UserConnectionTokenViewSet', 'TokenCacheMixin']
|
2019-02-27 12:55:28 +00:00
|
|
|
|
|
|
|
|
|
|
2021-08-02 08:18:34 +00:00
|
|
|
|
class ClientProtocolMixin:
|
2022-02-17 12:13:31 +00:00
|
|
|
|
"""
|
|
|
|
|
下载客户端支持的连接文件,里面包含了 token,和 其他连接信息
|
|
|
|
|
|
|
|
|
|
- [x] RDP
|
|
|
|
|
- [ ] KoKo
|
|
|
|
|
|
|
|
|
|
本质上,这里还是暴露出 token 来,进行使用
|
|
|
|
|
"""
|
2021-08-02 08:18:34 +00:00
|
|
|
|
request: Request
|
|
|
|
|
get_serializer: Callable
|
|
|
|
|
create_token: Callable
|
2022-04-12 09:45:10 +00:00
|
|
|
|
get_serializer_context: Callable
|
|
|
|
|
|
|
|
|
|
def get_smart_endpoint(self, protocol, asset=None, application=None):
|
|
|
|
|
if asset:
|
|
|
|
|
target_ip = asset.get_target_ip()
|
|
|
|
|
elif application:
|
|
|
|
|
target_ip = application.get_target_ip()
|
|
|
|
|
else:
|
|
|
|
|
target_ip = ''
|
|
|
|
|
endpoint = EndpointRule.match_endpoint(target_ip, protocol, self.request)
|
|
|
|
|
return endpoint
|
2021-02-23 06:37:42 +00:00
|
|
|
|
|
2021-08-02 08:18:34 +00:00
|
|
|
|
def get_request_resource(self, serializer):
|
|
|
|
|
asset = serializer.validated_data.get('asset')
|
|
|
|
|
application = serializer.validated_data.get('application')
|
|
|
|
|
system_user = serializer.validated_data['system_user']
|
2021-02-23 06:37:42 +00:00
|
|
|
|
|
2021-08-02 08:18:34 +00:00
|
|
|
|
user = serializer.validated_data.get('user')
|
2022-04-20 02:24:08 +00:00
|
|
|
|
if not user or not self.request.user.is_superuser:
|
|
|
|
|
user = self.request.user
|
2021-08-02 08:18:34 +00:00
|
|
|
|
return asset, application, system_user, user
|
2021-01-21 05:50:29 +00:00
|
|
|
|
|
2021-11-09 09:10:29 +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
|
|
|
|
|
|
2021-08-02 08:18:34 +00:00
|
|
|
|
def get_rdp_file_content(self, serializer):
|
2021-02-24 07:31:22 +00:00
|
|
|
|
options = {
|
|
|
|
|
'full address:s': '',
|
|
|
|
|
'username:s': '',
|
2021-08-03 02:57:57 +00:00
|
|
|
|
# 'screen mode id:i': '1',
|
2021-06-08 04:45:36 +00:00
|
|
|
|
# 'desktopwidth:i': '1280',
|
|
|
|
|
# 'desktopheight:i': '800',
|
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-09-07 10:39:36 +00:00
|
|
|
|
#'drivestoredirect:s': '*',
|
2021-06-09 02:39:03 +00:00
|
|
|
|
# 'domain:s': ''
|
2021-02-24 07:31:22 +00:00
|
|
|
|
# 'alternate shell:s:': '||MySQLWorkbench',
|
|
|
|
|
# 'remoteapplicationname:s': 'Firefox',
|
|
|
|
|
# 'remoteapplicationcmdline:s': '',
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-02 08:18:34 +00:00
|
|
|
|
asset, application, system_user, user = self.get_request_resource(serializer)
|
|
|
|
|
height = self.request.query_params.get('height')
|
|
|
|
|
width = self.request.query_params.get('width')
|
2021-08-03 02:57:57 +00:00
|
|
|
|
full_screen = is_true(self.request.query_params.get('full_screen'))
|
2021-09-09 08:19:39 +00:00
|
|
|
|
drives_redirect = is_true(self.request.query_params.get('drives_redirect'))
|
2022-02-28 11:28:58 +00:00
|
|
|
|
token, secret = self.create_token(user, asset, application, system_user)
|
2021-02-24 07:31:22 +00:00
|
|
|
|
|
2021-11-16 03:32:25 +00:00
|
|
|
|
# 设置磁盘挂载
|
2022-02-16 07:48:28 +00:00
|
|
|
|
if drives_redirect:
|
|
|
|
|
actions = 0
|
|
|
|
|
if asset:
|
|
|
|
|
actions = get_asset_actions(user, asset, system_user)
|
|
|
|
|
elif application:
|
|
|
|
|
actions = get_application_actions(user, application, system_user)
|
|
|
|
|
|
|
|
|
|
if actions & Action.UPDOWNLOAD == Action.UPDOWNLOAD:
|
2021-10-07 07:30:39 +00:00
|
|
|
|
options['drivestoredirect:s'] = '*'
|
|
|
|
|
|
2021-11-16 03:32:25 +00:00
|
|
|
|
# 全屏
|
2021-08-03 02:57:57 +00:00
|
|
|
|
options['screen mode id:i'] = '2' if full_screen else '1'
|
2021-11-16 03:32:25 +00:00
|
|
|
|
|
|
|
|
|
# RDP Server 地址
|
2022-04-12 09:45:10 +00:00
|
|
|
|
endpoint = self.get_smart_endpoint(
|
|
|
|
|
protocol='rdp', asset=asset, application=application
|
|
|
|
|
)
|
|
|
|
|
options['full address:s'] = f'{endpoint.host}:{endpoint.rdp_port}'
|
2021-11-16 03:32:25 +00:00
|
|
|
|
# 用户名
|
2021-04-20 03:27:02 +00:00
|
|
|
|
options['username:s'] = '{}|{}'.format(user.username, token)
|
2021-06-09 02:39:03 +00:00
|
|
|
|
if system_user.ad_domain:
|
|
|
|
|
options['domain:s'] = system_user.ad_domain
|
2021-11-16 03:32:25 +00:00
|
|
|
|
# 宽高
|
2021-06-08 04:45:36 +00:00
|
|
|
|
if width and height:
|
|
|
|
|
options['desktopwidth:i'] = width
|
|
|
|
|
options['desktopheight:i'] = height
|
2022-03-25 02:43:48 +00:00
|
|
|
|
options['winposstr:s:'] = f'0,1,0,0,{width},{height}'
|
2021-11-09 09:10:29 +00:00
|
|
|
|
|
|
|
|
|
options['session bpp:i'] = os.getenv('JUMPSERVER_COLOR_DEPTH', '32')
|
|
|
|
|
options['audiomode:i'] = self.parse_env_bool('JUMPSERVER_DISABLE_AUDIO', 'false', '2', '0')
|
|
|
|
|
|
2021-06-17 05:20:34 +00:00
|
|
|
|
if asset:
|
|
|
|
|
name = asset.hostname
|
|
|
|
|
elif application:
|
|
|
|
|
name = application.name
|
2021-09-24 07:31:25 +00:00
|
|
|
|
application.get_rdp_remote_app_setting()
|
|
|
|
|
|
|
|
|
|
app = f'||jmservisor'
|
|
|
|
|
options['remoteapplicationmode:i'] = '1'
|
|
|
|
|
options['alternate shell:s'] = app
|
|
|
|
|
options['remoteapplicationprogram:s'] = app
|
|
|
|
|
options['remoteapplicationname:s'] = name
|
|
|
|
|
options['remoteapplicationcmdline:s'] = '- ' + self.get_encrypt_cmdline(application)
|
2021-06-17 05:20:34 +00:00
|
|
|
|
else:
|
|
|
|
|
name = '*'
|
2021-09-24 07:31:25 +00:00
|
|
|
|
|
|
|
|
|
content = ''
|
|
|
|
|
for k, v in options.items():
|
|
|
|
|
content += f'{k}:{v}\n'
|
2021-07-27 05:35:25 +00:00
|
|
|
|
return name, content
|
|
|
|
|
|
2022-03-28 11:52:48 +00:00
|
|
|
|
def get_ssh_token(self, serializer):
|
|
|
|
|
asset, application, system_user, user = self.get_request_resource(serializer)
|
|
|
|
|
token, secret = self.create_token(user, asset, application, system_user)
|
|
|
|
|
if asset:
|
|
|
|
|
name = asset.hostname
|
|
|
|
|
elif application:
|
|
|
|
|
name = application.name
|
|
|
|
|
else:
|
|
|
|
|
name = '*'
|
|
|
|
|
|
2022-04-12 09:45:10 +00:00
|
|
|
|
endpoint = self.get_smart_endpoint(
|
|
|
|
|
protocol='ssh', asset=asset, application=application
|
|
|
|
|
)
|
2022-03-28 11:52:48 +00:00
|
|
|
|
content = {
|
2022-04-12 09:45:10 +00:00
|
|
|
|
'ip': endpoint.host,
|
2022-04-13 11:48:31 +00:00
|
|
|
|
'port': str(endpoint.ssh_port),
|
2022-03-28 11:52:48 +00:00
|
|
|
|
'username': f'JMS-{token}',
|
|
|
|
|
'password': secret
|
|
|
|
|
}
|
|
|
|
|
token = json.dumps(content)
|
|
|
|
|
return name, token
|
|
|
|
|
|
2021-09-24 07:31:25 +00:00
|
|
|
|
def get_encrypt_cmdline(self, app: Application):
|
|
|
|
|
parameters = app.get_rdp_remote_app_setting()['parameters']
|
|
|
|
|
parameters = parameters.encode('ascii')
|
|
|
|
|
|
|
|
|
|
lib_path = get_file_by_arch('xpack/libs', 'librailencrypt.so')
|
|
|
|
|
lib = ctypes.CDLL(lib_path)
|
|
|
|
|
lib.encrypt.argtypes = [ctypes.c_char_p, ctypes.c_int]
|
|
|
|
|
lib.encrypt.restype = ctypes.c_char_p
|
|
|
|
|
|
|
|
|
|
rst = lib.encrypt(parameters, len(parameters))
|
|
|
|
|
rst = rst.decode('ascii')
|
|
|
|
|
return rst
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
@action(methods=['POST', 'GET'], detail=False, url_path='rdp/file')
|
2021-07-27 05:35:25 +00:00
|
|
|
|
def get_rdp_file(self, request, *args, **kwargs):
|
2021-08-02 08:18:34 +00:00
|
|
|
|
if self.request.method == 'GET':
|
|
|
|
|
data = self.request.query_params
|
|
|
|
|
else:
|
|
|
|
|
data = self.request.data
|
|
|
|
|
serializer = self.get_serializer(data=data)
|
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
|
name, data = self.get_rdp_file_content(serializer)
|
2021-04-20 03:27:02 +00:00
|
|
|
|
response = HttpResponse(data, content_type='application/octet-stream')
|
2021-07-27 05:35:25 +00:00
|
|
|
|
filename = "{}-{}-jumpserver.rdp".format(self.request.user.username, name)
|
2021-04-20 08:17:18 +00:00
|
|
|
|
filename = urllib.parse.quote(filename)
|
|
|
|
|
response['Content-Disposition'] = 'attachment; filename*=UTF-8\'\'%s' % filename
|
2021-02-24 07:31:22 +00:00
|
|
|
|
return response
|
|
|
|
|
|
2021-08-02 08:18:34 +00:00
|
|
|
|
def get_valid_serializer(self):
|
|
|
|
|
if self.request.method == 'GET':
|
|
|
|
|
data = self.request.query_params
|
|
|
|
|
else:
|
|
|
|
|
data = self.request.data
|
|
|
|
|
serializer = self.get_serializer(data=data)
|
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
|
return serializer
|
|
|
|
|
|
|
|
|
|
def get_client_protocol_data(self, serializer):
|
|
|
|
|
asset, application, system_user, user = self.get_request_resource(serializer)
|
|
|
|
|
protocol = system_user.protocol
|
2021-10-21 11:12:02 +00:00
|
|
|
|
username = user.username
|
2022-03-28 11:52:48 +00:00
|
|
|
|
config, token = '', ''
|
2021-08-02 08:18:34 +00:00
|
|
|
|
if protocol == 'rdp':
|
|
|
|
|
name, config = self.get_rdp_file_content(serializer)
|
2021-11-16 03:32:25 +00:00
|
|
|
|
elif protocol == 'ssh':
|
2022-03-28 11:52:48 +00:00
|
|
|
|
name, token = self.get_ssh_token(serializer)
|
2021-11-16 03:32:25 +00:00
|
|
|
|
else:
|
|
|
|
|
raise ValueError('Protocol not support: {}'.format(protocol))
|
|
|
|
|
|
2021-10-21 11:12:02 +00:00
|
|
|
|
filename = "{}-{}-jumpserver".format(username, name)
|
2021-08-02 08:18:34 +00:00
|
|
|
|
data = {
|
2021-10-21 11:12:02 +00:00
|
|
|
|
"filename": filename,
|
2021-08-02 08:18:34 +00:00
|
|
|
|
"protocol": system_user.protocol,
|
2021-10-21 11:12:02 +00:00
|
|
|
|
"username": username,
|
2022-03-28 11:52:48 +00:00
|
|
|
|
"token": token,
|
2021-08-02 08:18:34 +00:00
|
|
|
|
"config": config
|
|
|
|
|
}
|
|
|
|
|
return data
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
@action(methods=['POST', 'GET'], detail=False, url_path='client-url')
|
2021-08-02 08:18:34 +00:00
|
|
|
|
def get_client_protocol_url(self, request, *args, **kwargs):
|
|
|
|
|
serializer = self.get_valid_serializer()
|
2021-11-16 03:32:25 +00:00
|
|
|
|
try:
|
|
|
|
|
protocol_data = self.get_client_protocol_data(serializer)
|
|
|
|
|
except ValueError as e:
|
|
|
|
|
return Response({'error': str(e)}, status=401)
|
|
|
|
|
|
|
|
|
|
protocol_data = json.dumps(protocol_data).encode()
|
|
|
|
|
protocol_data = base64.b64encode(protocol_data).decode()
|
2021-08-02 08:18:34 +00:00
|
|
|
|
data = {
|
|
|
|
|
'url': 'jms://{}'.format(protocol_data),
|
|
|
|
|
}
|
|
|
|
|
return Response(data=data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SecretDetailMixin:
|
|
|
|
|
valid_token: Callable
|
|
|
|
|
request: Request
|
|
|
|
|
get_serializer: Callable
|
2021-07-27 05:35:25 +00:00
|
|
|
|
|
2021-02-23 06:37:42 +00:00
|
|
|
|
@staticmethod
|
2021-06-09 02:39:03 +00:00
|
|
|
|
def _get_application_secret_detail(application):
|
2021-02-23 06:37:42 +00:00
|
|
|
|
gateway = None
|
2022-02-14 09:38:30 +00:00
|
|
|
|
remote_app = None
|
|
|
|
|
asset = None
|
2021-02-23 06:37:42 +00:00
|
|
|
|
|
2022-02-14 09:38:30 +00:00
|
|
|
|
if application.category_remote_app:
|
2021-02-23 06:37:42 +00:00
|
|
|
|
remote_app = application.get_rdp_remote_app_setting()
|
|
|
|
|
asset = application.get_remote_app_asset()
|
|
|
|
|
domain = asset.domain
|
2022-02-14 09:38:30 +00:00
|
|
|
|
else:
|
|
|
|
|
domain = application.domain
|
2021-02-23 06:37:42 +00:00
|
|
|
|
|
|
|
|
|
if domain and domain.has_gateway():
|
|
|
|
|
gateway = domain.random_gateway()
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
'asset': asset,
|
|
|
|
|
'application': application,
|
|
|
|
|
'gateway': gateway,
|
2022-02-18 03:24:57 +00:00
|
|
|
|
'domain': domain,
|
2021-02-23 06:37:42 +00:00
|
|
|
|
'remote_app': remote_app,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
2022-02-14 09:38:30 +00:00
|
|
|
|
def _get_asset_secret_detail(asset):
|
2021-02-23 06:37:42 +00:00
|
|
|
|
gateway = None
|
|
|
|
|
if asset and asset.domain and asset.domain.has_gateway():
|
|
|
|
|
gateway = asset.domain.random_gateway()
|
2021-06-09 02:39:03 +00:00
|
|
|
|
|
2021-02-23 06:37:42 +00:00
|
|
|
|
return {
|
|
|
|
|
'asset': asset,
|
|
|
|
|
'application': None,
|
2022-02-18 03:24:57 +00:00
|
|
|
|
'domain': asset.domain,
|
2021-02-23 06:37:42 +00:00
|
|
|
|
'gateway': gateway,
|
|
|
|
|
'remote_app': None,
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-17 12:13:31 +00:00
|
|
|
|
@action(methods=['POST'], detail=False, url_path='secret-info/detail')
|
2021-08-02 08:18:34 +00:00
|
|
|
|
def get_secret_detail(self, request, *args, **kwargs):
|
2022-02-17 12:13:31 +00:00
|
|
|
|
perm_required = 'authentication.view_connectiontokensecret'
|
|
|
|
|
|
|
|
|
|
# 非常重要的 api,再逻辑层再判断一下,双重保险
|
|
|
|
|
if not request.user.has_perm(perm_required):
|
|
|
|
|
raise PermissionDenied('Not allow to view secret')
|
|
|
|
|
|
2021-08-02 08:18:34 +00:00
|
|
|
|
token = request.data.get('token', '')
|
|
|
|
|
try:
|
2022-02-14 09:38:30 +00:00
|
|
|
|
value, user, system_user, asset, app, expired_at, actions = self.valid_token(token)
|
2021-08-02 08:18:34 +00:00
|
|
|
|
except serializers.ValidationError as e:
|
|
|
|
|
post_auth_failed.send(
|
|
|
|
|
sender=self.__class__, username='', request=self.request,
|
|
|
|
|
reason=_('Invalid token')
|
|
|
|
|
)
|
|
|
|
|
raise e
|
|
|
|
|
|
2022-02-14 09:38:30 +00:00
|
|
|
|
data = dict(
|
|
|
|
|
id=token, secret=value.get('secret', ''),
|
|
|
|
|
user=user, system_user=system_user,
|
|
|
|
|
expired_at=expired_at, actions=actions
|
|
|
|
|
)
|
2022-03-02 12:48:43 +00:00
|
|
|
|
cmd_filter_kwargs = {
|
|
|
|
|
'system_user_id': system_user.id,
|
|
|
|
|
'user_id': user.id,
|
|
|
|
|
}
|
2021-08-02 08:18:34 +00:00
|
|
|
|
if asset:
|
2022-02-14 09:38:30 +00:00
|
|
|
|
asset_detail = self._get_asset_secret_detail(asset)
|
2021-08-02 08:18:34 +00:00
|
|
|
|
system_user.load_asset_more_auth(asset.id, user.username, user.id)
|
|
|
|
|
data['type'] = 'asset'
|
|
|
|
|
data.update(asset_detail)
|
2022-03-02 12:48:43 +00:00
|
|
|
|
cmd_filter_kwargs['asset_id'] = asset.id
|
2021-08-02 08:18:34 +00:00
|
|
|
|
else:
|
|
|
|
|
app_detail = self._get_application_secret_detail(app)
|
2021-12-14 11:00:28 +00:00
|
|
|
|
system_user.load_app_more_auth(app.id, user.username, user.id)
|
2021-08-02 08:18:34 +00:00
|
|
|
|
data['type'] = 'application'
|
|
|
|
|
data.update(app_detail)
|
2022-03-02 12:48:43 +00:00
|
|
|
|
cmd_filter_kwargs['application_id'] = app.id
|
|
|
|
|
|
|
|
|
|
from assets.models import CommandFilterRule
|
|
|
|
|
cmd_filter_rules = CommandFilterRule.get_queryset(**cmd_filter_kwargs)
|
|
|
|
|
data['cmd_filter_rules'] = cmd_filter_rules
|
2021-08-02 08:18:34 +00:00
|
|
|
|
|
|
|
|
|
serializer = self.get_serializer(data)
|
|
|
|
|
return Response(data=serializer.data, status=200)
|
|
|
|
|
|
|
|
|
|
|
2022-03-30 03:08:50 +00:00
|
|
|
|
class TokenCacheMixin:
|
2022-04-12 09:45:10 +00:00
|
|
|
|
""" endpoint smart view 用到此类来解析token中的资产、应用 """
|
2022-03-30 03:08:50 +00:00
|
|
|
|
CACHE_KEY_PREFIX = 'CONNECTION_TOKEN_{}'
|
|
|
|
|
|
|
|
|
|
def get_token_cache_key(self, token):
|
|
|
|
|
return self.CACHE_KEY_PREFIX.format(token)
|
|
|
|
|
|
|
|
|
|
def get_token_ttl(self, token):
|
|
|
|
|
key = self.get_token_cache_key(token)
|
|
|
|
|
return cache.ttl(key)
|
|
|
|
|
|
|
|
|
|
def set_token_to_cache(self, token, value, ttl=5*60):
|
|
|
|
|
key = self.get_token_cache_key(token)
|
|
|
|
|
cache.set(key, value, timeout=ttl)
|
|
|
|
|
|
|
|
|
|
def get_token_from_cache(self, token):
|
|
|
|
|
key = self.get_token_cache_key(token)
|
|
|
|
|
value = cache.get(key, None)
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
def renewal_token(self, token, ttl=5*60):
|
|
|
|
|
value = self.get_token_from_cache(token)
|
|
|
|
|
if value:
|
|
|
|
|
pre_ttl = self.get_token_ttl(token)
|
|
|
|
|
self.set_token_to_cache(token, value, ttl)
|
|
|
|
|
post_ttl = self.get_token_ttl(token)
|
|
|
|
|
ok = True
|
|
|
|
|
msg = f'{pre_ttl}s is renewed to {post_ttl}s.'
|
|
|
|
|
else:
|
|
|
|
|
ok = False
|
|
|
|
|
msg = 'Token is not found.'
|
|
|
|
|
data = {
|
|
|
|
|
'ok': ok,
|
|
|
|
|
'msg': msg
|
|
|
|
|
}
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
|
|
2021-08-02 08:18:34 +00:00
|
|
|
|
class UserConnectionTokenViewSet(
|
|
|
|
|
RootOrgViewMixin, SerializerMixin, ClientProtocolMixin,
|
2022-03-30 03:08:50 +00:00
|
|
|
|
SecretDetailMixin, TokenCacheMixin, GenericViewSet
|
2021-08-02 08:18:34 +00:00
|
|
|
|
):
|
|
|
|
|
serializer_classes = {
|
|
|
|
|
'default': ConnectionTokenSerializer,
|
|
|
|
|
'get_secret_detail': ConnectionTokenSecretSerializer,
|
|
|
|
|
}
|
2022-02-17 12:13:31 +00:00
|
|
|
|
rbac_perms = {
|
2022-02-18 08:25:54 +00:00
|
|
|
|
'GET': 'authentication.view_connectiontoken',
|
|
|
|
|
'create': 'authentication.add_connectiontoken',
|
2022-03-30 03:08:50 +00:00
|
|
|
|
'renewal': 'authentication.add_superconnectiontoken',
|
2022-02-18 08:25:54 +00:00
|
|
|
|
'get_secret_detail': 'authentication.view_connectiontokensecret',
|
|
|
|
|
'get_rdp_file': 'authentication.add_connectiontoken',
|
|
|
|
|
'get_client_protocol_url': 'authentication.add_connectiontoken',
|
2022-02-17 12:13:31 +00:00
|
|
|
|
}
|
2021-08-02 08:18:34 +00:00
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def check_resource_permission(user, asset, application, system_user):
|
|
|
|
|
from perms.utils.asset import has_asset_system_permission
|
|
|
|
|
from perms.utils.application import has_application_system_permission
|
|
|
|
|
|
|
|
|
|
if asset and not has_asset_system_permission(user, asset, system_user):
|
|
|
|
|
error = f'User not has this asset and system user permission: ' \
|
|
|
|
|
f'user={user.id} system_user={system_user.id} asset={asset.id}'
|
|
|
|
|
raise PermissionDenied(error)
|
|
|
|
|
if application and not has_application_system_permission(user, application, system_user):
|
|
|
|
|
error = f'User not has this application and system user permission: ' \
|
|
|
|
|
f'user={user.id} system_user={system_user.id} application={application.id}'
|
|
|
|
|
raise PermissionDenied(error)
|
|
|
|
|
return True
|
|
|
|
|
|
2022-03-30 03:08:50 +00:00
|
|
|
|
@action(methods=[PATCH], detail=False)
|
|
|
|
|
def renewal(self, request, *args, **kwargs):
|
|
|
|
|
""" 续期 Token """
|
|
|
|
|
perm_required = 'authentication.add_superconnectiontoken'
|
|
|
|
|
if not request.user.has_perm(perm_required):
|
|
|
|
|
raise PermissionDenied('No permissions for authentication.add_superconnectiontoken')
|
|
|
|
|
token = request.data.get('token', '')
|
|
|
|
|
data = self.renewal_token(token)
|
|
|
|
|
status_code = 200 if data.get('ok') else 404
|
|
|
|
|
return Response(data=data, status=status_code)
|
|
|
|
|
|
|
|
|
|
def create_token(self, user, asset, application, system_user, ttl=5*60):
|
2022-03-02 12:48:43 +00:00
|
|
|
|
# 再次强调一下权限
|
|
|
|
|
perm_required = 'authentication.add_superconnectiontoken'
|
|
|
|
|
if user != self.request.user and not self.request.user.has_perm(perm_required):
|
|
|
|
|
raise PermissionDenied('Only can create user token')
|
2021-08-02 08:18:34 +00:00
|
|
|
|
self.check_resource_permission(user, asset, application, system_user)
|
|
|
|
|
token = random_string(36)
|
2022-02-14 09:38:30 +00:00
|
|
|
|
secret = random_string(16)
|
2021-08-02 08:18:34 +00:00
|
|
|
|
value = {
|
2022-02-14 09:38:30 +00:00
|
|
|
|
'id': token,
|
|
|
|
|
'secret': secret,
|
2021-08-02 08:18:34 +00:00
|
|
|
|
'user': str(user.id),
|
|
|
|
|
'username': user.username,
|
|
|
|
|
'system_user': str(system_user.id),
|
2022-02-14 09:38:30 +00:00
|
|
|
|
'system_user_name': system_user.name,
|
|
|
|
|
'created_by': str(self.request.user),
|
|
|
|
|
'date_created': str(timezone.now())
|
2021-08-02 08:18:34 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if asset:
|
|
|
|
|
value.update({
|
|
|
|
|
'type': 'asset',
|
|
|
|
|
'asset': str(asset.id),
|
|
|
|
|
'hostname': asset.hostname,
|
|
|
|
|
})
|
|
|
|
|
elif application:
|
|
|
|
|
value.update({
|
|
|
|
|
'type': 'application',
|
|
|
|
|
'application': application.id,
|
|
|
|
|
'application_name': str(application)
|
|
|
|
|
})
|
|
|
|
|
|
2022-03-30 03:08:50 +00:00
|
|
|
|
self.set_token_to_cache(token, value, ttl)
|
2022-02-28 11:28:58 +00:00
|
|
|
|
return token, secret
|
2021-08-02 08:18:34 +00:00
|
|
|
|
|
|
|
|
|
def create(self, request, *args, **kwargs):
|
|
|
|
|
serializer = self.get_serializer(data=request.data)
|
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
|
|
|
|
|
|
asset, application, system_user, user = self.get_request_resource(serializer)
|
2022-02-28 11:28:58 +00:00
|
|
|
|
token, secret = self.create_token(user, asset, application, system_user)
|
2022-03-07 03:19:03 +00:00
|
|
|
|
tp = 'app' if application else 'asset'
|
|
|
|
|
data = {
|
|
|
|
|
"id": token, 'secret': secret,
|
2022-04-15 08:24:17 +00:00
|
|
|
|
'type': tp, 'protocol': system_user.protocol,
|
|
|
|
|
'expire_time': self.get_token_ttl(token),
|
2022-03-07 03:19:03 +00:00
|
|
|
|
}
|
|
|
|
|
return Response(data, status=201)
|
2021-08-02 08:18:34 +00:00
|
|
|
|
|
2021-06-09 02:39:03 +00:00
|
|
|
|
def valid_token(self, token):
|
2021-02-23 06:37:42 +00:00
|
|
|
|
from users.models import User
|
2021-06-09 02:39:03 +00:00
|
|
|
|
from assets.models import SystemUser, Asset
|
|
|
|
|
from applications.models import Application
|
2021-07-05 08:20:42 +00:00
|
|
|
|
from perms.utils.asset.permission import validate_permission as asset_validate_permission
|
|
|
|
|
from perms.utils.application.permission import validate_permission as app_validate_permission
|
2021-02-23 06:37:42 +00:00
|
|
|
|
|
2022-03-30 03:08:50 +00:00
|
|
|
|
value = self.get_token_from_cache(token)
|
2021-02-23 06:37:42 +00:00
|
|
|
|
if not value:
|
2021-06-09 02:39:03 +00:00
|
|
|
|
raise serializers.ValidationError('Token not found')
|
|
|
|
|
|
2021-02-23 06:37:42 +00:00
|
|
|
|
user = get_object_or_404(User, id=value.get('user'))
|
2021-06-09 07:46:32 +00:00
|
|
|
|
if not user.is_valid:
|
2021-06-09 02:39:03 +00:00
|
|
|
|
raise serializers.ValidationError("User not valid, disabled or expired")
|
|
|
|
|
|
2021-02-23 06:37:42 +00:00
|
|
|
|
system_user = get_object_or_404(SystemUser, id=value.get('system_user'))
|
2021-06-09 02:39:03 +00:00
|
|
|
|
asset = None
|
|
|
|
|
app = None
|
2021-02-23 06:37:42 +00:00
|
|
|
|
if value.get('type') == 'asset':
|
2021-06-09 02:39:03 +00:00
|
|
|
|
asset = get_object_or_404(Asset, id=value.get('asset'))
|
2021-07-05 08:20:42 +00:00
|
|
|
|
if not asset.is_active:
|
|
|
|
|
raise serializers.ValidationError("Asset disabled")
|
2021-12-22 09:35:32 +00:00
|
|
|
|
has_perm, actions, expired_at = asset_validate_permission(user, asset, system_user)
|
2021-06-09 02:39:03 +00:00
|
|
|
|
else:
|
|
|
|
|
app = get_object_or_404(Application, id=value.get('application'))
|
2021-12-22 09:35:32 +00:00
|
|
|
|
has_perm, actions, expired_at = app_validate_permission(user, app, system_user)
|
2021-06-09 02:39:03 +00:00
|
|
|
|
|
2021-07-05 08:20:42 +00:00
|
|
|
|
if not has_perm:
|
2021-06-10 11:45:03 +00:00
|
|
|
|
raise serializers.ValidationError('Permission expired or invalid')
|
2022-02-14 09:38:30 +00:00
|
|
|
|
return value, user, system_user, asset, app, expired_at, actions
|
2021-06-09 02:39:03 +00:00
|
|
|
|
|
2019-02-27 12:55:28 +00:00
|
|
|
|
def get(self, request):
|
|
|
|
|
token = request.query_params.get('token')
|
2022-03-30 03:08:50 +00:00
|
|
|
|
value = self.get_token_from_cache(token)
|
2019-02-27 12:55:28 +00:00
|
|
|
|
if not value:
|
|
|
|
|
return Response('', status=404)
|
2021-01-21 05:50:29 +00:00
|
|
|
|
return Response(value)
|