statusd.py: delete unused parts, make it pep8 conform

This commit is contained in:
berhsi 2019-09-19 10:21:33 +02:00
parent c60bb326cc
commit 1fbd95facf

View file

@ -12,7 +12,7 @@ import ssl
import os
import logging
import json
from time import time, ctime, sleep
from time import time, sleep
from sys import exit
@ -35,7 +35,8 @@ def read_config(CONFIGFILE, CONFIG):
if key in CONFIG.keys():
value = strip_argument(value)
CONFIG[key] = value
else: pass
else:
pass
else:
logging.error('Failed to read {}'.format(CONFIGFILE))
logging.error('Using default values')
@ -45,12 +46,14 @@ def read_config(CONFIGFILE, CONFIG):
def certs_readable(config):
'''
checks at start, if the needed certificates defined (no nullstring) and readable.
checks at start, if the needed certificates defined (no nullstring) and
readable.
param 1: dictionary
return: boolean
'''
for i in (config['SERVER_KEY'], config['SERVER_CERT'], config['CLIENT_CERT']):
if i == '' or os.access(i, os.R_OK) == False:
for i in (config['SERVER_KEY'], config['SERVER_CERT'],
config['CLIENT_CERT']):
if i == '' or os.access(i, os.R_OK) is False:
logging.error('Cant read {}'.format(i))
return False
return True
@ -135,11 +138,10 @@ def change_status(raw_data, api):
param 2: string
return: boolean
'''
edit = False
logging.debug('Change status API')
data = read_api(api)
if data != False:
if data is not False:
status, timestamp = set_values(raw_data)
if os.access(api, os.W_OK):
logging.debug('API file is writable')
@ -170,16 +172,16 @@ def read_api(api):
'''
logging.debug('Open API file: {}'.format(api))
if os.access(api, os.R_OK):
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)
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)
logging.error('Failed to read API file')
return False
@ -196,7 +198,8 @@ def set_values(raw_data):
status = "true"
else:
status = "false"
logging.debug('Set values for timestamp: {} and status: {}'.format(timestamp, status))
logging.debug('Set values for timestamp: {} and status: {}'.format(
timestamp, status))
return (status, timestamp)
@ -217,18 +220,19 @@ def read_loglevel(CONFIG):
loglevel = logging.INFO
elif CONFIG['VERBOSITY'] == 'debug':
loglevel = logging.DEBUG
else: loglevel = False
else:
loglevel = False
return(loglevel)
def main():
'''
The main function - opens a socket, create a ssl context, load certs and
listen for connections. at ssl context we set some security options like
OP_NO_SSLv2 (SSLv3): they are insecure
PROTOCOL_TLS: only use tls
listen for connections. at ssl context we set only one available cipher
suite and disable compression.
OP_NO_COMPRESSION: prevention against crime attack
OP_DONT_ISERT_EMPTY_FRAGMENTS: prevention agains cbc 4 attack (cve-2011-3389)
OP_DONT_ISERT_EMPTY_FRAGMENTS: prevention agains cbc 4 attack
(cve-2011-3389)
'''
loglevel = logging.WARNING
@ -239,7 +243,7 @@ def main():
'HOST': 'localhost',
'PORT': 10001,
'SERVER_CERT': './server.crt',
'SERVER_KEY' : './server.key',
'SERVER_KEY': './server.key',
'CLIENT_CERT': './client.crt',
'TIMEOUT': 3.0,
'API': './api',
@ -249,28 +253,28 @@ def main():
CONFIG_FILE = './statusd.conf'
read_config(CONFIG_FILE, CONFIG)
loglevel = read_loglevel(CONFIG)
if loglevel != False:
if loglevel is not False:
logger = logging.getLogger()
logger.setLevel(loglevel)
else:
loglevel = logging.WARNING
logger = logging.getLogger()
logger.setLevel(loglevel)
loggin.warning('Invalid value for loglevel. Set default value')
logging.warning('Invalid value for loglevel. Set default value')
print_config(CONFIG)
# todo: zertifikate sollten nur lesbar sein!
if certs_readable(CONFIG) == False:
if certs_readable(CONFIG) is False:
logging.error('Cert check failed\nExit')
exit()
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.verify_mode = ssl.CERT_REQUIRED
context.load_cert_chain(certfile = CONFIG['SERVER_CERT'],
keyfile = CONFIG['SERVER_KEY'])
context.load_verify_locations(cafile = CONFIG['CLIENT_CERT'])
context.load_cert_chain(certfile=CONFIG['SERVER_CERT'],
keyfile=CONFIG['SERVER_KEY'])
context.load_verify_locations(cafile=CONFIG['CLIENT_CERT'])
context.set_ciphers('EECDH+AESGCM') # only ciphers for tls 1.2 and 1.3
context.options = ssl.OP_CIPHER_SERVER_PREFERENCE
# ssl + kompression = schlecht
@ -283,7 +287,8 @@ def main():
try:
mySocket.bind((CONFIG['HOST'], int(CONFIG['PORT'])))
mySocket.listen(5)
logging.info('Listen on {} at Port {}'.format(CONFIG['HOST'], CONFIG['PORT']))
logging.info('Listen on {} at Port {}'.format(CONFIG['HOST'],
CONFIG['PORT']))
except Exception as e:
logging.error('unable to bind and listen')
logging.error('{}'.format(e))
@ -291,30 +296,33 @@ def main():
while True:
try:
fromSocket, fromAddr = mySocket.accept()
logging.info('Client connected: {}:{}'.format(fromAddr[0], fromAddr[1]))
logging.info('Client connected: {}:{}'.format(fromAddr[0],
fromAddr[1]))
try:
fromSocket.settimeout(float(CONFIG['TIMEOUT']))
logging.debug('Connection timeout set to {}'.format(CONFIG['TIMEOUT']))
except Exception as e:
logging.error('Canot set timeout to {}'.format(CONFIG['TIMEOUT']))
logging.debug('Connection timeout set to {}'.format(
CONFIG['TIMEOUT']))
except Exception:
logging.error('Canot set timeout to {}'.format(
CONFIG['TIMEOUT']))
logging.error('Use default value: 3.0')
fromSocket.settimeout(3.0)
try:
conn = context.wrap_socket(fromSocket, server_side = True)
conn = context.wrap_socket(fromSocket, server_side=True)
conn.settimeout(3.0)
# display_peercert(conn.getpeercert())
logging.debug('Connection established')
logging.debug('Peer certificate commonName: {}'.format \
logging.debug('Peer certificate commonName: {}'.format
(conn.getpeercert()['subject'][5][0][1]))
logging.debug('Peer certificate serialNumber: {}'.format \
logging.debug('Peer certificate serialNumber: {}'.format
(conn.getpeercert()['serialNumber']))
except socket.timeout:
logging.error('Socket timeout')
except Exception as e:
logging.error('Connection failed: {}'.format(e))
raw_data = conn.recv(1)
if receive_buffer_is_valid(raw_data) == True:
if change_status(raw_data, CONFIG['API']) == True:
if receive_buffer_is_valid(raw_data) is True:
if change_status(raw_data, CONFIG['API']) is True:
logging.debug('Send {} back'.format(raw_data))
conn.send(raw_data)
# change_status returns false:
@ -324,11 +332,12 @@ def main():
conn.send(b'\x03')
# receive_handle returns false:
else:
logging.info('Invalid argument recived: {}'.format(raw_data))
logging.info('Invalid argument recived: {}'.format(
raw_data))
logging.debug('Send {} back'.format(b'\x03'))
if conn:
conn.send(b'\x03')
sleep(0.1) # protection against dos
sleep(0.1) # protection against dos
except KeyboardInterrupt:
logging.info('Exit')
exit()