def test_leave_permission_denied(self): network_uuid = create_network(uuid())[0] with self.assertRaises(NoPermissionsException): self.client.ms("network", ["leave"], uuid=network_uuid, device=uuid())
def admin_config(): config_db = model.Config.get_master_db() form = ConfigUpdateForm(obj=config_db) if form.validate_on_submit(): if form.trusted_hosts.data: form.trusted_hosts.data = set( [e.strip() for e in form.trusted_hosts.data.split(',')]) else: form.trusted_hosts.data = [] form.populate_obj(config_db) if not config_db.flask_secret_key: config_db.flask_secret_key = util.uuid() if not config_db.salt: config_db.salt = util.uuid() config_db.put() reload(config) app.config.update(CONFIG_DB=config_db) return flask.redirect(flask.url_for('admin')) form.trusted_hosts.data = ', '.join(config_db.trusted_hosts) return flask.render_template( 'admin/admin_config.html', title=_('App Config'), html_class='admin-config', form=form, api_url=flask.url_for('api.admin.config'), )
def test_invite_device_not_online(self): network_uuid = create_network(uuid())[0] with self.assertRaises(DeviceNotOnlineException): self.client.ms("network", ["invite"], uuid=network_uuid, device=uuid())
def user_activate(token): if auth.is_logged_in(): flask_login.logout_user() return flask.redirect(flask.request.path) user_db = model.User.get_by('token', token) if not user_db: flask.flash('That link is either invalid or expired.', category='danger') return flask.redirect(flask.url_for('welcome')) form = UserActivateForm(obj=user_db) if form.validate_on_submit(): form.populate_obj(user_db) user_db.password_hash = util.password_hash(user_db, form.password.data) user_db.session_token = util.uuid() user_db.token = util.uuid() user_db.verified = True user_db.put() return auth.signin_user_db(user_db) return flask.render_template( 'user/user_activate.html', title='Activate Account', html_class='user-activate', user_db=user_db, form=form, )
def user_reset(token=None): user_db = model.User.get_by('token', token) if not user_db: flask.flash('That link is either invalid or expired.', category='danger') return flask.redirect(flask.url_for('welcome')) if auth.is_logged_in(): flask_login.logout_user() return flask.redirect(flask.request.path) form = UserResetForm() if form.validate_on_submit(): user_db.password_hash = util.password_hash(user_db, form.new_password.data) user_db.session_token = util.uuid() user_db.token = util.uuid() user_db.verified = True user_db.put() flask.flash('Your password was changed succesfully.', category='success') return auth.signin_user_db(user_db) return flask.render_template( 'user/user_reset.html', title='Reset Password', html_class='user-reset', form=form, user_db=user_db, )
def create_user_db(auth_id, name, username, email='', verified=False, **props): email = email.lower() if email else '' if verified and email: user_dbs, cursors = model.User.get_dbs(email=email, verified=True, limit=2) if len(user_dbs) == 1: user_db = user_dbs[0] user_db.auth_ids.append(auth_id) user_db.put() task.new_user_notification(user_db) return user_db if isinstance(username, str): username = username.decode('utf-8') username = unidecode.unidecode(username.split('@')[0].lower()).strip() username = re.sub(r'[\W_]+', '.', username) new_username = username n = 1 while not model.User.is_username_available(new_username): new_username = '******' % (username, n) n += 1 user_db = model.User( name=name, email=email, username=new_username, auth_ids=[auth_id] if auth_id else [], verified=verified, token=util.uuid(), session_token=util.uuid(), **props ) user_db.put() task.new_user_notification(user_db) return user_db
def test_send_unknown(self): wallet_uuids, wallet_keys = create_wallet(10, 2, [super_uuid, uuid()]) # unknown source uuid with self.assertRaises(UnknownSourceOrDestinationException): self.client.ms( "currency", ["send"], source_uuid=uuid(), key=wallet_keys[0], send_amount=10, destination_uuid=wallet_uuids[1], usage="test", ) # unknown destination_uuid with self.assertRaises(UnknownSourceOrDestinationException): self.client.ms( "currency", ["send"], source_uuid=wallet_uuids[0], key=wallet_keys[0], send_amount=10, destination_uuid=uuid(), usage="test", )
def test_miner_wallet_device_not_found(self): service_uuid = create_service(uuid(), "miner")[0] with self.assertRaises(DeviceNotFoundException): self.client.ms("service", ["miner", "wallet"], service_uuid=service_uuid, wallet_uuid=uuid())
def admin_config_update(): config_db = model.Config.get_master_db() form = ConfigUpdateForm(obj=config_db) if form.validate_on_submit(): form.populate_obj(config_db) if not config_db.flask_secret_key: config_db.flask_secret_key = util.uuid() if not config_db.salt: config_db.salt = util.uuid() config_db.put() reload(config) app.config.update(CONFIG_DB=config_db) return flask.redirect(flask.url_for('welcome')) if flask.request.path.startswith('/_s/'): return util.jsonify_model_db(config_db) instances_url = None if config.PRODUCTION: instances_url = '%s?app_id=%s&version_id=%s' % ( 'https://appengine.google.com/instances', app_identity.get_application_id(), config.CURRENT_VERSION_ID, ) return flask.render_template( 'admin/config_update.html', title='Admin Config', html_class='admin-config', form=form, config_db=config_db, instances_url=instances_url, has_json=True, )
class Config(model.Base, model.ConfigAuth): analytics_id = ndb.StringProperty(default='', verbose_name='Tracking ID') announcement_html = ndb.TextProperty(default='', verbose_name='Announcement HTML') announcement_type = ndb.StringProperty(default='info', choices=['info', 'warning', 'success', 'danger']) anonymous_recaptcha = ndb.BooleanProperty(default=False, verbose_name='Use reCAPTCHA in forms for unauthorized users') brand_name = ndb.StringProperty(default=config.APPLICATION_ID) bucket_name = ndb.StringProperty(default=config.DEFAULT_GCS_BUCKET_NAME) check_unique_email = ndb.BooleanProperty(default=True, verbose_name='Check for uniqueness of the verified emails') email_authentication = ndb.BooleanProperty(default=False, verbose_name='Email authentication for sign in/sign up') feedback_email = ndb.StringProperty(default='') flask_secret_key = ndb.StringProperty(default=util.uuid()) letsencrypt_challenge = ndb.StringProperty(default='', verbose_name=u'Let’s Encrypt Challenge') letsencrypt_response = ndb.StringProperty(default='', verbose_name=u'Let’s Encrypt Response') notify_on_new_user = ndb.BooleanProperty(default=True, verbose_name='Send an email notification when a user signs up') recaptcha_private_key = ndb.StringProperty(default='', verbose_name='Private Key') recaptcha_public_key = ndb.StringProperty(default='', verbose_name='Public Key') salt = ndb.StringProperty(default=util.uuid()) trusted_hosts = ndb.StringProperty(repeated=True, verbose_name='Trusted Hosts') verify_email = ndb.BooleanProperty(default=True, verbose_name='Verify user emails') @property def has_anonymous_recaptcha(self): return bool(self.anonymous_recaptcha and self.has_recaptcha) @property def has_email_authentication(self): return bool(self.email_authentication and self.feedback_email and self.verify_email) @property def has_recaptcha(self): return bool(self.recaptcha_private_key and self.recaptcha_public_key) @classmethod def get_master_db(cls): return cls.get_or_insert('master') FIELDS = { 'analytics_id': fields.String, 'announcement_html': fields.String, 'announcement_type': fields.String, 'anonymous_recaptcha': fields.Boolean, 'brand_name': fields.String, 'bucket_name': fields.String, 'check_unique_email': fields.Boolean, 'email_authentication': fields.Boolean, 'feedback_email': fields.String, 'flask_secret_key': fields.String, 'letsencrypt_challenge': fields.String, 'letsencrypt_response': fields.String, 'notify_on_new_user': fields.Boolean, 'recaptcha_private_key': fields.String, 'recaptcha_public_key': fields.String, 'salt': fields.String, 'trusted_hosts': fields.List(fields.String), 'verify_email': fields.Boolean, } FIELDS.update(model.Base.FIELDS) FIELDS.update(model.ConfigAuth.FIELDS)
def test_miner_wallet_permission_denied(self): device_uuid = setup_device(owner=uuid())[0] service_uuid = create_service(device_uuid, "miner")[0] with self.assertRaises(PermissionDeniedException): self.client.ms("service", ["miner", "wallet"], service_uuid=service_uuid, wallet_uuid=uuid())
class Config(model.Base, model.ConfigAuth): analytics_id = ndb.StringProperty(default='') announcement_html = ndb.TextProperty(default='') announcement_type = ndb.StringProperty(default='info', choices=[ 'info', 'warning', 'success', 'danger', ]) anonymous_recaptcha = ndb.BooleanProperty(default=False) brand_name = ndb.StringProperty(default=config.APPLICATION_ID) check_unique_email = ndb.BooleanProperty(default=True) email_authentication = ndb.BooleanProperty(default=False) feedback_email = ndb.StringProperty(default='') flask_secret_key = ndb.StringProperty(default=util.uuid()) notify_on_new_user = ndb.BooleanProperty(default=True) recaptcha_private_key = ndb.StringProperty(default='') recaptcha_public_key = ndb.StringProperty(default='') salt = ndb.StringProperty(default=util.uuid()) verify_email = ndb.BooleanProperty(default=True) @property def has_anonymous_recaptcha(self): return bool(self.anonymous_recaptcha and self.has_recaptcha) @property def has_email_authentication(self): return bool(self.email_authentication and self.feedback_email and self.verify_email) @property def has_recaptcha(self): return bool(self.recaptcha_private_key and self.recaptcha_public_key) @classmethod def get_master_db(cls): return cls.get_or_insert('master') FIELDS = { 'analytics_id': fields.String, 'announcement_html': fields.String, 'announcement_type': fields.String, 'anonymous_recaptcha': fields.Boolean, 'brand_name': fields.String, 'check_unique_email': fields.Boolean, 'email_authentication': fields.Boolean, 'feedback_email': fields.String, 'flask_secret_key': fields.String, 'notify_on_new_user': fields.Boolean, 'recaptcha_private_key': fields.String, 'recaptcha_public_key': fields.String, 'salt': fields.String, 'verify_email': fields.Boolean, } FIELDS.update(model.Base.FIELDS) FIELDS.update(model.ConfigAuth.FIELDS)
def test_use_device_not_found(self): device_uuid = uuid() service_uuid = create_service(device_uuid, name="portscan")[0] with self.assertRaises(DeviceNotFoundException): self.client.ms("service", ["use"], device_uuid=device_uuid, service_uuid=service_uuid, target_device=uuid())
def test_bruteforce_status_device_powered_off(self): device_uuid = setup_device(2)[1] service_uuid = create_service(device_uuid, "bruteforce", speed=0.0)[0] create_bruteforce_service(service_uuid, uuid(), uuid()) with self.assertRaises(DeviceNotOnlineException): self.client.ms("service", ["bruteforce", "status"], device_uuid=device_uuid, service_uuid=service_uuid)
def test_bruteforce_attack_service_not_found(self): with self.assertRaises(ServiceNotFoundException): self.client.ms( "service", ["bruteforce", "attack"], device_uuid=uuid(), service_uuid=uuid(), target_device=uuid(), target_service=uuid(), )
def setup_session() -> str: token = uuid() clear_sessions() execute( "INSERT INTO session (uuid, user, token, created, valid) VALUES (%s, %s, %s, current_timestamp, true)", uuid(), super_uuid, token, ) return token
class Config(Base, ConfigAuth): """A class describing datastore config.""" analytics_id = ndb.StringProperty(default='') # Google Analytics ID brand_name = ndb.StringProperty( default=config.APPLICATION_NAME) # Webapp name description = ndb.StringProperty(default='') # Webapp description feedback_email = ndb.StringProperty( default='') # Admin's email, where feedback will be sent flask_secret_key = ndb.StringProperty(default=util.uuid()) notify_on_new_user = ndb.BooleanProperty( default=True) # Whether to send email to admin if user signs up recaptcha_forms = ndb.StringProperty( repeated=True) # List of form names where recaptcha is enabled recaptcha_private_key = ndb.StringProperty(default='') recaptcha_public_key = ndb.StringProperty(default='') salt = ndb.StringProperty(default=util.uuid()) weatherApiKey = ndb.StringProperty( default='fa7c1e2d25e0b8399540efa2b411c512') verify_email = ndb.BooleanProperty( default=True) # Whether to verify emails of newly registered users PUBLIC_PROPERTIES = ConfigAuth.get_public_properties() + \ ['analytics_id', 'brand_name', 'description', 'recaptcha_public_key', 'has_recaptcha', 'has_feedback_form', 'recaptcha_forms', 'verify_email', 'weatherApiKey'] @property def has_feedback_form(self): """If feedback form should be displayed""" return bool(self.feedback_email) @property def has_recaptcha(self): # pylint: disable=missing-docstring return bool(self.recaptcha_private_key and self.recaptcha_public_key) @classmethod def get_master_db(cls): """Get config entity doesn't exist, it creates new one. There's need only for one config - master""" return cls.get_or_insert('master') def to_dict(self, *args, **kwargs): """Creates dict representaion of config, recaptcha_forms are converted so angular models can easily use it""" repr_dict = super(Config, self).to_dict(*args, **kwargs) # repr_dict['recaptcha_forms'] = util.list_to_dict(repr_dict['recaptcha_forms']) return repr_dict @classmethod def get_all_properties(cls): """Excludes few properties, before sending to client""" all_properties = super(Config, cls).get_all_properties() all_properties += cls.PUBLIC_PROPERTIES return _.pull(_.uniq(all_properties), 'version', 'modified', 'created', 'key', 'id')
def test_use_permission_denied(self): device_uuid = setup_device(owner=uuid())[0] service_uuid = create_service(device_uuid, owner=uuid(), name="portscan")[0] with self.assertRaises(PermissionDeniedException): self.client.ms("service", ["use"], device_uuid=device_uuid, service_uuid=service_uuid, target_device=uuid())
class Config(model.Base, model.ConfigAuth): analytics_id = ndb.StringProperty(default='') announcement_html = ndb.TextProperty(default='') announcement_type = ndb.StringProperty(default='info', choices=[ 'info', 'warning', 'success', 'danger', ]) anonymous_recaptcha = True brand_name = 'gae-init-docs' check_unique_email = ndb.BooleanProperty(default=True) email_authentication = ndb.BooleanProperty(default=False) feedback_email = ndb.StringProperty(default='') flask_secret_key = ndb.StringProperty(default=util.uuid()) notify_on_new_user = ndb.BooleanProperty(default=True) recaptcha_private_key = ndb.StringProperty(default='') recaptcha_public_key = ndb.StringProperty(default='') salt = ndb.StringProperty(default=util.uuid()) verify_email = ndb.BooleanProperty(default=True) @property def has_anonymous_recaptcha(self): return bool(self.anonymous_recaptcha and self.has_recaptcha) @property def has_email_authentication(self): return bool(self.email_authentication and self.feedback_email and self.verify_email) @property def has_recaptcha(self): return bool(self.recaptcha_private_key and self.recaptcha_public_key) _PROPERTIES = model.Base._PROPERTIES.union({ 'analytics_id', 'announcement_html', 'announcement_type', 'anonymous_recaptcha', 'brand_name', 'check_unique_email', 'email_authentication', 'feedback_email', 'flask_secret_key', 'notify_on_new_user', 'recaptcha_private_key', 'recaptcha_public_key', 'salt', 'verify_email', }).union(model.ConfigAuth._PROPERTIES) @classmethod def get_master_db(cls): return cls.get_or_insert('master')
def test_bruteforce_status_successful(self): device_uuid = setup_device()[0] service_uuid = create_service(device_uuid, "bruteforce", speed=0.0)[0] create_bruteforce_service(service_uuid, uuid(), uuid(), True) actual = self.client.ms("service", ["bruteforce", "status"], device_uuid=device_uuid, service_uuid=service_uuid) self.assert_dict_with_keys( actual, ["uuid", "started", "target_device", "target_service", "progress"]) self.assertEqual(service_uuid, actual["uuid"]) self.assertEqual(1.0, actual["progress"]) self.assert_valid_uuid(actual["target_device"]) self.assert_valid_uuid(actual["target_service"]) self.assertIsInstance(actual["started"], int)
def test_bruteforce_attack_permission_denied(self): device_uuid = setup_device(owner=uuid())[0] service_uuid = create_service(device_uuid, name="bruteforce", n=2, speed=0.0)[1] with self.assertRaises(PermissionDeniedException): self.client.ms( "service", ["bruteforce", "attack"], device_uuid=device_uuid, service_uuid=service_uuid, target_device=uuid(), target_service=uuid(), )
def test_bruteforce_attack_already_running(self): device_uuid = setup_device()[0] service_uuid = create_service(device_uuid, name="bruteforce", n=1, speed=1.0)[0] with self.assertRaises(AttackAlreadyRunning): self.client.ms( "service", ["bruteforce", "attack"], device_uuid=device_uuid, service_uuid=service_uuid, target_device=uuid(), target_service=uuid(), )
def verify_email_notification(user_db): if not (config.CONFIG_DB.verify_email and user_db.email) or user_db.verified: return user_db.token = util.uuid() user_db.put() to = '%s <%s>' % (user_db.name, user_db.email) body = '''Hello %(name)s, it seems someone (hopefully you) tried to verify your email with %(brand)s. In case it was you, please verify it by following this link: %(link)s If it wasn't you, we apologize. You can either ignore this email or reply to it so we can take a look. Best regards, %(brand)s ''' % { 'name': user_db.name, 'link': flask.url_for('user_verify', token=user_db.token, _external=True), 'brand': config.CONFIG_DB.brand_name, } send_mail_notification('Verify your email!', body, to)
def test_bruteforce_attack_device_powered_off(self): device_uuid = setup_device(2)[1] service_uuid = create_service(device_uuid, name="bruteforce", n=2, speed=0.0)[1] with self.assertRaises(DeviceNotOnlineException): self.client.ms( "service", ["bruteforce", "attack"], device_uuid=device_uuid, service_uuid=service_uuid, target_device=uuid(), target_service=uuid(), )
def user_reset(token=None): user_db = model.User.get_by('token', token) if not user_db: flask.flash(__('That link is either invalid or expired.'), category='danger') return flask.redirect(flask.url_for('welcome')) if auth.is_logged_in(): login.logout_user() return flask.redirect(flask.request.path) form = UserResetForm() if form.validate_on_submit(): user_db.password_hash = util.password_hash(user_db, form.new_password.data) user_db.token = util.uuid() user_db.verified = True user_db.put() flask.flash(__('Your password was changed succesfully.'), category='success') return auth.signin_user_db(user_db) return flask.render_template( 'user/user_reset.html', title='Reset Password', html_class='user-reset', form=form, user_db=user_db, )
def create_user_db(auth_id, name, username, email='', verified=False, **props): email = email.lower() if email else '' if verified and email: user_dbs, _ = model.User.get_dbs(email=email, verified=True, limit=2) if len(user_dbs) == 1: user_db = user_dbs[0] user_db.auth_ids.append(auth_id) user_db.put() task.new_user_notification(user_db) return user_db if isinstance(username, str): username = username.decode('utf-8') username = unidecode.unidecode(username.split('@')[0].lower()).strip() username = re.sub(r'[\W_]+', '.', username) new_username = username n = 1 while not model.User.is_username_available(new_username): new_username = '******' % (username, n) n += 1 user_db = model.User( name=name, email=email, username=new_username, auth_ids=[auth_id], verified=verified, token=util.uuid(), **props ) user_db.put() task.new_user_notification(user_db) return user_db
def test_send_successful(self): wallet_uuids, wallet_keys = create_wallet(amount=10, n=2, owner=[super_uuid, uuid()]) expected = {"ok": True} actual = self.client.ms( "currency", ["send"], source_uuid=wallet_uuids[0], key=wallet_keys[0], send_amount=10, destination_uuid=wallet_uuids[1], usage="test", ) self.assertEqual(actual, expected) self.assertEqual( 0, Wallet.get_wallet(self.client, wallet_uuids[0], wallet_keys[0]).amount) self.assertEqual( 20, Wallet.get_wallet(self.client, wallet_uuids[1], wallet_keys[1]).amount)
def verify_user_email_notification(user_db): """Sends email, which user can use to verify his email address Args: user_db (model.User): user, who should verify his email """ if not user_db.email: return user_db.token = util.uuid() user_db.put() receiver = user_db.email body = '''Welcome to %(brand)s. Follow the link below to confirm your email address and activate your account: %(link)s If it wasn't you, we apologize. You can either ignore this email or reply to it so we can take a look. Best regards, %(brand)s ''' % { 'link': flask.url_for('user_verify', token=user_db.token, _external=True), 'brand': config.CONFIG_DB.brand_name, } send_mail_notification('Verify your email', body, receiver)
def test_miner_power_device_not_found(self): service_uuid = create_service(uuid(), "miner")[0] with self.assertRaises(DeviceNotFoundException): self.client.ms("service", ["miner", "power"], service_uuid=service_uuid, power=0.5)
def test_delete_unknown(self): _, wallet_key = create_wallet() wallet_uuid = uuid() with self.assertRaises(UnknownSourceOrDestinationException): self.client.ms("currency", ["delete"], source_uuid=wallet_uuid, key=wallet_key)
def activate_user_notification(user_db): if not user_db.email: return user_db.token = util.uuid() user_db.put() to = user_db.email body = '''Welcome to %(brand)s. Follow the link below to confirm your email address and activate your account: %(link)s If it wasn't you, we apologize. You can either ignore this email or reply to it so we can take a look. Best regards, %(brand)s ''' % { 'link': flask.url_for('user_activate', token=user_db.token, _external=True), 'brand': config.CONFIG_DB.brand_name, } flask.flash( 'An activation link has been sent to your email address.', category='success', ) send_mail_notification('Activate your account', body, to)
def reset_password_notification(user_db): if not user_db.email: return user_db.token = util.uuid() user_db.put() to = '%s <%s>' % (user_db.name, user_db.email) body = '''Hello %(name)s, it seems someone (hopefully you) tried to reset your password with %(brand)s. In case it was you, please reset it by following this link: %(link)s If it wasn't you, we apologize. You can either ignore this email or reply to it so we can take a look. Best regards, %(brand)s ''' % { 'name': user_db.name, 'link': flask.url_for('user_reset', token=user_db.token, _external=True), 'brand': config.CONFIG_DB.brand_name, } flask.flash( 'A reset link has been sent to your email address.', category='success', ) send_mail_notification('Reset your password', body, to)
def admin_config_update(): config_db = model.Config.get_master_db() form = ConfigUpdateForm(obj=config_db) if form.validate_on_submit(): form.populate_obj(config_db) if not config_db.flask_secret_key: config_db.flask_secret_key = util.uuid() config_db.put() reload(config) app.config.update(CONFIG_DB=config_db) return flask.redirect(flask.url_for('welcome')) if flask.request.path.startswith('/_s/'): return util.jsonify_model_db(config_db) instances_url = None if config.PRODUCTION: instances_url = '%s?app_id=%s&version_id=%s' % ( 'https://appengine.google.com/instances', app_identity.get_application_id(), config.CURRENT_VERSION_ID, ) return flask.render_template( 'admin/config_update.html', title='Admin Config', html_class='admin-config', form=form, config_db=config_db, instances_url=instances_url, has_json=True, )
def user_activate(token): if auth.is_logged_in(): login.logout_user() return flask.redirect(flask.request.path) user_db = model.User.get_by('token', token) if not user_db: flask.flash(__('That link is either invalid or expired.'), category='danger') return flask.redirect(flask.url_for('welcome')) form = UserActivateForm(obj=user_db) if form.validate_on_submit(): form.populate_obj(user_db) user_db.password_hash = util.password_hash(user_db, form.password.data) user_db.token = util.uuid() user_db.verified = True user_db.put() return auth.signin_user_db(user_db) return flask.render_template( 'user/user_activate.html', title='Activate Account', html_class='user-activate', user_db=user_db, form=form, )
def reset_password_notification(user_db): """Sends email with url, which user can use to reset his password Args: user_db (model.User): User, who requested password reset """ if not user_db.email: return user_db.token = util.uuid() user_db.put() receiver = '%s <%s>' % (user_db.name, user_db.email) body = '''Hello %(name)s, it seems someone (hopefully you) tried to reset your password with %(brand)s. In case it was you, please reset it by following this link: %(link)s If it wasn't you, we apologize. You can either ignore this email or reply to it so we can take a look. Best regards, %(brand)s ''' % { 'name': user_db.name, 'link': flask.url_for('user_reset', token=user_db.token, _external=True), 'brand': config.CONFIG_DB.brand_name, } send_mail_notification('Reset your password', body, receiver)
def test_bruteforce_attack_successful(self): random_owner = uuid() device_uuid = setup_device()[0] setup_workload(device_uuid, clear_device=False) target_device = setup_device(owner=random_owner, clear_device=False)[0] service_uuid = create_service(device_uuid, name="bruteforce", n=2, speed=1.0)[1] target_service = create_service(target_device, clear_service=False, speed=1.0)[0] create_bruteforce_service(service_uuid, target_device, target_service, True) expected = {"ok": True} actual = self.client.ms( "service", ["bruteforce", "attack"], device_uuid=device_uuid, service_uuid=service_uuid, target_device=target_device, target_service=target_service, ) self.assertEqual(expected, actual)
def test_bruteforce_attack_device_not_found(self): device_uuid = uuid() service_uuid = create_service(device_uuid, name="bruteforce", n=2, speed=0.0)[1] with self.assertRaises(DeviceNotFoundException): self.client.ms( "service", ["bruteforce", "attack"], device_uuid=device_uuid, service_uuid=service_uuid, target_device=uuid(), target_service=uuid(), )
def incoming_call(user_id): ''' Entry point for new, incoming calls. ''' numberInfo = mongo.db.numbers.find_one({'number': request.form['To']}) # Verify that the dialed phone number is in the database if not numberInfo: app.logger.info("WARNING: Number {} not in database.".format(request.form['To'])) err = plivoxml.Response() err.addSpeak(body="There has been an error. Please contact somebody.") return Response(str(err), mimetype='text/xml') # Get basic data from the POST caller_number = request.form['From'] dialed_number = request.form['To'] route_type = numberInfo['defaultRoute'][0]['type'] bridge_name = uuid() # Get list of numbers to ring if route_type == "ringOne": connect_to_number = numberInfo['defaultRoute'][0]['number'] connect_to_number_digits = readable_digits(connect_to_number) numbers_to_try = [connect_to_number] elif route_type == "ringMany": numbers_to_try = [number for number in numberInfo['defaultRoute'][0]['numbers']] connect_to_number_digits = "one of multiple phone numbers." if DEBUG: log_state('incoming_call', locals()) r = plivoxml.Response() r.addSpeak(body="I will attempt to connect you to " + connect_to_number_digits) r.addConference( body=bridge_name, waitSound=base_url_for( 'wait_sound', user_id=user_id ), callbackUrl=base_url_for( 'bridge_enter_exit', user_id=user_id, bridge_name=bridge_name, caller_number=caller_number, dialed_number=dialed_number, numbers_to_try='+'.join(numbers_to_try) ), action=base_url_for( 'action_by_caller', user_id=user_id, bridge_name=bridge_name, caller_number=caller_number, dialed_number=dialed_number ) ) return Response(str(r), mimetype='text/xml')
def add(self, file, type): # if /dev/null, say bye bye if self.url == "/dev/null": return name = os.path.basename(file) id = util.uuid() shutil.copy(file, path.ftp_queue_dir + '/' + id) self.queue.append({'name': name, 'id': id, 'type': type}) st = os.stat(path.ftp_queue_dir + '/' + id) self.status += "%10d %s\n" % (st.st_size, name)
def user_verify(token): user_db = auth.current_user_db() if user_db.token != token: flask.flash(__('That link is either invalid or expired.'), category='danger') return flask.redirect(flask.url_for('profile')) user_db.verified = True user_db.token = util.uuid() user_db.put() flask.flash(__('Hooray! Your email is now verified.'), category='success') return flask.redirect(flask.url_for('profile'))
def user_verify(token): user_db = auth.current_user_db() if user_db.token != token: flask.flash("That link is either invalid or expired.", category="danger") return flask.redirect(flask.url_for("profile")) user_db.verified = True user_db.token = util.uuid() user_db.put() flask.flash("Hooray! Your email is now verified.", category="success") return flask.redirect(flask.url_for("profile"))
def send_rpmqa(): tmp = path.build_dir + '/' + util.uuid() + '/' os.mkdir(tmp) log = tmp + config.rpmqa_filename open(log, 'a').write("Query done at: %s\n" % datetime.datetime.now().isoformat(' ')) chroot.run("rpm -qa|sort", logfile=log) os.chmod(log,0644) ftp.init(rpmqa=True) ftp.add(log) ftp.flush() os.unlink(log) os.rmdir(tmp)
def admin_config(): config_db = model.Config.get_master_db() form = ConfigUpdateForm(obj=config_db) if form.validate_on_submit(): form.populate_obj(config_db) if not config_db.flask_secret_key: config_db.flask_secret_key = util.uuid() if not config_db.salt: config_db.salt = util.uuid() config_db.put() reload(config) app.config.update(CONFIG_DB=config_db) return flask.redirect(flask.url_for('admin')) return flask.render_template( 'admin/admin_config.html', title='App Config', html_class='admin-config', form=form, api_url=flask.url_for('api.config'), )
def admin_config(): config_db = model.Config.get_master_db() form = ConfigUpdateForm(obj=config_db) if form.validate_on_submit(): form.populate_obj(config_db) if not config_db.flask_secret_key: config_db.flask_secret_key = util.uuid() if not config_db.salt: config_db.salt = util.uuid() config_db.put() reload(config) app.config.update(CONFIG_DB=config_db) return flask.redirect(flask.url_for('admin')) if flask.request.path.startswith('/_s/'): return util.jsonify_model_db(config_db) return flask.render_template( 'admin/admin_config.html', title='App Config', html_class='admin-config', form=form, has_json=True, )
def post(self): """Sets new password given by user if he provided valid token Notice ndb.toplevel decorator here, so we can perform asynchronous put and signing in in parallel """ parser = reqparse.RequestParser() parser.add_argument('token', type=UserValidator.create('token')) parser.add_argument('newPassword', type=UserValidator.create('password'), dest='new_password') args = parser.parse_args() user_db = User.get_by('token', args.token) user_db.password_hash = util.password_hash(args.new_password) user_db.token = util.uuid() user_db.verified = True user_db.put_async() auth.signin_user_db(user_db) return user_db.to_dict(include=User.get_private_properties())
def rename_section(section, section_product_cls, section_name): section_products = section_product_cls.query(section_product_cls.section_key == section.key) for section_product in section_products: product_mem_key = uuid() if not section_product.product_key: continue memcache.add( product_mem_key, {'%s' % section_name: section.name}, 7200 ) taskqueue.add( url=url_for( 'product.task.update_product', key_id=section_product.product_key.id(), mem_key=product_mem_key ))
def user_verify(token): """Verifies user's email by token provided in url""" if auth.is_logged_in(): login.logout_user() return flask.redirect(flask.request.path) user_db = model.User.get_by('token', token) if user_db and not user_db.verified: # setting new token is necessary, so this one can't be reused user_db.token = util.uuid() user_db.verified = True user_db.put() auth.signin_user_db(user_db) flask.flash('Welcome on board %s!' % user_db.username) else: flask.flash('Sorry, activation link is either invalid or expired.') return flask.redirect(flask.url_for('index'))
def create_user_db(auth_id, name, username, email='', verified=False, password='', **props): """Saves new user into datastore""" if password: password = util.password_hash(password) email = email.lower() user_db = model.User( name=name, email=email, username=username, auth_ids=[auth_id] if auth_id else [], verified=verified, token=util.uuid(), password_hash=password, **props ) user_db.put() task.new_user_notification(user_db) return user_db
def create_user_db(auth_id, name, username, email='', verified=False, **params): username = unidecode.unidecode(username.split('@')[0].lower()).strip() username = re.sub(r'[\W_]+', '.', username) new_username = username n = 1 while not model.User.is_username_available(new_username): new_username = '******' % (username, n) n += 1 user_db = model.User( name=name, email=email.lower(), username=new_username, auth_ids=[auth_id], verified=verified, token=util.uuid(), **params ) user_db.put() task.new_user_notification(user_db) return user_db
def user_activate(token): if auth.is_logged_in(): login.logout_user() return flask.redirect(flask.request.path) user_db = models.User.get_by("token", token) if not user_db: flask.flash("That link is either invalid or expired.", category="danger") return flask.redirect(flask.url_for("welcome")) form = forms.UserActivateForm(obj=user_db) if form.validate_on_submit(): form.populate_obj(user_db) user_db.password_hash = util.password_hash(user_db, form.password.data) user_db.token = util.uuid() user_db.verified = True user_db.put() return auth.signin_user_db(user_db) return flask.render_template( "user/user_activate.html", title="Activate Account", html_class="user-activate", user_db=user_db, form=form )
def user_reset(token=None): user_db = models.User.get_by("token", token) if not user_db: flask.flash("That link is either invalid or expired.", category="danger") return flask.redirect(flask.url_for("welcome")) if auth.is_logged_in(): login.logout_user() return flask.redirect(flask.request.path) form = forms.UserResetForm() if form.validate_on_submit(): user_db.password_hash = util.password_hash(user_db, form.new_password.data) user_db.token = util.uuid() user_db.verified = True user_db.put() flask.flash("Your password was changed succesfully.", category="success") return auth.signin_user_db(user_db) return flask.render_template( "user/user_reset.html", title="Reset Password", html_class="user-reset", form=form, user_db=user_db )
def add_page(section_id): section = CountrySection.retrieve_by_id(section_id) if not section: return redirect(url_for('country.admin.index')) country = section.country_key if country: country = country.get() form = SimplePageForm() if form.validate_on_submit(): page_ = SimplePage() page_.uid = uuid() form.populate_obj(page_) section.pages.append(page_) section.put() return redirect(url_for('country.admin.view_section', section_id=section_id)) sections = CountrySection.query() return render_template( 'country/admin/add_page.html', form=form, country=country, sections=sections, cur_section=section_id )
def create_user_db(auth_id, name, username, email='', verified=False, **props): # block signup based on configuration if not config.CONFIG_DB.signup_enabled: flask.flash("Signing up is disabled", category="info") return None email = email.lower() if email else '' if verified and email: user_dbs, cursors = model.User.get_dbs(email=email, verified=True, limit=2) if len(user_dbs) == 1: user_db = user_dbs[0] user_db.auth_ids.append(auth_id) user_db.put() task.new_user_notification(user_db) return user_db if isinstance(username, str): username = username.decode('utf-8') username = unidecode.unidecode(username.split('@')[0].lower()).strip() username = re.sub(r'[\W_]+', '.', username) new_username = username n = 1 while not model.User.is_username_available(new_username): new_username = '******' % (username, n) n += 1 user_db = model.User( name=name, email=email, username=new_username, auth_ids=[auth_id] if auth_id else [], verified=verified, token=util.uuid(), **props ) user_db.put() task.new_user_notification(user_db) return user_db
def admin_init(): config_db = model.Config.get_master_db() if not config_db.app_initialized: form = InitForm(obj=config_db) config_db = model.Config.get_master_db() form = InitForm(obj=config_db) if form.validate_on_submit(): form.populate_obj(config_db) if not config_db.flask_secret_key: config_db.flask_secret_key = util.uuid() if not config_db.salt: config_db.salt = util.uuid() config_db.put() reload(config) app.config.update(CONFIG_DB=config_db) # init models col_key = control.collection_init() # ICON init icons = icon_init.icons_new names = "" tag_icon_ids = {} fs = flask.request.files.getlist("icon") cnt = 0 for f in fs: icon = f.read() name = f.filename.split('.')[0] i = icons.get(name,{}) # icon dict tags = model.Tag.validate_tag(i.get('tags',"")\ .split(',')) if i.get('tags') else [] keywords = model.Tag.validate_tag(i.get('keywords',"")\ .split(',')) if i.get('keywords') else [] icon_key = model.Icon.create(icon=icon, name=name, author_html = i.get('author_html'), comment = i.get('comment'), filetype = i.get('filetype'), keywords = keywords.extend(tags) ) for tag in tags: try: tag_icon_ids[tag] = icon_key.id() except: pass ## TAG init tags_new = tag_init.tags_new for name in tags_new: for tag in tags_new[name]["tags"]: try: icon_id = tag_icon_ids[tag] except: icon_id = None model.Tag.add(tag,color=tags_new[name]["color"],icon_id=icon_id,\ auto_incr=False,approved=True) keys = model.TagRelation.add(tags_new[name]["tags"],\ _incr_step=tags_new[name]["incr"]) tags_relation = tag_init.tags_relation for name in tags_relation: keys = model.TagRelation.add(tags_relation[name]["tags"],\ _incr_step=tags_relation[name]["incr"]) return flask.redirect(flask.url_for('admin')) return flask.render_template( 'admin/admin_init.html', title='App Init', html_class='admin-init', form=form, api_url=None#flask.url_for('api.config'), ) else: return flask.redirect(flask.url_for('admin'))
def build_all(r, build_fnc): status.email = r.requester_email notify.begin(r) tmp = path.build_dir + '/' + util.uuid() + "/" r.tmp_dir = tmp os.mkdir(tmp) atexit.register(util.clean_tmp, tmp) log.notice("started processing %s" % r.id) r.chroot_files = [] r.some_ok = 0 for batch in r.batches: can_build = 1 failed_dep = "" for dep in batch.depends_on: if dep.build_failed: can_build = 0 failed_dep = dep.spec if batch.is_command() and can_build: batch.logfile = tmp + "command" if config.builder in batch.builders: log.notice("running %s" % batch.command) stopwatch.start() batch.build_failed = run_command(batch) if batch.build_failed: log.notice("running %s FAILED" % batch.command) notify.add_batch(batch, "FAIL") else: r.some_ok = 1 log.notice("running %s OK" % batch.command) notify.add_batch(batch, "OK") batch.build_time = stopwatch.stop() report.add_pld_builder_info(batch) buildlogs.add(batch.logfile, failed = batch.build_failed, id=r.id) else: log.notice("not running command, not for me.") batch.build_failed = 0 batch.log_line("queued command %s for other builders" % batch.command) r.some_ok = 1 buildlogs.add(batch.logfile, failed = batch.build_failed, id=r.id) elif can_build: log.notice("building %s" % batch.spec) stopwatch.start() batch.logfile = tmp + batch.spec + ".log" batch.gb_id=r.id batch.requester=r.requester batch.requester_email=r.requester_email batch.build_failed = build_fnc(r, batch) if batch.build_failed: log.notice("building %s FAILED (%s)" % (batch.spec, batch.build_failed)) notify.add_batch(batch, batch.build_failed) else: r.some_ok = 1 log.notice("building %s OK" % (batch.spec)) notify.add_batch(batch, "OK") batch.build_time = stopwatch.stop() report.add_pld_builder_info(batch) buildlogs.add(batch.logfile, failed = batch.build_failed, id=r.id) else: batch.build_failed = 1 batch.skip_reason = "SKIPED [%s failed]" % failed_dep batch.logfile = None batch.build_time = "" log.notice("building %s %s" % (batch.spec, batch.skip_reason)) notify.add_batch(batch, "SKIP") buildlogs.flush() chroot.run("rm -f %s" % string.join(r.chroot_files))
import config import model import util from main import app linkedin_config = dict( access_token_method='POST', access_token_url='https://www.linkedin.com/uas/oauth2/accessToken', authorize_url='https://www.linkedin.com/uas/oauth2/authorization', base_url='https://api.linkedin.com/v1/', consumer_key=config.CONFIG_DB.linkedin_api_key, consumer_secret=config.CONFIG_DB.linkedin_secret_key, request_token_params={ 'scope': 'r_basicprofile r_emailaddress', 'state': util.uuid(), }, ) linkedin = auth.create_oauth_app(linkedin_config, 'linkedin') def change_linkedin_query(uri, headers, body): headers['x-li-format'] = 'json' return uri, headers, body linkedin.pre_request = change_linkedin_query @app.route('/api/auth/callback/linkedin/')
def _pre_put_hook(self): if not self.api_key: self.api_key = uuid()