Changed OS Detection system

This commit is contained in:
Adolfo Gómez García 2022-02-15 14:45:11 +01:00
parent ccd429454e
commit 18d4147d59
16 changed files with 89 additions and 83 deletions

View File

@ -126,7 +126,7 @@ class Transports(ModelHandler):
'value': [], 'value': [],
'values': sorted( 'values': sorted(
[ [
{'id': x, 'text': x.replace('CrOS', 'Chrome OS')} {'id': x.value[0], 'text': x.value[0].replace('CrOS', 'Chrome OS')}
for x in OsDetector.knownOss for x in OsDetector.knownOss
], ],
key=lambda x: x['text'].lower(), key=lambda x: x['text'].lower(),

View File

@ -229,7 +229,7 @@ def __registerUser(
events.addEvent( events.addEvent(
authenticator, authenticator,
events.ET_PLATFORM, events.ET_PLATFORM,
platform=request.os['OS'], platform=request.os['OS'].value[0],
browser=request.os['Browser'], browser=request.os['Browser'],
version=request.os['Version'], version=request.os['Version'],
) )
@ -383,7 +383,7 @@ def webLogin(
user.name, user.name,
password, password,
get_language() or '', get_language() or '',
request.os['OS'], request.os['OS'].value[0],
user.is_admin, user.is_admin,
user.staff_member, user.staff_member,
cookie, cookie,
@ -460,7 +460,7 @@ def authLogLogin(
authenticator.name, authenticator.name,
userName, userName,
request.ip, request.ip,
request.os['OS'], request.os['OS'].value[0],
logStr, logStr,
request.META.get('HTTP_USER_AGENT', 'Undefined'), request.META.get('HTTP_USER_AGENT', 'Undefined'),
] ]
@ -471,7 +471,7 @@ def authLogLogin(
authenticator, authenticator,
level, level,
'user {} has {} from {} where os is {}'.format( 'user {} has {} from {} where os is {}'.format(
userName, logStr, request.ip, request.os['OS'] userName, logStr, request.ip, request.os['OS'].value[0]
), ),
log.WEB, log.WEB,
) )
@ -481,7 +481,7 @@ def authLogLogin(
log.doLog( log.doLog(
user, user,
level, level,
'{} from {} where OS is {}'.format(logStr, request.ip, request.os['OS']), '{} from {} where OS is {}'.format(logStr, request.ip, request.os['OS'].value[0]),
log.WEB, log.WEB,
) )
except Exception: except Exception:

View File

@ -152,12 +152,12 @@ class Transport(Module):
return False return False
@classmethod @classmethod
def supportsOs(cls, osName: str) -> bool: def supportsOs(cls, osType: OsDetector.KnownOS) -> bool:
""" """
Helper method to check if transport supports requested operating system. Helper method to check if transport supports requested operating system.
Class method Class method
""" """
return cls.supportedOss.count(osName) > 0 return cls.supportedOss.count(osType) > 0
@classmethod @classmethod
def providesConnetionInfo(cls) -> bool: def providesConnetionInfo(cls) -> bool:

View File

@ -30,44 +30,47 @@
""" """
@author: Adolfo Gómez, dkmaster at dkmon dot com @author: Adolfo Gómez, dkmaster at dkmon dot com
""" """
import enum
import re import re
import logging import logging
import typing import typing
from sympy import Li
from .tools import DictAsObj from .tools import DictAsObj
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Knowns OSs class KnownOS(enum.Enum):
Linux = 'Linux' Linux = ('Linux', 'armv7l')
ChromeOS = 'CrOS' ChromeOS = ('CrOS',)
WindowsPhone = 'Windows Phone' WindowsPhone = ('Windows Phone',)
Windows = 'Windows' Windows = ('Windows',)
Macintosh = 'Mac' Macintosh = ('Mac',)
Android = 'Android' Android = ('Android',)
iPad = 'iPad' # iPad = ('iPad',) #
iPhone = 'iPhone' # In fact, these are IOS both, but we can diferentiate it... iPhone = ('iPhone',) # In fact, these are IOS both, but we can diferentiate it...
WYSE = 'WYSE' WYSE = ('WYSE',)
Unknown = 'Unknown' Unknown = ('Unknown',)
knownOss = ( knownOss = (
WindowsPhone, KnownOS.WindowsPhone,
Android, KnownOS.Android,
Linux, KnownOS.Linux,
Windows, KnownOS.Windows,
iPad, KnownOS.iPad,
iPhone, KnownOS.iPhone,
Macintosh, KnownOS.Macintosh,
ChromeOS, KnownOS.ChromeOS,
WYSE, KnownOS.WYSE,
) # Android is linux also, so it is cheched on first place ) # Android is linux also, so it is cheched on first place
allOss = knownOss + (Unknown,) allOss = knownOss + (KnownOS.Unknown,)
desktopOss = (Linux, Windows, Macintosh) desktopOss = (KnownOS.Linux, KnownOS.Windows, KnownOS.Macintosh)
mobilesODD = list(set(allOss) - set(desktopOss)) mobilesODD = list(set(allOss) - set(desktopOss))
DEFAULT_OS = 'Windows' DEFAULT_OS = KnownOS.Windows
# Known browsers # Known browsers
Firefox = 'Firefox' Firefox = 'Firefox'
@ -115,18 +118,18 @@ def getOsFromUA(
Basic OS Client detector (very basic indeed :-)) Basic OS Client detector (very basic indeed :-))
""" """
if ua is None: if ua is None:
ua = Unknown ua = KnownOS.Unknown.value[0]
os = Unknown res = DictAsObj({'OS': KnownOS.Unknown, 'Version': '0.0', 'Browser': 'unknown'})
found: bool = False
res = DictAsObj({'OS': os, 'Version': '0.0', 'Browser': 'unknown'})
for os in knownOss: for os in knownOss:
try: if found:
ua.index(os)
res.OS = os # type: ignore
break break
except Exception: for osName in os.value:
pass if osName in ua:
res.OS = os # type: ignore
found = True
break
match = None match = None

View File

@ -129,9 +129,12 @@ def packageRelativeFile(moduleName: str, fileName: str) -> str:
Helper to get image path from relative to a module. Helper to get image path from relative to a module.
This allows to keep images alongside report This allows to keep images alongside report
""" """
pkgpath = os.path.dirname(sys.modules[moduleName].__file__) mod = sys.modules[moduleName]
return os.path.join(pkgpath, fileName) if mod and mod.__file__:
pkgpath = os.path.dirname(mod.__file__)
return os.path.join(pkgpath, fileName)
# Not found, return fileName
return fileName
def timestampAsStr(stamp, format_='SHORT_DATETIME_FORMAT'): def timestampAsStr(stamp, format_='SHORT_DATETIME_FORMAT'):
""" """

View File

@ -96,7 +96,7 @@ class RDPTransport(BaseRDPTransport):
userService: 'models.UserService', userService: 'models.UserService',
transport: 'models.Transport', transport: 'models.Transport',
ip: str, ip: str,
os: typing.Dict[str, str], os: typing.Dict[str, typing.Any],
user: 'models.User', user: 'models.User',
password: str, password: str,
request: 'HttpRequest', request: 'HttpRequest',
@ -144,9 +144,9 @@ class RDPTransport(BaseRDPTransport):
r.enforcedShares = self.enforceDrives.value r.enforcedShares = self.enforceDrives.value
osName = { osName = {
OsDetector.Windows: 'windows', OsDetector.KnownOS.Windows: 'windows',
OsDetector.Linux: 'linux', OsDetector.KnownOS.Linux: 'linux',
OsDetector.Macintosh: 'macosx', OsDetector.KnownOS.Macintosh: 'macosx',
}.get(os['OS']) }.get(os['OS'])
if osName is None: if osName is None:

View File

@ -77,7 +77,7 @@ class RDPFile:
width: typing.Union[str, int], width: typing.Union[str, int],
height: typing.Union[str, int], height: typing.Union[str, int],
bpp: str, bpp: str,
target: str = OsDetector.Windows, target: OsDetector.KnownOS = OsDetector.KnownOS.Windows,
): ):
self.width = str(width) self.width = str(width)
self.height = str(height) self.height = str(height)
@ -86,7 +86,7 @@ class RDPFile:
self.target = target self.target = target
def get(self): def get(self):
if self.target in (OsDetector.Windows, OsDetector.Linux, OsDetector.Macintosh): if self.target in (OsDetector.KnownOS.Windows, OsDetector.KnownOS.Linux, OsDetector.KnownOS.Macintosh):
return self.getGeneric() return self.getGeneric()
# Unknown target # Unknown target
return '' return ''
@ -115,7 +115,7 @@ class RDPFile:
params.append('/smartcard') params.append('/smartcard')
if self.redirectAudio: if self.redirectAudio:
if self.alsa and self.target != OsDetector.Macintosh: if self.alsa and self.target != OsDetector.KnownOS.Macintosh:
params.append('/sound:sys:alsa,format:1,quality:high') params.append('/sound:sys:alsa,format:1,quality:high')
params.append('/microphone:sys:alsa') params.append('/microphone:sys:alsa')
else: else:
@ -126,7 +126,7 @@ class RDPFile:
params.append('/video') params.append('/video')
if self.redirectDrives != 'false': if self.redirectDrives != 'false':
if self.target in (OsDetector.Linux, OsDetector.Macintosh): if self.target in (OsDetector.KnownOS.Linux, OsDetector.KnownOS.Macintosh):
params.append('/drive:home,$HOME') params.append('/drive:home,$HOME')
else: else:
params.append('/drive:Users,/Users') params.append('/drive:Users,/Users')
@ -152,7 +152,7 @@ class RDPFile:
params.append('/multimon') params.append('/multimon')
if self.fullScreen: if self.fullScreen:
if self.target != OsDetector.Macintosh: if self.target != OsDetector.KnownOS.Macintosh:
params.append('/f') params.append('/f')
else: # On mac, will fix this later... else: # On mac, will fix this later...
params.append('/w:#WIDTH#') params.append('/w:#WIDTH#')
@ -221,7 +221,7 @@ class RDPFile:
if self.username: if self.username:
res += 'username:s:' + self.username + '\n' res += 'username:s:' + self.username + '\n'
res += 'domain:s:' + self.domain + '\n' res += 'domain:s:' + self.domain + '\n'
if self.target == OsDetector.Windows: if self.target == OsDetector.KnownOS.Windows:
res += 'password 51:b:' + password + '\n' res += 'password 51:b:' + password + '\n'
res += 'alternate shell:s:' + '\n' res += 'alternate shell:s:' + '\n'

View File

@ -140,7 +140,7 @@ class TRDPTransport(BaseRDPTransport):
userService: 'models.UserService', userService: 'models.UserService',
transport: 'models.Transport', transport: 'models.Transport',
ip: str, ip: str,
os: typing.Dict[str, str], os: typing.Dict[str, typing.Any],
user: 'models.User', user: 'models.User',
password: str, password: str,
request: 'HttpRequest', request: 'HttpRequest',
@ -197,9 +197,9 @@ class TRDPTransport(BaseRDPTransport):
r.enforcedShares = self.enforceDrives.value r.enforcedShares = self.enforceDrives.value
osName = { osName = {
OsDetector.Windows: 'windows', OsDetector.KnownOS.Windows: 'windows',
OsDetector.Linux: 'linux', OsDetector.KnownOS.Linux: 'linux',
OsDetector.Macintosh: 'macosx', OsDetector.KnownOS.Macintosh: 'macosx',
}.get(os['OS']) }.get(os['OS'])
if osName is None: if osName is None:

View File

@ -65,12 +65,12 @@ class SPICETransport(BaseSpiceTransport):
autoNewUsbShare = BaseSpiceTransport.autoNewUsbShare autoNewUsbShare = BaseSpiceTransport.autoNewUsbShare
smartCardRedirect = BaseSpiceTransport.smartCardRedirect smartCardRedirect = BaseSpiceTransport.smartCardRedirect
def getUDSTransportScript( # pylint: disable=too-many-locals def getUDSTransportScript(
self, self,
userService: 'models.UserService', userService: 'models.UserService',
transport: 'models.Transport', transport: 'models.Transport',
ip: str, ip: str,
os: typing.Dict[str, str], os: typing.Dict[str, typing.Any],
user: 'models.User', user: 'models.User',
password: str, password: str,
request: 'HttpRequest', request: 'HttpRequest',
@ -100,9 +100,9 @@ class SPICETransport(BaseSpiceTransport):
r.smartcard = self.smartCardRedirect.isTrue() r.smartcard = self.smartCardRedirect.isTrue()
osName = { osName = {
OsDetector.Windows: 'windows', OsDetector.KnownOS.Windows: 'windows',
OsDetector.Linux: 'linux', OsDetector.KnownOS.Linux: 'linux',
OsDetector.Macintosh: 'macosx', OsDetector.KnownOS.Macintosh: 'macosx',
}.get(os['OS']) }.get(os['OS'])
if osName is None: if osName is None:

View File

@ -112,7 +112,7 @@ class TSPICETransport(BaseSpiceTransport):
userService: 'models.UserService', userService: 'models.UserService',
transport: 'models.Transport', transport: 'models.Transport',
ip: str, ip: str,
os: typing.Dict[str, str], os: typing.Dict[str, typing.Any],
user: 'models.User', user: 'models.User',
password: str, password: str,
request: 'HttpRequest', request: 'HttpRequest',
@ -155,9 +155,9 @@ class TSPICETransport(BaseSpiceTransport):
r.smartcard = self.smartCardRedirect.isTrue() r.smartcard = self.smartCardRedirect.isTrue()
osName = { osName = {
OsDetector.Windows: 'windows', OsDetector.KnownOS.Windows: 'windows',
OsDetector.Linux: 'linux', OsDetector.KnownOS.Linux: 'linux',
OsDetector.Macintosh: 'macosx', OsDetector.KnownOS.Macintosh: 'macosx',
}.get(os['OS']) }.get(os['OS'])
if osName is None: if osName is None:

View File

@ -74,7 +74,7 @@ class X2GOTransport(BaseX2GOTransport):
userService: 'models.UserService', userService: 'models.UserService',
transport: 'models.Transport', transport: 'models.Transport',
ip: str, ip: str,
os: typing.Dict[str, str], os: typing.Dict[str, typing.Any],
user: 'models.User', user: 'models.User',
password: str, password: str,
request: 'HttpRequest', request: 'HttpRequest',
@ -106,8 +106,8 @@ class X2GOTransport(BaseX2GOTransport):
) )
osName = { osName = {
OsDetector.Windows: 'windows', OsDetector.KnownOS.Windows: 'windows',
OsDetector.Linux: 'linux', OsDetector.KnownOS.Linux: 'linux',
# OsDetector.Macintosh: 'macosx' # OsDetector.Macintosh: 'macosx'
}.get(os['OS']) }.get(os['OS'])

View File

@ -63,7 +63,7 @@ class BaseX2GOTransport(transports.Transport):
iconFile = 'x2go.png' iconFile = 'x2go.png'
protocol = transports.protocols.X2GO protocol = transports.protocols.X2GO
supportedOss = (OsDetector.Linux, OsDetector.Windows) supportedOss = (OsDetector.KnownOS.Linux, OsDetector.KnownOS.Windows)
fixedName = gui.TextField( fixedName = gui.TextField(
order=2, order=2,

View File

@ -121,7 +121,7 @@ class TX2GOTransport(BaseX2GOTransport):
userService: 'models.UserService', userService: 'models.UserService',
transport: 'models.Transport', transport: 'models.Transport',
ip: str, ip: str,
os: typing.Dict[str, str], os: typing.Dict[str, typing.Any],
user: 'models.User', user: 'models.User',
password: str, password: str,
request: 'HttpRequest', request: 'HttpRequest',
@ -180,8 +180,8 @@ class TX2GOTransport(BaseX2GOTransport):
m = tools.DictAsObj(data) m = tools.DictAsObj(data)
osName = { osName = {
OsDetector.Windows: 'windows', OsDetector.KnownOS.Windows: 'windows',
OsDetector.Linux: 'linux', OsDetector.KnownOS.Linux: 'linux',
# OsDetector.Macintosh: 'macosx' # OsDetector.Macintosh: 'macosx'
}.get(os['OS']) }.get(os['OS'])

View File

@ -151,7 +151,7 @@ def udsJs(request: 'ExtendedHttpRequest') -> str:
getAuthInfo(auth) for auth in authenticators if auth.getType() getAuthInfo(auth) for auth in authenticators if auth.getType()
], ],
'tag': tag, 'tag': tag,
'os': request.os['OS'], 'os': request.os['OS'].value[0],
'csrf_field': CSRF_FIELD, 'csrf_field': CSRF_FIELD,
'csrf': csrf_token, 'csrf': csrf_token,
'image_size': Image.MAX_IMAGE_SIZE, 'image_size': Image.MAX_IMAGE_SIZE,

View File

@ -97,8 +97,8 @@ def getServicesData(
nets = '' nets = ''
validTrans = '' validTrans = ''
osName = request.os['OS'] osType = request.os['OS']
logger.debug('OS: %s', osName) logger.debug('OS: %s', osType)
if request.user.isStaff(): if request.user.isStaff():
nets = ','.join([n.name for n in Network.networksFor(request.ip)]) nets = ','.join([n.name for n in Network.networksFor(request.ip)])
@ -120,8 +120,8 @@ def getServicesData(
if ( if (
typeTrans typeTrans
and t.validForIp(request.ip) and t.validForIp(request.ip)
and typeTrans.supportsOs(osName) and typeTrans.supportsOs(osType)
and t.validForOs(osName) and t.validForOs(osType)
): ):
yield t yield t
except Exception as e: except Exception as e:
@ -200,8 +200,8 @@ def getServicesData(
if ( if (
typeTrans typeTrans
and t.validForIp(request.ip) and t.validForIp(request.ip)
and typeTrans.supportsOs(osName) and typeTrans.supportsOs(osType)
and t.validForOs(osName) and t.validForOs(osType)
): ):
metaTransports = [ metaTransports = [
{ {
@ -272,8 +272,8 @@ def getServicesData(
if ( if (
typeTrans typeTrans
and t.validForIp(request.ip) and t.validForIp(request.ip)
and typeTrans.supportsOs(osName) and typeTrans.supportsOs(osType)
and t.validForOs(osName) and t.validForOs(osType)
): ):
if typeTrans.ownLink: if typeTrans.ownLink:
link = reverse('TransportOwnLink', args=('F' + sPool.uuid, t.uuid)) link = reverse('TransportOwnLink', args=('F' + sPool.uuid, t.uuid))

View File

@ -283,7 +283,7 @@ def ticketAuth(
except Authenticator.DoesNotExist: except Authenticator.DoesNotExist:
logger.error('Ticket has an non existing authenticator') logger.error('Ticket has an non existing authenticator')
return errors.errorView(request, errors.ACCESS_DENIED) return errors.errorView(request, errors.ACCESS_DENIED)
except ServicePool.DoesNotExist: except ServicePool.DoesNotExist: # type: ignore # DoesNotExist is different for each model
logger.error('Ticket has an invalid Service Pool') logger.error('Ticket has an invalid Service Pool')
return errors.errorView(request, errors.SERVICE_NOT_FOUND) return errors.errorView(request, errors.SERVICE_NOT_FOUND)
except Exception as e: except Exception as e: