#!/usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author:  Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
#          https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.

# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.md

"""See the check's README for more details.
"""

import argparse  # pylint: disable=C0413
import random  # pylint: disable=C0413
import string  # pylint: disable=C0413
import sys  # pylint: disable=C0413

import lib.base  # pylint: disable=C0413
import lib.db_mysql  # pylint: disable=C0413
import lib.txt  # pylint: disable=C0413
from lib.globals import STATE_OK, STATE_UNKNOWN  # pylint: disable=C0413

__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2025031401'

DESCRIPTION = """Check user's security in MySQL/MariaDB."""

DEFAULT_DEFAULTS_FILE = '/var/spool/icinga2/.my.cnf'
DEFAULT_DEFAULTS_GROUP = 'client'
DEFAULT_SERVERITY = 'warn'
DEFAULT_TIMEOUT = 3


def parse_args():
    """Parse command line arguments using argparse.
    """
    parser = argparse.ArgumentParser(description=DESCRIPTION)

    parser.add_argument(
        '-V', '--version',
        action='version',
        version='{0}: v{1} by {2}'.format('%(prog)s', __version__, __author__)
    )

    parser.add_argument(
        '--always-ok',
        help='Always returns OK.',
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--defaults-file',
        help='Specifies a cnf file to read parameters like user, host and password from '
             '(instead of specifying them on the command line), '
             'for example `/var/spool/icinga2/.my.cnf`. Default: %(default)s',
        dest='DEFAULTS_FILE',
        default=DEFAULT_DEFAULTS_FILE,
    )

    parser.add_argument(
        '--defaults-group',
        help='Group/section to read from in the cnf file. Default: %(default)s',
        dest='DEFAULTS_GROUP',
        default=DEFAULT_DEFAULTS_GROUP,
    )

    parser.add_argument(
        '--severity',
        help='Severity for alerts that do not depend on thresholds. One of "warn" or "crit". Default: %(default)s',
        dest='SEVERITY',
        default=DEFAULT_SERVERITY,
        choices=['warn', 'crit'],
    )

    parser.add_argument(
        '--timeout',
        help='Network timeout in seconds. Default: %(default)s (seconds)',
        dest='TIMEOUT',
        type=int,
        default=DEFAULT_TIMEOUT,
    )

    return parser.parse_args()


def main():
    """The main function. Hier spielt die Musik.
    """

    # logic taken from mysqltuner.pl:security_recommendations(), v1.9.8
    # including variable names

    # parse the command line, exit with UNKNOWN if it fails
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)

    mysql_connection = {
        'defaults_file':  args.DEFAULTS_FILE,
        'defaults_group': args.DEFAULTS_GROUP,
        'timeout':        args.TIMEOUT,
    }
    conn = lib.base.coe(lib.db_mysql.connect(mysql_connection))
    lib.base.coe(lib.db_mysql.check_select_privileges(conn))

    # init some vars
    msg_header, msg_body = '', ''
    state = STATE_OK

    # Looking for Anonymous users
    sql = '''
        select concat(quote(user), "@", quote(host)) as user
        from mysql.user
        where trim(user) = ""
            or user is null;
    '''
    users = lib.base.coe(lib.db_mysql.select(conn, sql))
    if len(users):
        state = lib.base.str2state(args.SEVERITY)
        msg_header += '{} anonymous user {}{}. '.format(
            len(users),
            lib.txt.pluralize('account', len(users)),
            lib.base.state2str(lib.base.str2state(args.SEVERITY), prefix=' '),
        )
        msg_body += '\nRemove anonymous users:\n'
        for user in users:
            msg_body += '* DROP USER {};\n'.format(user['user'])

    # possible password column names:
    pass_column_names = [
        'password',
        'authentication_string',
        'IF(plugin="mysql_native_password", authentication_string, password)',
    ]

    # Looking for users having empty passwords
    # MariaDB 10.4+:
    sql = '''
        select concat(quote(user), "@", quote(host)) as user
        from mysql.global_priv
        where user != ""
            and user != "mariadb.sys"
            and user != "mysql.sys"
            and json_contains(priv, '"mysql_native_password"', "$.plugin")
            and json_contains(priv, '""', "$.authentication_string")
            and not json_contains(priv, '"true"', "$.account_locked");
    '''
    success, users = lib.db_mysql.select(conn, sql)
    if not success:
        # all other versions:
        for pass_column_name in pass_column_names:
            sql = '''
                select concat(quote(user), "@", quote(host)) as user
                from mysql.user
                where ({0} = "" or {0} is null)
                    and user != ""
                    and user != "mariadb.sys"
                    and user != "mysql.sys"
                    /*!50501 and plugin not in ("auth_socket", "unix_socket", "win_socket", "auth_pam_compat") */
                    /*!80000 and account_locked = "N" and password_expired = "N" */;
            '''.format(pass_column_name)
            success, users = lib.db_mysql.select(conn, sql)
            if success:
                break
    if success and len(users):
        state = lib.base.str2state(args.SEVERITY)
        msg_header += '{} {} without password{}. '.format(
            len(users),
            lib.txt.pluralize('user', len(users)),
            lib.base.state2str(state, prefix=' '),
        )
        msg_body += '\nSet user passwords:\n'
        for user in users:
            msg_body += '* SET PASSWORD FOR {} = PASSWORD("{}");\n'.format(
                user['user'],
                ''.join(random.choice(string.ascii_letters + string.digits) for i in range(40))
            )

    # Looking for users with user / uppercase / capitalise user as password
    # does not work on MySQL 8
    for pass_column_name in pass_column_names:
        sql = '''
            select concat(quote(user), "@", quote(host)) as user
            from mysql.user
            where user != ""
                and user != "mariadb.sys"
                and user != "mysql.sys"
                and (
                    cast({0} as binary) = password(user)
                    or cast({0} as binary) = password(upper(user))
                    or cast({0} as binary) = password(concat(upper(left(user, 1)), substring(user, 2, length(user))))
                );
        '''.format(pass_column_name)
        success, users = lib.db_mysql.select(conn, sql)
        if success:
            break
    if success and len(users):
        state = lib.base.str2state(args.SEVERITY)
        msg_header += '{} {} with username as password{}. '.format(
            len(users),
            lib.txt.pluralize('user', len(users)),
            lib.base.state2str(state, prefix=' '),
        )
        msg_body += '\nChange user passwords:\n'
        for user in users:
            msg_body += '* SET PASSWORD FOR {} = PASSWORD("{}");\n'.format(
                user['user'],
                ''.join(random.choice(string.ascii_letters + string.digits) for i in range(40))
            )

    # Looking for users without hostname restriction
    sql = '''
        select concat(quote(user), "@", quote(host)) as user
        from mysql.user
        where host = "%";
    '''
    users = lib.base.coe(lib.db_mysql.select(conn, sql))
    if len(users):
        state = lib.base.str2state(args.SEVERITY)
        msg_header += '{} {} without hostname restriction{}. '.format(
            len(users),
            lib.txt.pluralize('account', len(users)),
            lib.base.state2str(lib.base.str2state(args.SEVERITY), prefix=' '),
        )
        msg_body += '\nRestrict users:\n'
        for user in users:
            msg_body += '* RENAME USER {} TO {};\n'.format(
                user['user'],
                user['user'].replace("'%", "'LimitedIPRangeOrLocalhost")
            )

    lib.db_mysql.close(conn)

    msg = msg_header + '\n' + msg_body
    if not msg.strip():
        msg = 'Everything is ok.'

    # over and out
    lib.base.oao(msg, state, always_ok=args.ALWAYS_OK)


if __name__ == '__main__':
    try:
        main()
    except Exception:   # pylint: disable=W0703
        lib.base.cu()
