#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# Example output from agent:
# <<<sshd_config>>>
# Port 22
# Port 12345
# Protocol 2,1
# ChallengeResponseAuthentication no
# UsePAM yes
# X11Forwarding yes
# PrintMotd no
# AcceptEnv LANG LC_*
# Subsystem sftp /usr/lib/openssh/sftp-server


def parse_sshd_config(info):
    identity = lambda x: x

    def map_permit_root_login(value):
        if value in [u"prohibit-password", u"without-password"]:
            return u"key-based"
        return value

    relevant_options = {
        #option                             parse function
        "Protocol": lambda x: ",".join(sorted(x.split(","))),
        # Port can be defined multiple times in sshd_config.
        # Therefore we use a list of ints.
        "Port": lambda x: [int(x)],
        "PermitRootLogin": map_permit_root_login,
        "PasswordAuthentication": identity,
        "PermitEmptyPasswords": identity,
        "ChallengeResponseAuthentication": identity,
        "X11Forwarding": identity,
        "UsePAM": identity,
        "Ciphers": lambda x: sorted(x.split(",")),
    }

    parsed = {}
    for line in info:
        if len(line) < 2:
            continue

        key, val = line[0], " ".join(line[1:])
        if key not in relevant_options:
            continue

        parse_func = relevant_options[key]
        val = parse_func(val)

        if not key in parsed:
            parsed[key] = val
        else:
            parsed[key] += val

    return parsed


def inventory_sshd_config(parsed):
    return [(None, {})]


def check_sshd_config(_no_item, params, parsed):
    root_login = params.get("PermitRootLogin", "")
    if root_login == "without-password":
        params["PermitRootLogin"] = "key-based"

    # type_ is needed because info contains unicode and params str
    convert = lambda x, type_: (x if isinstance(x, type_) else ", ".join(map(type_, x)))

    for option, val in parsed.items():
        state = 0
        infotext = "%s: %s" % (option, convert(val, str))

        expected = params.get(option)
        if expected and expected != val:
            state = 2
            infotext += " (expected %s)" % convert(expected, str)

        yield state, infotext

    for option in params:
        if not option in parsed:
            yield 2, "%s: not present in sshd_config" % option


check_info["sshd_config"] = {
    "parse_function": parse_sshd_config,
    "inventory_function": inventory_sshd_config,
    "check_function": check_sshd_config,
    "service_description": "SSH daemon configuration",
    "group": "sshd_config",
}
