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
|
2021-07-27 05:35:25 +00:00
|
|
|
import base64
|
2021-08-02 08:18:34 +00:00
|
|
|
from typing import Callable
|
2021-11-09 09:10:29 +00:00
|
|
|
import os
|
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
|
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-06-10 10:02:55 +00:00
|
|
|
from authentication.signals import post_auth_failed, post_auth_success
|
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-02-23 06:37:42 +00:00
|
|
|
from common.permissions import IsSuperUserOrAppUser, IsValidUser, IsSuperUser
|
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-10-07 07:30:39 +00:00
|
|
|
from perms.utils.asset.permission import get_asset_system_user_ids_with_actions_by_user
|
|
|
|
from perms.models.asset_permission import Action
|
|
|
|
from authentication.errors import NotHaveUpDownLoadPerm
|
2021-01-21 05:50:29 +00:00
|
|
|
|
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__)
|
2021-02-23 06:37:42 +00:00
|
|
|
__all__ = ['UserConnectionTokenViewSet']
|
2019-02-27 12:55:28 +00:00
|
|
|
|
|
|
|
|
2021-08-02 08:18:34 +00:00
|
|
|
class ClientProtocolMixin:
|
|
|
|
request: Request
|
|
|
|
get_serializer: Callable
|
|
|
|
create_token: Callable
|
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')
|
|
|
|
if not user or not self.request.user.is_superuser:
|
|
|
|
user = self.request.user
|
|
|
|
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',
|
2021-06-09 02:39:03 +00:00
|
|
|
'smart sizing:i': '0',
|
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'))
|
2021-02-24 07:31:22 +00:00
|
|
|
token = self.create_token(user, asset, application, system_user)
|
|
|
|
|
2021-10-07 07:30:39 +00:00
|
|
|
if drives_redirect and asset:
|
|
|
|
systemuser_actions_mapper = get_asset_system_user_ids_with_actions_by_user(user, asset)
|
|
|
|
actions = systemuser_actions_mapper.get(system_user.id, [])
|
|
|
|
if actions & Action.UPDOWNLOAD:
|
|
|
|
options['drivestoredirect:s'] = '*'
|
|
|
|
else:
|
|
|
|
raise NotHaveUpDownLoadPerm
|
|
|
|
|
2021-08-03 02:57:57 +00:00
|
|
|
options['screen mode id:i'] = '2' if full_screen else '1'
|
2021-06-08 07:23:40 +00:00
|
|
|
address = settings.TERMINAL_RDP_ADDR
|
|
|
|
if not address or address == 'localhost:3389':
|
2021-08-02 08:18:34 +00:00
|
|
|
address = self.request.get_host().split(':')[0] + ':3389'
|
2021-02-24 07:31:22 +00:00
|
|
|
options['full address:s'] = address
|
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-06-08 04:45:36 +00:00
|
|
|
if width and height:
|
|
|
|
options['desktopwidth:i'] = width
|
|
|
|
options['desktopheight:i'] = height
|
|
|
|
else:
|
|
|
|
options['smart sizing:i'] = '1'
|
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-07-27 05:35:25 +00:00
|
|
|
content = ''
|
2021-02-24 07:31:22 +00:00
|
|
|
for k, v in options.items():
|
2021-07-27 05:35:25 +00:00
|
|
|
content += f'{k}:{v}\n'
|
2021-06-17 05:20:34 +00:00
|
|
|
if asset:
|
|
|
|
name = asset.hostname
|
|
|
|
elif application:
|
|
|
|
name = application.name
|
|
|
|
else:
|
|
|
|
name = '*'
|
2021-07-27 05:35:25 +00:00
|
|
|
return name, content
|
|
|
|
|
|
|
|
@action(methods=['POST', 'GET'], detail=False, url_path='rdp/file', permission_classes=[IsValidUser])
|
|
|
|
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
|
|
|
|
name = ''
|
2021-08-02 08:18:34 +00:00
|
|
|
if protocol == 'rdp':
|
|
|
|
name, config = self.get_rdp_file_content(serializer)
|
|
|
|
elif protocol == 'vnc':
|
|
|
|
raise HttpResponse(status=404, data={"error": "VNC not support"})
|
|
|
|
else:
|
|
|
|
config = 'ssh://system_user@asset@user@jumpserver-ssh'
|
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,
|
2021-08-02 08:18:34 +00:00
|
|
|
"config": config
|
|
|
|
}
|
|
|
|
return data
|
|
|
|
|
|
|
|
@action(methods=['POST', 'GET'], detail=False, url_path='client-url', permission_classes=[IsValidUser])
|
|
|
|
def get_client_protocol_url(self, request, *args, **kwargs):
|
|
|
|
serializer = self.get_valid_serializer()
|
|
|
|
protocol_data = self.get_client_protocol_data(serializer)
|
|
|
|
protocol_data = base64.b64encode(json.dumps(protocol_data).encode()).decode()
|
|
|
|
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
|
|
|
from perms.models import Action
|
|
|
|
gateway = None
|
|
|
|
|
|
|
|
if not application.category_remote_app:
|
|
|
|
actions = Action.NONE
|
|
|
|
remote_app = {}
|
|
|
|
asset = None
|
|
|
|
domain = application.domain
|
|
|
|
else:
|
|
|
|
remote_app = application.get_rdp_remote_app_setting()
|
|
|
|
actions = Action.CONNECT
|
|
|
|
asset = application.get_remote_app_asset()
|
|
|
|
domain = asset.domain
|
|
|
|
|
|
|
|
if domain and domain.has_gateway():
|
|
|
|
gateway = domain.random_gateway()
|
|
|
|
|
|
|
|
return {
|
|
|
|
'asset': asset,
|
|
|
|
'application': application,
|
|
|
|
'gateway': gateway,
|
|
|
|
'remote_app': remote_app,
|
|
|
|
'actions': actions
|
|
|
|
}
|
|
|
|
|
|
|
|
@staticmethod
|
2021-06-09 02:39:03 +00:00
|
|
|
def _get_asset_secret_detail(asset, user, system_user):
|
2021-03-08 02:08:51 +00:00
|
|
|
from perms.utils.asset import get_asset_system_user_ids_with_actions_by_user
|
|
|
|
systemuserid_actions_mapper = get_asset_system_user_ids_with_actions_by_user(user, asset)
|
2021-02-23 06:37:42 +00:00
|
|
|
actions = systemuserid_actions_mapper.get(system_user.id, [])
|
2021-06-09 02:39:03 +00:00
|
|
|
|
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,
|
|
|
|
'gateway': gateway,
|
|
|
|
'remote_app': None,
|
|
|
|
'actions': actions,
|
|
|
|
}
|
|
|
|
|
2021-08-02 08:18:34 +00:00
|
|
|
@action(methods=['POST'], detail=False, permission_classes=[IsSuperUserOrAppUser], url_path='secret-info/detail')
|
|
|
|
def get_secret_detail(self, request, *args, **kwargs):
|
|
|
|
token = request.data.get('token', '')
|
|
|
|
try:
|
|
|
|
value, user, system_user, asset, app, expired_at = self.valid_token(token)
|
|
|
|
except serializers.ValidationError as e:
|
|
|
|
post_auth_failed.send(
|
|
|
|
sender=self.__class__, username='', request=self.request,
|
|
|
|
reason=_('Invalid token')
|
|
|
|
)
|
|
|
|
raise e
|
|
|
|
|
|
|
|
data = dict(user=user, system_user=system_user, expired_at=expired_at)
|
|
|
|
if asset:
|
|
|
|
asset_detail = self._get_asset_secret_detail(asset, user=user, system_user=system_user)
|
|
|
|
system_user.load_asset_more_auth(asset.id, user.username, user.id)
|
|
|
|
data['type'] = 'asset'
|
|
|
|
data.update(asset_detail)
|
|
|
|
else:
|
|
|
|
app_detail = self._get_application_secret_detail(app)
|
|
|
|
system_user.load_app_more_auth(app.id, user.id)
|
|
|
|
data['type'] = 'application'
|
|
|
|
data.update(app_detail)
|
|
|
|
|
|
|
|
self.request.session['auth_backend'] = settings.AUTH_BACKEND_AUTH_TOKEN
|
|
|
|
post_auth_success.send(sender=self.__class__, user=user, request=self.request, login_type='T')
|
|
|
|
|
|
|
|
serializer = self.get_serializer(data)
|
|
|
|
return Response(data=serializer.data, status=200)
|
|
|
|
|
|
|
|
|
|
|
|
class UserConnectionTokenViewSet(
|
|
|
|
RootOrgViewMixin, SerializerMixin, ClientProtocolMixin,
|
|
|
|
SecretDetailMixin, GenericViewSet
|
|
|
|
):
|
|
|
|
permission_classes = (IsSuperUserOrAppUser,)
|
|
|
|
serializer_classes = {
|
|
|
|
'default': ConnectionTokenSerializer,
|
|
|
|
'get_secret_detail': ConnectionTokenSecretSerializer,
|
|
|
|
}
|
|
|
|
CACHE_KEY_PREFIX = 'CONNECTION_TOKEN_{}'
|
|
|
|
|
|
|
|
@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
|
|
|
|
|
|
|
|
def create_token(self, user, asset, application, system_user, ttl=5 * 60):
|
|
|
|
if not self.request.user.is_superuser and user != self.request.user:
|
|
|
|
raise PermissionDenied('Only super user can create user token')
|
|
|
|
self.check_resource_permission(user, asset, application, system_user)
|
|
|
|
token = random_string(36)
|
|
|
|
value = {
|
|
|
|
'user': str(user.id),
|
|
|
|
'username': user.username,
|
|
|
|
'system_user': str(system_user.id),
|
|
|
|
'system_user_name': system_user.name
|
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
|
|
|
})
|
|
|
|
|
|
|
|
key = self.CACHE_KEY_PREFIX.format(token)
|
|
|
|
cache.set(key, value, timeout=ttl)
|
|
|
|
return token
|
|
|
|
|
|
|
|
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)
|
|
|
|
token = self.create_token(user, asset, application, system_user)
|
|
|
|
return Response({"token": token}, status=201)
|
|
|
|
|
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
|
|
|
|
|
|
|
key = self.CACHE_KEY_PREFIX.format(token)
|
|
|
|
value = cache.get(key, None)
|
|
|
|
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")
|
|
|
|
|
|
|
|
has_perm, expired_at = asset_validate_permission(user, asset, system_user, 'connect')
|
2021-06-09 02:39:03 +00:00
|
|
|
else:
|
|
|
|
app = get_object_or_404(Application, id=value.get('application'))
|
2021-07-05 08:20:42 +00:00
|
|
|
has_perm, 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')
|
2021-07-05 08:20:42 +00:00
|
|
|
return value, user, system_user, asset, app, expired_at
|
2021-06-09 02:39:03 +00:00
|
|
|
|
2021-02-23 06:37:42 +00:00
|
|
|
def get_permissions(self):
|
2021-02-24 07:31:22 +00:00
|
|
|
if self.action in ["create", "get_rdp_file"]:
|
2021-02-23 06:37:42 +00:00
|
|
|
if self.request.data.get('user', None):
|
|
|
|
self.permission_classes = (IsSuperUser,)
|
|
|
|
else:
|
|
|
|
self.permission_classes = (IsValidUser,)
|
|
|
|
return super().get_permissions()
|
|
|
|
|
2019-02-27 12:55:28 +00:00
|
|
|
def get(self, request):
|
|
|
|
token = request.query_params.get('token')
|
2021-02-23 06:37:42 +00:00
|
|
|
key = self.CACHE_KEY_PREFIX.format(token)
|
|
|
|
value = cache.get(key, None)
|
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)
|