-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient_api.py
4962 lines (4823 loc) · 331 KB
/
client_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Decompiled with PyLingual (https://pylingual.io)
# Internal filename: client_api.py
# Bytecode version: 3.8.0rc1+ (3413)
# Source timestamp: 1970-01-01 00:00:00 UTC (0)
import tempfile
import typing
from urllib.error import URLError
import uuid
import hashlib
import cherrypy
import traceback
import logging
import logging.config
import time
import datetime
import json
import os
import stripe
import pyotp
import base64
import urllib.request
import requests
import ssl
import jwt
import random
import webauthn
from urllib.parse import urlparse, urlunparse
from socket import gethostbyname, gaierror
from decimal import Decimal
from provider_manager import ProviderManager
from data.data_access_factory import DataAccessFactory
from data.categories import ALL_CATEGORIES
from data.enums import CONNECTION_PROXY_TYPE, CONNECTION_TYPE, SESSION_OPERATIONAL_STATUS, LANGUAGES, TIMEZONES, IMAGE_TYPE, STORAGE_PROVIDER_TYPES, JWT_AUTHORIZATION, SERVER_OPERATIONAL_STATUS
from data.lookup_tables import LANGUAGE_MAPPING_TO_TERRITORIES
from data.data_utils import generate_password
from utils import passwordComplexityCheck, Authenticated, JwtAuthenticated, CookieAuthenticated, LicenseHelper, check_usage, get_usage, update_hubspot_contact_by_email, generate_hmac, validate_session_token_ex, validate_recaptcha, func_timing, ConnectionError, is_healthy, generate_jwt_token, generate_guac_client_secret, object_storage_variable_substitution, Unauthenticated
from authentication.ldap_auth import LDAPAuthentication
from authentication.saml.saml_auth import SamlAuthentication
from authentication.oidc import OIDCAuthentication
from storage_providers import GoogleDrive, Dropbox, OneDrive, S3, Nextcloud, CustomStorageProvider
from filtering.kasm_web_filter import KasmWebFilter
from cachetools.func import ttl_cache
from pydantic import ValidationError
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.fernet import Fernet
from providers.aws_provider import AwsObjectStorageProvider
from webauthn.helpers.structs import AuthenticatorSelectionCriteria, UserVerificationRequirement, RegistrationCredential, AuthenticationCredential, PublicKeyCredentialDescriptor
from http.cookies import Morsel
Morsel._reserved['samesite'] = 'SameSite'
class ClientApi(object):
def __init__(self, config):
self.config = config
self.logger = logging.getLogger('client_api_server')
self._db = DataAccessFactory.createSession(config['database']['type'], config)
self.hubspot_api_key = None
if self._db.config.get('subscription') and self._db.config['subscription'].get('hubspot_api_key'):
self.hubspot_api_key = self._db.config['subscription']['hubspot_api_key'].value
self.zone_name = self.config['server']['zone_name']
self.provider_manager = ProviderManager(config, self._db, self.logger)
self.installation_id = str(self._db.getInstallation().installation_id)
if self._db.hasFilterWithCategorization():
self.init_webfilter()
else: # inserted
self.kasm_web_filter = None
self.logger.info('%s initialized' % self.__class__.__name__)
def init_webfilter(self):
self.kasm_web_filter = KasmWebFilter(self._db.get_config_setting_value('web_filter', 'web_filter_update_url'), self.installation_id, self.logger)
@staticmethod
@ttl_cache(maxsize=200, ttl=600)
def is_sso_licensed(logger):
license_helper = LicenseHelper(cherrypy.request.db, logger)
return license_helper.is_sso_ok()
@staticmethod
@ttl_cache(maxsize=200, ttl=600)
def is_allow_kasm_sharing_licensed(logger):
license_helper = LicenseHelper(cherrypy.request.db, logger)
return license_helper.is_allow_kasm_sharing_ok()
@staticmethod
@ttl_cache(maxsize=200, ttl=600)
def is_usage_limit_licensed(logger):
license_helper = LicenseHelper(cherrypy.request.db, logger)
return license_helper.is_usage_limit_ok()
@staticmethod
@ttl_cache(maxsize=200, ttl=600)
def is_session_recording_licensed(logger):
license_helper = LicenseHelper(cherrypy.request.db, logger)
return license_helper.is_session_recording_ok()
@cherrypy.expose(['__healthcheck'])
@cherrypy.tools.json_out()
@Unauthenticated()
def healthcheck(self):
response = {'ok': True}
cherrypy.request.db.getInstallation()
return response
@cherrypy.expose
@Unauthenticated()
def acs(self, **params):
if not self.is_sso_licensed(self.logger):
return 'Access Denied. This feature is not licensed'
if 'id' in cherrypy.request.params:
config = cherrypy.request.db.get_saml_config(cherrypy.request.params['id'])
else: # inserted
return 'Login Failure: No saml ID in request'
if config:
saml = SamlAuthentication(cherrypy.request, config, '/api/acs')
response = saml.acs()
if 'error' in response and response['error'] or response['auth'] is False:
return response['error']
sanitized_username = response['userid'].strip().lower()
user = cherrypy.request.db.getUser(sanitized_username)
if not user:
license_helper = LicenseHelper(cherrypy.request.db, self.logger)
if license_helper.is_per_named_user_ok(with_user_added=True):
user = cherrypy.request.db.createUser(username=sanitized_username, realm='saml', saml_id=cherrypy.request.params['id'])
else: # inserted
msg = 'License limit exceeded. Unable to create user'
self.logger.error(msg)
return
if user.realm == 'saml':
if cherrypy.request.db.serializable(user.saml_id) == cherrypy.request.params['id']:
self.process_sso_group_membership(user, response['attributes'].get(config.group_attribute, []), 'saml', config.saml_id)
attributes = response['attributes'] if 'attributes' in response else {}
for sso_attribute_mapping in config.user_attribute_mappings:
if sso_attribute_mapping.attribute_name.lower() == 'debug':
self.logger.debug(f'SAML Attributes: {str(attributes)}')
else: # inserted
value = sso_attribute_mapping.process_attributes(user, attributes)
self.logger.debug(f'New attribute value ({value}) applied to user {sanitized_username} for {sso_attribute_mapping.user_field}')
if len(config.user_attribute_mappings) > 0:
cherrypy.request.db.updateUser(user)
priv_key = str.encode(self._db.get_config_setting_value_cached('auth', 'api_private_key'))
session_lifetime = int(self._db.get_config_setting_value_cached('auth', 'session_lifetime'))
session_token = cherrypy.request.db.createSessionToken(user)
user_id = cherrypy.request.db.serializable(user.user_id)
session_jwt = session_token.generate_jwt(priv_key, session_lifetime)
raise cherrypy.HTTPRedirect(response['base_url'] + '/#/sso/' + user_id + '/' + session_jwt, status=302)
else: # inserted
return 'Saml login rejected: different Saml ID expected for user'
else: # inserted
return 'Saml login rejected: Non Saml user'
else: # inserted
self.logger.error('No Saml configuration with that ID found in the acs request')
return 'Error: wrong Saml ID'
@typing.Dict
def process_sso_group_membership(self, user, sso_groups: str, sso_type: str, sso_id: str):
group_mappings = cherrypy.request.db.getGroupMappingBySsoID(sso_type=sso_type, sso_id=sso_id)
sso_groups = [x.lower() for x in sso_groups]
user_group_ids = [x.group_id for x in user.groups]
distinct_groups = set()
[distinct_groups.add(x.group) for x in group_mappings]
distinct_groups = list(distinct_groups)
for group in distinct_groups:
sso_group_mappings = [x for x in group.group_mappings if x.sso_id == sso_id]
self.logger.debug(f'Processing Group ({group.name}) with ({len(sso_group_mappings)}) sso_mappings for sso type {sso_type}, id: ({sso_id})')
do_add = False
for group_mapping in sso_group_mappings:
if group_mapping.apply_to_all_users:
do_add = True
self.logger.debug(f'User ({user.username}) should be assigned to group ({group.name}) : Apply to All Users')
break
if group_mapping.sso_group_attributes.lower() in sso_groups:
self.logger.debug(f'User ({user.username}) should be assigned to group ({group.name}). Matched group attribute ({group_mapping.sso_group_attributes})')
do_add = True
if do_add:
if group.group_id in user_group_ids:
self.logger.debug(f'User ({user.username}) already a member of group ({group.name}). No Action')
else: # inserted
self.logger.debug(f'Adding User ({user.username}) to Group ({group.name})')
cherrypy.request.db.addUserGroup(user, group)
else: # inserted
if group.group_id in user_group_ids:
self.logger.debug(f'Removing User ({user.username}) from Group ({group.name})')
cherrypy.request.db.removeUserGroup(user, group)
else: # inserted
self.logger.debug(f'User ({user.username}) is not a member of group ({group.name}). No Action')
@cherrypy.expose
@Unauthenticated()
def slo(self, **params):
if 'id' in cherrypy.request.params:
config = cherrypy.request.db.get_saml_config(cherrypy.request.params['id'])
else: # inserted
response = 'No saml ID'
return response
if config:
saml = SamlAuthentication(cherrypy.request, config, '/api/slo')
url, name_id = saml.sls()
if name_id:
sanitized_username = name_id.strip().lower()
user = cherrypy.request.db.getUser(sanitized_username)
cherrypy.request.db.remove_all_session_tokens(user)
if not url:
url = cherrypy.request.base.replace('http', 'https')
raise cherrypy.HTTPRedirect(url, status=301)
self.logger.error('Saml Logout Error: No config for this Saml ID')
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
@Unauthenticated()
def sso(self, **params):
response = {}
event = cherrypy.request.json
if 'id' in event:
if 'sso_type' in event and event['sso_type'] == 'saml_id':
config = cherrypy.request.db.get_saml_config(event['id'])
saml = SamlAuthentication(cherrypy.request, config, '/api/sso')
response['url'] = saml.sso()
else: # inserted
if 'sso_type' in event and event['sso_type'] == 'oidc_id':
config = cherrypy.request.db.get_oidc_config(event['id'])
response['url'] = OIDCAuthentication(config).get_login_url()
else: # inserted
response['error_message'] = 'No SSO ID'
return response
return response
@cherrypy.expose
@Unauthenticated()
def sso_login(self, **params):
if 'id' in cherrypy.request.params:
id = cherrypy.request.params['id']
config = cherrypy.request.db.get_saml_config(id)
if config:
url = SamlAuthentication(cherrypy.request, config, '/api/sso_login').sso()
raise cherrypy.HTTPRedirect(url, status=301)
config = cherrypy.request.db.get_oidc_config(id)
if config:
url = OIDCAuthentication(config).get_login_url()
raise cherrypy.HTTPRedirect(url, status=301)
cherrypy.response.status = 403
else: # inserted
cherrypy.response.status = 403
@cherrypy.expose
@Unauthenticated()
def metadata(self, **params):
response = {}
if 'id' in cherrypy.request.params:
config = cherrypy.request.db.get_saml_config(cherrypy.request.params['id'])
else: # inserted
return 'No saml ID'
if config:
saml = SamlAuthentication(cherrypy.request, config, '/api/metadata')
response = saml.metadata()
cherrypy.response.headers['Content-Type'] = 'text/xml; charset=utf-8'
else: # inserted
response['error_message'] = 'No saml Configuration'
if 'error_message' in response:
return response['error_message']
return response['metadata']
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
@Authenticated(requested_actions=[JWT_AUTHORIZATION.USER], read_only=True)
def get_available_storage_providers(self):
response = {'storage_providers': []}
user = cherrypy.request.authenticated_user
is_admin = JWT_AUTHORIZATION.is_authorized_action(cherrypy.request.authorizations, JWT_AUTHORIZATION.STORAGE_PROVIDERS_VIEW)
if is_admin or (user and user.get_setting_value('allow_user_storage_mapping', False)):
storage_providers = cherrypy.request.db.get_storage_providers(enabled=True)
for storage_provider in storage_providers:
if is_admin or storage_provider.storage_provider_type!= STORAGE_PROVIDER_TYPES.CUSTOM.value:
response['storage_providers'].append({'name': storage_provider.name, 'storage_provider_id': str(storage_provider.storage_provider_id), 'storage_provider_type': storage_provider.storage_provider_type})
return response
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
@Authenticated(requested_actions=[JWT_AUTHORIZATION.USER], read_only=True)
def get_storage_mappings(self):
response = {'storage_mappings': []}
user = cherrypy.request.authenticated_user
is_admin = JWT_AUTHORIZATION.any_authorized_actions(cherrypy.request.authorizations, [JWT_AUTHORIZATION.USERS_VIEW, JWT_AUTHORIZATION.GROUPS_VIEW, JWT_AUTHORIZATION.GROUPS_VIEW_IFMEMBER, JWT_AUTHORIZATION.GROUPS_VIEW_SYSTEM, JWT_AUTHORIZATION.IMAGES_VIEW])
event = cherrypy.request.json
target_storage_mapping = event.get('target_storage_mapping', {})
if target_storage_mapping:
_user_id = target_storage_mapping.get('user_id')
_group_id = target_storage_mapping.get('group_id')
_image_id = target_storage_mapping.get('image_id')
_storage_mapping_id = target_storage_mapping.get('storage_mapping_id')
_test = [x for x in [_user_id, _group_id, _image_id, _storage_mapping_id] if x is not None]
if len(_test) == 1:
if is_admin:
storage_mappings = cherrypy.request.db.get_storage_mappings(storage_mapping_id=_storage_mapping_id, user_id=_user_id, group_id=_group_id, image_id=_image_id)
response['storage_mappings'] = []
for storage_mapping in storage_mappings:
is_authorized = False
if storage_mapping.user:
is_authorized = storage_mapping.user.user_id == user.user_id or JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.USERS_VIEW, target_user=storage_mapping.user)
else: # inserted
if storage_mapping.group:
is_authorized = JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.GROUPS_VIEW, target_group=storage_mapping.group)
else: # inserted
if storage_mapping.image:
is_authorized = JWT_AUTHORIZATION.is_authorized_action(cherrypy.request.authorizations, JWT_AUTHORIZATION.IMAGES_VIEW)
if is_authorized:
response['storage_mappings'].append(cherrypy.request.db.serializable(storage_mapping.jsonDict))
else: # inserted
if not _user_id or _user_id!= user.user_id.hex:
msg = 'Unauthorized attempt to update storage mappings for other user/group/image'
self.logger.error(msg)
response['error_message'] = 'Access Denied'
return response
storage_mappings = cherrypy.request.db.get_storage_mappings(user_id=user.user_id)
for vc in storage_mappings:
response['storage_mappings'].append({'storage_mapping_id': str(vc.storage_mapping_id), 'storage_provider_type': vc.storage_provider.storage_provider_type, 'user_id': str(vc.user_id), 'name': vc.name, 'storage_provider_id': str(vc.storage_provider_id), 'enabled': vc.enabled, 'read_only': vc.read_only, 'target': vc.target, 's3_access_key_id': vc.s3_access_key_id, 's3_secret_access_key': '**********', 's3_bucket': vc.s3_bucket, 'webdav_user': vc.webdav_user, 'webdav_pass': '**********'})
else: # inserted
msg = 'Invalid request. Only one of the following parameters may be defined (storage_mapping_id, user_id, group_id, image_id)'
self.logger.error(msg)
response['error_message'] = msg
else: # inserted
msg = 'Invalid request. Missing required parameters'
self.logger.error(msg)
response['error_message'] = msg
return response
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
@Authenticated(requested_actions=[JWT_AUTHORIZATION.USER], read_only=False)
def delete_storage_mapping(self):
response = {}
user = cherrypy.request.authenticated_user
event = cherrypy.request.json
target_storage_mapping = event.get('target_storage_mapping')
is_admin = JWT_AUTHORIZATION.any_authorized_actions(cherrypy.request.authorizations, [JWT_AUTHORIZATION.USERS_MODIFY, JWT_AUTHORIZATION.USERS_MODIFY_ADMIN, JWT_AUTHORIZATION.GROUPS_MODIFY, JWT_AUTHORIZATION.IMAGES_MODIFY, JWT_AUTHORIZATION.USERS_VIEW, JWT_AUTHORIZATION.GROUPS_VIEW, JWT_AUTHORIZATION.IMAGES_VIEW])
is_authorized = False
if target_storage_mapping:
storage_mapping_id = target_storage_mapping.get('storage_mapping_id')
if storage_mapping_id:
if is_admin:
storage_mapping = cherrypy.request.db.get_storage_mapping(storage_mapping_id=storage_mapping_id)
if storage_mapping:
if not storage_mapping.user or user:
is_authorized = storage_mapping.user.user_id == user.user_id or JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.USERS_MODIFY, target_user=storage_mapping.user)
else: # inserted
if storage_mapping.group:
is_authorized = JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.GROUPS_MODIFY, target_group=storage_mapping.group)
else: # inserted
if storage_mapping.image:
is_authorized = JWT_AUTHORIZATION.is_authorized_action(cherrypy.request.authorizations, JWT_AUTHORIZATION.IMAGES_MODIFY)
else: # inserted
storage_mapping = cherrypy.request.db.get_storage_mapping(storage_mapping_id=storage_mapping_id, user_id=user.user_id)
is_authorized = True
if storage_mapping:
if not is_authorized or storage_mapping.storage_provider_type == STORAGE_PROVIDER_TYPES.CUSTOM.value:
if not is_admin:
pass # postinserted
if not is_authorized:
self.logger.error(f'User ({cherrypy.request.kasm_user_id}) unauthorized to delete storage mapping ({storage_mapping_id}).')
else: # inserted
self.logger.error(f'User ({cherrypy.request.kasm_user_id}) unauthorized to delete Custom storage mapping ({storage_mapping_id}).')
response['error_message'] = 'Unauthorized Action'
cherrypy.response.status = 401
return response
cherrypy.request.db.delete_storage_mapping(storage_mapping)
self.logger.info('Successfully deleted storage_mapping_id (%s)' % storage_mapping_id, extra={'storage_mapping_id': storage_mapping_id})
else: # inserted
msg = 'Storage Mapping ID (%s) Not found' % storage_mapping_id
self.logger.error(msg)
response['error_message'] = msg
else: # inserted
msg = 'Invalid request. Missing required parameters'
self.logger.error(msg)
response['error_message'] = msg
else: # inserted
msg = 'Invalid request. Missing required parameters'
self.logger.error(msg)
response['error_message'] = msg
return response
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
@Authenticated(requested_actions=[JWT_AUTHORIZATION.USER], read_only=False)
def create_storage_mapping(self):
response = {}
user = cherrypy.request.authenticated_user
is_admin = JWT_AUTHORIZATION.any_authorized_actions(cherrypy.request.authorizations, [JWT_AUTHORIZATION.USERS_MODIFY, JWT_AUTHORIZATION.USERS_MODIFY_ADMIN, JWT_AUTHORIZATION.GROUPS_MODIFY, JWT_AUTHORIZATION.IMAGES_MODIFY, JWT_AUTHORIZATION.USERS_VIEW, JWT_AUTHORIZATION.GROUPS_VIEW, JWT_AUTHORIZATION.IMAGES_VIEW])
event = cherrypy.request.json
target_storage_mapping = event.get('target_storage_mapping')
if not is_admin and (not user.get_setting_value('allow_user_storage_mapping', False)) or target_storage_mapping:
_user_id = target_storage_mapping.get('user_id')
_group_id = target_storage_mapping.get('group_id')
_image_id = target_storage_mapping.get('image_id')
_storage_provider_id = target_storage_mapping.get('storage_provider_id')
target_user = None
_test = [x for x in [_user_id, _group_id, _image_id] if x is not None]
if len(_test) == 1:
if not is_admin and (target_storage_mapping.get('target') or target_storage_mapping.get('config')):
msg = 'Unauthorized attempt to define restricted storage mapping property'
self.logger.error(msg)
response['error_message'] = 'Access Denied'
return response
if not _user_id or _user_id!= user.user_id.hex:
msg = 'Unauthorized attempt to create storage mappings for other user/group/image'
self.logger.error(msg)
response['error_message'] = 'Access Denied'
return response
if _user_id:
target_user = cherrypy.request.db.get_user_by_id(user_id=_user_id)
if target_user:
max_user_storage_mappings = target_user.get_setting_value('max_user_storage_mappings', 2)
if len(target_user.storage_mappings) >= max_user_storage_mappings:
msg = 'Unable to create storage mapping. Limit exceeded'
self.logger.error(msg)
response['error_message'] = msg
return response
else: # inserted
msg = 'Invalid user_id'
self.logger.error(msg)
response['error_message'] = msg
return response
is_authorized = False
if target_user:
if user:
if target_user.user_id == user.user_id:
is_authorized = True
if is_admin:
if target_user:
is_authorized = JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.USERS_MODIFY, target_user=target_user)
else: # inserted
if _group_id:
target_group = cherrypy.request.db.getGroup(group_id=_group_id)
is_authorized = target_group and JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.GROUPS_MODIFY, target_group=target_group)
else: # inserted
if _image_id:
is_authorized = JWT_AUTHORIZATION.is_authorized_action(cherrypy.request.authorizations, JWT_AUTHORIZATION.IMAGES_MODIFY)
if not is_authorized:
self.logger.error(f'User ({cherrypy.request.kasm_user_id}) attempted to create a storage mapping but is not authorized to modify the target group, user, or image.')
response['error_message'] = 'Unauthorized to modify the target user/group/image for the storage mapping.'
response['ui_show_error'] = True
cherrypy.response.status = 401
return response
storage_provider_id = target_storage_mapping.get('storage_provider_id')
if storage_provider_id:
storage_provider = cherrypy.request.db.get_storage_provider(storage_provider_id=storage_provider_id)
if storage_provider:
jwt_priv_key = str.encode(cherrypy.request.db.get_config_setting_value_cached('auth', 'api_private_key'))
encoded_jwt = None
if storage_provider.storage_provider_type == STORAGE_PROVIDER_TYPES.GOOGLE_DRIVE.value:
url, encoded_jwt = GoogleDrive(storage_provider).get_login_url(target_storage_mapping, jwt_priv_key)
response['url'] = url
else: # inserted
if storage_provider.storage_provider_type == STORAGE_PROVIDER_TYPES.DROPBOX.value:
url, encoded_jwt = Dropbox(storage_provider).get_login_url(target_storage_mapping, jwt_priv_key)
response['url'] = url
else: # inserted
if storage_provider.storage_provider_type == STORAGE_PROVIDER_TYPES.ONEDRIVE.value:
url, encoded_jwt = OneDrive(storage_provider).get_login_url(target_storage_mapping, jwt_priv_key)
response['url'] = url
else: # inserted
if storage_provider.storage_provider_type == STORAGE_PROVIDER_TYPES.S3.value:
error_message = S3(storage_provider).validate_storage_mapping(target_storage_mapping)
if error_message:
response['error_message'] = error_message
else: # inserted
storage_mapping = cherrypy.request.db.create_storage_mapping(name='%s Storage Mapping' % storage_provider.name, enabled=target_storage_mapping.get('enabled'), read_only=target_storage_mapping.get('read_only'), user_id=target_storage_mapping.get('user_id'), group_id=target_storage_mapping.get('group_id'), image_id=target_storage_mapping.get('image_id'), storage_provider_id=target_storage_mapping.get('storage_provider_id'), s3_access_key_id=target_storage_mapping.get('s3_access_key_id'), s3_secret_access_key=target_storage_mapping.get('s3_secret_access_key'), s3_bucket=target_storage_mapping.get('s3_bucket'))
response['storage_mapping'] = cherrypy.request.db.serializable(storage_mapping.jsonDict)
self.logger.info('Successfully created storage_mapping_id (%s)' % storage_mapping.storage_mapping_id, extra={'storage_mapping_id': storage_mapping.storage_mapping_id})
else: # inserted
if storage_provider.storage_provider_type == STORAGE_PROVIDER_TYPES.NEXTCLOUD.value:
error_message = Nextcloud(storage_provider).validate_storage_mapping(target_storage_mapping)
if error_message:
response['error_message'] = error_message
else: # inserted
storage_mapping = cherrypy.request.db.create_storage_mapping(name='%s Storage Mapping' % storage_provider.name, enabled=target_storage_mapping.get('enabled'), read_only=target_storage_mapping.get('read_only'), user_id=target_storage_mapping.get('user_id'), group_id=target_storage_mapping.get('group_id'), image_id=target_storage_mapping.get('image_id'), storage_provider_id=target_storage_mapping.get('storage_provider_id'), webdav_user=target_storage_mapping.get('webdav_user'), webdav_pass=target_storage_mapping.get('webdav_pass'))
response['storage_mapping'] = cherrypy.request.db.serializable(storage_mapping.jsonDict)
self.logger.info('Successfully created storage_mapping_id (%s)' % storage_mapping.storage_mapping_id, extra={'storage_mapping_id': storage_mapping.storage_mapping_id})
else: # inserted
if storage_provider.storage_provider_type == STORAGE_PROVIDER_TYPES.CUSTOM.value:
if is_admin:
error_message = CustomStorageProvider(storage_provider).validate_storage_mapping(target_storage_mapping)
if error_message:
response['error_message'] = error_message
else: # inserted
storage_mapping = cherrypy.request.db.create_storage_mapping(name='%s Storage Mapping' % storage_provider.name, enabled=target_storage_mapping.get('enabled'), read_only=target_storage_mapping.get('read_only'), user_id=target_storage_mapping.get('user_id'), group_id=target_storage_mapping.get('group_id'), image_id=target_storage_mapping.get('image_id'), storage_provider_id=target_storage_mapping.get('storage_provider_id'), webdav_user=target_storage_mapping.get('webdav_user'), webdav_pass=target_storage_mapping.get('webdav_pass'))
response['storage_mapping'] = cherrypy.request.db.serializable(storage_mapping.jsonDict)
self.logger.info('Successfully created storage_mapping_id (%s)' % storage_mapping.storage_mapping_id, extra={'storage_mapping_id': storage_mapping.storage_mapping_id})
msg = 'Unknown Storage Provider Type'
self.logger.error(msg)
response['error_message'] = msg
if encoded_jwt:
kasm_auth_domain = self._db.get_config_setting_value('auth', 'kasm_auth_domain')
if kasm_auth_domain:
if kasm_auth_domain.lower() == '$request_host$':
kasm_auth_domain = cherrypy.request.headers['HOST']
same_site = self._db.get_config_setting_value('auth', 'same_site')
cherrypy.response.cookie['storage_token'] = encoded_jwt
cherrypy.response.cookie['storage_token']['Path'] = '/'
cherrypy.response.cookie['storage_token']['Max-Age'] = 300
cherrypy.response.cookie['storage_token']['Domain'] = kasm_auth_domain
cherrypy.response.cookie['storage_token']['Secure'] = True
cherrypy.response.cookie['storage_token']['httpOnly'] = True
@same_site
cherrypy.response.cookie['storage_token']['SameSite'] = cherrypy.response.cookie['storage_token']
else: # inserted
msg = 'Invalid Storage Provider ID (%s)' % storage_provider_id
self.logger.error(msg)
@msg
response['error_message'] = response
else: # inserted
msg = 'Invalid Request. Missing required parameters'
self.logger.error(msg)
@msg
response['error_message'] = response
pass
else: # inserted
msg = 'Invalid request. Only one attribute group_id, user_id, or image_id may be set'
self.logger.error(msg)
response['error_message'] = response
else: # inserted
msg = 'Invalid request. Missing required parameters'
@self.logger.error
msg)
response['error_message'] = response
msg = 'Creating a storage mapping is not allowed for this user'
else: # inserted
self.logger.error(msg)
response['error_message'] = response
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
@Authenticated
@JWT_AUTHORIZATION.USER(requested_actions=[JWT_AUTHORIZATION.USER], read_only=False)
def update_storage_mapping(self):
response = {}
user = cherrypy.request.authenticated_user
is_admin = JWT_AUTHORIZATION.any_authorized_actions(cherrypy.request.authorizations, [JWT_AUTHORIZATION.USERS_MODIFY, JWT_AUTHORIZATION.USERS_MODIFY_ADMIN, JWT_AUTHORIZATION.GROUPS_MODIFY, JWT_AUTHORIZATION.IMAGES_MODIFY, JWT_AUTHORIZATION.USERS_VIEW, JWT_AUTHORIZATION.GROUPS_VIEW, JWT_AUTHORIZATION.IMAGES_VIEW])
event = cherrypy.request.json
target_storage_mapping = event.get('target_storage_mapping')
target_user = None
if not is_admin and (not user.get_setting_value('allow_user_storage_mapping', False)) or target_storage_mapping:
_user_id = target_storage_mapping.get('user_id')
_group_id = target_storage_mapping.get('group_id')
_image_id = target_storage_mapping.get('image_id')
storage_mapping_id = target_storage_mapping.get('storage_mapping_id')
_test = [x for x in [_user_id, _group_id, _image_id] if x is not None]
if len(_test) == 1 and (is_admin or target_storage_mapping.get('target') or target_storage_mapping.get('config')):
msg = 'Unauthorized attempt to define target or config in storage mapping'
self.logger.error(msg)
response['error_message'] = 'Access Denied'
return response
if not _user_id or _user_id!= user.user_id.hex:
msg = 'Unauthorized attempt to create storage mappings for other user/group/image'
self.logger.error(msg)
response['error_message'] = 'Access Denied'
return response
if _user_id:
target_user = cherrypy.request.db.get_user_by_id(user_id=_user_id)
if target_user:
max_user_storage_mappings = target_user.get_setting_value('max_user_storage_mappings', 2)
if len(target_user.storage_mappings) >= max_user_storage_mappings:
msg = 'Unable to create storage mapping. Limit exceeded'
self.logger.error(msg)
response['error_message'] = msg
return response
else: # inserted
msg = 'Invalid user_id'
self.logger.error(msg)
response['error_message'] = msg
return response
if storage_mapping_id:
is_authorized = False
if target_user and user:
if target_user.user_id == user.user_id:
is_authorized = True
if is_admin:
if target_user:
is_authorized = JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.USERS_MODIFY, target_user=target_user)
else: # inserted
if _group_id:
target_group = cherrypy.request.db.getGroup(group_id=_group_id)
is_authorized = target_group and JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.GROUPS_MODIFY, target_group=target_group)
else: # inserted
if _image_id:
is_authorized = JWT_AUTHORIZATION.is_authorized_action(cherrypy.request.authorizations, JWT_AUTHORIZATION.IMAGES_MODIFY)
if not is_authorized:
self.logger.error(f'User ({cherrypy.request.kasm_user_id}) attempted to update a storage mapping but is not authorized to modify the target group, user, or image.')
response['error_message'] = 'Unauthorized to modify the target user/group/image for the storage mapping.'
response['ui_show_error'] = True
cherrypy.response.status = 401
return response
storage_mapping = cherrypy.request.db.get_storage_mapping(storage_mapping_id=storage_mapping_id, user_id=None if is_admin else user.user_id)
if not storage_mapping or storage_mapping.storage_provider_type == STORAGE_PROVIDER_TYPES.CUSTOM.value:
if not is_admin:
msg = 'Unauthorized attempted to modify Custom Storage mapping'
self.logger.error(msg)
response['error_message'] = 'Access Denied'
return response
if cherrypy.request.db.update_storage_mapping(storage_mapping, target_storage_mapping.get('name'), is_admin=is_admin):
return {'config': target_storage_mapping.get('config') if target_storage_mapping.get('config') else None, 'enabled': target_storage_mapping.get('enabled'), 'read_only': target_storage_mapping.get('read_only'), 'user_id': target_storage_mapping.get('user_id'), 'group_id': target_storage_mapping.get('group_id'), 'image_id': target_storage_mapping.get('image_id'), 'gaierror': target_storage_mapping.get('gaierror') if is_admin else None, 'Decimal': target_storage_mapping.get('Decimal'), 'ProviderManager': target_storage_mapping.get('ProviderManager'), 'DataAccessFactory': target_storage_mapping.get('DataAccessFactory'), 'ALL_CATEGORIES': target_storage_mapping.get('ALL_CATEGORIES'), 'CONNECTION_PROXY_TYPE': target_storage_mapping.get('CONNECTION_PROXY_TYPE'), 'CONNECTION_TYPE': target_storage_mapping.get('CONNECTION_TYPE'), 'SESSION_OPERATIONAL_STATUS': target_storage_mapping.get('SESSION_OPERATIONAL_STATUS'), 'LANGUAGES': target_storage_mapping.get('LANGUAGES'), 'TIMEZONES': target_storage_mapping.get(
storage_mapping = target_storage_mapping.get('target') if target_storage_mapping.get('target') else None, name: target_storage_mapping.get('webdav_user'), config: target_storage_mapping.get('webdav_pass'), enabled: target_storage_mapping.get('s3_access_key_id'), read_only: target_storage_mapping.get('s3_secret_access_key'), user_id: target_storage_mapping.get('s3_bucket'), group_id: target_storage_mapping.get('storage_mapping'), image_id: target_storage_mapping.get('SESSION_OPERATIONAL_STATUS'), target: target_storage_mapping.get('LANGUAGES'), webdav_user: target_storage_mapping.get('TIMEZONES'), webdav_pass: target_storage_mapping.get('IMAGE_TYPE'), s3_access_key_id: target_storage_mapping.get('STORAGE_PROVIDER_TYPES'), s3_secret_access_key: target_storage_mapping.get('JWT_AUTHORIZATION'), s3_bucket: target_storage_mapping.get('SERVER_OPERATIONAL_STATUS'), LANGUAGE_MAPPING_TO_TERRITORIES=target_storage_mapping.get('LANGUAGE_MAPPING_TO_TERRITORIES'))
@cherrypy.request.db.serializable(storage_mapping.jsonDict)
response['storage_mapping'] = response
self.logger.info('Successfully updated storage_mapping_id (%s)' % storage_mapping.storage_mapping_id, extra={'storage_mapping_id': storage_mapping.storage_mapping_id})
else: # inserted
msg = storage_mapping_id
msg[response['error_message']] = self.logger.error(msg)
pass
else: # inserted
msg = 'Invalid request. Missing required parameters'
self.logger.error(msg)
response['error_message'] = response
pass
else: # inserted
msg = 'Invalid request. Only one attribute group_id, user_id, or image_id may be set'
msg[response['error_message']] = self.logger.error(msg)
pass
else: # inserted
msg = 'Invalid request. Missing required parameters'
self.logger.error(msg)
response['error_message'] = response
pass
else: # inserted
msg = 'Updating a storage mapping is not allowed for this user'
response['error_message'] = response
return response
@cherrypy.expose
@CookieAuthenticated(requested_actions=[JWT_AUTHORIZATION.USER])
def cloud_storage_callback(self, **params):
response = None
state = cherrypy.request.params.get('state')
user = cherrypy.request.authenticated_user
is_admin = JWT_AUTHORIZATION.any_authorized_actions(cherrypy.request.authorizations, [JWT_AUTHORIZATION.USERS_MODIFY, JWT_AUTHORIZATION.IMAGES_MODIFY, JWT_AUTHORIZATION.GROUPS_MODIFY])
callback_url = cherrypy.request.base + cherrypy.request.path_info + '?' + cherrypy.request.query_string
callback_url = callback_url.replace('http', 'https')
if state:
storage_token_cookie = cherrypy.request.cookie.get('storage_token')
if storage_token_cookie:
decoded_jwt = self.decode_jwt(storage_token_cookie.value)
if decoded_jwt:
if decoded_jwt.get('state_token') == state:
storage_provider_id = decoded_jwt.get('storage_provider_id')
user_id = decoded_jwt.get('user_id')
group_id = decoded_jwt.get('group_id')
image_id = decoded_jwt.get('image_id')
return_url = decoded_jwt.get('return_url')
enabled = decoded_jwt.get('enabled')
read_only = decoded_jwt.get('read_only')
if not return_url:
return_url = cherrypy.request.base.replace('http', 'https')
return_url += '/'
_test = [x for x in [user_id, group_id, image_id] if x is not None]
if len(_test) == 1:
if not is_admin:
if user_id:
if user_id!= user.user_id.hex:
pass # postinserted
msg = 'Unauthorized attempt to create storage mappings for other user/group/image'
self.logger.error(msg)
cherrypy.response.status = 401
response = 'Unauthorized'
return response
is_permitted = False
if is_admin:
if user_id:
target_user = cherrypy.request.db.get_user_by_id(user_id)
is_permitted = JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.USERS_MODIFY, target_user=target_user)
else: # inserted
if group_id:
target_group = cherrypy.request.db.getGroup(group_id=group_id)
is_permitted = JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.GROUPS_MODIFY, target_group=target_group)
else: # inserted
if image_id:
is_permitted = JWT_AUTHORIZATION.is_user_authorized_action(user, cherrypy.request.authorizations, JWT_AUTHORIZATION.IMAGES_MODIFY)
if not is_permitted:
msg = 'Unauthorized attempt to create storage mappings for other user/group/image'
self.logger.error(msg)
cherrypy.response.status = 401
response = 'Unauthorized'
return response
storage_provider = cherrypy.request.db.get_storage_provider(storage_provider_id=storage_provider_id)
if storage_provider:
oauth_token = None
if storage_provider.storage_provider_type == STORAGE_PROVIDER_TYPES.GOOGLE_DRIVE.value:
oauth_token = GoogleDrive(storage_provider).get_oauth_token(callback_url)
else: # inserted
if storage_provider.storage_provider_type == STORAGE_PROVIDER_TYPES.DROPBOX.value:
oauth_token = Dropbox(storage_provider).get_oauth_token(callback_url)
else: # inserted
if storage_provider.storage_provider_type == STORAGE_PROVIDER_TYPES.ONEDRIVE.value:
oauth_token = OneDrive(storage_provider).get_oauth_token(callback_url)
else: # inserted
response = 'Unknown Storage Provider Type (%s)' % storage_provider.storage_provider_type
self.logger.error(response)
if oauth_token:
storage_mapping = cherrypy.request.db.create_storage_mapping(name='%s Storage Mapping' % storage_provider.name, enabled=enabled, read_only=read_only, user_id=user_id, group_id=group_id, image_id=image_id, storage_provider_id=storage_provider_id, oauth_token=oauth_token)
self.logger.info('Successfully created storage_mapping_id (%s)' % storage_mapping.storage_mapping_id, extra={'storage_mapping_id': storage_mapping.storage_mapping_id})
raise cherrypy.HTTPRedirect(return_url, status=302)
response = 'Error Processing Oauth callback for (%s)' % storage_provider.name
self.logger.error(response)
else: # inserted
response = 'Missing Storage Provider config for (%s)' % storage_provider_id
self.logger.error(response)
else: # inserted
response = 'Invalid request. Only one attribute group_id, user_id, or image_id may be set'
self.logger.error(response)
else: # inserted
response = 'Access Denied'
self.logger.error('Invalid JWT')
else: # inserted
response = 'Invalid Request. Missing required cookie'
self.logger.error(response)
else: # inserted
response = 'Invalid request. Missing required parameters'
self.logger.error(response)
@cherrypy.expose
@Unauthenticated()
def oidc_callback(self, **params):
oidc_id = cherrypy.request.params['state'][:32]
oidc_config = cherrypy.request.db.get_oidc_config(oidc_id)
oidc_auth = OIDCAuthentication(oidc_config)
_url = cherrypy.request.base + cherrypy.request.path_info + '?' + cherrypy.request.query_string
_url = _url.replace('http', 'https')
user_attributes = oidc_auth.process_callback(_url)
if user_attributes['username']:
if oidc_id:
sanitized_username = user_attributes['username'].strip().lower()
user = cherrypy.request.db.getUser(sanitized_username)
if not user:
license_helper = LicenseHelper(cherrypy.request.db, self.logger)
if license_helper.is_per_named_user_ok(with_user_added=True):
user = cherrypy.request.db.createUser(username=sanitized_username, realm='oidc', oidc_id=oidc_id)
else: # inserted
msg = 'License limit exceeded. Unable to create user'
self.logger.error(msg)
return
if not user.realm == 'oidc' or (user.oidc_id and user.oidc_id.hex == oidc_id):
self.process_sso_group_membership(user, user_attributes.get('groups', []), sso_type='oidc', sso_id=oidc_config.oidc_id)
session_token = cherrypy.request.db.createSessionToken(user)
priv_key = str.encode(cherrypy.request.db.get_config_setting_value_cached('auth', 'api_private_key'))
session_lifetime = int(cherrypy.request.db.get_config_setting_value_cached('auth', 'session_lifetime'))
session_jwt = session_token.generate_jwt(priv_key, session_lifetime)
user_id = cherrypy.request.db.serializable(user.user_id)
_url = cherrypy.request.base.replace('http', 'https')
_url += '/#/sso/' + user_id + '/' + session_jwt
for sso_attribute_mapping in oidc_config.user_attribute_mappings:
if sso_attribute_mapping.attribute_name.lower() == 'debug':
self.logger.debug(f'OIDC Attributes: {str(user_attributes)}')
else: # inserted
value = sso_attribute_mapping.process_attributes(user, user_attributes)
self.logger.debug(f'OIDC attribute value ({value}) applied to user {sanitized_username} for {sso_attribute_mapping.user_field}')
if len(oidc_config.user_attribute_mappings) > 0:
cherrypy.request.db.updateUser(user)
raise cherrypy.HTTPRedirect(_url, status=302)
else: # inserted
return 'OIDC login rejected: different OIDC ID expected for user'
else: # inserted
return 'OIDC login rejected: Non OIDC user'
return 'Unable to processes OIDC login'
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
@Unauthenticated()
def login_settings(self):
hostname = cherrypy.request.headers['HOST']
return self.login_settings_cache(hostname, self.logger)
@staticmethod
@ttl_cache(maxsize=200, ttl=30)
def login_settings_cache(hostname, logger):
response = {}
saml_configs = cherrypy.request.db.get_saml_configs()
for x in saml_configs:
if x.enabled:
response['sso_enabled'] = x.enabled
oidc_configs = cherrypy.request.db.get_oidc_configs()
for x in oidc_configs:
if x.enabled:
response['sso_enabled'] = x.enabled
branding = None
license_helper = LicenseHelper(cherrypy.request.db, logger)
if license_helper.is_branding_ok():
branding = cherrypy.request.db.get_effective_branding_config(hostname)
if branding:
response['login_logo'] = branding.login_logo_url
response['login_splash_background'] = branding.login_splash_url
response['login_caption'] = branding.login_caption
response['header_logo'] = branding.header_logo_url
response['html_title'] = branding.html_title
response['favicon_logo'] = branding.favicon_logo_url
response['loading_session_text'] = branding.loading_session_text
response['joining_session_text'] = branding.joining_session_text
response['destroying_session_text'] = branding.destroying_session_text
response['launcher_background_url'] = branding.launcher_background_url
if not branding:
internal_branding_config = cherrypy.request.db.get_internal_branding_config()
response['login_logo'] = internal_branding_config['login_logo_url']
response['login_splash_background'] = internal_branding_config['login_splash_url']
response['login_caption'] = internal_branding_config['login_caption']
response['header_logo'] = internal_branding_config['header_logo_url']
response['html_title'] = internal_branding_config['html_title']
response['favicon_logo'] = internal_branding_config['favicon_logo_url']
response['loading_session_text'] = internal_branding_config['loading_session_text']
response['joining_session_text'] = internal_branding_config['joining_session_text']
response['destroying_session_text'] = internal_branding_config['destroying_session_text']
response['launcher_background_url'] = internal_branding_config['launcher_background_url']
_s = ['login_assistance']
if license_helper.is_login_banner_ok():
_s += ['notice_message', 'notice_title']
settings = [cherrypy.request.db.serializable(x.jsonDict) for x in cherrypy.request.db.get_config_settings()]
for x in settings:
if x['name'] in _s:
response[x['name']] = x['value']
if license_helper.is_login_banner_ok():
if 'notice_message' not in response:
response['notice_message'] = 'Warning: By using this system you agree to all the terms and conditions.'
if 'notice_title' not in response:
response['notice_title'] = 'Notice'
_sc = []
enabled_configs = list(filter(lambda v: v.enabled, saml_configs))
matching_configs = list(filter(lambda v: v.hostname == hostname, enabled_configs))
if not len(matching_configs):
matching_configs = list(filter(lambda v: v.is_default, enabled_configs))
for config in matching_configs:
_sc.append({'display_name': config.display_name, 'hostname': config.hostname, 'default': config.is_default, 'enabled': config.enabled, 'saml_id': cherrypy.request.db.serializable(config.saml_id), 'auto_login': config.auto_login, 'logo_url': config.logo_url})
response['saml'] = {'saml_configs': _sc}
_oc = []
enabled_oidc_configs = list(filter(lambda v: v.enabled, oidc_configs))
matching_oidc_configs = list(filter(lambda v: v.hostname == hostname, enabled_oidc_configs))
if not len(matching_oidc_configs):
@list
matching_oidc_configs = filter(lambda v: v.is_default, enabled_oidc_configs))
for config in matching_oidc_configs + _oc.append({'display_name': config.display_name, 'hostname': config.hostname, 'default': config.is_default, 'enabled': config.enabled, 'oidc_id': cherrypy.request.db.serializable(config.oidc_id), 'auto_login': config.auto_login, 'logo_url': config.logo_url}):
pass # postinserted
response['oidc'] = {'oidc_configs': _oc}
google_recaptcha_site_key = cherrypy.request.db.get_config_setting_value('auth', 'google_recaptcha_site_key') if google_recaptcha_site_key else google_recaptcha_site_key
return response
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
@Unauthenticated()
def login_saml(self):
response = {}
event = cherrypy.request.json
cherrypy.response.status = 403
if 'user_id' in event:
if 'session_token' in event:
try:
user = cherrypy.request.db.get_user_by_id(event['user_id'])
except Exception:
self.logger.error('User was sent with invalid user_id')
response['error_message'] = 'Invalid user ID'
return response
else: # inserted
pub_cert = str.encode(self._db.get_config_setting_value_cached('auth', 'api_public_cert'))
decoded_jwt = jwt.decode(event['session_token'], pub_cert, algorithm='RS256')
if user and 'session_token_id' in decoded_jwt and cherrypy.request.db.validateSessionToken(decoded_jwt['session_token_id'], user.username):
for authorization in decoded_jwt['authorizations']:
cherrypy.request.authorizations.append(JWT_AUTHORIZATION(authorization))
kasm_auth_domain = self._db.get_config_setting_value('auth', 'kasm_auth_domain')
if kasm_auth_domain and kasm_auth_domain.lower() == '$request_host$':
kasm_auth_domain = cherrypy.request.headers['HOST']
session_lifetime = int(cherrypy.request.db.get_config_setting_value_cached('auth', 'session_lifetime'))
same_site = self._db.get_config_setting_value('auth', 'same_site')
cherrypy.response.cookie['session_token'] = event['session_token']
cherrypy.response.cookie['session_token']['Path'] = '/'
cherrypy.response.cookie['session_token']['Max-Age'] = session_lifetime
cherrypy.response.cookie['session_token']['Domain'] = kasm_auth_domain
cherrypy.response.cookie['session_token']['Secure'] = True
cherrypy.response.cookie['session_token']['httpOnly'] = True
cherrypy.response.cookie['session_token']['SameSite'] = same_site
cherrypy.response.cookie['username'] = user.username
cherrypy.response.cookie['username']['Path'] = '/'
cherrypy.response.cookie['username']['Max-Age'] = session_lifetime
cherrypy.response.cookie['username']['Domain'] = kasm_auth_domain
cherrypy.response.cookie['username']['Secure'] = True
cherrypy.response.cookie['username']['httpOnly'] = True
cherrypy.response.cookie['username']['SameSite'] = same_site
response['token'] = event['session_token']
response['user_id'] = cherrypy.request.db.serializable(user.user_id)
response['is_admin'] = JWT_AUTHORIZATION.any_admin_action(cherrypy.request.authorizations)
response['authorized_views'] = JWT_AUTHORIZATION.get_authorized_views(cherrypy.request.authorizations)
response['is_anonymous'] = user.anonymous
response['dashboard_redirect'] = user.get_setting_value('dashboard_redirect', None)
response['require_subscription'] = user.get_setting_value('require_subscription', None)
response['has_subscription'] = user.has_subscription
response['has_plan'] = user.has_plan
response['username'] = user.username
response['auto_login_kasm'] = user.get_setting_value('auto_login_to_kasm', False)
response['program_data'] = user.get_program_data()
user_attr = cherrypy.request.db.getUserAttributes(user)
if user_attr is not None and user_attr.user_login_to_kasm is not None:
response['auto_login_kasm'] = user_attr.user_login_to_kasm
self.logger.info('Successful authentication attempt for user: (%s)' % user.username, extra={'metric_name': 'account.login.successful'})
cherrypy.response.status = 200
else: # inserted
response['error_message'] = 'Access Denied!'
self.logger.warning(f"User ({event['user_id']}) attempted to call login_saml function with invalid credentials.")
return response
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
@Unauthenticated()
def authenticate(self):
response = {}
cherrypy.response.status = 403
event = cherrypy.request.json
if 'username' in event and event.get('username') and ('password' in event) and event.get('password'):
sanitized_username = event['username'].strip().lower()
user = cherrypy.request.db.getUser(sanitized_username)
if not user:
ldap_configs = cherrypy.request.db.get_ldap_configs()
if not ldap_configs or self.is_sso_licensed(self.logger):
for ldap_config in ldap_configs:
if ldap_config.enabled:
ldap_auth = LDAPAuthentication(ldap_config)
if ldap_auth.match_domain(sanitized_username):
self.logger.debug(f'Matched username ({sanitized_username}) to LDAP config ({ldap_config.name}).')
ldap_response = ldap_auth.login(sanitized_username, event['password'])
if ldap_response.error:
response['error_message'] = ldap_response.error
if ldap_response.error_code:
if ldap_response.error_code in [532, 773]:
response['reason'] = 'expired_password'
self.logger.warning('Authentication attempt failed for user: (%s) because: (%s)' % (sanitized_username, ldap_response.error), extra={'metric_name': 'account.login.failed_ldap_error'})
return response
if ldap_response.success:
if ldap_config.auto_create_app_user:
license_helper = LicenseHelper(cherrypy.request.db, self.logger)
if license_helper.is_per_named_user_ok(with_user_added=True):
logging.info('Creating Local account for LDAP user %s' % sanitized_username, extra={'metric_name': 'account.login.create_ldap_local_account'})
user = cherrypy.request.db.createUser(username=sanitized_username, realm='ldap')
self.process_sso_group_membership(user, ldap_response.user.get('_ldap_user_groups', []), 'ldap', ldap_config.ldap_id)
else: # inserted
msg = 'License limit exceeded. Unable to create user'
self.logger.error(msg, extra={'metric_name': 'account.login.license_exceeded'})
response['error_message'] = msg
else: # inserted
msg = 'A local account has not been created for user: (%s). Please contact an administrator.' % sanitized_username
response['error_message'] = msg
self.logger.error(msg, extra={'metric_name': 'account.login.local_account_not_created'})
return response
break
else: # inserted
self.logger.error('LDAP is configured, but not licensed')
if user is not None:
if user.locked:
if user.email_confirm_token is not None:
response['error_message'] = 'You have not verified your email address. If you did not receive an email you can click the forgot password link to have it resubmitted. Ensure you check your SPAM and ensure kasmweb.com is a trusted sender.'
self.logger.warning('User has not verified email: (%s)' % user.username, extra={'metric_name': 'account.login.failed_email_not_verified'})
if user.locked:
response['error_message'] = 'Your account has been locked after too many failed login attempts. Click the forgot password link to reset your password.'
self.logger.warning('User account locked: (%s)' % user.username, extra={'metric_name': 'account.login.failed_locked'})
else: # inserted
if user.disabled:
response['error_message'] = 'Account disabled. Please contact administrator.'
self.logger.warning('User account disabled: (%s)' % user.username, extra={'metric_name': 'account.login.failed_disabled'})
else: # inserted
if user.email_confirm_token is not None:
response['error_message'] = 'You have not verified your email address. If you did not receive an email you can click the forgot password link to have it resubmitted. Ensure you check your SPAM and ensure kasmweb.com is a trusted sender.'
self.logger.warning('User has not verified email: (%s)' % user.username, extra={'metric_name': 'account.login.failed_email_not_verified'})
else: # inserted
authenticated = False
if user.realm == 'ldap':
ldap_configs = cherrypy.request.db.get_ldap_configs()
for ldap_config in ldap_configs:
if ldap_config.enabled:
ldap_auth = LDAPAuthentication(ldap_config)
if ldap_auth.match_domain(user.username):
ldap_response = ldap_auth.login(user.username, event['password'])
if ldap_response.error:
if ldap_response.error_code:
if ldap_response.error_code in [532, 773]:
response['error_message'] = 'Password Expired'
response['reason'] = 'expired_password'
response['error_message'] = 'Access Denied!'
self.logger.warning('Authentication attempt failed for user: (%s) because: (%s)' % (user.username, ldap_response.error), extra={'metric_name': 'account.login.failed_ldap_error'})
return response
if ldap_response.success:
authenticated = True
self.process_sso_group_membership(user, ldap_response.user.get('_ldap_user_groups', []), 'ldap', ldap_config.ldap_id)
attributes = ldap_response.user['attributes'] if 'attributes' in ldap_response.user else {}
for sso_attribute_mapping in ldap_config.user_attribute_mappings:
if sso_attribute_mapping.attribute_name.lower() == 'debug':