def main(): try: env = get_controls()['002']['env'] env['filename'] = quote(env['filename']) ssh = get_transport('SSH') data = ssh.execute_show( 'stat --printf="%a %U %G" {filename}'.format(**env)) if not data: return Status.NOT_APPLICABLE, 'File not found' else: data = data.split() if data[0] != env['permissions']: return Status.NOT_COMPLIANT, None try: if data[1] != env['owner']: return Status.NOT_COMPLIANT, None elif data[2] != env['group']: return Status.NOT_COMPLIANT, None except KeyError: pass return Status.COMPLIANT, None except (TransportConnectionError, RemoteHostCommandError): return Status.NOT_APPLICABLE, 'No SSH connection' except Exception as e_info: return Status.ERROR, str(e_info)
def test_get_mysql_transport_from_params_pass(run_docker): sql = get_transport(transport_name='MySQL', host='localhost', port=port_sql, user='******', password=env_sql['MYSQL_ROOT_PASSWORD']) assert isinstance(sql, MySQLTransport)
def snmp_audit(): sysDescr = '.1.3.6.1.2.1.1.1.0' ifNumber = '.1.3.6.1.2.1.2.1.0' ifDescr = '.1.3.6.1.2.1.2.2.1.2.{num}' ifOperStatus = '.1.3.6.1.2.1.2.2.1.8.{num}' ifaces = list() try: snmp = get_transport('SNMP') sysDescr_data = snmp.get_snmpdata(sysDescr)[0] iface_number = int(snmp.get_snmpdata(ifNumber)[0]) for i_num in range(1, iface_number + 1): ifaces.append( snmp.get_snmpdata(ifDescr.format(num=i_num), ifOperStatus.format(num=i_num))) except (TransportConnectionError, SNMPError, SNMPStatusError): return ifaces = tuple(map(lambda x: [x[0], IfaceStatus(int(x[1])).name], ifaces)) vendor, version, = sysDescr_data.split('\n')[:2] attributes = dict(vendor=vendor, software_version=version, interfaces='\n'.join([ "Ifnterface: {}, status: {}".format(*iface) for iface in ifaces ])) with sqlite3.connect(DB_NAME) as db: curr = db.cursor() curr.execute("PRAGMA foreign_keys = ON") for attribute, value in attributes.items(): curr.execute("INSERT INTO audit VALUES (NULL, ?, ?, ?, ?)", (attribute, value, 'SNMP', get_scan_id()))
def test_002_permissions_1(run_docker): env = get_controls()['002']['env'] env['filename'] = quote(env['filename']) ssh = get_transport('SSH') ssh.execute('chmod {permissions} {filename}'.format(**env)) ssh.execute('chown {owner}:{group} {filename}'.format(**env)) assert test.main()[0] == Status.COMPLIANT
def test_002_permissions_2(run_docker): env = get_controls()['002']['env'] env['filename'] = quote(env['filename']) ssh = get_transport('SSH') ssh.execute('chmod {permissions} {filename}'.format( permissions=int(env['permissions']) ^ 1, filename=env['filename'])) assert test.main()[0] == Status.NOT_COMPLIANT
def test_000_file_exist_2(run_docker): env = get_controls()['000']['env'] env['filename'] = quote(env['filename']) ssh = get_transport('SSH') try: ssh.execute('rm -f {filename}'.format(**env)) except Exception: pass assert test.main()[0] == Status.NOT_COMPLIANT
def test_sqlexec_request(self, run_docker): sql = get_transport('MySQL') sql.sqlexec('CREATE DATABASE IF NOT EXISTS test_db') sql.connect('test_db') sql.sqlexec("""CREATE TABLE IF NOT EXISTS test ( name VARCHAR(20), owner VARCHAR(20))""") sql.sqlexec("INSERT INTO test VALUES ('Dolly', 'Me')") data = sql.sqlexec('SELECT * FROM test') assert data == [{'name': 'Dolly', 'owner': 'Me'}]
def test_001_database_exist_1(run_docker): env = get_controls()['001']['env'] sql = get_transport('MySQL') sql.sqlexec('CREATE DATABASE IF NOT EXISTS {db_name}'.format(**env)) sql.connect(database=env['db_name']) sql.sqlexec("""CREATE TABLE IF NOT EXISTS {table_name} ( name VARCHAR(20), owner VARCHAR(20))""".format(**env)) sql.sqlexec( "INSERT INTO {table_name} VALUES ('Dolly', 'Me')".format(**env)) assert test.main()[0] == Status.COMPLIANT
def main(): try: env = get_controls()['000']['env'] ssh = get_transport('SSH') ssh.get_file(env['filename']) except SSHFileNotFound: return Status.NOT_COMPLIANT, None except TransportConnectionError: return Status.NOT_APPLICABLE, 'No connection' except Exception as e_info: return Status.ERROR, str(e_info) return Status.COMPLIANT, None
def ssh_audit(): try: ssh = get_transport('SSH') except TransportConnectionError: return # Как что-то ещё определить? attributes = dict(OS=ssh.execute_show('cat /proc/version'), Users=ssh.execute_show('cat /etc/passwd'), MACs=ssh.execute_show('ip l'), Packages='\n'.join( '{}: {}'.format(pkg, ver) for pkg, ver in get_packages(ssh).items())) with sqlite3.connect(DB_NAME) as db: curr = db.cursor() curr.execute("PRAGMA foreign_keys = ON") for attribute, value in attributes.items(): curr.execute("INSERT INTO audit VALUES (NULL, ?, ?, ?, ?)", (attribute, value, 'SSH', get_scan_id()))
def main(): try: ssh = get_transport('SSH') data = ssh.execute_show('show mem | strings | grep password') if not data: return Status.COMPLIANT, None else: # Пока только 1 вариант обрабатывается data = tuple(map(lambda x: x.split(), data.split('\n')))[0] login = data[1] password = cisco_type7.decode(data[4]) with sqlite3.connect(DB_NAME) as db: curr = db.cursor() curr.execute( "UPDATE control SET prescription = ? WHERE id = ?", ("Found credentials: {}: {}".format(login, password), TEST_NUM)) return Status.NOT_COMPLIANT, None except (TransportConnectionError, RemoteHostCommandError): return Status.NOT_APPLICABLE, 'No connection' except Exception as e_info: return Status.ERROR, str(e_info)
def main(): try: env = get_controls()['001']['env'] sql = get_transport('MySQL') databases = [db['Database'] for db in sql.sqlexec('SHOW DATABASES')] if env['db_name'] not in databases: return Status.NOT_COMPLIANT, None tables = [ table['Tables_in_{db_name}'.format(**env)] for table in sql.sqlexec('SHOW TABLES FROM {db_name}'.format( **env)) ] if env['table_name'] not in tables: return Status.NOT_COMPLIANT, None sql.connect(env['db_name']) if sql.sqlexec('SELECT * FROM {table_name}'.format(**env)): return Status.COMPLIANT, None return Status.NOT_COMPLIANT, None except TransportConnectionError: return Status.NOT_APPLICABLE, 'No connection' except Exception as e_info: return Status.ERROR, str(e_info)
def test_get_file_except(self, run_docker): ssh = get_transport('SSH') with pytest.raises(SSHFileNotFound): ssh.get_file('/wrong_file')
def test_with_connect(self, run_docker): with get_transport('MySQL') as sql: sql.sqlexec('SHOW DATABASES')
def test_connect_wrong_db(self, run_docker): with pytest.raises(UnknownDatabase): sql = get_transport('MySQL') sql.connect('wrong_database')
def test_get_transport_except(run_docker): with pytest.raises(UnknownTransport): get_transport('noway')
def test_connect_pass(self, run_docker): sql = get_transport('MySQL') sql.sqlexec('SHOW DATABASES')
def test_execute_except(self, run_docker): ssh = get_transport('SSH') with pytest.raises(TransportError): ssh.execute('wrong_command')
def test_get_mysql_transport_from_config_pass(run_docker): sql = get_transport('MySQL') assert isinstance(sql, MySQLTransport)
def test_get_ssh_transport_from_config_pass(run_docker): ssh = get_transport('SSH') assert isinstance(ssh, SSHTransport)
def test_get_file_pass(self, run_docker): ssh = get_transport('SSH') assert isinstance(ssh.get_file('/etc/passwd'), bytes)
def test_connect_wrong_auth(self, run_docker): with pytest.raises(AuthenticationError): get_transport('SSH', password='******')
def test_with_connect(self, run_docker): with get_transport('SSH') as ssh: ssh.execute('ls')
def test_sqlexec_wrong_request(self, run_docker): sql = get_transport('MySQL') with pytest.raises(MySQLError): sql.sqlexec('WRONG REQUEST')
def test_connect_pass(self, run_docker): ssh = get_transport('SSH') ssh.execute('ls')
def test_connect(self, run_docker): get_transport('SNMP')
def test_persistent_connection(self, run_docker): assert get_transport('SSH') is get_transport('SSH')
def test_get_snmpdata(self, run_docker): snmp = get_transport('SNMP') assert snmp.get_snmpdata('.1.3.6.1.2.1.1.1.0')
def test_connect_wrong_host(self, run_docker): with pytest.raises(TransportConnectionError): get_transport('SSH', port=WRONG_PORT)
def test_get_ssh_transport_from_params_pass(run_docker): ssh = get_transport('SSH', 'localhost', port_ssh, 'root', 'pwd') assert isinstance(ssh, SSHTransport)