#! /usr/bin/env python

# This file is part of IVRE.
# Copyright 2011 - 2014 Pierre LALET <pierre.lalet@cea.fr>
#
# IVRE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# IVRE 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 IVRE. If not, see <http://www.gnu.org/licenses/>.

import ivre.keys
import ivre.utils
import re
import sys

KNOWN_KEYS = {}


def read_known_keys(listname, keytype, keylen, filename):
    for l in open(filename):
        add_known_key(listname, keytype, keylen, l)


def add_known_key(listname, keytype, keylen, key):
    key = key.replace(':', '').strip().decode('hex')
    k = KNOWN_KEYS.get(key, [])
    k.append('%s-%s-%d' % (listname, keytype, keylen))
    KNOWN_KEYS[key] = k


def check_ssh_keys():
    for k in ivre.keys.SSHKey().get_hashes():
        if k['hash'] in KNOWN_KEYS:
            svcs = "" % ()
            print 'SERVICE %s:%d has key %s listed as %r' % (
                ivre.utils.int2ip(k['host']),
                k['port'],
                k['hash'].encode('hex'),
                KNOWN_KEYS[k['hash']])

if __name__ == '__main__':
    read_known_keys('DebianWeakKeys', 'dsa',
                    1024, 'data/DebianSSHWeakKeys-dsa-1024')
    read_known_keys('DebianWeakKeys', 'rsa',
                    2048, 'data/DebianSSHWeakKeys-rsa-2048')
    add_known_key('LittleBlackBox', 'rsa', 2048,
                  '19:c6:8b:c2:1a:8a:ec:2d:d7:7a:f3:eb:d4:bc:68:d0')
    check_ssh_keys()
