def db(app, request): _db.drop_all() _db.create_all() _db.app = app user = user_service.create('user', 'test', '*****@*****.**', True, None, []) admin_role = role_service.create('admin') admin = user_service.create('admin', 'admin', '*****@*****.**', True, None, [admin_role]) _db.session.commit() yield _db
def run(self, password): create() user = user_service.get_by_username("lemur") if not user: if not password: sys.stdout.write( "We need to set Lemur's password to continue!\n") password = prompt_pass("Password") password1 = prompt_pass("Confirm Password") if password != password1: sys.stderr.write("[!] Passwords do not match!\n") sys.exit(1) role = role_service.get_by_name('admin') if role: sys.stdout.write( "[-] Admin role already created, skipping...!\n") else: # we create an admin role role = role_service.create( 'admin', description='this is the lemur administrator role') sys.stdout.write("[+] Created 'admin' role\n") user_service.create("lemur", password, 'lemur@nobody', True, None, [role]) sys.stdout.write( "[+] Added a 'lemur' user and added it to the 'admin' role!\n") else: sys.stdout.write( "[-] Default user has already been created, skipping...!\n") sys.stdout.write("[+] Creating expiration email notifications!\n") sys.stdout.write( "[!] Using {0} as specified by LEMUR_SECURITY_TEAM_EMAIL for notifications\n" .format("LEMUR_SECURITY_TEAM_EMAIL")) intervals = current_app.config.get( "LEMUR_DEFAULT_EXPIRATION_NOTIFICATION_INTERVALS", []) sys.stdout.write( "[!] Creating {num} notifications for {intervals} days as specified by LEMUR_DEFAULT_EXPIRATION_NOTIFICATION_INTERVALS\n" .format(num=len(intervals), intervals=",".join([str(x) for x in intervals]))) recipients = current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL') notification_service.create_default_expiration_notifications( "DEFAULT_SECURITY", recipients=recipients) sys.stdout.write("[/] Done!\n")
def update_user(user, profile, roles): """Updates user with current profile information and associated roles. :param user: :param profile: :param roles: """ # if we get an sso user create them an account if not user: user = user_service.create( profile['email'], get_psuedo_random_string(), profile['email'], True, profile.get('thumbnailPhotoUrl'), roles ) else: # we add 'lemur' specific roles, so they do not get marked as removed for ur in user.roles: if not ur.third_party: roles.append(ur) # update any changes to the user user_service.update( user.id, profile['email'], profile['email'], True, profile.get('thumbnailPhotoUrl'), # profile isn't google+ enabled roles )
def _update_user(self, roles): """ create or update a local user instance. """ # try to get user from local database user = user_service.get_by_email(self.ldap_principal) # create them a local account if not user: user = user_service.create( self.ldap_username, get_psuedo_random_string(), self.ldap_principal, True, '', # thumbnailPhotoUrl list(roles)) else: # we add 'lemur' specific roles, so they do not get marked as removed for ur in user.roles: if not ur.third_party: roles.add(ur) # update any changes to the user user_service.update(user.id, self.ldap_username, self.ldap_principal, user.active, user.profile_picture, list(roles)) return user
def _update_user(self, roles): """ create or update a local user instance. """ # try to get user from local database user = user_service.get_by_email(self.ldap_principal) # create them a local account if not user: user = user_service.create( self.ldap_username, get_psuedo_random_string(), self.ldap_principal, True, '', # thumbnailPhotoUrl list(roles) ) else: # we add 'lemur' specific roles, so they do not get marked as removed for ur in user.roles: if ur.authority_id: roles.add(ur) # update any changes to the user user_service.update( user.id, self.ldap_username, self.ldap_principal, user.active, user.profile_picture, list(roles) ) return user
def run(self, password): create() user = user_service.get_by_username("lemur") if not user: if not password: sys.stdout.write("We need to set Lemur's password to continue!\n") password = prompt_pass("Password") password1 = prompt_pass("Confirm Password") if password != password1: sys.stderr.write("[!] Passwords do not match!\n") sys.exit(1) role = role_service.get_by_name("admin") if role: sys.stdout.write("[-] Admin role already created, skipping...!\n") else: # we create an admin role role = role_service.create("admin", description="this is the lemur administrator role") sys.stdout.write("[+] Created 'admin' role\n") user_service.create("lemur", password, "lemur@nobody", True, None, [role]) sys.stdout.write("[+] Added a 'lemur' user and added it to the 'admin' role!\n") else: sys.stdout.write("[-] Default user has already been created, skipping...!\n") sys.stdout.write("[+] Creating expiration email notifications!\n") sys.stdout.write( "[!] Using {0} as specified by LEMUR_SECURITY_TEAM_EMAIL for notifications\n".format( "LEMUR_SECURITY_TEAM_EMAIL" ) ) intervals = current_app.config.get("LEMUR_DEFAULT_EXPIRATION_NOTIFICATION_INTERVALS", []) sys.stdout.write( "[!] Creating {num} notifications for {intervals} days as specified by LEMUR_DEFAULT_EXPIRATION_NOTIFICATION_INTERVALS\n".format( num=len(intervals), intervals=",".join([str(x) for x in intervals]) ) ) recipients = current_app.config.get("LEMUR_SECURITY_TEAM_EMAIL") notification_service.create_default_expiration_notifications("DEFAULT_SECURITY", recipients=recipients) sys.stdout.write("[/] Done!\n")
def post(self, data=None): """ .. http:post:: /users Creates a new user **Example request**: .. sourcecode:: http POST /users HTTP/1.1 Host: example.com Accept: application/json, text/javascript Content-Type: application/json;charset=UTF-8 { "username": "******", "email": "*****@*****.**", "active": true, "roles": [ {'id': 1} - or - {'name': 'myRole'} ] } **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: text/javascript { "id": 3, "active": True, "email": "[email protected], "username": "******", "profileImage": null } :arg username: username for new user :arg email: email address for new user :arg password: password for new user :arg active: boolean, if the user is currently active :arg roles: list, roles that the user should be apart of :reqheader Authorization: OAuth token to authenticate :statuscode 200: no error """ return service.create( data["username"], data["password"], data["email"], data["active"], None, data["roles"], )
def run(self, username, email, active, roles): role_objs = [] for r in roles: role_obj = role_service.get_by_name(r) if role_obj: role_objs.append(role_obj) else: sys.stderr.write("[!] Cannot find role {0}".format(r)) sys.exit(1) password1 = prompt_pass("Password") password2 = prompt_pass("Confirm Password") if password1 != password2: sys.stderr.write("[!] Passwords do not match") sys.exit(1) user_service.create(username, password1, email, active, None, role_objs) sys.stdout.write("[+] Created new user: {0}".format(username))
def run(self, username, email, active, roles): role_objs = [] for r in roles: role_obj = role_service.get_by_name(r) if role_obj: role_objs.append(role_obj) else: sys.stderr.write("[!] Cannot find role {0}\n".format(r)) sys.exit(1) password1 = prompt_pass("Password") password2 = prompt_pass("Confirm Password") if password1 != password2: sys.stderr.write("[!] Passwords do not match!\n") sys.exit(1) user_service.create(username, password1, email, active, None, role_objs) sys.stdout.write("[+] Created new user: {0}\n".format(username))
def post(self): """ .. http:post:: /users Creates a new user **Example request**: .. sourcecode:: http POST /users HTTP/1.1 Host: example.com Accept: application/json, text/javascript { "username": "******", "email": "*****@*****.**", "active": true, "roles": [] } **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: text/javascript { "id": 3, "active": True, "email": "[email protected], "username": "******", "profileImage": null } :arg username: username for new user :arg email: email address for new user :arg password: password for new user :arg active: boolean, if the user is currently active :arg roles: list, roles that the user should be apart of :reqheader Authorization: OAuth token to authenticate :statuscode 200: no error """ self.reqparse.add_argument('username', type=str, location='json', required=True) self.reqparse.add_argument('email', type=str, location='json', required=True) self.reqparse.add_argument('password', type=str, location='json', required=True) self.reqparse.add_argument('active', type=bool, default=True, location='json') self.reqparse.add_argument('roles', type=roles, default=[], location='json') args = self.reqparse.parse_args() return service.create(args['username'], args['password'], args['email'], args['active'], None, args['roles'])
def post(self): """ .. http:post:: /users Creates a new user **Example request**: .. sourcecode:: http POST /users HTTP/1.1 Host: example.com Accept: application/json, text/javascript { "username": "******", "email": "*****@*****.**", "active": true, "roles": [] } **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: text/javascript { "id": 3, "active": True, "email": "[email protected], "username": "******", "profileImage": null } :arg username: username for new user :arg email: email address for new user :arg password: password for new user :arg active: boolean, if the user is currently active :arg roles: list, roles that the user should be apart of :reqheader Authorization: OAuth token to authenticate :statuscode 200: no error """ self.reqparse.add_argument('username', type=str, location='json', required=True) self.reqparse.add_argument('email', type=str, location='json', required=True) self.reqparse.add_argument('password', type=str, location='json', default=None) self.reqparse.add_argument('active', type=bool, default=True, location='json') self.reqparse.add_argument('roles', type=roles, default=[], location='json') args = self.reqparse.parse_args() return service.create(args['username'], args['password'], args['email'], args['active'], None, args['roles'])
def post(self, data=None): """ .. http:post:: /users Creates a new user **Example request**: .. sourcecode:: http POST /users HTTP/1.1 Host: example.com Accept: application/json, text/javascript { "username": "******", "email": "*****@*****.**", "active": true, "roles": [ {'id': 1} - or - {'name': 'myRole'} ] } **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Vary: Accept Content-Type: text/javascript { "id": 3, "active": True, "email": "[email protected], "username": "******", "profileImage": null } :arg username: username for new user :arg email: email address for new user :arg password: password for new user :arg active: boolean, if the user is currently active :arg roles: list, roles that the user should be apart of :reqheader Authorization: OAuth token to authenticate :statuscode 200: no error """ return service.create(data['username'], data['password'], data['email'], data['active'], None, data['roles'])
def update_user(user, profile, roles): """Updates user with current profile information and associated roles. :param user: :param profile: :param roles: """ # if we get an sso user create them an account if not user: user = user_service.create( profile["email"], get_psuedo_random_string(), profile["email"], True, profile.get("thumbnailPhotoUrl"), roles, ) else: # we add 'lemur' specific roles, so they do not get marked as removed removed_roles = [] for ur in user.roles: if not ur.third_party: roles.append(ur) elif ur not in roles: # This is a role assigned in lemur, but not returned by sso during current login removed_roles.append(ur.name) if removed_roles: log_service.audit_log("unassign_role", user.username, f"Un-assigning roles {removed_roles}") # update any changes to the user user_service.update( user.id, profile["email"], profile["email"], True, profile.get("thumbnailPhotoUrl"), # profile isn't google+ enabled roles, ) return user
def post(self): self.reqparse.add_argument("clientId", type=str, required=True, location="json") self.reqparse.add_argument("redirectUri", type=str, required=True, location="json") self.reqparse.add_argument("code", type=str, required=True, location="json") args = self.reqparse.parse_args() # take the information we have received from the provider to create a new request params = { "client_id": args["clientId"], "grant_type": "authorization_code", "scope": "openid email profile address", "redirect_uri": args["redirectUri"], "code": args["code"], } # you can either discover these dynamically or simply configure them access_token_url = current_app.config.get("PING_ACCESS_TOKEN_URL") user_api_url = current_app.config.get("PING_USER_API_URL") # the secret and cliendId will be given to you when you signup for the provider token = "{0}:{1}".format(args["clientId"], current_app.config.get("PING_SECRET")) if sys.version_info >= (3, 0): basic = base64.b64encode(bytes(token, "utf-8")) headers = {"authorization": "basic {0}".format(basic.decode("utf-8"))} else: basic = base64.b64encode(token, "utf-8") headers = {"authorization": "basic {0}".format(basic)} # exchange authorization code for access token. r = requests.post(access_token_url, headers=headers, params=params) id_token = r.json()["id_token"] access_token = r.json()["access_token"] # fetch token public key header_data = fetch_token_header(id_token) jwks_url = current_app.config.get("PING_JWKS_URL") # retrieve the key material as specified by the token header r = requests.get(jwks_url) for key in r.json()["keys"]: if key["kid"] == header_data["kid"]: secret = get_rsa_public_key(key["n"], key["e"]) algo = header_data["alg"] break else: return dict(message="Key not found"), 403 # validate your token based on the key it was signed with try: if sys.version_info >= (3, 0): jwt.decode(id_token, secret.decode("utf-8"), algorithms=[algo], audience=args["clientId"]) else: jwt.decode(id_token, secret, algorithms=[algo], audience=args["clientId"]) except jwt.DecodeError: return dict(message="Token is invalid"), 403 except jwt.ExpiredSignatureError: return dict(message="Token has expired"), 403 except jwt.InvalidTokenError: return dict(message="Token is invalid"), 403 user_params = dict(access_token=access_token, schema="profile") # retrieve information about the current user. r = requests.get(user_api_url, params=user_params) profile = r.json() user = user_service.get_by_email(profile["email"]) metrics.send("successful_login", "counter", 1) # update their google 'roles' roles = [] for group in profile["googleGroups"]: role = role_service.get_by_name(group) if not role: role = role_service.create(group, description="This is a google group based role created by Lemur") roles.append(role) role = role_service.get_by_name(profile["email"]) if not role: role = role_service.create(profile["email"], description="This is a user specific role") roles.append(role) # if we get an sso user create them an account if not user: # every user is an operator (tied to a default role) if current_app.config.get("LEMUR_DEFAULT_ROLE"): v = role_service.get_by_name(current_app.config.get("LEMUR_DEFAULT_ROLE")) if v: roles.append(v) user = user_service.create( profile["email"], get_psuedo_random_string(), profile["email"], True, profile.get("thumbnailPhotoUrl"), roles, ) else: # we add 'lemur' specific roles, so they do not get marked as removed for ur in user.roles: if ur.authority_id: roles.append(ur) # update any changes to the user user_service.update( user.id, profile["email"], profile["email"], True, profile.get("thumbnailPhotoUrl"), # incase profile isn't google+ enabled roles, ) # Tell Flask-Principal the identity changed identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) return dict(token=create_token(user))
def run(self, dns, elb_name, owner, authority, description, notifications, destinations, region, dport, sport, dryrun): from lemur.certificates import service from lemur.plugins.lemur_aws import elb from boto.exception import BotoServerError # configure the owner if we can find it, or go for default, and put it in the global owner = self.configure_user(owner) # make a config blob from the command line arguments cert_options = self.build_cert_options( destinations=destinations, notifications=notifications, description=description, owner=owner, dns=dns, authority=authority) aws_account = self.get_destination_account(destinations) if dryrun: import json cert_options['authority'] = cert_options['authority'].name sys.stdout.write('Will create certificate using options: {}\n' .format(json.dumps(cert_options, sort_keys=True, indent=2))) sys.stdout.write('Will create listener {}->{} HTTPS using the new certificate to elb {}\n' .format(sport, dport, elb_name)) sys.exit(0) if self.check_duplicate_listener(elb_name, region, aws_account, sport, dport): sys.stderr.write("ELB {} already has a listener {}->{}\nAborting...\n".format(elb_name, sport, dport)) sys.exit(1) # create the certificate try: sys.stdout.write('Creating certificate for {}\n'.format(cert_options['commonName'])) cert = service.create(**cert_options) except Exception as e: if e.message == 'Duplicate certificate: a certificate with the same common name exists already': sys.stderr.write("Certificate already exists named: {}\n".format(dns[0])) sys.exit(1) raise e cert_arn = cert.get_arn(aws_account) sys.stderr.write('cert arn: {}\n'.format(cert_arn)) sys.stderr.write('Configuring elb {} from port {} to port {} in region {} with cert {}\n' .format(elb_name, sport, dport, region, cert_arn)) delay = 1 done = False retries = 5 while not done and retries > 0: try: elb.create_new_listeners(aws_account, region, elb_name, [(sport, dport, 'HTTPS', cert_arn)]) except BotoServerError as bse: # if the server returns ad error, the certificate if bse.error_code == 'CertificateNotFound': sys.stderr.write('Certificate not available yet in the AWS account, waiting {}, {} retries left\n' .format(delay, retries)) time.sleep(delay) delay *= 2 retries -= 1 elif bse.error_code == 'DuplicateListener': sys.stderr.write('ELB {} already has a listener {}->{}'.format(elb_name, sport, dport)) sys.exit(1) else: raise bse else: done = True
def post(self): self.reqparse.add_argument('clientId', type=str, required=True, location='json') self.reqparse.add_argument('redirectUri', type=str, required=True, location='json') self.reqparse.add_argument('code', type=str, required=True, location='json') args = self.reqparse.parse_args() # take the information we have received from the provider to create a new request params = { 'client_id': args['clientId'], 'grant_type': 'authorization_code', 'scope': 'openid email profile address', 'redirect_uri': args['redirectUri'], 'code': args['code'] } # you can either discover these dynamically or simply configure them access_token_url = current_app.config.get('PING_ACCESS_TOKEN_URL') user_api_url = current_app.config.get('PING_USER_API_URL') # the secret and cliendId will be given to you when you signup for the provider basic = base64.b64encode('{0}:{1}'.format( args['clientId'], current_app.config.get("PING_SECRET"))) headers = {'Authorization': 'Basic {0}'.format(basic)} # exchange authorization code for access token. r = requests.post(access_token_url, headers=headers, params=params) id_token = r.json()['id_token'] access_token = r.json()['access_token'] # fetch token public key header_data = fetch_token_header(id_token) jwks_url = current_app.config.get('PING_JWKS_URL') # retrieve the key material as specified by the token header r = requests.get(jwks_url) for key in r.json()['keys']: if key['kid'] == header_data['kid']: secret = get_rsa_public_key(key['n'], key['e']) algo = header_data['alg'] break else: return dict(message='Key not found'), 403 # validate your token based on the key it was signed with try: jwt.decode(id_token, secret, algorithms=[algo], audience=args['clientId']) except jwt.DecodeError: return dict(message='Token is invalid'), 403 except jwt.ExpiredSignatureError: return dict(message='Token has expired'), 403 except jwt.InvalidTokenError: return dict(message='Token is invalid'), 403 user_params = dict(access_token=access_token, schema='profile') # retrieve information about the current user. r = requests.get(user_api_url, params=user_params) profile = r.json() user = user_service.get_by_email(profile['email']) # update their google 'roles' roles = [] for group in profile['googleGroups']: role = role_service.get_by_name(group) if not role: role = role_service.create( group, description= 'This is a google group based role created by Lemur') roles.append(role) # if we get an sso user create them an account # we still pick a random password in case sso is down if not user: # every user is an operator (tied to a default role) if current_app.config.get('LEMUR_DEFAULT_ROLE'): v = role_service.get_by_name( current_app.config.get('LEMUR_DEFAULT_ROLE')) if v: roles.append(v) user = user_service.create(profile['email'], get_psuedo_random_string(), profile['email'], True, profile.get('thumbnailPhotoUrl'), roles) else: # we add 'lemur' specific roles, so they do not get marked as removed for ur in user.roles: if ur.authority_id: roles.append(ur) # update any changes to the user user_service.update( user.id, profile['email'], profile['email'], True, profile.get('thumbnailPhotoUrl' ), # incase profile isn't google+ enabled roles) # Tell Flask-Principal the identity changed identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) return dict(token=create_token(user))
def post(self): self.reqparse.add_argument('clientId', type=str, required=True, location='json') self.reqparse.add_argument('redirectUri', type=str, required=True, location='json') self.reqparse.add_argument('code', type=str, required=True, location='json') args = self.reqparse.parse_args() # take the information we have received from the provider to create a new request params = { 'grant_type': 'authorization_code', 'scope': 'openid email profile groups', 'redirect_uri': args['redirectUri'], 'code': args['code'], } # you can either discover these dynamically or simply configure them access_token_url = current_app.config.get('OAUTH2_ACCESS_TOKEN_URL') user_api_url = current_app.config.get('OAUTH2_USER_API_URL') verify_cert = current_app.config.get('OAUTH2_VERIFY_CERT', True) # the secret and cliendId will be given to you when you signup for the provider token = '{0}:{1}'.format(args['clientId'], current_app.config.get("OAUTH2_SECRET")) basic = base64.b64encode(bytes(token, 'utf-8')) headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'authorization': 'basic {0}'.format(basic.decode('utf-8')) } # exchange authorization code for access token. # Try Params first r = requests.post(access_token_url, headers=headers, params=params, verify=verify_cert) if r.status_code == 400: r = requests.post(access_token_url, headers=headers, data=params, verify=verify_cert) id_token = r.json()['id_token'] access_token = r.json()['access_token'] # fetch token public key header_data = fetch_token_header(id_token) jwks_url = current_app.config.get('OAUTH2_JWKS_URL') # retrieve the key material as specified by the token header r = requests.get(jwks_url, verify=verify_cert) for key in r.json()['keys']: if key['kid'] == header_data['kid']: secret = get_rsa_public_key(key['n'], key['e']) algo = header_data['alg'] break else: return dict(message='Key not found'), 401 # validate your token based on the key it was signed with try: if sys.version_info >= (3, 0): jwt.decode(id_token, secret.decode('utf-8'), algorithms=[algo], audience=args['clientId']) else: jwt.decode(id_token, secret, algorithms=[algo], audience=args['clientId']) except jwt.DecodeError: return dict(message='Token is invalid'), 401 except jwt.ExpiredSignatureError: return dict(message='Token has expired'), 401 except jwt.InvalidTokenError: return dict(message='Token is invalid'), 401 headers = {'authorization': 'Bearer {0}'.format(access_token)} # retrieve information about the current user. r = requests.get(user_api_url, headers=headers, verify=verify_cert) profile = r.json() user = user_service.get_by_email(profile['email']) metrics.send('successful_login', 'counter', 1) # update with roles sent by identity provider roles = [] if 'roles' in profile: for group in profile['roles']: role = role_service.get_by_name(group) if not role: role = role_service.create( group, description= 'This is a group configured by identity provider', third_party=True) if not role.third_party: role = role_service.set_third_party( role.id, third_party_status=True) roles.append(role) role = role_service.get_by_name(profile['email']) if not role: role = role_service.create( profile['email'], description='This is a user specific role', third_party=True) if not role.third_party: role = role_service.set_third_party(role.id, third_party_status=True) roles.append(role) # if we get an sso user create them an account if not user: # every user is an operator (tied to a default role) if current_app.config.get('LEMUR_DEFAULT_ROLE'): v = role_service.get_by_name( current_app.config.get('LEMUR_DEFAULT_ROLE')) if not v.third_party: v = role_service.set_third_party(v.id, third_party_status=True) if v: roles.append(v) user = user_service.create(profile['name'], get_psuedo_random_string(), profile['email'], True, profile.get('thumbnailPhotoUrl'), roles) else: # we add 'lemur' specific roles, so they do not get marked as removed for ur in user.roles: if not ur.third_party: roles.append(ur) # update any changes to the user user_service.update( user.id, profile['name'], profile['email'], True, profile.get('thumbnailPhotoUrl' ), # incase profile isn't google+ enabled roles) # Tell Flask-Principal the identity changed identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) return dict(token=create_token(user))
def post(self): self.reqparse.add_argument('clientId', type=str, required=True, location='json') self.reqparse.add_argument('redirectUri', type=str, required=True, location='json') self.reqparse.add_argument('code', type=str, required=True, location='json') args = self.reqparse.parse_args() # take the information we have received from the provider to create a new request params = { 'client_id': args['clientId'], 'grant_type': 'authorization_code', 'scope': 'openid email profile address', 'redirect_uri': args['redirectUri'], 'code': args['code'] } # you can either discover these dynamically or simply configure them access_token_url = current_app.config.get('PING_ACCESS_TOKEN_URL') user_api_url = current_app.config.get('PING_USER_API_URL') # the secret and cliendId will be given to you when you signup for the provider basic = base64.b64encode('{0}:{1}'.format(args['clientId'], current_app.config.get("PING_SECRET"))) headers = {'Authorization': 'Basic {0}'.format(basic)} # exchange authorization code for access token. r = requests.post(access_token_url, headers=headers, params=params) id_token = r.json()['id_token'] access_token = r.json()['access_token'] # fetch token public key header_data = fetch_token_header(id_token) jwks_url = current_app.config.get('PING_JWKS_URL') # retrieve the key material as specified by the token header r = requests.get(jwks_url) for key in r.json()['keys']: if key['kid'] == header_data['kid']: secret = get_rsa_public_key(key['n'], key['e']) algo = header_data['alg'] break else: return dict(message='Key not found'), 403 # validate your token based on the key it was signed with try: jwt.decode(id_token, secret, algorithms=[algo], audience=args['clientId']) except jwt.DecodeError: return dict(message='Token is invalid'), 403 except jwt.ExpiredSignatureError: return dict(message='Token has expired'), 403 except jwt.InvalidTokenError: return dict(message='Token is invalid'), 403 user_params = dict(access_token=access_token, schema='profile') # retrieve information about the current user. r = requests.get(user_api_url, params=user_params) profile = r.json() user = user_service.get_by_email(profile['email']) # update their google 'roles' roles = [] for group in profile['googleGroups']: role = role_service.get_by_name(group) if not role: role = role_service.create(group, description='This is a google group based role created by Lemur') roles.append(role) # if we get an sso user create them an account # we still pick a random password in case sso is down if not user: # every user is an operator (tied to a default role) if current_app.config.get('LEMUR_DEFAULT_ROLE'): v = role_service.get_by_name(current_app.config.get('LEMUR_DEFAULT_ROLE')) if v: roles.append(v) user = user_service.create( profile['email'], get_psuedo_random_string(), profile['email'], True, profile.get('thumbnailPhotoUrl'), roles ) else: # we add 'lemur' specific roles, so they do not get marked as removed for ur in user.roles: if ur.authority_id: roles.append(ur) # update any changes to the user user_service.update( user.id, profile['email'], profile['email'], True, profile.get('thumbnailPhotoUrl'), # incase profile isn't google+ enabled roles ) # Tell Flask-Principal the identity changed identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) return dict(token=create_token(user))
def run(self, password): create() user = user_service.get_by_username("lemur") admin_role = role_service.get_by_name("admin") if admin_role: sys.stdout.write("[-] Admin role already created, skipping...!\n") else: # we create an admin role admin_role = role_service.create( "admin", description="This is the Lemur administrator role.") sys.stdout.write("[+] Created 'admin' role\n") operator_role = role_service.get_by_name("operator") if operator_role: sys.stdout.write( "[-] Operator role already created, skipping...!\n") else: # we create an operator role operator_role = role_service.create( "operator", description="This is the Lemur operator role.") sys.stdout.write("[+] Created 'operator' role\n") read_only_role = role_service.get_by_name("read-only") if read_only_role: sys.stdout.write( "[-] Read only role already created, skipping...!\n") else: # we create an read only role read_only_role = role_service.create( "read-only", description="This is the Lemur read only role.") sys.stdout.write("[+] Created 'read-only' role\n") if not user: if not password: sys.stdout.write( "We need to set Lemur's password to continue!\n") password = prompt_pass("Password") password1 = prompt_pass("Confirm Password") if password != password1: sys.stderr.write("[!] Passwords do not match!\n") sys.exit(1) user_service.create("lemur", password, "*****@*****.**", True, None, [admin_role]) sys.stdout.write( "[+] Created the user 'lemur' and granted it the 'admin' role!\n" ) else: sys.stdout.write( "[-] Default user has already been created, skipping...!\n") intervals = current_app.config.get( "LEMUR_DEFAULT_EXPIRATION_NOTIFICATION_INTERVALS", []) sys.stdout.write( "[!] Creating {num} notifications for {intervals} days as specified by LEMUR_DEFAULT_EXPIRATION_NOTIFICATION_INTERVALS\n" .format(num=len(intervals), intervals=",".join([str(x) for x in intervals]))) recipients = current_app.config.get("LEMUR_SECURITY_TEAM_EMAIL") sys.stdout.write("[+] Creating expiration email notifications!\n") sys.stdout.write( "[!] Using {0} as specified by LEMUR_SECURITY_TEAM_EMAIL for notifications\n" .format(recipients)) notification_service.create_default_expiration_notifications( "DEFAULT_SECURITY", recipients=recipients) _DEFAULT_ROTATION_INTERVAL = "default" default_rotation_interval = policy_service.get_by_name( _DEFAULT_ROTATION_INTERVAL) if default_rotation_interval: sys.stdout.write( "[-] Default rotation interval policy already created, skipping...!\n" ) else: days = current_app.config.get("LEMUR_DEFAULT_ROTATION_INTERVAL", 30) sys.stdout.write( "[+] Creating default certificate rotation policy of {days} days before issuance.\n" .format(days=days)) policy_service.create(days=days, name=_DEFAULT_ROTATION_INTERVAL) sys.stdout.write("[/] Done!\n")
def run(self, password): create() user = user_service.get_by_username("lemur") admin_role = role_service.get_by_name('admin') if admin_role: sys.stdout.write("[-] Admin role already created, skipping...!\n") else: # we create an admin role admin_role = role_service.create('admin', description='This is the Lemur administrator role.') sys.stdout.write("[+] Created 'admin' role\n") operator_role = role_service.get_by_name('operator') if operator_role: sys.stdout.write("[-] Operator role already created, skipping...!\n") else: # we create an operator role operator_role = role_service.create('operator', description='This is the Lemur operator role.') sys.stdout.write("[+] Created 'operator' role\n") read_only_role = role_service.get_by_name('read-only') if read_only_role: sys.stdout.write("[-] Read only role already created, skipping...!\n") else: # we create an read only role read_only_role = role_service.create('read-only', description='This is the Lemur read only role.') sys.stdout.write("[+] Created 'read-only' role\n") if not user: if not password: sys.stdout.write("We need to set Lemur's password to continue!\n") password = prompt_pass("Password") password1 = prompt_pass("Confirm Password") if password != password1: sys.stderr.write("[!] Passwords do not match!\n") sys.exit(1) user_service.create("lemur", password, '*****@*****.**', True, None, [admin_role]) sys.stdout.write("[+] Created the user 'lemur' and granted it the 'admin' role!\n") else: sys.stdout.write("[-] Default user has already been created, skipping...!\n") intervals = current_app.config.get("LEMUR_DEFAULT_EXPIRATION_NOTIFICATION_INTERVALS", []) sys.stdout.write( "[!] Creating {num} notifications for {intervals} days as specified by LEMUR_DEFAULT_EXPIRATION_NOTIFICATION_INTERVALS\n".format( num=len(intervals), intervals=",".join([str(x) for x in intervals]) ) ) recipients = current_app.config.get('LEMUR_SECURITY_TEAM_EMAIL') sys.stdout.write("[+] Creating expiration email notifications!\n") sys.stdout.write("[!] Using {0} as specified by LEMUR_SECURITY_TEAM_EMAIL for notifications\n".format(recipients)) notification_service.create_default_expiration_notifications("DEFAULT_SECURITY", recipients=recipients) _DEFAULT_ROTATION_INTERVAL = 'default' default_rotation_interval = policy_service.get_by_name(_DEFAULT_ROTATION_INTERVAL) if default_rotation_interval: sys.stdout.write("[-] Default rotation interval policy already created, skipping...!\n") else: days = current_app.config.get("LEMUR_DEFAULT_ROTATION_INTERVAL", 30) sys.stdout.write("[+] Creating default certificate rotation policy of {days} days before issuance.\n".format( days=days)) policy_service.create(days=days, name=_DEFAULT_ROTATION_INTERVAL) sys.stdout.write("[/] Done!\n")