aboutsummaryrefslogtreecommitdiffstats
path: root/lib/acme/reports.py
blob: 682852adc524ffd8aba1c334e43d5f5b77b9e3bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#
# Security Response Tool Implementation
#
# Copyright (C) 2017-2018 Wind River Systems
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# Please run flake8 on this file before sending patches

import os
import re
import logging
import json
from collections import Counter
from datetime import datetime, date
import csv

from orm.models import Product
from srtgui.api import readCveDetails, writeCveDetails, summaryCveDetails

from srtgui.reports import Report, ReportManager, ProductsReport


from django.db.models import Q, F
from django.db import Error
from srtgui.templatetags.projecttags import filtered_filesizeformat

logger = logging.getLogger("srt")

SRT_BASE_DIR = os.environ['SRT_BASE_DIR']
SRT_REPORT_DIR = '%s/reports' % SRT_BASE_DIR

# quick development/debugging support
from srtgui.api import _log

def _log_args(msg, *args, **kwargs):
    s = '%s:(' % msg
    if args:
        for a in args:
            s += '%s,' % a
    s += '),('
    if kwargs:
        for key, value in kwargs.items():
            s += '(%s=%s),' % (key,value)
    s += ')'
    _log(s)

#
# EXAMPLE: simple custom extention to the Products report
#
class AcmeProductsReport(ProductsReport):
    """Report for the Products Page"""

    def __init__(self, parent_page, *args, **kwargs):
        _log_args("ACME_REPORT_PRODUCTS_INIT(%s)" % parent_page, *args, **kwargs)
        super(AcmeProductsReport, self).__init__(parent_page, *args, **kwargs)

    def get_context_data(self, *args, **kwargs):
        _log_args("ACME_REPORT_PRODUCTS_CONTEXT", *args, **kwargs)

        # Fetch the default report context definition
        context = super(AcmeProductsReport, self).get_context_data(*args, **kwargs)

        # Add a custom extension report type
        context['report_type_list'] += '\
                <option value="acme_summary">ACME Products Table</option> \
        '

        # Done!
        return context

    def exec_report(self, *args, **kwargs):
        _log_args("ACME_REPORT_PRODUCTS_EXEC", *args, **kwargs)

        request_POST = self.request.POST

        records = request_POST.get('records', '')
        format = request_POST.get('format', '')
        title = request_POST.get('title', '')
        report_type = request_POST.get('report_type', '')
        record_list = request_POST.get('record_list', '')

        # Default to the regular report output if not our custom extension
        if 'acme_summary' != report_type:
            return(super(AcmeProductsReport, self).exec_report(*args, **kwargs))

        # CUSTOM: prepend "acme" to the generated file name
        report_name = '%s/acme_products_%s_%s.%s' % (SRT_REPORT_DIR,report_type,datetime.today().strftime('%Y%m%d%H%M'),format)
        with open(report_name, 'w') as file:

            if 'csv' == format:
                tab = "\t"
            else:
                tab = ","

            if ('acme_summary' == report_type):
                if 'csv' == format:
                    # CUSTOM: prepend "ACME" to the generated header
                    file.write("ACME Name\tVersion\tProfile\tCPE\tSRT SPE\tInvestigations\tDefects\n")
                if 'txt' == format:
                    # CUSTOM: prepend "ACME" to the generated title
                    file.write("Report : ACME Products Table\n")
                    file.write("\n")
                    # CUSTOM: prepend "ACME" to the generated header
                    file.write("ACME Name,Version,Profile,CPE,SRT SPE,Investigations,Defects\n")

                for product in Product.objects.all():
                    # CUSTOM: prepend "ACME" to the product name
                    file.write("ACME %s%s" % (product.name,tab))
                    file.write("%s%s" % (product.version,tab))
                    file.write("%s%s" % (product.profile,tab))
                    file.write("%s%s" % (product.cpe,tab))
                    file.write("%s%s" % (product.defect_tags,tab))
                    file.write("%s%s" % (product.product_tags,tab))

                    for i,pi in enumerate(product.product_investigation.all()):
                        if i > 0:
                            file.write(" ")
                        file.write("%s" % (pi.name))
                    file.write("%s" % tab)
                    for i,pd in enumerate(product.product_defect.all()):
                        if i > 0:
                            file.write(" ")
                        file.write("%s" % (pd.name))
                    #file.write("%s" % tab)
                    file.write("\n")

        return report_name,os.path.basename(report_name)


# Available 'parent_page' values:
#   cve
#   vulnerability
#   investigation
#   defect
#   cves
#   select-cves
#   vulnerabilities
#   investigations
#   defects
#   products
#   select-publish
#   update-published
#   package-filters
#   cpes_srtool
class AcmeReportManager():
    @staticmethod
    def get_report_class(parent_page, *args, **kwargs):
        if 'products' == parent_page:
            # Extend the Products report
            return AcmeProductsReport(parent_page, *args, **kwargs)
        else:
            # Return the default for all other reports
            return ReportManager.get_report_class(parent_page, *args, **kwargs)

    @staticmethod
    def get_context_data(parent_page, *args, **kwargs):
        _log_args("ACME_REPORTMANAGER_CONTEXT", *args, **kwargs)
        reporter = AcmeReportManager.get_report_class(parent_page, *args, **kwargs)
        return reporter.get_context_data(*args, **kwargs)

    @staticmethod
    def exec_report(parent_page, *args, **kwargs):
        _log_args("ACME_REPORTMANAGER_EXEC", *args, **kwargs)
        reporter = AcmeReportManager.get_report_class(parent_page,  *args, **kwargs)
        return reporter.exec_report(*args, **kwargs)