forked from Krautspace/doorstatus
Umwandlung in eine Klasse
This commit is contained in:
parent
cc77f32afa
commit
a2a533ac65
1 changed files with 202 additions and 193 deletions
395
setstatus.py
395
setstatus.py
|
@ -1,4 +1,4 @@
|
||||||
#!/usr/bin/python3
|
#!/usr/bin/env python3
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
# file: setstatus.py
|
# file: setstatus.py
|
||||||
|
@ -21,206 +21,215 @@ from time import sleep
|
||||||
from sys import exit, argv
|
from sys import exit, argv
|
||||||
|
|
||||||
|
|
||||||
|
# basic configuration
|
||||||
def check_certs(certs):
|
loglevel = logging.WARNING
|
||||||
'''
|
formatstring = '%(asctime)s: %(levelname)s: %(message)s'
|
||||||
Check if certs readable.
|
logging.basicConfig(format=formatstring, level=loglevel)
|
||||||
'''
|
|
||||||
logging.debug('Check certificates')
|
|
||||||
for certfile in certs:
|
|
||||||
if os.access(certfile, os.R_OK) is False:
|
|
||||||
logging.error('Failed to read certificate: {}'.format(certfile))
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
def check_arguments(argv):
|
|
||||||
'''
|
|
||||||
Checks length and validity of command line argument vectors. If there is
|
|
||||||
no argument or argument is not valid, it returns None. Otherwise it
|
|
||||||
converts the string value into a byte value.
|
|
||||||
param 1: array of strings
|
|
||||||
return: None or byte value
|
|
||||||
'''
|
|
||||||
if len(argv) == 1:
|
|
||||||
byte_value = None
|
|
||||||
else:
|
|
||||||
if argv[1].strip() == '0' or argv[1].strip() == '1':
|
|
||||||
i = int(argv[1].strip())
|
|
||||||
logging.debug('Set value to {}'.format(i))
|
|
||||||
byte_value = bytes([i])
|
|
||||||
else:
|
|
||||||
byte_value = None
|
|
||||||
return byte_value
|
|
||||||
|
|
||||||
def log_config(config):
|
|
||||||
'''
|
|
||||||
Logs the config if loglevel is debug.
|
|
||||||
'''
|
|
||||||
logging.debug('Using config:')
|
|
||||||
for section in config.sections():
|
|
||||||
logging.debug('Section {}'.format(section))
|
|
||||||
for i in config[section]:
|
|
||||||
logging.debug(' {}: {}'.format(i, config[section][i]))
|
|
||||||
|
|
||||||
def create_ssl_context(config):
|
|
||||||
'''
|
|
||||||
'''
|
|
||||||
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
|
|
||||||
cafile=config['server']['cert'])
|
|
||||||
if not context:
|
|
||||||
logging.error('Failed to create SSL Context')
|
|
||||||
return False
|
|
||||||
context.set_ciphers('EECDH+AESGCM') # only ciphers for tls 1.2 and 1.3
|
|
||||||
context.options |= getattr(ssl._ssl, 'OP_NO_COMPRESSION', 0)
|
|
||||||
try:
|
|
||||||
context.load_cert_chain(certfile=config['client']['cert'],
|
|
||||||
keyfile=config['client']['key'])
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('Failed to load cert chain')
|
|
||||||
return False;
|
|
||||||
logging.debug('SSL context created')
|
|
||||||
return context
|
|
||||||
|
|
||||||
def create_ssl_socket(config, context):
|
|
||||||
'''
|
|
||||||
'''
|
|
||||||
bare_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
|
|
||||||
if not bare_socket:
|
|
||||||
logging.error('Socket creation failed')
|
|
||||||
return False
|
|
||||||
logging.debug('Socket created')
|
|
||||||
try:
|
|
||||||
secure_socket = context.wrap_socket(bare_socket, server_side=False,
|
|
||||||
server_hostname=config['server']['fqdn'])
|
|
||||||
logging.debug('Socket wrapped with SSL')
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('Context wrapper failed: {}'.format(e))
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
secure_socket.settimeout(float(config['general']['timeout']))
|
|
||||||
except Exception as e:
|
|
||||||
logging.debug('Failed to set timeout: {}'.format(e))
|
|
||||||
return secure_socket
|
|
||||||
|
|
||||||
def create_ssl_connection(config, context):
|
|
||||||
'''
|
|
||||||
'''
|
|
||||||
counter = 0
|
|
||||||
conn = False
|
|
||||||
|
|
||||||
while conn is False and counter < 5:
|
|
||||||
ssl_socket = create_ssl_socket(config, context)
|
|
||||||
if ssl_socket is False:
|
|
||||||
exit(4)
|
|
||||||
try:
|
|
||||||
logging.debug('Connect {}: {}'.format(config['server']['host'],
|
|
||||||
int(config['server']['port'])))
|
|
||||||
conn = ssl_socket.connect((config['server']['host'],
|
|
||||||
int(config['server']['port'])))
|
|
||||||
except socket.timeout:
|
|
||||||
logging.error('Connection timeout')
|
|
||||||
ssl_socket.close()
|
|
||||||
sleep(5)
|
|
||||||
counter += 1
|
|
||||||
except Exception as e:
|
|
||||||
logging.error('Connection failed: {}'.format(e))
|
|
||||||
exit(5)
|
|
||||||
logging.debug('Conection established')
|
|
||||||
logging.debug('Peer certificate commonName: {}'.format(
|
|
||||||
ssl_socket.getpeercert()['subject'][5][0][1]))
|
|
||||||
logging.debug('Peer certificate serialNumber: {}'.format(
|
|
||||||
ssl_socket.getpeercert()['serialNumber']))
|
|
||||||
return ssl_socket
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
class SetStatus:
|
||||||
|
|
||||||
STATUS = None
|
def __init__(self):
|
||||||
RESPONSE = None
|
"""
|
||||||
|
"""
|
||||||
# basic configuration
|
self.status = None
|
||||||
loglevel = logging.WARNING
|
self.config = None
|
||||||
formatstring = '%(asctime)s: %(levelname)s: %(message)s'
|
self.log = None
|
||||||
logging.basicConfig(format=formatstring, level=loglevel)
|
self.context = None
|
||||||
|
self.connection = None
|
||||||
default_config = {
|
self.configfile = './setstatus.conf'
|
||||||
'general': {
|
self.config = configparser.ConfigParser()
|
||||||
'timeout': 5.0,
|
self.default_config = {
|
||||||
'loglevel': 'warning'
|
'general': {
|
||||||
},
|
'timeout': 5.0,
|
||||||
'server': {
|
'loglevel': 'warning'
|
||||||
'host': 'localhost',
|
},
|
||||||
'port': 10001,
|
'server': {
|
||||||
'cert': './certs/server-pub.pem',
|
'host': 'localhost',
|
||||||
'fqdn': 'kraut.space'
|
'port': 10001,
|
||||||
},
|
'cert': './certs/server-pub.pem',
|
||||||
'client': {
|
'fqdn': 'kraut.space'
|
||||||
'cert': './certs/client-pub.pem',
|
},
|
||||||
'key': './certs/client-key.pem'
|
'client': {
|
||||||
|
'cert': './certs/client-pub.pem',
|
||||||
|
'key': './certs/client-key.pem'
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
# read config file
|
|
||||||
configfile = './setstatus.conf'
|
|
||||||
config = configparser.ConfigParser()
|
|
||||||
config.read_dict(default_config)
|
|
||||||
if not config.read(configfile):
|
|
||||||
logging.warning('Configuration file {} not found or not readable.'.format(
|
|
||||||
configfile))
|
|
||||||
logging.warning('Using default values.')
|
|
||||||
# set loglevel
|
|
||||||
logger = logging.getLogger()
|
|
||||||
if not config['general']['loglevel'].lower() in ('critical', 'error',
|
|
||||||
'warning', 'info',
|
|
||||||
'debug'):
|
|
||||||
logging.warning('Invalid loglevel %s given. Using default level %s.',
|
|
||||||
config['general']['loglevel'],
|
|
||||||
default_config['general']['loglevel'])
|
|
||||||
config.set('general', 'loglevel', default_config['general']['loglevel'])
|
|
||||||
logger.setLevel(config['general']['loglevel'].upper())
|
|
||||||
# log config if level is debug
|
|
||||||
if config['general']['loglevel'].lower() == 'debug':
|
|
||||||
log_config(config)
|
|
||||||
|
|
||||||
# check certificates are readable
|
def check_status(self):
|
||||||
certs = (config['server']['cert'],
|
"""
|
||||||
config['client']['cert'],
|
return: boolean
|
||||||
config['client']['key'])
|
"""
|
||||||
if check_certs(certs) is False:
|
if self.status in (0, 1):
|
||||||
exit(1)
|
self.log.debug('Set value to {}'.format(self.status))
|
||||||
|
self.status = bytes([self.status])
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
# check cli arguments
|
def set_config(self):
|
||||||
STATUS = check_arguments(argv)
|
"""
|
||||||
if STATUS is None:
|
"""
|
||||||
logging.error('No valid status given')
|
self.log = logging.getLogger()
|
||||||
exit(2)
|
# read config file
|
||||||
|
self.config.read_dict(self.default_config)
|
||||||
|
if not self.config.read(self.configfile):
|
||||||
|
self.log.warning('Configuration file {} not found or not '
|
||||||
|
' readable.'.format(self.configfile))
|
||||||
|
self.log.warning('Using default values.')
|
||||||
|
# set loglevel
|
||||||
|
config_loglevel = self.config['general']['loglevel']
|
||||||
|
default_loglevel = self.default_config['general']['loglevel']
|
||||||
|
if not config_loglevel.lower() in ('critical', 'error','warning',
|
||||||
|
'info', 'debug'):
|
||||||
|
self.log.warning('Invalid loglevel {} given. Using default '
|
||||||
|
'level {}.'.format(config_loglevel,
|
||||||
|
default_loglevel))
|
||||||
|
self.config.set('general', 'loglevel', default_loglevel)
|
||||||
|
self.log.setLevel(config_loglevel.upper())
|
||||||
|
|
||||||
# create ssl context
|
def check_certs(self, certs):
|
||||||
context = create_ssl_context(config)
|
"""
|
||||||
if context is False:
|
Check if certs readable.
|
||||||
exit(3)
|
"""
|
||||||
|
self.log.debug('Check certificates')
|
||||||
|
for certfile in certs:
|
||||||
|
if os.access(certfile, os.R_OK) is False:
|
||||||
|
self.log.error('Failed to read certificate: {}'.format( \
|
||||||
|
certfile))
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
# get connection
|
def log_config(self):
|
||||||
conn = create_ssl_connection(config, context)
|
"""
|
||||||
|
Logs the config if loglevel is debug.
|
||||||
|
"""
|
||||||
|
logging.debug('Using config:')
|
||||||
|
for section in self.config.sections():
|
||||||
|
logging.debug('Section {}'.format(section))
|
||||||
|
for i in self.config[section]:
|
||||||
|
logging.debug(' {}: {}'.format(i, self.config[section][i]))
|
||||||
|
|
||||||
# send status
|
def create_ssl_context(self):
|
||||||
try:
|
"""
|
||||||
logging.debug('Send new status: {}'.format(STATUS))
|
"""
|
||||||
conn.send(STATUS)
|
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
|
||||||
except Exception as e:
|
cafile=self.config['server']['cert'])
|
||||||
logging.error('Error: {}'.format(e))
|
if not context:
|
||||||
exit(6)
|
self.log.error('Failed to create SSL Context')
|
||||||
try:
|
return False
|
||||||
RESPONSE = conn.recv(1)
|
context.set_ciphers('EECDH+AESGCM') # only ciphers for tls 1.2 and 1.3
|
||||||
logging.debug('Server returns: {}'.format(RESPONSE))
|
context.options |= getattr(ssl._ssl, 'OP_NO_COMPRESSION', 0)
|
||||||
if RESPONSE == STATUS:
|
try:
|
||||||
logging.info('Status sucessfull updated')
|
context.load_cert_chain(certfile=self.config['client']['cert'],
|
||||||
else:
|
keyfile=self.config['client']['key'])
|
||||||
logging.error('Failed to update status')
|
except Exception as e:
|
||||||
logging.debug('Disconnect from server')
|
self.log.error('Failed to load cert chain')
|
||||||
except Exception as e:
|
return False;
|
||||||
logging.error('Error: {}'.format(e))
|
self.log.debug('SSL context created')
|
||||||
exit(7)
|
return context
|
||||||
|
|
||||||
|
def create_ssl_socket(self, config, context):
|
||||||
|
"""
|
||||||
|
"""
|
||||||
|
bare_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
|
||||||
|
if not bare_socket:
|
||||||
|
logging.error('Socket creation failed')
|
||||||
|
return False
|
||||||
|
logging.debug('Socket created')
|
||||||
|
try:
|
||||||
|
secure_socket = context.wrap_socket(bare_socket, server_side=False,
|
||||||
|
server_hostname=config['server']['fqdn'])
|
||||||
|
logging.debug('Socket wrapped with SSL')
|
||||||
|
except Exception as e:
|
||||||
|
logging.error('Context wrapper failed: {}'.format(e))
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
secure_socket.settimeout(float(config['general']['timeout']))
|
||||||
|
except Exception as e:
|
||||||
|
logging.debug('Failed to set timeout: {}'.format(e))
|
||||||
|
return secure_socket
|
||||||
|
|
||||||
|
def create_ssl_connection(self):
|
||||||
|
"""
|
||||||
|
"""
|
||||||
|
counter = 0
|
||||||
|
conn = False
|
||||||
|
|
||||||
|
while conn is False and counter < 5:
|
||||||
|
ssl_socket = self.create_ssl_socket(self.config, self.context)
|
||||||
|
if ssl_socket is False:
|
||||||
|
exit(4)
|
||||||
|
try:
|
||||||
|
self.log.debug('Connect {}: {}'.format(self.config['server']['host'],
|
||||||
|
int(self.config['server']['port'])))
|
||||||
|
conn = ssl_socket.connect((self.config['server']['host'],
|
||||||
|
int(self.config['server']['port'])))
|
||||||
|
except socket.timeout:
|
||||||
|
self.log.error('Connection timeout')
|
||||||
|
ssl_socket.close()
|
||||||
|
sleep(5)
|
||||||
|
counter += 1
|
||||||
|
except Exception as e:
|
||||||
|
self.log.error('Connection failed: {}'.format(e))
|
||||||
|
exit(5)
|
||||||
|
self.log.debug('Conection established')
|
||||||
|
self.log.debug('Peer certificate commonName: {}'.format(
|
||||||
|
ssl_socket.getpeercert()['subject'][5][0][1]))
|
||||||
|
self.log.debug('Peer certificate serialNumber: {}'.format(
|
||||||
|
ssl_socket.getpeercert()['serialNumber']))
|
||||||
|
return ssl_socket
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
def run(self, status):
|
||||||
main()
|
"""
|
||||||
|
starts the engine.
|
||||||
|
param 1: integer
|
||||||
|
"""
|
||||||
|
self.status = status
|
||||||
|
|
||||||
|
# read config
|
||||||
|
self.set_config()
|
||||||
|
|
||||||
|
# check given status
|
||||||
|
if self.check_status() is False:
|
||||||
|
self.log.error('No valid status given')
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
# log config if level is debug
|
||||||
|
if self.config['general']['loglevel'].lower() == 'debug':
|
||||||
|
self.log_config()
|
||||||
|
|
||||||
|
# check certificates are readable
|
||||||
|
certs = (self.config['server']['cert'],
|
||||||
|
self.config['client']['cert'],
|
||||||
|
self.config['client']['key'])
|
||||||
|
if self.check_certs(certs) is False:
|
||||||
|
exit(2)
|
||||||
|
|
||||||
|
# create ssl context
|
||||||
|
self.context = self.create_ssl_context()
|
||||||
|
if self.context is False:
|
||||||
|
exit(3)
|
||||||
|
|
||||||
|
# get connection
|
||||||
|
self.connection = self.create_ssl_connection()
|
||||||
|
|
||||||
|
# send status
|
||||||
|
try:
|
||||||
|
self.log.debug('Send new status: {}'.format(self.status))
|
||||||
|
self.connection.send(self.status)
|
||||||
|
except Exception as e:
|
||||||
|
self.log.error('Error: {}'.format(e))
|
||||||
|
exit(6)
|
||||||
|
try:
|
||||||
|
response = self.connection.recv(1)
|
||||||
|
self.log.debug('Server returns: {}'.format(response))
|
||||||
|
if response == self.status:
|
||||||
|
self.log.info('Status sucessfull updated')
|
||||||
|
else:
|
||||||
|
self.log.error('Failed to update status')
|
||||||
|
self.log.debug('Disconnect from server')
|
||||||
|
except Exception as e:
|
||||||
|
self.log.error('Error: {}'.format(e))
|
||||||
|
exit(7)
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue