Exemple #1
0
class SampleResource(BaseResource):
    schema = SampleSchema()
    pagination_schema = get_pagination_compatible_schema(SampleSchema)
    queryset = Sample.objects.get_with_tlp_level_filter
    query_key_field = 'id'
    filter_parameters = [
        ('ip_address', str), ('ip_address__startswith', str), ('domain', str),
        ('domain__contains', str), ('domain__startswith', str),
        ('domain__endswith', str), ('uri', str), ('uri__contains', str),
        ('uri__startswith', str), ('uri__endswith', str), ('md5sum', str),
        ('sha1sum', str), ('sha256sum', str), ('sha512sum', str),
        ('mime_type', str), ('file_names', str), ('file_size__lte', int),
        ('file_size__gte', int), ('shannon_entropy__lte', float),
        ('shannon_entropy__gte', float),
        ('delivery_date__lte', BaseResource._create_date_from_string),
        ('delivery_date__gte', BaseResource._create_date_from_string),
        ('first_seen__lte', BaseResource._create_date_from_string),
        ('first_seen__gte', BaseResource._create_date_from_string),
        ('tags__all', BaseResource._create_list_from_string), ('_cls', str),
        ('_cls__startswith', str)
    ]

    @privilege_required(AuthenticatedPrivilege())
    def get_list(self):
        """
        ---
        get:
            description: Get a list of all samples.
            parameters:
                - in: query
                  name: md5sum
                  type: string
                - in: query
                  name: sha1sum
                  type: string
                - in: query
                  name: sha256sum
                  type: string
                - in: query
                  name: sha512sum
                  type: string
                - in: query
                  name: mime_type
                  type: string
                - in: query
                  name: file_names
                  type: string
                - in: query
                  name: file_size__lte
                  type: integer
                - in: query
                  name: file_size_gte
                  type: interger
                - in: query
                  name: shannon_entropy__lte
                  type: float
                - in: query
                  name: shannon_entropy__gte
                  type: float
                - in: query
                  name: delivery_date__lte
                  type: string
                  format: dateTime
                - in: query
                  name: delivery_date__gte
                  type: string
                  format: dateTime
                - in: query
                  name: first_seen__lte
                  type: string
                  format: dateTime
                - in: query
                  name: first_seen__gte
                  type: string
                  format: dateTime
                - in: query
                  name: tags__all
                  type: string
            responses:
                200:
                    description: A list of samples is returned.
                    schema: SampleSchema
        """
        serialized_samples = []
        paginated_samples = self._get_list()
        for sample in paginated_samples['results']:
            schema = SchemaMapping.get_schema_for_model_class(
                sample.__class__.__name__)
            serialized_samples.append(schema().dump(sample).data)
        return jsonify({
            'results': serialized_samples,
            'next': paginated_samples['next'],
            'previous': paginated_samples['previous']
        })

    @privilege_required(AuthenticatedPrivilege())
    def get_detail(self, **kwargs):
        """
        ---
        get:
            description: Get a single sample object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                200:
                    description: The sample is returned.
                    schema: SampleSchema
                404:
                    description: No sample with the specified id has been found.
        """
        try:
            sample = self.queryset().get(id=kwargs['id'])
            schema = SchemaMapping.get_schema_for_model_class(
                sample.__class__.__name__)
            data = schema().dump(sample).data
            return jsonify(data)
        except DoesNotExist:
            return jsonify({
                'error':
                'No object with key \'{}\' found'.format(kwargs['id'])
            }), 404

    def post(self):
        return jsonify({
            'error':
            'Posting samples directly to the sample endpoint is not allowed. Instead please use the respective endpoints of each specific sample type.'
        }), 400

    def put(self, **kwargs):
        return jsonify({
            'error':
            'Updating sample objects via the API is not supported yet.'
        }), 400

    @privilege_required(RolePrivilege('admin'))
    def delete(self, **kwargs):
        """
        ---
        delete:
            description: Delete an existing sample object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                204:
                    description: The object has been deleted.
                400:
                    description: The server was not able to delete an object based on the request data.
                404:
                    description: No sample with the specified id has been found.
        """
        return super(SampleResource, self).delete(**kwargs)

    @privilege_required(AuthenticatedPrivilege())
    def download_file(self, **kwargs):
        """
        ---
        get:
            description: Get the raw file for a file sample object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                200:
                    description: The raw file is returned.
                400:
                    description: There is no file available for this sample.
                404:
                    description: No sample with the specified id has been found.
        """
        try:
            sample = self.queryset().get(id=kwargs['id'])
            if not isinstance(sample, FileSample):
                return jsonify(
                    {'error':
                     'There is no file available for this sample'}), 400
            else:
                file = sample.file.read()
                return file, 200, {'Content-Type': 'application/octet-stream'}
        except DoesNotExist:
            return jsonify({
                'error':
                'No object with key \'{}\' found'.format(kwargs['id'])
            }), 404

    @privilege_required(AuthenticatedPrivilege())
    def submit_file(self):
        """
        ---
        post:
            description: Upload a file sample to the MASS server
            parameters:
                - in: formData
                  name: file
                  type: file
            responses:
                201:
                    description: The file sample has been uploaded to the MASS server. The metadata of the sample is returned.
                    schema: FileSampleSchema
                400:
                    description: No file has been attached to the request or the request is malformed.
        """
        if 'file' not in request.files:
            return jsonify({'error':
                            'File payload missing in POST request.'}), 400
        else:
            if 'metadata' in request.form:
                metadata = json.loads(request.form['metadata'])
            else:
                metadata = {}
            data = {'file': request.files['file']}
            data.update(metadata)
            sample = FileSample.create_or_update(**data)
            sample.save()
            sample = Sample.objects.get(id=sample.id)
            schema = SchemaMapping.get_schema_for_model_class(
                sample.__class__.__name__)
            return jsonify(schema().dump(sample).data), 201

    @privilege_required(AuthenticatedPrivilege())
    def submit_ip(self):
        """
        ---
        post:
            description: Submit an IP address to the MASS server
            parameters:
                - in: body
                  name: body
                  type: string
            responses:
                201:
                    description: The IP address sample has been created on the MASS server. The metadata of the sample is returned.
                    schema: IPSampleSchema
                400:
                    description: No IP address has been given or the request is malformed.
        """
        json_data = request.get_json()
        if not json_data:
            return jsonify({
                'error':
                'No JSON data provided. Make sure to set the content type of your request to: application/json'
            }), 400
        else:
            sample = IPSample.create_or_update(**json_data)
            sample.save()
            schema = SchemaMapping.get_schema_for_model_class(
                sample.__class__.__name__)
            return jsonify(schema().dump(sample).data), 201

    @privilege_required(AuthenticatedPrivilege())
    def submit_domain(self):
        """
        ---
        post:
            description: Submit a domain name to the MASS server
            parameters:
                - in: body
                  name: body
                  type: string
            responses:
                201:
                    description: The domain name sample has been created on the MASS server. The metadata of the sample is returned.
                    schema: DomainSampleSchema
                400:
                    description: No domain name has been given or the request is malformed.
        """
        json_data = request.get_json()
        if not json_data:
            return jsonify({
                'error':
                'No JSON data provided. Make sure to set the content type of your request to: application/json'
            }), 400
        else:
            sample = DomainSample.create_or_update(**json_data)
            sample.save()
            schema = SchemaMapping.get_schema_for_model_class(
                sample.__class__.__name__)
            return jsonify(schema().dump(sample).data), 201

    @privilege_required(AuthenticatedPrivilege())
    def submit_uri(self):
        """
        ---
        post:
            description: Submit a URI to the MASS server
            parameters:
                - in: body
                  name: body
                  type: string
            responses:
                201:
                    description: The URI sample has been created on the MASS server. The metadata of the sample is returned.
                    schema: URISampleSchema
                400:
                    description: No URI has been given or the request is malformed.
        """
        json_data = request.get_json()
        if not json_data:
            return jsonify({
                'error':
                'No JSON data provided. Make sure to set the content type of your request to: application/json'
            }), 400
        else:
            sample = URISample.create_or_update(**json_data)
            sample.save()
            schema = SchemaMapping.get_schema_for_model_class(
                sample.__class__.__name__)
            return jsonify(schema().dump(sample).data), 201

    @privilege_required(AuthenticatedPrivilege())
    def reports(self, **kwargs):
        """
        ---
        get:
            description: Get the reports associated to the given sample
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                200:
                    description: The list of reports is returned.
                    schema: ReportSchema
                404:
                    description: No sample with the specified id has been found.
        """
        try:
            sample = self.queryset().get(id=kwargs['id'])
            reports = Report.objects(sample=sample)
            serialized_result = ReportSchema(many=True).dump(reports)
            return jsonify({
                'results': serialized_result.data,
            })
        except DoesNotExist:
            return jsonify({
                'error':
                'No object with key \'{}\' found'.format(kwargs['id'])
            }), 404

    @privilege_required(AuthenticatedPrivilege())
    def relation_graph(self, **kwargs):
        """
        ---
        get:
            description: Get a graph representation of the sample relations of the given sample
            parameters:
                - in: path
                  name: id
                  type: string
                - in: query
                  name: depth
                  type: integer
            responses:
                200:
                    description: The relation graph is returned.
                404:
                    description: No sample with the specified id has been found.
        """
        try:
            sample = self.queryset().get(id=kwargs['id'])
            if 'depth' in request.args:
                sample_relations = GraphFunctions.get_relation_graph(
                    sample, int(request.args['depth']))
            else:
                sample_relations = GraphFunctions.get_relation_graph(sample)
            serialized_sample_relations = []
            for sample_relation in sample_relations:
                schema = SchemaMapping.get_schema_for_model_class(
                    sample_relation.__class__.__name__)
                serialized_sample_relations.append(
                    schema().dump(sample_relation).data)
            return jsonify({'results': serialized_sample_relations})
        except DoesNotExist:
            return jsonify({
                'error':
                'No object with key \'{}\' found'.format(kwargs['id'])
            }), 404
Exemple #2
0
from flask import flash, render_template, redirect, url_for
from flask_modular_auth import current_authenticated_entity, privilege_required, RolePrivilege

from mass_flask_config.app import app
from mass_flask_webui.config import webui_blueprint
from mass_flask_webui.forms.login import LoginForm


@webui_blueprint.route('/login/', methods=['GET', 'POST'])
def login():
    if current_authenticated_entity.is_authenticated:
        return redirect(url_for('.profile'))
    else:
        form = LoginForm()
        if form.validate_on_submit():
            app.session_provider.login_entity(form.user)
            flash('Logged in successfully!', 'success')
            return redirect(url_for('.profile'))
        return render_template('login.html', form=form)


@webui_blueprint.route('/logout/', methods=['GET'])
@privilege_required(RolePrivilege('user'))
def logout():
    app.session_provider.logout_entity()
    flash('Logged out successfully!', 'success')
    return redirect(url_for('mass_flask_webui.index'))
class SampleRelationResource(BaseResource):
    schema = SampleRelationSchema()
    pagination_schema = get_pagination_compatible_schema(SampleRelationSchema)
    queryset = SampleRelation.objects
    query_key_field = 'id'
    filter_parameters = []

    @privilege_required(AuthenticatedPrivilege())
    def get_list(self):
        """
        ---
        get:
            description: Get a list of all sample relations.
            responses:
                200:
                    description: A list of sample relations is returned.
                    schema: SampleRelationSchema
        """
        serialized_sample_relations = []
        paginated_sample_relations = self._get_list()
        for sample_relation in paginated_sample_relations['results']:
            schema = SchemaMapping.get_schema_for_model_class(
                sample_relation.__class__.__name__)
            serialized_sample_relations.append(
                schema().dump(sample_relation).data)
        return jsonify({
            'results': serialized_sample_relations,
            'next': paginated_sample_relations['next'],
            'previous': paginated_sample_relations['previous']
        })

    @privilege_required(AuthenticatedPrivilege())
    def get_detail(self, **kwargs):
        """
        ---
        get:
            description: Get a single sample relation object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                200:
                    description: The sample relation is returned.
                    schema: SampleRelationSchema
                404:
                    description: No sample relation with the specified id has been found.
        """
        try:
            sample_relation = self.queryset.get(id=kwargs['id'])
            schema = SchemaMapping.get_schema_for_model_class(
                sample_relation.__class__.__name__)
            return jsonify(schema().dump(sample_relation).data)
        except DoesNotExist:
            return jsonify({
                'error':
                'No object with key \'{}\' found'.format(kwargs['id'])
            }), 404

    def post(self):
        return jsonify({
            'error':
            'Posting sample relations directly to the sample relation endpoint is not allowed. Instead please use the respective endpoints of each specific relation type.'
        }), 400

    def put(self, **kwargs):
        return jsonify({
            'error':
            'Updating relation objects via the API is not supported yet.'
        }), 400

    @privilege_required(RolePrivilege('admin'))
    def delete(self, **kwargs):
        """
        ---
        delete:
            description: Delete an existing relation object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                204:
                    description: The object has been deleted.
                400:
                    description: The server was not able to delete an object based on the request data.
                404:
                    description: No relation with the specified id has been found.
        """
        return super(SampleRelationResource, self).delete(**kwargs)

    @privilege_required(RolePrivilege('admin'),
                        RolePrivilege('analysis_system_instance'))
    def submit_dropped_by_sample_relation(self):
        """
        ---
        post:
            description: Submit a sample relation between a file and a sample to the MASS server
            parameters:
                - in: body
                  name: body
                  type: DroppedBySampleRelationSchema
            responses:
                201:
                    description: The relation has been uploaded to the MASS server. The metadata of the sample is returned.
                    schema: DroppedBySampleRelationSchema
                400:
                    description: The request is malformed.
        """
        data = request.get_json()
        schema = DroppedBySampleRelationSchema()
        sample_relation = schema.load(data).data
        sample_relation.save()
        return jsonify(schema.dump(sample_relation).data), 201

    @privilege_required(RolePrivilege('admin'),
                        RolePrivilege('analysis_system_instance'))
    def submit_resolved_by_sample_relation(self):
        """
        ---
        post:
            description: Submit a sample relation between a domain and a sample to the MASS server
            parameters:
                - in: body
                  name: body
                  type: ResolvedBySampleRelationSchema
            responses:
                201:
                    description: The relation has been uploaded to the MASS server. The metadata of the sample is returned.
                    schema: ResolvedBySampleRelationSchema
                400:
                    description: The request is malformed.
        """
        data = request.get_json()
        schema = ResolvedBySampleRelationSchema()
        sample_relation = schema.load(data).data
        sample_relation.save()
        return jsonify(schema.dump(sample_relation).data), 201

    @privilege_required(RolePrivilege('admin'),
                        RolePrivilege('analysis_system_instance'))
    def submit_contacted_by_sample_relation(self):
        """
        ---
        post:
            description: Submit a sample relation between an IP and a sample to the MASS server
            parameters:
                - in: body
                  name: body
                  type: ContactedBySampleRelationSchema
            responses:
                201:
                    description: The relation has been uploaded to the MASS server. The metadata of the sample is returned.
                    schema: ContactedBySampleRelationSchema
                400:
                    description: The request is malformed.
        """
        data = request.get_json()
        schema = ContactedBySampleRelationSchema()
        sample_relation = schema.load(data).data
        sample_relation.save()
        return jsonify(schema.dump(sample_relation).data), 201

    @privilege_required(RolePrivilege('admin'),
                        RolePrivilege('analysis_system_instance'))
    def submit_retrieved_by_sample_relation(self):
        """
        ---
        post:
            description: Submit a sample relation between a HTTP(S) URL and a sample to the MASS server
            parameters:
                - in: body
                  name: body
                  type: RetrievedBySampleRelationSchema
            responses:
                201:
                    description: The relation has been uploaded to the MASS server. The metadata of the sample is returned.
                    schema: RetrievedBySampleRelationSchema
                400:
                    description: The request is malformed.
        """
        data = request.get_json()
        schema = RetrievedBySampleRelationSchema()
        sample_relation = schema.load(data).data
        sample_relation.save()
        return jsonify(schema.dump(sample_relation).data), 201

    @privilege_required(RolePrivilege('admin'),
                        RolePrivilege('analysis_system_instance'))
    def submit_ssdeep_sample_relation(self):
        """
        ---
        post:
            description: Submit a sample relation between two sample files.
            parameters:
                - in: body
                  name: body
                  type: SsdeepSampleRelationSchema
            responses:
                201:
                    description: The relation has been uploaded to the MASS server. The metadata of the sample is returned.
                    schema: SsdeepSampleRelationSchema
                400:
                    description: The request is malformed.
        """
        data = request.get_json()
        schema = SsdeepSampleRelationSchema()

        sample_relation = schema.load(data).data
        sample_relation.save()

        return jsonify(schema.dump(sample_relation).data), 201
Exemple #4
0
class ReportResource(BaseResource):
    schema = ReportSchema()
    pagination_schema = get_pagination_compatible_schema(ReportSchema)
    queryset = Report.objects
    query_key_field = 'id'
    filter_parameters = []

    @privilege_required(AuthenticatedPrivilege())
    def get_list(self):
        """
        ---
        get:
            description: Get a list of all reports.
            responses:
                200:
                    description: A list of reports is returned.
                    schema: ReportSchema
        """
        return super(ReportResource, self).get_list()

    @privilege_required(AuthenticatedPrivilege())
    def get_detail(self, **kwargs):
        """
        ---
        get:
            description: Get a single report object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                200:
                    description: The report is returned.
                    schema: ReportSchema
                404:
                    description: No report with the specified id has been found.
        """
        return super(ReportResource, self).get_detail(**kwargs)

    def post(self):
        return jsonify({'error': 'Method not allowed for this endpoint.'}), 405

    def put(self, **kwargs):
        return jsonify({'error': 'Method not allowed for this endpoint.'}), 405

    @privilege_required(RolePrivilege('admin'))
    def delete(self, **kwargs):
        """
        ---
        delete:
            description: Delete an existing report object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                204:
                    description: The object has been deleted.
                400:
                    description: The server was not able to delete an object based on the request data.
                404:
                    description: No report with the specified id has been found.
        """
        return super(ReportResource, self).delete(**kwargs)

    @privilege_required(AuthenticatedPrivilege())
    def get_json_report_object(self, **kwargs):
        """
        ---
        get:
            description: Get the contents of a JSON report object
            parameters:
                - in: path
                  name: id
                  type: string
                - in: path
                  name: object_name
                  type: string
            responses:
                200:
                    description: The JSON report object is returned.
                400:
                    description: Invalid request.
                404:
                    description: No report with the specified id has been found.
        """
        try:
            report = self.queryset.get(id=kwargs['id'])
            obj = report.json_report_objects[kwargs['object_name']]
            if not obj:
                return jsonify({
                    'error':
                    'No object with key \'{}\' found'.format(
                        kwargs['object_name'])
                }), 404
            else:
                file = obj.read()
                return file, 200, {'Content-Type': 'application/json'}
        except DoesNotExist:
            return jsonify({
                'error':
                'No object with key \'{}\' found'.format(kwargs['id'])
            }), 404

    @privilege_required(AuthenticatedPrivilege())
    def get_raw_report_object(self, **kwargs):
        """
        ---
        get:
            description: Get the contents of a raw binary report object
            parameters:
                - in: path
                  name: id
                  type: string
                - in: path
                  name: object_name
                  type: string
            responses:
                200:
                    description: The raw binary report object is returned.
                400:
                    description: Invalid request.
                404:
                    description: No report with the specified id has been found.
        """
        try:
            report = self.queryset.get(id=kwargs['id'])
            obj = report.raw_report_objects[kwargs['object_name']]
            if not obj:
                return jsonify({
                    'error':
                    'No object with key \'{}\' found'.format(
                        kwargs['object_name'])
                }), 404
            else:
                file = obj.read()
                return file, 200, {'Content-Type': 'binary/octet-stream'}
        except DoesNotExist:
            return jsonify({
                'error':
                'No object with key \'{}\' found'.format(kwargs['id'])
            }), 404
Exemple #5
0
class ScheduledAnalysisResource(BaseResource):
    schema = ScheduledAnalysisSchema()
    pagination_schema = get_pagination_compatible_schema(
        ScheduledAnalysisSchema)
    queryset = ScheduledAnalysis.objects
    query_key_field = 'id'
    filter_parameters = []

    @privilege_required(RolePrivilege('admin'))
    def get_list(self):
        """
        ---
        get:
            description: Get a list of all scheduled analyses.
            responses:
                200:
                    description: A list of scheduled analyses is returned.
                    schema: ScheduledAnalysisSchema
        """
        return super(ScheduledAnalysisResource, self).get_list()

    @privilege_required(RolePrivilege('admin'),
                        RolePrivilege('analysis_system_instance'))
    def get_detail(self, **kwargs):
        """
        ---
        get:
            description: Get a single scheduled analysis object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                200:
                    description: The scheduled analysis is returned.
                    schema: ScheduledAnalysisSchema
                404:
                    description: No scheduled analysis with the specified id has been found.
        """
        return super(ScheduledAnalysisResource, self).get_detail(**kwargs)

    @privilege_required(RolePrivilege('admin'))
    def post(self):
        """
        ---
        post:
            description: Create a new scheduled analysis
            parameters:
                - in: body
                  name: body
                  schema: ScheduledAnalysisSchema
            responses:
                201:
                    description: The object has been created. The reply contains the newly created object.
                    schema: ScheduledAnalysisSchema
                400:
                    description: The server was not able to create an object based on the request data.
        """
        return super(ScheduledAnalysisResource, self).post()

    def put(self, **kwargs):
        return jsonify({'error': 'Method not allowed for this endpoint.'}), 405

    @privilege_required(RolePrivilege('admin'))
    def delete(self, **kwargs):
        """
        ---
        delete:
            description: Delete an existing scheduled analysis object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                204:
                    description: The object has been deleted.
                400:
                    description: The server was not able to delete an object based on the request data.
                404:
                    description: No scheduled analysis with the specified id has been found.
        """
        return super(ScheduledAnalysisResource, self).delete(**kwargs)

    @privilege_required(RolePrivilege('admin'),
                        RolePrivilege('analysis_system_instance'))
    def submit_report(self, **kwargs):
        """
        ---
        post:
            description: Submit the report for the specified scheduled analysis
            parameters:
                - in: path
                  name: id
                  type: string
                - in: body
                  name: body
                  schema: ReportSchema
            responses:
                204:
                    description: The report has been submitted. The scheduled analysis object has been deleted.
                400:
                    description: The server was not able to process the request based on the request data.
                404:
                    description: No scheduled analysis with the specified id has been found.
        """
        try:
            scheduled_analysis = self.queryset.get(id=kwargs['id'])

            if 'metadata' not in request.form:
                return jsonify(
                    {'error': 'JSON metadata missing in POST request.'}), 400
            else:
                data = json.loads(request.form['metadata'])
                data['json_report_objects'] = {}
                data['raw_report_objects'] = {}

                parsed_report = ReportSchema().load(data, partial=True)
                if parsed_report.errors:
                    return jsonify(parsed_report.errors), 400
                report = parsed_report.data

                report.sample = scheduled_analysis.sample
                report.analysis_system = scheduled_analysis.analysis_system_instance.analysis_system

                for key, f in request.files.items():
                    if f.mimetype == "application/json":
                        report.add_json_report_object(f)
                    else:
                        report.add_raw_report_object(f)

                report.save()
                scheduled_analysis.delete()
                return jsonify(ReportSchema().dump(report).data), 201
        except DoesNotExist:
            return jsonify({
                'error':
                'No object with key \'{}\' found'.format(kwargs['id'])
            }), 404
Exemple #6
0
class AnalysisRequestResource(BaseResource):
    schema = AnalysisRequestSchema()
    pagination_schema = get_pagination_compatible_schema(AnalysisRequestSchema)
    queryset = AnalysisRequest.objects
    query_key_field = 'id'
    filter_parameters = []

    @privilege_required(RolePrivilege('admin'))
    def get_list(self):
        """
        ---
        get:
            description: Get a list of all analysis requests.
            responses:
                200:
                    description: A list of analysis requests is returned.
                    schema: AnalysisRequestSchema
        """
        return super(AnalysisRequestResource, self).get_list()

    @privilege_required(RolePrivilege('admin'))
    def get_detail(self, **kwargs):
        """
        ---
        get:
            description: Get a single analysis request object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                200:
                    description: The analysis request is returned.
                    schema: AnalysisRequestSchema
                404:
                    description: No analysis request with the specified id has been found.
        """
        return super(AnalysisRequestResource, self).get_detail(**kwargs)

    @privilege_required(RolePrivilege('admin'))
    def post(self):
        """
        ---
        post:
            description: Create a new analysis request
            parameters:
                - in: body
                  name: body
                  schema: AnalysisRequestSchema
            responses:
                201:
                    description: The object has been created. The reply contains the newly created object.
                    schema: AnalysisRequestSchema
                400:
                    description: The server was not able to create an object based on the request data.
        """
        return super(AnalysisRequestResource, self).post()

    @privilege_required(RolePrivilege('admin'))
    def put(self, **kwargs):
        """
        ---
        put:
            description: Update an existing analysis request object
            parameters:
                - in: path
                  name: id
                  type: string
                - in: body
                  name: body
                  schema: AnalysisRequestSchema
            responses:
                200:
                    description: The object has been updated. The reply contains the updated object.
                    schema: AnalysisRequestSchema
                400:
                    description: The server was not able to update an object based on the request data.
                404:
                    description: No analysis request with the specified id has been found.
        """
        return super(AnalysisRequestResource, self).put(**kwargs)

    @privilege_required(RolePrivilege('admin'))
    def delete(self, **kwargs):
        """
        ---
        delete:
            description: Delete an existing analysis request object
            parameters:
                - in: path
                  name: id
                  type: string
            responses:
                204:
                    description: The object has been deleted.
                400:
                    description: The server was not able to delete an object based on the request data.
                404:
                    description: No analysis request with the specified id has been found.
        """
        return super(AnalysisRequestResource, self).delete(**kwargs)
Exemple #7
0
from mass_flask_core import models
from mass_flask_config.app import db
from mass_flask_core.models import AnalysisSystem, AnalysisSystemInstance, InstanceAPIKey, User
from mass_flask_webui.config import webui_blueprint


def _get_db_statistics():
    result = []
    for name, obj in inspect.getmembers(models):
        if inspect.isclass(obj) and issubclass(obj, db.Document):
            result.append((name, obj.objects.count()))
    return result


@webui_blueprint.route('/admin/', methods=['GET'])
@privilege_required(RolePrivilege('admin'))
def admin():
    _get_db_statistics()
    return render_template('admin/admin.html',
                           database_statistics=_get_db_statistics())


@webui_blueprint.route('/admin/analysis_systems/', methods=['GET', 'POST'])
@privilege_required(RolePrivilege('admin'))
def admin_analysis_systems():
    if request.method == 'POST':
        _process_analysis_system_action()
    analysis_systems = AnalysisSystem.objects()
    for system in analysis_systems:
        system.instances = AnalysisSystemInstance.objects(
            analysis_system=system.id)
class AnalysisSystemInstanceResource(BaseResource):
    schema = AnalysisSystemInstanceSchema()
    pagination_schema = get_pagination_compatible_schema(
        AnalysisSystemInstanceSchema)
    queryset = AnalysisSystemInstance.objects
    query_key_field = 'uuid'
    filter_parameters = []

    @privilege_required(AuthenticatedPrivilege())
    def get_list(self):
        """
        ---
        get:
            description: Get a list of all analysis system instances.
            responses:
                200:
                    description: A list of analysis system instances is returned.
                    schema: AnalysisSystemInstanceSchema
        """
        return super(AnalysisSystemInstanceResource, self).get_list()

    @privilege_required(AuthenticatedPrivilege())
    def get_detail(self, **kwargs):
        """
        ---
        get:
            description: Get a single analysis system instance object
            parameters:
                - in: path
                  name: uuid
                  type: string
            responses:
                200:
                    description: The analysis system instance is returned.
                    schema: AnalysisSystemInstanceSchema
                404:
                    description: No analysis system instance with the specified uuid has been found.
        """
        return super(AnalysisSystemInstanceResource, self).get_detail(**kwargs)

    @privilege_required(RolePrivilege('admin'))
    def post(self):
        """
        ---
        post:
            description: Create a new analysis system instance
            parameters:
                - in: body
                  name: body
                  schema: AnalysisSystemInstanceSchema
            responses:
                201:
                    description: The object has been created. The reply contains the newly created object.
                    schema: AnalysisSystemInstanceSchema
                400:
                    description: The server was not able to create an object based on the request data.
        """
        return super(AnalysisSystemInstanceResource, self).post()

    @privilege_required(RolePrivilege('admin'))
    def put(self, **kwargs):
        """
        ---
        put:
            description: Update an existing analysis system instance object
            parameters:
                - in: path
                  name: uuid
                  type: string
                - in: body
                  name: body
                  schema: AnalysisSystemInstanceSchema
            responses:
                200:
                    description: The object has been updated. The reply contains the updated object.
                    schema: AnalysisSystemInstanceSchema
                400:
                    description: The server was not able to update an object based on the request data.
                404:
                    description: No analysis system with the specified uuid has been found.
        """
        return super(AnalysisSystemInstanceResource, self).put(**kwargs)

    @privilege_required(RolePrivilege('admin'))
    def delete(self, **kwargs):
        """
        ---
        delete:
            description: Delete an existing analysis system instance object
            parameters:
                - in: path
                  name: uuid
                  type: string
            responses:
                204:
                    description: The object has been deleted.
                400:
                    description: The server was not able to delete an object based on the request data.
                404:
                    description: No analysis system instance with the specified uuid has been found.
        """
        return super(AnalysisSystemInstanceResource, self).delete(**kwargs)

    @privilege_required(RolePrivilege('admin'),
                        RolePrivilege('analysis_system_instance'))
    def scheduled_analyses(self, **kwargs):
        """
        ---
        get:
            description: Get the scheduled analyses of a specific analysis system instance object
            parameters:
                - in: path
                  name: uuid
                  type: string
            responses:
                200:
                    description: The list of scheduled analyses is returned.
                    schema: ScheduledAnalysisSchema
                404:
                    description: No analysis system instance with the specified uuid has been found.
        """
        if kwargs['uuid'] is None:
            return jsonify({
                'error':
                'Parameter \'{}\' must be specified'.format(
                    self.query_key_field)
            }), 400
        elif (isinstance(current_authenticated_entity._get_current_object(), AnalysisSystemInstance) and current_authenticated_entity.uuid == kwargs['uuid']) \
            or (isinstance(current_authenticated_entity._get_current_object(), User) and current_authenticated_entity.is_admin):
            analysis_system_instance = AnalysisSystemInstance.objects.get(
                uuid=kwargs['uuid'])
            if not analysis_system_instance:
                return jsonify({
                    'error':
                    'No object with key \'{}\' found'.format(
                        kwargs[self.query_key_field])
                }), 404
            analysis_system_instance.update_last_seen()
            scheduled_analyses = ScheduledAnalysis.objects(
                analysis_system_instance=analysis_system_instance)
            serialized_result = ScheduledAnalysisSchema(
                many=True).dump(scheduled_analyses)
            return jsonify({
                'results': serialized_result.data,
            })
        else:
            return jsonify({
                'error':
                'Analysis instance  \'{}\' not found'.format(
                    kwargs[self.query_key_field])
            }), 404