#!/usr/bin/python
#
#    openvpn-vulnkey: check a database of md5'd static key hashes for
#      known vulnerable keys
#    Copyright (C) 2008 Canonical Ltd.
#    Author: Jamie Strandboge <jamie@canonical.com>
#
#    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, see <http://www.gnu.org/licenses/>.
#

from optparse import OptionParser
import md5
import re
import sys

version = "0.1"
db = "/usr/share/openvpn-blacklist/blacklist.RSA-2048"

parser = OptionParser(usage="%prog FILE [FILE]", \
                      version="%prog: " + version, \
                      description="This program checks if FILEs are known " + \
                                  "vulnerable static keys")
parser.add_option("-q", "--quiet", action="store_true", dest="quiet", \
                  help="be quiet")
(options, args) = parser.parse_args()

if not args:
    parser.print_help()
    sys.exit(1)

# Read in the database
try:
    fh = open(db, 'r')
except:
    print >> sys.stderr, "ERROR: could not open database"
    sys.exit(1)

db_lines = fh.read().split('\n')
fh.close()

# Check each file
found = False
for f in args:
    try:
        fh = open(f, 'r')
    except:
        if not options.quiet:
            print >> sys.stderr, "'%s' could not be opened (skipping)" % (f)
        continue

    keyfile = ""
    for line in fh:
        # Only get the actual key, not the comment text
        if re.match(r'^[0-9a-f]', line):
            keyfile += line
    fh.close()

    key = md5.new(keyfile).hexdigest()
    if key[12:] in db_lines:
        if not options.quiet:
            print "COMPROMISED: %s %s" % (key, f)
        found = True
    else:
        if not options.quiet:
            print "Not blacklisted: %s %s" % (key, f)

if found:
    sys.exit(1)

