2019-07-27 16:51:56 +02:00
|
|
|
#!/usr/bin/python3
|
|
|
|
|
|
|
|
# file: statusd.py
|
|
|
|
# date: 26.07.2019
|
|
|
|
# email: berhsi@web.de
|
|
|
|
|
2019-09-17 19:07:07 +02:00
|
|
|
# server, which listens for ipv4 connections at port 10001. now with ssl
|
2019-07-29 18:32:27 +02:00
|
|
|
# encrypted connection and client side authentication.
|
2019-07-27 16:51:56 +02:00
|
|
|
|
|
|
|
import socket
|
2019-07-29 18:32:27 +02:00
|
|
|
import ssl
|
2019-07-27 16:51:56 +02:00
|
|
|
import os
|
|
|
|
import logging
|
2019-09-10 09:47:53 +02:00
|
|
|
import json
|
2019-09-19 10:21:33 +02:00
|
|
|
from time import time, sleep
|
2019-09-13 10:29:38 +02:00
|
|
|
from sys import exit
|
2019-07-27 16:51:56 +02:00
|
|
|
|
|
|
|
|
|
|
|
def read_config(CONFIGFILE, CONFIG):
|
|
|
|
'''
|
|
|
|
reads the given config file and sets the values are founded.
|
|
|
|
param 1: string
|
|
|
|
param 2: dictionary
|
|
|
|
return: boolean
|
|
|
|
'''
|
|
|
|
logging.debug('Read configfile {}'.format(CONFIGFILE))
|
|
|
|
if os.access(CONFIGFILE, os.R_OK):
|
|
|
|
logging.debug('Configfile is readable')
|
|
|
|
with open(CONFIGFILE, 'r') as config:
|
|
|
|
logging.debug('Configfile successfull read')
|
|
|
|
for line in config.readlines():
|
|
|
|
if not line[0] in ('#', ';', '\n', '\r'):
|
|
|
|
key, value = (line.strip().split('='))
|
2019-07-29 18:32:27 +02:00
|
|
|
key = strip_argument(key).upper()
|
2019-09-17 19:07:07 +02:00
|
|
|
if key in CONFIG.keys():
|
|
|
|
value = strip_argument(value)
|
|
|
|
CONFIG[key] = value
|
2019-09-19 10:21:33 +02:00
|
|
|
else:
|
|
|
|
pass
|
2019-07-27 16:51:56 +02:00
|
|
|
else:
|
|
|
|
logging.error('Failed to read {}'.format(CONFIGFILE))
|
|
|
|
logging.error('Using default values')
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2019-07-30 22:06:07 +02:00
|
|
|
def certs_readable(config):
|
2019-07-30 22:20:45 +02:00
|
|
|
'''
|
2019-09-19 10:21:33 +02:00
|
|
|
checks at start, if the needed certificates defined (no nullstring) and
|
|
|
|
readable.
|
2019-07-30 22:20:45 +02:00
|
|
|
param 1: dictionary
|
|
|
|
return: boolean
|
|
|
|
'''
|
2019-09-19 10:21:33 +02:00
|
|
|
for i in (config['SERVER_KEY'], config['SERVER_CERT'],
|
|
|
|
config['CLIENT_CERT']):
|
|
|
|
if i == '' or os.access(i, os.R_OK) is False:
|
2019-07-30 22:06:07 +02:00
|
|
|
logging.error('Cant read {}'.format(i))
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2019-07-29 18:32:27 +02:00
|
|
|
def strip_argument(argument):
|
|
|
|
'''
|
|
|
|
Becomes a string and strips at first whitespaces, second apostrops and
|
|
|
|
returns the clear string.
|
|
|
|
param 1: string
|
|
|
|
return: string
|
|
|
|
'''
|
|
|
|
argument = argument.strip()
|
|
|
|
argument = argument.strip('"')
|
|
|
|
argument = argument.strip("'")
|
|
|
|
return argument
|
|
|
|
|
|
|
|
|
2019-07-27 16:51:56 +02:00
|
|
|
def print_config(CONFIG):
|
|
|
|
'''
|
|
|
|
Prints the used configuration, if loglevel ist debug.
|
|
|
|
param 1: dictionary
|
|
|
|
return: boolean (allways true)
|
|
|
|
'''
|
|
|
|
logging.debug('Using config:')
|
|
|
|
for i in CONFIG.keys():
|
|
|
|
logging.debug('{}: {}'.format(i, CONFIG[i]))
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2019-09-10 15:33:27 +02:00
|
|
|
def print_ciphers(cipherlist):
|
2019-09-13 10:29:38 +02:00
|
|
|
'''
|
|
|
|
This function prints the list of the allowed ciphers.
|
|
|
|
param1: dictionary
|
|
|
|
return: boolean
|
|
|
|
'''
|
2019-09-10 15:33:27 +02:00
|
|
|
print('Available ciphers')
|
|
|
|
for i in cipherlist:
|
|
|
|
print('\n')
|
|
|
|
for j in i.keys():
|
|
|
|
print('{}: {}'.format(j, i[j]))
|
|
|
|
print('\n')
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2019-07-29 18:32:27 +02:00
|
|
|
def display_peercert(cert):
|
2019-09-13 10:29:38 +02:00
|
|
|
'''
|
|
|
|
This function displays the values of a given certificate.
|
|
|
|
param1: dictionary
|
|
|
|
return: boolean
|
|
|
|
'''
|
2019-07-29 18:32:27 +02:00
|
|
|
for i in cert.keys():
|
2019-09-10 17:29:39 +02:00
|
|
|
print('{}:'.format(i))
|
|
|
|
if i in ('subject', 'issuer'):
|
|
|
|
for j in cert[i]:
|
|
|
|
print('\t{}'.format(j))
|
|
|
|
else:
|
|
|
|
print('\t{}'.format(cert[i]))
|
|
|
|
return True
|
2019-07-29 18:32:27 +02:00
|
|
|
|
|
|
|
|
2019-07-27 16:51:56 +02:00
|
|
|
def receive_buffer_is_valid(raw_data):
|
|
|
|
'''
|
|
|
|
checks, if the received buffer from the connection is valid or not.
|
|
|
|
param 1: byte
|
|
|
|
return: boolean
|
|
|
|
'''
|
2019-07-29 18:32:27 +02:00
|
|
|
if raw_data == b'\x00' or raw_data == b'\x01':
|
2019-07-27 16:51:56 +02:00
|
|
|
logging.debug('Argument is valid: {}'.format(raw_data))
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
logging.debug('Argument is not valid: {}'.format(raw_data))
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def change_status(raw_data, api):
|
|
|
|
'''
|
|
|
|
Becomes the received byte and the path to API file. Grabs the content of
|
|
|
|
the API with read_api() and replaces "open" and "lastchange". Write all
|
|
|
|
lines back to API file.
|
|
|
|
param 1: byte
|
|
|
|
param 2: string
|
|
|
|
return: boolean
|
|
|
|
'''
|
|
|
|
|
|
|
|
logging.debug('Change status API')
|
|
|
|
data = read_api(api)
|
2019-09-19 10:21:33 +02:00
|
|
|
if data is not False:
|
2019-07-27 16:51:56 +02:00
|
|
|
status, timestamp = set_values(raw_data)
|
|
|
|
if os.access(api, os.W_OK):
|
2019-07-27 19:06:35 +02:00
|
|
|
logging.debug('API file is writable')
|
2019-07-27 16:51:56 +02:00
|
|
|
with open(api, 'w') as api_file:
|
2019-07-27 19:06:35 +02:00
|
|
|
logging.debug('API file open successfull')
|
2019-09-10 09:47:53 +02:00
|
|
|
data["state"]["open"] = status
|
|
|
|
data["state"]["lastchange"] = timestamp
|
|
|
|
try:
|
|
|
|
json.dump(data, api_file, indent=4)
|
|
|
|
except Exception as e:
|
|
|
|
logging.error('Failed to change API file')
|
|
|
|
logging.error('{}'.format(e))
|
2019-07-27 19:40:16 +02:00
|
|
|
logging.debug('API file changed')
|
2019-07-27 19:23:13 +02:00
|
|
|
else:
|
2019-07-27 19:25:23 +02:00
|
|
|
logging.error('API file is not writable. Wrong permissions?')
|
|
|
|
return False
|
2019-07-27 16:51:56 +02:00
|
|
|
logging.info('Status successfull changed to {}'.format(status))
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def read_api(api):
|
|
|
|
'''
|
|
|
|
Reads the API file in an buffer und returns the buffer. If anything goes
|
|
|
|
wrong, it returns False - otherwise it returns the buffer.
|
|
|
|
param 1: string
|
|
|
|
return: string or boolean
|
|
|
|
'''
|
2019-07-27 18:58:51 +02:00
|
|
|
logging.debug('Open API file: {}'.format(api))
|
2019-07-27 16:51:56 +02:00
|
|
|
if os.access(api, os.R_OK):
|
2019-09-19 10:21:33 +02:00
|
|
|
logging.debug('API is readable')
|
|
|
|
with open(api, 'r') as api_file:
|
|
|
|
logging.debug('API opened successfull')
|
|
|
|
try:
|
|
|
|
api_json_data = json.load(api_file)
|
|
|
|
logging.debug('API file read successfull')
|
|
|
|
except Exception as e:
|
|
|
|
logging.error('Failed to read API file(): {}'.format(e))
|
|
|
|
return False
|
|
|
|
return (api_json_data)
|
2019-07-27 17:31:03 +02:00
|
|
|
logging.error('Failed to read API file')
|
2019-07-27 16:51:56 +02:00
|
|
|
return False
|
2019-09-19 10:21:33 +02:00
|
|
|
|
2019-07-27 16:51:56 +02:00
|
|
|
|
|
|
|
def set_values(raw_data):
|
|
|
|
'''
|
|
|
|
Create a timestamp, changes the value of the given byte into a string
|
|
|
|
and returns both.
|
|
|
|
param 1: byte
|
|
|
|
return: tuple
|
|
|
|
'''
|
|
|
|
timestamp = str(time()).split('.')[0]
|
2019-09-10 09:47:53 +02:00
|
|
|
if raw_data == b'\x01':
|
2019-07-27 16:51:56 +02:00
|
|
|
status = "true"
|
|
|
|
else:
|
|
|
|
status = "false"
|
2019-09-19 10:21:33 +02:00
|
|
|
logging.debug('Set values for timestamp: {} and status: {}'.format(
|
|
|
|
timestamp, status))
|
2019-07-27 16:51:56 +02:00
|
|
|
return (status, timestamp)
|
|
|
|
|
|
|
|
|
2019-09-11 21:24:28 +02:00
|
|
|
def read_loglevel(CONFIG):
|
|
|
|
'''
|
|
|
|
The function translates the value string from config verbosity option to
|
|
|
|
a valid logging option.
|
|
|
|
param1: dictionary
|
|
|
|
return: boolean or integer
|
|
|
|
'''
|
|
|
|
if CONFIG['VERBOSITY'] == 'critical':
|
|
|
|
loglevel = logging.CRITICAL
|
|
|
|
elif CONFIG['VERBOSITY'] == 'error':
|
|
|
|
loglevel = logging.ERROR
|
|
|
|
elif CONFIG['VERBOSITY'] == 'warning':
|
|
|
|
loglevel = logging.WARNING
|
|
|
|
elif CONFIG['VERBOSITY'] == 'info':
|
|
|
|
loglevel = logging.INFO
|
|
|
|
elif CONFIG['VERBOSITY'] == 'debug':
|
|
|
|
loglevel = logging.DEBUG
|
2019-09-19 10:21:33 +02:00
|
|
|
else:
|
|
|
|
loglevel = False
|
2019-09-11 21:24:28 +02:00
|
|
|
return(loglevel)
|
|
|
|
|
|
|
|
|
2019-07-27 16:51:56 +02:00
|
|
|
def main():
|
|
|
|
'''
|
2019-07-29 18:32:27 +02:00
|
|
|
The main function - opens a socket, create a ssl context, load certs and
|
2019-09-19 10:21:33 +02:00
|
|
|
listen for connections. at ssl context we set only one available cipher
|
|
|
|
suite and disable compression.
|
2019-08-02 14:20:08 +02:00
|
|
|
OP_NO_COMPRESSION: prevention against crime attack
|
2019-09-19 10:21:33 +02:00
|
|
|
OP_DONT_ISERT_EMPTY_FRAGMENTS: prevention agains cbc 4 attack
|
|
|
|
(cve-2011-3389)
|
2019-07-27 16:51:56 +02:00
|
|
|
'''
|
2019-09-11 21:24:28 +02:00
|
|
|
|
|
|
|
loglevel = logging.WARNING
|
|
|
|
formatstring = '%(asctime)s: %(levelname)s: %(message)s'
|
|
|
|
logging.basicConfig(format=formatstring, level=loglevel)
|
|
|
|
|
2019-07-27 16:51:56 +02:00
|
|
|
CONFIG = {
|
|
|
|
'HOST': 'localhost',
|
|
|
|
'PORT': 10001,
|
2019-07-29 18:32:27 +02:00
|
|
|
'SERVER_CERT': './server.crt',
|
2019-09-19 10:21:33 +02:00
|
|
|
'SERVER_KEY': './server.key',
|
2019-07-29 18:32:27 +02:00
|
|
|
'CLIENT_CERT': './client.crt',
|
2019-07-27 16:51:56 +02:00
|
|
|
'TIMEOUT': 3.0,
|
2019-07-29 18:32:27 +02:00
|
|
|
'API': './api',
|
|
|
|
'API_TEMPLATE': './api_template',
|
2019-09-11 21:24:28 +02:00
|
|
|
'VERBOSITY': 'warning'
|
2019-07-27 16:51:56 +02:00
|
|
|
}
|
|
|
|
CONFIG_FILE = './statusd.conf'
|
|
|
|
read_config(CONFIG_FILE, CONFIG)
|
2019-09-11 21:24:28 +02:00
|
|
|
loglevel = read_loglevel(CONFIG)
|
2019-09-19 10:21:33 +02:00
|
|
|
if loglevel is not False:
|
2019-09-11 21:24:28 +02:00
|
|
|
logger = logging.getLogger()
|
|
|
|
logger.setLevel(loglevel)
|
2019-09-17 19:07:07 +02:00
|
|
|
else:
|
|
|
|
loglevel = logging.WARNING
|
|
|
|
logger = logging.getLogger()
|
|
|
|
logger.setLevel(loglevel)
|
2019-09-19 10:21:33 +02:00
|
|
|
logging.warning('Invalid value for loglevel. Set default value')
|
2019-09-11 21:24:28 +02:00
|
|
|
|
2019-07-27 16:51:56 +02:00
|
|
|
print_config(CONFIG)
|
|
|
|
|
2019-09-17 19:07:07 +02:00
|
|
|
# todo: zertifikate sollten nur lesbar sein!
|
|
|
|
|
2019-09-19 10:21:33 +02:00
|
|
|
if certs_readable(CONFIG) is False:
|
2019-07-30 22:06:07 +02:00
|
|
|
logging.error('Cert check failed\nExit')
|
|
|
|
exit()
|
|
|
|
|
2019-07-29 18:32:27 +02:00
|
|
|
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
|
|
|
|
context.verify_mode = ssl.CERT_REQUIRED
|
2019-09-19 10:21:33 +02:00
|
|
|
context.load_cert_chain(certfile=CONFIG['SERVER_CERT'],
|
|
|
|
keyfile=CONFIG['SERVER_KEY'])
|
|
|
|
context.load_verify_locations(cafile=CONFIG['CLIENT_CERT'])
|
2019-09-10 15:33:27 +02:00
|
|
|
context.set_ciphers('EECDH+AESGCM') # only ciphers for tls 1.2 and 1.3
|
|
|
|
context.options = ssl.OP_CIPHER_SERVER_PREFERENCE
|
2019-09-17 19:07:07 +02:00
|
|
|
# ssl + kompression = schlecht
|
2019-09-10 15:33:27 +02:00
|
|
|
context.options |= getattr(ssl._ssl, 'OP_NO_COMPRESSION', 0)
|
2019-07-29 18:32:27 +02:00
|
|
|
logging.debug('SSL context created')
|
2019-09-10 15:33:27 +02:00
|
|
|
# print_ciphers(context.get_ciphers())
|
2019-07-29 18:32:27 +02:00
|
|
|
|
2019-07-27 16:51:56 +02:00
|
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as mySocket:
|
|
|
|
logging.debug('Socket created')
|
|
|
|
try:
|
|
|
|
mySocket.bind((CONFIG['HOST'], int(CONFIG['PORT'])))
|
|
|
|
mySocket.listen(5)
|
2019-09-19 10:21:33 +02:00
|
|
|
logging.info('Listen on {} at Port {}'.format(CONFIG['HOST'],
|
|
|
|
CONFIG['PORT']))
|
2019-07-27 16:51:56 +02:00
|
|
|
except Exception as e:
|
|
|
|
logging.error('unable to bind and listen')
|
|
|
|
logging.error('{}'.format(e))
|
|
|
|
exit()
|
|
|
|
while True:
|
|
|
|
try:
|
2019-07-29 18:32:27 +02:00
|
|
|
fromSocket, fromAddr = mySocket.accept()
|
2019-09-19 10:21:33 +02:00
|
|
|
logging.info('Client connected: {}:{}'.format(fromAddr[0],
|
|
|
|
fromAddr[1]))
|
2019-07-27 16:51:56 +02:00
|
|
|
try:
|
2019-07-29 18:32:27 +02:00
|
|
|
fromSocket.settimeout(float(CONFIG['TIMEOUT']))
|
2019-09-19 10:21:33 +02:00
|
|
|
logging.debug('Connection timeout set to {}'.format(
|
|
|
|
CONFIG['TIMEOUT']))
|
|
|
|
except Exception:
|
|
|
|
logging.error('Canot set timeout to {}'.format(
|
|
|
|
CONFIG['TIMEOUT']))
|
2019-07-27 16:51:56 +02:00
|
|
|
logging.error('Use default value: 3.0')
|
2019-07-29 18:32:27 +02:00
|
|
|
fromSocket.settimeout(3.0)
|
|
|
|
try:
|
2019-09-19 10:21:33 +02:00
|
|
|
conn = context.wrap_socket(fromSocket, server_side=True)
|
2019-09-14 14:01:52 +02:00
|
|
|
conn.settimeout(3.0)
|
2019-07-29 18:32:27 +02:00
|
|
|
# display_peercert(conn.getpeercert())
|
2019-09-14 14:01:52 +02:00
|
|
|
logging.debug('Connection established')
|
2019-09-19 10:21:33 +02:00
|
|
|
logging.debug('Peer certificate commonName: {}'.format
|
2019-09-14 14:01:52 +02:00
|
|
|
(conn.getpeercert()['subject'][5][0][1]))
|
2019-09-19 10:21:33 +02:00
|
|
|
logging.debug('Peer certificate serialNumber: {}'.format
|
2019-09-14 14:01:52 +02:00
|
|
|
(conn.getpeercert()['serialNumber']))
|
|
|
|
except socket.timeout:
|
|
|
|
logging.error('Socket timeout')
|
2019-07-29 18:32:27 +02:00
|
|
|
except Exception as e:
|
2019-09-14 14:01:52 +02:00
|
|
|
logging.error('Connection failed: {}'.format(e))
|
2019-07-27 16:51:56 +02:00
|
|
|
raw_data = conn.recv(1)
|
2019-09-19 10:21:33 +02:00
|
|
|
if receive_buffer_is_valid(raw_data) is True:
|
|
|
|
if change_status(raw_data, CONFIG['API']) is True:
|
2019-07-27 16:51:56 +02:00
|
|
|
logging.debug('Send {} back'.format(raw_data))
|
|
|
|
conn.send(raw_data)
|
|
|
|
# change_status returns false:
|
|
|
|
else:
|
|
|
|
logging.info('Failed to change status')
|
2019-07-29 18:32:27 +02:00
|
|
|
if conn:
|
|
|
|
conn.send(b'\x03')
|
2019-09-17 19:07:07 +02:00
|
|
|
# receive_handle returns false:
|
2019-07-27 16:51:56 +02:00
|
|
|
else:
|
2019-09-19 10:21:33 +02:00
|
|
|
logging.info('Invalid argument recived: {}'.format(
|
|
|
|
raw_data))
|
2019-07-27 16:51:56 +02:00
|
|
|
logging.debug('Send {} back'.format(b'\x03'))
|
2019-07-29 18:32:27 +02:00
|
|
|
if conn:
|
|
|
|
conn.send(b'\x03')
|
2019-09-19 10:21:33 +02:00
|
|
|
sleep(0.1) # protection against dos
|
2019-07-27 16:51:56 +02:00
|
|
|
except KeyboardInterrupt:
|
|
|
|
logging.info('Exit')
|
|
|
|
exit()
|
|
|
|
except Exception as e:
|
|
|
|
logging.error('{}'.format(e))
|
2019-07-29 18:32:27 +02:00
|
|
|
continue
|
2019-08-02 14:20:08 +02:00
|
|
|
return 0
|
2019-07-27 16:51:56 +02:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|