Guest User

debsecan

a guest
Feb 19th, 2012
367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 46.11 KB | None | 0 0
  1. #!/usr/bin/python
  2. # debsecan - Debian Security Analyzer
  3. # Copyright (C) 2005, 2006, 2007 Florian Weimer
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  18.  
  19. VERSION = "0.4"
  20.  
  21. import copy
  22. from cStringIO import StringIO
  23. from optparse import OptionParser
  24. import os
  25. import os.path
  26. import re
  27. import socket
  28. import sys
  29. import time
  30. import types
  31. import urllib2
  32. import zlib
  33. import apt_pkg
  34.  
  35. apt_pkg.init()
  36. try:
  37.     version_compare = apt_pkg.version_compare
  38. except AttributeError:
  39.     version_compare = apt_pkg.VersionCompare
  40.  
  41. ######################################################################
  42. # From debian_support in the secure-testing repository.  Needs to be
  43. # kept in sync manually.  (We duplicate here to avoid a library
  44. # dependency, and make it easy to run the script even when it is not
  45. # installed on the system.)
  46.  
  47. class ParseError(Exception):
  48.     """An exception which is used to signal a parse failure.
  49.  
  50.    Attributes:
  51.  
  52.    filename - name of the file
  53.    lineno - line number in the file
  54.    msg - error message
  55.  
  56.    """
  57.  
  58.     def __init__(self, filename, lineno, msg):
  59.         assert type(lineno) == types.IntType
  60.         self.filename = filename
  61.         self.lineno = lineno
  62.         self.msg = msg
  63.  
  64.     def __str__(self):
  65.         return self.msg
  66.  
  67.     def __repr__(self):
  68.         return "ParseError(%s, %d, %s)" % (`self.filename`,
  69.                                            self.lineno,
  70.                                            `self.msg`)
  71.  
  72.     def printOut(self, file):
  73.         """Writes a machine-parsable error message to file."""
  74.         file.write("%s:%d: %s\n" % (self.filename, self.lineno, self.msg))
  75.         file.flush()
  76.  
  77. class Version:
  78.     """Version class which uses the original APT comparison algorithm."""
  79.     def __init__(self, version):
  80.         """Creates a new Version object."""
  81.         assert type(version) == types.StringType, `version`
  82.         assert version <> ""
  83.         self.__asString = version
  84.  
  85.     def __str__(self):
  86.         return self.__asString
  87.  
  88.     def __repr__(self):
  89.         return 'Version(%s)' % `self.__asString`
  90.  
  91.     def __cmp__(self, other):
  92.         return version_compare(self.__asString, other.__asString)
  93.  
  94. class PackageFile:
  95.     """A Debian package file.
  96.  
  97.    Objects of this class can be used to read Debian's Source and
  98.    Packages files."""
  99.  
  100.     re_field = re.compile(r'^([A-Za-z][A-Za-z0-9-]+):(?:\s+(.*?))?\s*$')
  101.  
  102.     def __init__(self, name, fileObj=None):
  103.         """Creates a new package file object.
  104.  
  105.        name - the name of the file the data comes from
  106.        fileObj - an alternate data source; the default is to open the
  107.                  file with the indicated name.
  108.        """
  109.         if fileObj is None:
  110.             fileObj = safe_open(name)
  111.         self.name = name
  112.         self.file = fileObj
  113.         self.lineno = 0
  114.  
  115.     def __iter__(self):
  116.         line = self.file.readline()
  117.         self.lineno += 1
  118.         pkg = []
  119.         while line:
  120.             if line == '\n':
  121.                 if len(pkg) == 0:
  122.                     self.raiseSyntaxError('expected package record')
  123.                 yield pkg
  124.                 pkg = []
  125.                 line = self.file.readline()
  126.                 self.lineno += 1
  127.                 continue
  128.  
  129.             match = self.re_field.match(line)
  130.             if not match:
  131.                 self.raiseSyntaxError("expected package field, got " + `line`)
  132.             (name, contents) = match.groups()
  133.             contents = contents or ''
  134.  
  135.             while True:
  136.                 line = self.file.readline()
  137.                 self.lineno += 1
  138.                 if line and line[0] in " \t":
  139.                     ncontents = line[1:]
  140.                     if ncontents:
  141.                         if ncontents[-1] == '\n':
  142.                             ncontents = ncontents[:-1]
  143.                     else:
  144.                         break
  145.                     contents = "%s\n%s" % (contents, ncontents)
  146.                 else:
  147.                     break
  148.             pkg.append((name, contents))
  149.         if pkg:
  150.             yield pkg
  151.  
  152.     def raiseSyntaxError(self, msg, lineno=None):
  153.         if lineno is None:
  154.             lineno = self.lineno
  155.         raise ParseError(self.name, lineno, msg)
  156.  
  157. # End of code from debian_support
  158. ######################################################################
  159.  
  160. # General support routines
  161.  
  162. def safe_open(name, mode="r"):
  163.     try:
  164.         return file(name, mode)
  165.     except IOError, e:
  166.         sys.stdout.write("error: could not open %s: %s\n" % (`name`, e.strerror))
  167.         sys.exit(2)
  168.  
  169. # Configuration file parser
  170.  
  171. class ConfigParser:
  172.     def __init__(self, name, file=None):
  173.         self.name = name
  174.         if file is None:
  175.             if os.path.exists(name):
  176.                 self.file = safe_open(name)
  177.             else:
  178.                 self.file = None
  179.         else:
  180.             self.file = file
  181.  
  182.     def onComment(self, line, number):
  183.         pass
  184.  
  185.     def onKey(self, line, number, key, value, trailer):
  186.         pass
  187.  
  188.     def onError(self, line, number):
  189.         sys.stderr.write("%s:%d: invalid configuration file syntax"
  190.                          % (line, number))
  191.         sys.exit(2)
  192.  
  193.     def parse(self, re_comment=re.compile(r'^\s*(?:#.*)?$'),
  194.               re_key=re.compile(r'^\s*([A-Z]+)=(.*?)\s*$'),
  195.               re_quote=re.compile(r'^"(.*)"\s*$')):
  196.         if self.file is None:
  197.             return
  198.         lineno = 0
  199.         for line in self.file:
  200.             lineno += 1
  201.             match = re_comment.match(line)
  202.             if match is not None:
  203.                 self.onComment(line, lineno)
  204.                 continue
  205.  
  206.             match = re_key.match(line)
  207.             if match is not None:
  208.                 (k, v) = match.groups()
  209.                 match = re_quote.match(v)
  210.                 if match is not None:
  211.                     # This is not perfect, but proper parsing is
  212.                     # probably not worth the effort.
  213.                     (v,) = match.groups()
  214.                 self.onKey(line, lineno, k, v, '\n')
  215.                 continue
  216.  
  217.             onError(line, lineno)
  218.  
  219. def read_config(name, file=None):
  220.     """Read the configuration file NAME into a dictionary and return it."""
  221.     config = {}
  222.     class Parser(ConfigParser):
  223.         def onKey(self, line, number, key, value, trailer):
  224.             config[key] = value
  225.     Parser(name, file).parse()
  226.     return config
  227.  
  228. def update_config(name):
  229.     """Update the configuration file NAME with data from standard input."""
  230.     new_config = read_config('<stdin>', sys.stdin)
  231.  
  232.     new_file = []
  233.     class Parser(ConfigParser):
  234.         def onComment(self, line, lineno):
  235.             new_file.append(line)
  236.         def onKey(self, line, lineno, key, value, trailer):
  237.             if new_config.has_key(key):
  238.                 if new_config[key] <> value:
  239.                     new_file.append("%s=%s%s"
  240.                                     % (key, new_config[key], trailer))
  241.                 else:
  242.                     new_file.append(line)
  243.                 del new_config[key]
  244.             else:
  245.                 new_file.append(line)
  246.     Parser(name).parse()
  247.  
  248.     remaining = new_config.keys()
  249.     remaining.sort()
  250.     if remaining:
  251.         if remaining[-1] <> "\n":
  252.             new_file.append("\n")
  253.         for k in remaining:
  254.             new_file.append("%s=%s\n" % (k, new_config[k]))
  255.  
  256.     conf = file(name, "w+")
  257.     try:
  258.         for line in new_file:
  259.             conf.write(line)
  260.     finally:
  261.         conf.close()
  262.  
  263. # Command line parser
  264.  
  265. def parse_cli():
  266.     """Reads sys.argv and returns an options object."""
  267.     parser = OptionParser(usage="%prog OPTIONS...")
  268.     parser.add_option("--config", metavar="FILE",
  269.                       help="sets the name of the configuration file",
  270.                       default='/etc/default/debsecan')
  271.     parser.add_option("--suite", type="choice",
  272.                       choices=['woody', 'sarge', 'etch', 'lenny', 'squeeze', 'wheezy',
  273.                                'sid'],
  274.                       help="set the Debian suite of this installation")
  275.     parser.add_option("--source", metavar="URL",
  276.                       help="sets the URL for the vulnerability information")
  277.     parser.add_option("--status", metavar="NAME",
  278.                       default="/var/lib/dpkg/status",
  279.                       help="name of the dpkg status file")
  280.     parser.add_option("--format", type="choice",
  281.                       choices=['bugs', 'packages', 'summary', 'detail',
  282.                                'report', 'simple'],
  283.                       default="summary",
  284.                       help="change output format")
  285.     parser.add_option("--only-fixed", action="store_true", dest="only_fixed",
  286.                 help="list only vulnerabilities for which a fix is available")
  287.     parser.add_option("--no-obsolete", action="store_true", dest="no_obsolete",
  288.                 help="do not list obsolete packages (not recommend)")
  289.     parser.add_option("--history", default="/var/lib/debsecan/history",
  290.                       metavar="NAME",
  291.                       help="sets the file name of debsecan's internal status "
  292.                       + "file")
  293.     parser.add_option("--line-length", default=72, type="int",
  294.                       dest="line_length",
  295.                       help="maximum line length in report mode")
  296.     parser.add_option("--update-history", action="store_true",
  297.                       dest="update_history",
  298.                       help="update the history file after reporting")
  299.     parser.add_option("--mailto", help="send report to an email address")
  300.     parser.add_option("--cron", action="store_true",
  301.                       help="debsecan is invoked from cron")
  302.     parser.add_option("--whitelist", metavar="NAME",
  303.                       default="/var/lib/debsecan/whitelist",
  304.                       help="sets the name of the whitelist file")
  305.     parser.add_option("--add-whitelist", action="store_true",
  306.                       dest="whitelist_add",
  307.                       help="add entries to the whitelist")
  308.     parser.add_option("--remove-whitelist", action="store_true",
  309.                       dest="whitelist_remove",
  310.                       help="remove entries from the whitelist")
  311.     parser.add_option("--show-whitelist", action="store_true",
  312.                       dest="whitelist_show",
  313.                       help="display entries on the whitelist")
  314.     parser.add_option("--update-config", action="store_true",
  315.                       dest="update_config", help=None)
  316.     (options, args) = parser.parse_args()
  317.  
  318.     def process_whitelist_options():
  319.         """Check the whitelist options.  They conflict with everything
  320.        else."""
  321.         count = 0
  322.         for x in (options.whitelist_add, options.whitelist_remove,
  323.                   options.whitelist_show):
  324.             if x:
  325.                 count += 1
  326.         if count == 0:
  327.             return
  328.         if count > 1:
  329.             sys.stderr.write(
  330.                 "error: at most one whitelist option may be specified\n")
  331.             sys.exit(1)
  332.  
  333.         for (k, v) in options.__dict__.items():
  334.             if type(v) == types.MethodType or v is None:
  335.                 continue
  336.             if k not in ("whitelist", "whitelist_add", "whitelist_remove",
  337.                          # The following options have defaults and are
  338.                          # always present.
  339.                          "history", "status", "format", "line_length"):
  340.                 sys.stderr.write(
  341.         "error: when editing the whitelist, no other options are allowed\n")
  342.                 sys.exit(1)
  343.  
  344.     if options.whitelist_add:
  345.         whitelist_add(options, args)
  346.         sys.exit(0)
  347.     if options.whitelist_remove:
  348.         whitelist_remove(options, args)
  349.         sys.exit(0)
  350.     if options.whitelist_show:
  351.         whitelist_show(options, args)
  352.         sys.exit(0)
  353.  
  354.     process_whitelist_options()
  355.  
  356.     if options.cron:
  357.         options.format = 'report'
  358.         options.update_history = True
  359.     if options.only_fixed and not options.suite:
  360.         sys.stderr.write("error: --only-fixed requires --suite\n")
  361.         sys.exit(1)
  362.     if options.no_obsolete and not options.suite:
  363.         sys.stderr.write("error: --no-obsolete requires --suite\n")
  364.         sys.exit(1)
  365.     if options.update_history and options.format <> 'report':
  366.         sys.stderr.write("error: --update-history requires report format\n")
  367.         sys.exit(1)
  368.     if options.cron and options.format <> 'report':
  369.         sys.stderr.write("error: --cron requires report format\n")
  370.         sys.exit(1)
  371.     if options.mailto and options.format <> 'report':
  372.         sys.stderr.write("error: --mailto requires report format\n")
  373.         sys.exit(1)
  374.     options.need_history = options.format == 'report'
  375.  
  376.     config = read_config(options.config)
  377.     if options.cron and not options.mailto:
  378.         options.mailto = config.get('MAILTO', '')
  379.         if options.mailto == '':
  380.             options.mailto = 'root'
  381.     options.suite = options.suite or config.get('SUITE', None)
  382.     if options.suite == 'GENERIC':
  383.         options.suite = None
  384.     options.subject = config.get(
  385.         'SUBJECT', 'Debian security status of %(hostname)s')
  386.  
  387.     return (options, config, args)
  388.  
  389. # Vulnerabilities
  390.  
  391. class Vulnerability:
  392.     """Stores a vulnerability name/package name combination."""
  393.  
  394.     urgency_conversion = {' ' : '',
  395.                         'L' : 'low',
  396.                         'M' : 'medium',
  397.                         'H' : 'high'}
  398.  
  399.     def __init__(self, vuln_names, str):
  400.         """Creates a new vulnerability object from a string."""
  401.         (package, vnum, flags, unstable_version, other_versions) \
  402.                   = str.split(',', 4)
  403.         vnum = int(vnum)
  404.         self.bug = vuln_names[vnum][0]
  405.         self.package = package
  406.         self.binary_packages = None
  407.         self.unstable_version = unstable_version
  408.         self.other_versions = other_versions.split(' ')
  409.         if self.other_versions == ['']:
  410.             self.other_versions = []
  411.         self.description = vuln_names[vnum][1]
  412.         self.binary_package = flags[0] == 'B'
  413.         self.urgency = self.urgency_conversion[flags[1]]
  414.         self.remote = {'?' : None,
  415.                        'R' : True,
  416.                        ' ' : False}[flags[2]]
  417.         self.fix_available = flags[3] == 'F'
  418.  
  419.     def is_vulnerable(self, (bin_pkg, bin_ver), (src_pkg, src_ver)):
  420.         """Returns true if the specified binary package is subject to
  421.        this vulnerability."""
  422.         self._parse()
  423.         if self.binary_package and bin_pkg == self.package:
  424.             if self.unstable_version:
  425.                 return bin_ver < self.unstable_version
  426.             else:
  427.                 return True
  428.         elif src_pkg == self.package:
  429.             if self.unstable_version:
  430.                 return src_ver < self.unstable_version \
  431.                        and src_ver not in self.other_versions
  432.             else:
  433.                 return src_ver not in self.other_versions
  434.         else:
  435.             return False
  436.  
  437.     def obsolete(self, bin_name=None):
  438.         if self.binary_packages is None:
  439.             return
  440.         if bin_name is None:
  441.             bin_name = self.installed_package
  442.         return bin_name not in self.binary_packages
  443.  
  444.     def installed(self, src_name, bin_name):
  445.         """Returns a new vulnerability object for the installed package."""
  446.         v = copy.copy(self)
  447.         v.installed_package = bin_name
  448.         return v
  449.  
  450.     def _parse(self):
  451.         """Further parses the object."""
  452.         if type(self.unstable_version) == types.StringType:
  453.             if self.unstable_version:
  454.                 self.unstable_version = Version(self.unstable_version)
  455.             else:
  456.                 self.unstable_version = None
  457.             self.other_versions = map(Version, self.other_versions)
  458.  
  459. def fetch_data(options, config):
  460.     """Returns a dictionary PACKAGE -> LIST-OF-VULNERABILITIES."""
  461.     url = options.source or config.get("SOURCE", None) \
  462.         or "http://secure-testing.debian.net/debian-secure-testing/" \
  463.            "project/debsecan/release/1/"
  464.     if url[-1] <> "/":
  465.         url += "/"
  466.     if options.suite:
  467.         url += options.suite
  468.     else:
  469.         url += 'GENERIC'
  470.     r = urllib2.Request(url)
  471.     r.add_header('User-Agent', 'debsecan/' + VERSION)
  472.     try:
  473.         u = urllib2.urlopen(r)
  474.         # In cron mode, we suppress almost all errors because we
  475.         # assume that they are due to lack of Internet connectivity.
  476.     except urllib2.HTTPError, e:
  477.         if (not options.cron) or e.code == 404:
  478.             sys.stderr.write("error: while downloading %s:\n%s\n" % (url, e))
  479.             sys.exit(1)
  480.         else:
  481.             sys.exit(0)
  482.     except urllib2.URLError, e:
  483.         if not options.cron:            # no e.code check here
  484.             # Be conservative about the attributes offered by
  485.             # URLError.  They are undocumented, and strerror is not
  486.             # available even though it is documented for
  487.             # EnvironmentError.
  488.             msg = e.__dict__.get('reason', '')
  489.             if msg:
  490.                 msg = "error: while downloading %s:\nerror: %s\n" % (url, msg)
  491.             else:
  492.                 msg = "error: while downloading %s:\n" % url
  493.             sys.stderr.write(msg)
  494.             sys.exit(1)
  495.         else:
  496.             sys.exit(0)
  497.  
  498.     data = []
  499.     while 1:
  500.         d = u.read(4096)
  501.         if d:
  502.             data.append(d)
  503.         else:
  504.             break
  505.     data = StringIO(zlib.decompress(''.join(data)))
  506.     if data.readline() <> "VERSION 1\n":
  507.         sys.stderr.write("error: server sends data in unknown format\n")
  508.         sys.exit(1)
  509.  
  510.     vuln_names = []
  511.     for line in data:
  512.         if line[-1:] == '\n':
  513.             line = line[:-1]
  514.         if line == '':
  515.             break
  516.         (name, flags, desc) = line.split(',', 2)
  517.         vuln_names.append((name, desc))
  518.  
  519.     packages = {}
  520.     for line in data:
  521.         if line[-1:] == '\n':
  522.             line = line[:-1]
  523.         if line == '':
  524.             break
  525.         v = Vulnerability(vuln_names, line)
  526.         try:
  527.             packages[v.package].append(v)
  528.         except KeyError:
  529.             packages[v.package] = [v]
  530.  
  531.     source_to_binary = {}
  532.     for line in data:
  533.         if line[-1:] == '\n':
  534.             line = line[:-1]
  535.         if line == '':
  536.             break
  537.         (sp, bps) = line.split(',')
  538.         if bps:
  539.             source_to_binary[sp] = bps.split(' ')
  540.         else:
  541.             source_to_binary[sp] = []
  542.  
  543.     for vs in packages.values():
  544.         for v in vs:
  545.             if not v.binary_package:
  546.                 v.binary_packages = source_to_binary.get(v.package, None)
  547.  
  548.     return packages
  549.  
  550. # Previous state (for incremental reporting)
  551.  
  552. class History:
  553.     def __init__(self, options):
  554.         self.options = options
  555.         self.last_updated = 86400
  556.         self._read_history(self.options.history)
  557.  
  558.     def data(self):
  559.         """Returns a dictionary (BUG, PACKAGE) -> UPDATE-AVAILABLE.
  560.        The result is not shared with the internal dictionary."""
  561.         return self.history.copy()
  562.  
  563.     def expired(self):
  564.         """Returns true if the stored history file is out of date."""
  565.         if self.options.cron:
  566.             old = time.localtime(self.last_updated)
  567.             now = time.localtime()
  568.             def ymd(t):
  569.                 return (t.tm_year, t.tm_mon, t.tm_mday)
  570.             if ymd(old) == ymd(now):
  571.                 return False
  572.             return now.tm_hour >= 2
  573.         else:
  574.             # If we aren't run from cron, we always download new data.
  575.             return True
  576.  
  577.     def known(self, v):
  578.         """Returns true if the vulnerability is known."""
  579.         return self.history.has_key(v)
  580.  
  581.     def fixed(self, v):
  582.         """Returns true if the vulnerability is known and has been
  583.        fixed."""
  584.         return self.history.get(v, False)
  585.  
  586.     def _read_history(self, name):
  587.         """Reads the named history file.  Returns a dictionary
  588.        (BUG, PACKAGE) -> UPDATE-AVAILABLE."""
  589.  
  590.         self.history = {}
  591.  
  592.         try:
  593.             f = file(name)
  594.         except IOError:
  595.             return
  596.  
  597.         line = f.readline()
  598.         if line == 'VERSION 0\n':
  599.             pass
  600.         elif line == 'VERSION 1\n':
  601.             line = f.readline()
  602.             self.last_updated = int(line)
  603.         else:
  604.             return
  605.  
  606.         for line in f:
  607.             if line[-1:] == '\n':
  608.                 line = line[:-1]
  609.             (bug, package, fixed) = line.split(',')
  610.             self.history[(bug, package)] = fixed == 'F'
  611.         f.close()
  612.  
  613. # Whitelisting vulnerabilities
  614.  
  615. class Whitelist:
  616.     def __init__(self, name):
  617.         """Read a whitelist from disk.
  618.  
  619.        name - file name of the white list.  If None, no file is read.
  620.        """
  621.         self.name = name
  622.         self.bug_dict = {}
  623.         self.bug_package_dict = {}
  624.         if name and os.path.exists(name):
  625.             src = safe_open(name)
  626.             line = src.readline()
  627.             if line <> 'VERSION 0\n':
  628.                 raise SyntaxError, "invalid whitelist file, got: " + `line`
  629.             for line in src:
  630.                 if line[-1] == '\n':
  631.                     line = line[:-1]
  632.                 (bug, pkg) = line.split(',')
  633.                 self.add(bug, pkg)
  634.         self._dirty = False
  635.  
  636.     def add(self, bug, pkg=None):
  637.         """Adds a bug/package pair to the whitelist.
  638.        If the package is not specified (or empty), the bug is whitelisted
  639.        completely."""
  640.         if pkg:
  641.             self.bug_package_dict[(bug, pkg)] = True
  642.         else:
  643.             self.bug_dict[bug] = True
  644.         self._dirty = True
  645.  
  646.     def remove(self, bug, pkg=None):
  647.         """Removes a bug/package pair from the whitelist.
  648.        If the package is not specified, *all* whitelisted packages for
  649.        that bug are removed."""
  650.         removed = False
  651.         if pkg:
  652.             try:
  653.                 del self.bug_package_dict[(bug, pkg)]
  654.                 removed = True
  655.             except KeyError:
  656.                 pass
  657.         else:
  658.             try:
  659.                 del self.bug_dict[bug]
  660.                 removed = True
  661.             except KeyError:
  662.                 pass
  663.             for bug_pkg in self.bug_package_dict.keys():
  664.                 if bug_pkg[0] == bug:
  665.                     del self.bug_package_dict[bug_pkg]
  666.                     removed = True
  667.  
  668.         if removed:
  669.             self._dirty = True
  670.         else:
  671.             if pkg:
  672.                 sys.stderr.write(
  673.                     "error: no matching whitelist entry for %s %s\n"
  674.                     % (bug, pkg))
  675.             else:
  676.                 sys.stderr.write("error: no matching whitelist entry for %s\n"
  677.                                  % bug)
  678.             sys.exit(1)
  679.  
  680.     def check(self, bug, package):
  681.         """Returns true if the bug/package pair is whitelisted."""
  682.         return self.bug_dict.has_key(bug) \
  683.                or self.bug_package_dict.has_key((bug, package))
  684.  
  685.     def update(self):
  686.         """Write the whitelist file back to disk, if the data has changed."""
  687.         if not (self._dirty and self.name):
  688.             return
  689.         new_name = self.name + '.new'
  690.         f = safe_open(new_name, "w+")
  691.         f.write("VERSION 0\n")
  692.         l = self.bug_dict.keys()
  693.         l.sort()
  694.         for bug in l:
  695.             f.write(bug + ",\n")
  696.         l = self.bug_package_dict.keys()
  697.         l.sort()
  698.         for bug_pkg in l:
  699.             f.write("%s,%s\n" % bug_pkg)
  700.         f.close()
  701.         os.rename(new_name, self.name)
  702.  
  703.     def show(self, file):
  704.         l = []
  705.         for bug in self.bug_dict.keys():
  706.             file.write("%s (all packages)\n" % bug)
  707.         for (bug, pkg) in self.bug_package_dict.keys():
  708.             l.append("%s %s\n" % (bug, pkg))
  709.         l.sort()
  710.         for line in l:
  711.             file.write(line)
  712.  
  713. def __whitelist_edit(options, args, method):
  714.     w = Whitelist(options.whitelist)
  715.     while args:
  716.         bug = args[0]
  717.         if bug == '' or (not ('A' <= bug[0] <= 'Z')) or ',' in bug:
  718.             sys.stderr.write("error: %s is not a bug name\n" % `bug`)
  719.             sys.exit(1)
  720.         del args[0]
  721.         pkg_found = False
  722.         while args:
  723.             pkg = args[0]
  724.             if (not pkg) or ',' in pkg:
  725.                 sys.stderr.write("error: %s is not a package name\n" % `bug`)
  726.                 sys.exit(1)
  727.             if 'A' <= pkg[0] <= 'Z':
  728.                 break
  729.             method(w, bug, pkg)
  730.             del args[0]
  731.             pkg_found = True
  732.         if not pkg_found:
  733.             method(w, bug, None)
  734.     w.update()
  735.  
  736. def whitelist_add(options, args):
  737.     __whitelist_edit(options, args, lambda w, bug, pkg: w.add(bug, pkg))
  738. def whitelist_remove(options, args):
  739.     __whitelist_edit(options, args, lambda w, bug, pkg: w.remove(bug, pkg))
  740. def whitelist_show(options, args):
  741.     Whitelist(options.whitelist).show(sys.stdout)
  742.  
  743. # Classes for output formatting
  744.  
  745. class Formatter:
  746.     def __init__(self, target, options, history):
  747.         self.target = target
  748.         self.options = options
  749.         self.history = history
  750.         self.whitelist = Whitelist(self.options.whitelist)
  751.         self._invalid_versions = False
  752.     def invalid_version(self, package, version):
  753.         sys.stdout.flush()
  754.         sys.stderr.write("error: invalid version %s of package %s\n"
  755.                          % (version, package))
  756.         if not self._invalid_versions:
  757.             sys.stderr.write(
  758.     "error: install the python-apt package for invalid versions support\n")
  759.             self._invalid_versions = True
  760.         sys.stderr.flush()
  761.     def invalid_source_version(self, package, version):
  762.         sys.stdout.flush()
  763.         sys.stderr.write("error: invalid source version %s of package %s\n"
  764.                          % (version, package))
  765.         if not self._invalid_versions:
  766.             sys.stderr.write(
  767.     "error: install the python-apt package for invalid versions support\n")
  768.             self._invalid_versions = True
  769.         sys.stderr.flush()
  770.     def maybe_record(self, v, bp, sp):
  771.         """Invoke self.record, honouring --only-fixed.  Can be
  772.        overridden to implement a different form of --only-fixed
  773.        processing."""
  774.         if self.whitelist.check(v.bug, bp[0]):
  775.             return
  776.         if not (self.options.only_fixed and not v.fix_available):
  777.             if self.options.no_obsolete and v.obsolete(bp[0]):
  778.                 return
  779.             self.record(v, bp, sp)
  780.     def finish(self):
  781.         pass
  782.  
  783. class BugFormatter(Formatter):
  784.     def __init__(self, target, options, history):
  785.         Formatter.__init__(self, target, options, history)
  786.         self.bugs = {}
  787.     def record(self, v, bp, sp):
  788.         self.bugs[v.bug] = 1
  789.     def finish(self):
  790.         bugs = self.bugs.keys()
  791.         bugs.sort()
  792.         for b in bugs:
  793.             self.target.write(b)
  794.  
  795. class PackageFormatter(Formatter):
  796.     def __init__(self, target, options, history):
  797.         Formatter.__init__(self, target, options, history)
  798.         self.packages = {}
  799.     def record(self, v, (bin_name, bin_version), sp):
  800.         self.packages[bin_name] = 1
  801.     def finish(self):
  802.         packages = self.packages.keys()
  803.         packages.sort()
  804.         for p in packages:
  805.             self.target.write(p)
  806.  
  807. class SummaryFormatter(Formatter):
  808.     def record(self, v,
  809.                (bin_name, bin_version), (src_name, src_version)):
  810.         notes = []
  811.         if v.fix_available:
  812.             notes.append("fixed")
  813.         if v.remote:
  814.             notes.append("remotely exploitable")
  815.         if v.urgency:
  816.             notes.append(v.urgency + " urgency")
  817.         if v.obsolete(bin_name):
  818.             notes.append('obsolete')
  819.         notes = ', '.join(notes)
  820.         if notes:
  821.             self.target.write("%s %s (%s)" % (v.bug, bin_name, notes))
  822.         else:
  823.             self.target.write("%s %s" % (v.bug, bin_name))
  824.  
  825. class SimpleFormatter(Formatter):
  826.     def record(self, v,
  827.                (bin_name, bin_version), (src_name, src_version)):
  828.         self.target.write("%s %s" % (v.bug, bin_name))
  829.  
  830. class DetailFormatter(Formatter):
  831.     def record(self, v,
  832.                (bin_name, bin_version), (src_name, src_version)):
  833.         notes = []
  834.         if v.fix_available:
  835.             notes.append("fixed")
  836.         if v.remote:
  837.             notes.append("remotely exploitable")
  838.         if v.urgency:
  839.             notes.append(v.urgency + " urgency")
  840.         notes = ', '.join(notes)
  841.         if notes:
  842.             self.target.write("%s (%s)" % (v.bug, notes))
  843.         else:
  844.             self.target.write(v.bug)
  845.         self.target.write("  " + v.description)
  846.         self.target.write("  installed: %s %s"
  847.                           % (bin_name, bin_version))
  848.         self.target.write("             (built from %s %s)"
  849.                           % (src_name, src_version))
  850.         if v.obsolete(bin_name):
  851.             self.target.write("             package is obsolete")
  852.  
  853.         if v.binary_package:
  854.             k = 'binary'
  855.         else:
  856.             k = 'source'
  857.         if v.unstable_version:
  858.             self.target.write("  fixed in unstable: %s %s (%s package)"
  859.                               % (v.package, v.unstable_version, k))
  860.         for vb in v.other_versions:
  861.             self.target.write("  fixed on branch:   %s %s (%s package)"
  862.                               % (v.package, vb, k))
  863.         if v.fix_available:
  864.             self.target.write("  fix is available for the selected suite (%s)"
  865.                               % self.options.suite)
  866.         self.target.write("")
  867.  
  868. class ReportFormatter(Formatter):
  869.     def __init__(self, target, options, history):
  870.         Formatter.__init__(self, target, options, history)
  871.         self.bugs = {}
  872.         self.invalid = []
  873.  
  874.         # self.record will put new package status information here.
  875.         self.new_history = {}
  876.  
  877.         # Fixed bugs are deleted from self.fixed_bugs by self.record.
  878.         self.fixed_bugs = self.history.data()
  879.  
  880.         # True if some bugs have been whitelisted.
  881.         self._whitelisted = False
  882.  
  883.     def _write_history(self, name):
  884.         """Writes self.new_history to the named history file.
  885.        The file is replaced atomically."""
  886.         new_name = name + '.new'
  887.         f = safe_open(new_name, "w+")
  888.         f.write("VERSION 1\n%d\n" % int(time.time()))
  889.         for ((bug, package), fixed) in self.new_history.items():
  890.             if fixed:
  891.                 fixed = 'F'
  892.             else:
  893.                 fixed = ' '
  894.             f.write("%s,%s,%s\n" % (bug, package, fixed))
  895.         f.close()
  896.         os.rename(new_name, name)
  897.  
  898.     def maybe_record(self, v, bp, sp):
  899.         # --only-fixed processing happens in self.finish, and we need
  900.         # all records to detect changes properly.  Whitelisted bugs
  901.         # need special treatment, too.
  902.         self.record(v, bp, sp)
  903.  
  904.     def record(self, v,
  905.                (bin_name, bin_version), (src_name, src_version)):
  906.  
  907.         v = v.installed(src_name, bin_name)
  908.         bn = (v.bug, bin_name)
  909.         if not self.whitelist.check(v.bug, bin_name):
  910.             if self.bugs.has_key(v.bug):
  911.                 self.bugs[v.bug].append(v)
  912.             else:
  913.                 self.bugs[v.bug] = [v]
  914.             self.new_history[bn] = v.fix_available
  915.         else:
  916.             self._whitelisted = True
  917.         # If we whitelist a bug, do not list it as fixed, so we always
  918.         # remove it from the fixed_bugs dict.
  919.         try:
  920.             del self.fixed_bugs[bn]
  921.         except KeyError:
  922.             pass
  923.  
  924.     def invalid_version(self, package, version):
  925.         self.invalid.append(package)
  926.     def invalid_source_version(self, package, version):
  927.         self.invalid.append(package)
  928.  
  929.     def _status_changed(self):
  930.         """Returns true if the system's vulnerability status changed
  931.        since the last run."""
  932.  
  933.         for (k, v) in self.new_history.items():
  934.             if (not self.history.known(k)) or self.history.fixed(k) <> v:
  935.                 return True
  936.         return len(self.fixed_bugs.keys()) > 0
  937.  
  938.     def finish(self):
  939.         if self.options.mailto and not self._status_changed():
  940.             if options.update_history:
  941.                 self._write_history(self.options.history)
  942.             return
  943.  
  944.         w = self.target.write
  945.         if self.options.suite:
  946.             w("Security report based on the %s release" % self.options.suite)
  947.         else:
  948.             w("Security report based on general data")
  949.             w("")
  950.             w(
  951. """If you specify a proper suite, this report will include information
  952. regarding available security updates and obsolete packages.  To set
  953. the correct suite, run "dpkg-reconfigure debsecan" as root.""")
  954.         w("")
  955.  
  956.         for vlist in self.bugs.values():
  957.             vlist.sort(lambda a, b: cmp(a.package, b.package))
  958.  
  959.         blist = self.bugs.items()
  960.         blist.sort()
  961.  
  962.         self._bug_found = False
  963.  
  964.         def print_headline(fix_status, new_status):
  965.             if fix_status:
  966.                 if new_status:
  967.                     w("*** New security updates")
  968.                 else:
  969.                     w("*** Available security updates")
  970.             else:
  971.                 if new_status:
  972.                     w("*** New vulnerabilities")
  973.                 else:
  974.                     if self.options.suite:
  975.                         w("*** Vulnerabilities without updates")
  976.                     else:
  977.                         # If no suite has been specified, all
  978.                         # vulnerabilities lack updates, technically
  979.                         # speaking.
  980.                         w("*** Vulnerabilities")
  981.             w("")
  982.  
  983.         def score_urgency(urgency):
  984.             return {'high' : 100,
  985.                     'medium' : 50,
  986.                     }.get(urgency, 0)
  987.  
  988.         def vuln_to_notes(v):
  989.             notes = []
  990.             notes_score = 0
  991.             if v.remote:
  992.                 notes.append("remotely exploitable")
  993.                 notes_score += 25
  994.             if v.urgency:
  995.                 notes.append(v.urgency + " urgency")
  996.                 notes_score += score_urgency(v.urgency)
  997.             if v.obsolete():
  998.                 notes.append('obsolete')
  999.             return (-notes_score, ', '.join(notes))
  1000.  
  1001.         def truncate(line):
  1002.             if len(line) <= self.options.line_length:
  1003.                 return line
  1004.             result = []
  1005.             length = 0
  1006.             max_length = self.options.line_length - 3
  1007.             for c in line.split(' '):
  1008.                 l = len(c)
  1009.                 new_length = length + l + 1
  1010.                 if new_length < max_length:
  1011.                     result.append(c)
  1012.                     length = new_length
  1013.                 else:
  1014.                     return ' '.join(result) + '...'
  1015.             return ' '.join(result)     # should not be reachedg
  1016.  
  1017.         def write_url(bug):
  1018.             w("  <http://security-tracker.debian.org/tracker/%s>" % bug)
  1019.  
  1020.         def scan(fix_status, new_status):
  1021.             have_obsolete = False
  1022.             first_bug = True
  1023.             for (bug, vlist) in blist:
  1024.                 pkg_vulns = {}
  1025.                 for v in vlist:
  1026.                     bug_package = (v.bug, v.installed_package)
  1027.                     if v.fix_available:
  1028.                         is_new = not self.history.fixed(bug_package)
  1029.                     else:
  1030.                         is_new = (not self.history.known(bug_package)) \
  1031.                                  or self.history.fixed(bug_package)
  1032.                     if v.fix_available <> fix_status or is_new <> new_status:
  1033.                         continue
  1034.  
  1035.                     if first_bug:
  1036.                         print_headline(fix_status, new_status)
  1037.                         first_bug = False
  1038.  
  1039.                     if v.obsolete():
  1040.                         if self.options.no_obsolete:
  1041.                             continue
  1042.                         have_obsolete = True
  1043.  
  1044.                     notes = vuln_to_notes(v)
  1045.                     if pkg_vulns.has_key(notes):
  1046.                         pkg_vulns[notes].append(v)
  1047.                     else:
  1048.                         pkg_vulns[notes] = [v]
  1049.  
  1050.                 indent = "    "
  1051.                 if len(pkg_vulns) > 0:
  1052.                     self._bug_found = True
  1053.                     notes = pkg_vulns.keys()
  1054.                     notes.sort()
  1055.                     # any v will do, because we've aggregated by v.bug
  1056.                     v = pkg_vulns[notes[0]][0]
  1057.                     w(truncate("%s %s" % (v.bug, v.description)))
  1058.                     write_url(v.bug)
  1059.  
  1060.                     for note in notes:
  1061.                         note_text = note[1]
  1062.                         line = "  - "
  1063.                         comma_needed = False
  1064.                         for v in pkg_vulns[note]:
  1065.                             pkg = v.installed_package
  1066.                             # Wrap the package list if the line length
  1067.                             # is exceeded.
  1068.                             if len(line) + len(pkg) + 3 \
  1069.                                    > self.options.line_length:
  1070.                                 w(line + ',')
  1071.                                 line = indent + pkg
  1072.                                 comma_needed = True
  1073.                             else:
  1074.                                 if comma_needed:
  1075.                                     line += ", "
  1076.                                 else:
  1077.                                     comma_needed = True
  1078.                                 line += pkg
  1079.                         if note_text:
  1080.                             if len(line) + len(note_text) + 3 \
  1081.                                    > self.options.line_length:
  1082.                                 w(line)
  1083.                                 w("%s(%s)" % (indent, note_text))
  1084.                             else:
  1085.                                 w("%s (%s)" % (line, note_text))
  1086.                         else:
  1087.                             w(line)
  1088.                     w("")
  1089.  
  1090.             if have_obsolete:
  1091.                 w(
  1092. """Note that some packages were marked as obsolete.  To deal with the
  1093. vulnerabilities in them, you need to remove them.  Before you can do
  1094. this, you may have to upgrade other packages depending on them.
  1095. """)
  1096.  
  1097.         def scan_fixed():
  1098.             bugs = {}
  1099.             for (bug, package) in self.fixed_bugs.keys():
  1100.                 if bugs.has_key(bug):
  1101.                     bugs[bug].append(package)
  1102.                 else:
  1103.                     bugs[bug] = [package]
  1104.             bug_names = bugs.keys()
  1105.             bug_names.sort()
  1106.  
  1107.             first_bug = True
  1108.             for bug in bug_names:
  1109.                 if first_bug:
  1110.                     w("*** Fixed vulnerabilities")
  1111.                     w("")
  1112.                     first_bug = False
  1113.                     self._bug_found = True
  1114.                 w(bug)
  1115.                 write_url(bug)
  1116.                 bugs[bug].sort()
  1117.                 for p in bugs[bug]:
  1118.                     w("  - %s" % p)
  1119.                 w("")
  1120.  
  1121.         def scan_invalid():
  1122.             if self.invalid:
  1123.                 self._bug_found = True
  1124.                 self.invalid.sort()
  1125.                 w("*** Packages with invalid versions")
  1126.                 w("")
  1127.                 w("The following non-official packages have invalid versions and cannot")
  1128.                 w("be classified correctly:")
  1129.                 w("")
  1130.                 for p in self.invalid:
  1131.                     w("  - " + p)
  1132.  
  1133.         scan(fix_status=True, new_status=True)
  1134.         scan_fixed()
  1135.         scan(fix_status=True, new_status=False)
  1136.         if not self.options.only_fixed:
  1137.             scan(fix_status=False, new_status=True)
  1138.             scan(fix_status=False, new_status=False)
  1139.         scan_invalid()
  1140.  
  1141.         if not self._bug_found:
  1142.             if self.options.only_fixed:
  1143.                 w(
  1144. """No known vulnerabilities for which updates are available were found
  1145. on the system.""")
  1146.             else:
  1147.                 w("No known vulnerabilities were found on the system.")
  1148.             if self._whitelisted:
  1149.                 w("")
  1150.                 w("However, some bugs have been whitelisted.")
  1151.         else:
  1152.             if self._whitelisted:
  1153.                 w(
  1154. """Note that some vulnerablities have been whitelisted and are not included
  1155. in this report.""")
  1156.  
  1157.         if options.update_history:
  1158.             self._write_history(self.options.history)
  1159.  
  1160. formatters = {'bugs' : BugFormatter,
  1161.               'packages' : PackageFormatter,
  1162.               'summary' : SummaryFormatter,
  1163.               'simple' : SimpleFormatter,
  1164.               'detail' : DetailFormatter,
  1165.               'report' : ReportFormatter}
  1166.  
  1167. # Mini-template processing
  1168.  
  1169. format_values = {
  1170.     'hostname' : socket.gethostname(),
  1171.     'fqdn' : socket.getfqdn()
  1172. }
  1173. try:
  1174.     format_values['ip'] = socket.gethostbyname(format_values['hostname'])
  1175. except socket.gaierror:
  1176.     format_values['ip'] = "unknown"
  1177.  
  1178. def format_string(msg):
  1179.     try:
  1180.         return msg % format_values
  1181.     except ValueError:
  1182.         sys.stderr.write("error: invalid format string: %s\n" % `msg`)
  1183.         sys.exit(2)
  1184.     except KeyError, e:
  1185.         sys.stderr.write("error: invalid key %s in format string %s\n"
  1186.                          % (`e.args[0]`, `msg`))
  1187.         sys.exit(2)
  1188.  
  1189. # Targets
  1190.  
  1191. class Target:
  1192.     def __init__(self, options):
  1193.         pass
  1194.     def finish(self):
  1195.         pass
  1196.  
  1197. class TargetMail(Target):
  1198.     def __init__(self, options):
  1199.         assert options.mailto
  1200.         self.options = options
  1201.         self.sendmail = None
  1202.         self.opt_subject = format_string(self.options.subject)
  1203.  
  1204.         # Legacy addresses may contain "%" characters, without
  1205.         # proper template syntax.
  1206.         self.opt_mailto = format_string(
  1207.             re.sub(r'%([a-z0-9])', r'%%\1', self.options.mailto))
  1208.  
  1209.     def _open(self):
  1210.         self.sendmail = os.popen("/usr/sbin/sendmail -t", "w")
  1211.         self.sendmail.write("""Subject: %s
  1212. To: %s
  1213.  
  1214. """ % (self.opt_subject, self.opt_mailto))
  1215.  
  1216.     def write(self, line):
  1217.         if self.sendmail is None:
  1218.             self._open()
  1219.         self.sendmail.write(line + '\n')
  1220.  
  1221.     def finish(self):
  1222.         if self.sendmail is not None:
  1223.             self.sendmail.close()
  1224.  
  1225. class TargetPrint(Target):
  1226.     def write(self, line):
  1227.         print line
  1228.  
  1229.  
  1230. def rate_system(target, options, vulns, history):
  1231.     """Read /var/lib/dpkg/status and discover vulnerable packages.
  1232.    The results are printed using one of the formatter classes.
  1233.  
  1234.    options: command line options
  1235.    vulns: list of vulnerabiltiies"""
  1236.     packages = PackageFile(options.status)
  1237.     re_source = re.compile\
  1238.                 (r'^([a-zA-Z0-9.+-]+)(?:\s+\((\S+)\))?$')
  1239.     formatter = formatters[options.format](target, options, history)
  1240.     for pkg in packages:
  1241.         pkg_name = None
  1242.         pkg_status = None
  1243.         pkg_version = None
  1244.         pkg_arch = None
  1245.         pkg_source = None
  1246.         pkg_source_version = None
  1247.  
  1248.         for (name, contents) in pkg:
  1249.             if name == "Package":
  1250.                 pkg_name = contents
  1251.             if name == "Status":
  1252.                 pkg_status = contents
  1253.             elif name == "Version":
  1254.                 pkg_version = contents
  1255.             elif name == "Source":
  1256.                 match = re_source.match(contents)
  1257.                 if match is None:
  1258.                     raise SyntaxError(('package %s references '
  1259.                                        + 'invalid source package %s') %
  1260.                                       (pkg_name, `contents`))
  1261.                 (pkg_source, pkg_source_version) = match.groups()
  1262.         if pkg_name is None:
  1263.             raise SyntaxError\
  1264.                   ("package record does not contain package name")
  1265.         if pkg_status is None:
  1266.             raise SyntaxError\
  1267.                   ("package record does not contain status")
  1268.         if 'installed' not in pkg_status.split(' '):
  1269.             # Package is not installed.
  1270.             continue
  1271.         if pkg_version is None:
  1272.             raise SyntaxError\
  1273.                   ("package record does not contain version information")
  1274.         if pkg_source_version is None:
  1275.             pkg_source_version = pkg_version
  1276.         if not pkg_source:
  1277.             pkg_source = pkg_name
  1278.  
  1279.         try:
  1280.             pkg_version = Version(pkg_version)
  1281.         except ValueError:
  1282.             formatter.invalid_version(pkg_name, pkg_version)
  1283.             continue
  1284.         try:
  1285.             pkg_source_version = Version(pkg_source_version)
  1286.         except ValueError:
  1287.             formatter.invalid_source_version(pkg_name, pkg_source_version)
  1288.             continue
  1289.  
  1290.         try:
  1291.             vlist = vulns[pkg_source]
  1292.         except KeyError:
  1293.             try:
  1294.                 vlist = vulns[pkg_name]
  1295.             except:
  1296.                 continue
  1297.         for v in vlist:
  1298.             bp = (pkg_name, pkg_version)
  1299.             sp = (pkg_source, pkg_source_version)
  1300.             if v.is_vulnerable (bp, sp):
  1301.                 formatter.maybe_record(v, bp, sp)
  1302.     formatter.finish()
  1303.     target.finish()
  1304.  
  1305. if __name__ == "__main__":
  1306.     (options, config, args) = parse_cli()
  1307.     if (options.update_config):
  1308.         update_config(options.config)
  1309.         sys.exit(0)
  1310.     if options.cron and config.get("REPORT", "true") <> "true":
  1311.         # Do nothing in cron mode if reporting is disabled.
  1312.         sys.exit(0)
  1313.     if options.need_history:
  1314.         history = History(options)
  1315.         if not history.expired():
  1316.             sys.exit(0)
  1317.     else:
  1318.         history = None
  1319.     if options.mailto:
  1320.         target = TargetMail(options)
  1321.     else:
  1322.         target = TargetPrint(options)
  1323.     rate_system(target, options, fetch_data(options, config), history)
Advertisement
Add Comment
Please, Sign In to add comment