2019-07-26 21:33:40 +02:00
|
|
|
#!/usr/bin/python3
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2019-09-14 14:01:52 +02:00
|
|
|
# file: setstatus.py
|
2019-07-26 21:33:40 +02:00
|
|
|
# date: 26.07.2019
|
|
|
|
# email: berhsi@web.de
|
|
|
|
|
2020-07-09 20:12:49 +02:00
|
|
|
# Setstatus.py is part of doorstatus - a programm to deal with the
|
|
|
|
# krautspaces doorstatus.
|
|
|
|
|
2019-09-19 09:44:52 +02:00
|
|
|
# client, who connects to the statusserver at port 10001 to update the
|
|
|
|
# krautspace door status. If no status is given as argument, he reads from
|
|
|
|
# stdin until input is 0 or 1.
|
2019-07-26 21:33:40 +02:00
|
|
|
|
2020-09-04 19:58:23 +02:00
|
|
|
import os
|
2019-07-29 18:27:53 +02:00
|
|
|
import ssl
|
2020-07-09 20:12:49 +02:00
|
|
|
import socket
|
|
|
|
import logging
|
|
|
|
import configparser
|
2020-09-07 15:19:07 +02:00
|
|
|
from time import sleep
|
2019-09-19 09:44:52 +02:00
|
|
|
from sys import exit, argv
|
2019-07-26 21:33:40 +02:00
|
|
|
|
|
|
|
|
2020-09-04 19:58:23 +02:00
|
|
|
|
|
|
|
def check_certs(certs):
|
|
|
|
'''
|
|
|
|
Check if certs readable.
|
|
|
|
'''
|
|
|
|
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
|
|
|
|
|
2019-07-26 21:33:40 +02:00
|
|
|
def check_arguments(argv):
|
2019-07-27 00:44:53 +02:00
|
|
|
'''
|
|
|
|
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
|
|
|
|
'''
|
2019-07-26 21:33:40 +02:00
|
|
|
if len(argv) == 1:
|
2019-07-27 00:44:53 +02:00
|
|
|
byte_value = None
|
2019-07-26 21:33:40 +02:00
|
|
|
else:
|
|
|
|
if argv[1].strip() == '0' or argv[1].strip() == '1':
|
2019-07-27 00:44:53 +02:00
|
|
|
i = int(argv[1].strip())
|
2020-07-09 20:12:49 +02:00
|
|
|
logging.debug('Set value to {}'.format(i))
|
2019-07-27 00:44:53 +02:00
|
|
|
byte_value = bytes([i])
|
2019-07-26 21:33:40 +02:00
|
|
|
else:
|
2019-07-27 00:44:53 +02:00
|
|
|
byte_value = None
|
|
|
|
return byte_value
|
2019-07-26 21:33:40 +02:00
|
|
|
|
2020-09-04 19:58:23 +02:00
|
|
|
def log_config(config):
|
2020-07-09 20:12:49 +02:00
|
|
|
'''
|
2020-09-07 15:19:07 +02:00
|
|
|
Logs the config if loglevel is debug.
|
2020-07-09 20:12:49 +02:00
|
|
|
'''
|
|
|
|
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]))
|
|
|
|
|
2020-09-07 15:19:07 +02:00
|
|
|
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
|
|
|
|
|
2019-07-26 21:33:40 +02:00
|
|
|
|
2019-09-19 09:44:52 +02:00
|
|
|
def main():
|
2019-07-26 21:33:40 +02:00
|
|
|
|
|
|
|
STATUS = None
|
2019-07-27 00:44:53 +02:00
|
|
|
RESPONSE = None
|
2019-07-26 21:33:40 +02:00
|
|
|
|
2020-09-04 19:58:23 +02:00
|
|
|
# basic configuration
|
|
|
|
loglevel = logging.WARNING
|
2020-07-09 20:12:49 +02:00
|
|
|
formatstring = '%(asctime)s: %(levelname)s: %(message)s'
|
|
|
|
logging.basicConfig(format=formatstring, level=loglevel)
|
|
|
|
|
|
|
|
default_config = {
|
|
|
|
'general': {
|
|
|
|
'timeout': 5.0,
|
|
|
|
'loglevel': 'warning'
|
|
|
|
},
|
|
|
|
'server': {
|
|
|
|
'host': 'localhost',
|
|
|
|
'port': 10001,
|
2020-09-04 19:58:23 +02:00
|
|
|
'cert': './certs/server-pub.pem',
|
|
|
|
'fqdn': 'kraut.space'
|
2020-07-09 20:12:49 +02:00
|
|
|
},
|
|
|
|
'client': {
|
2020-09-04 19:58:23 +02:00
|
|
|
'cert': './certs/client-pub.pem',
|
|
|
|
'key': './certs/client-key.pem'
|
2020-07-09 20:12:49 +02:00
|
|
|
}
|
|
|
|
}
|
2020-09-04 19:58:23 +02:00
|
|
|
# read config file
|
2020-07-09 20:12:49 +02:00
|
|
|
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.')
|
2020-09-04 19:58:23 +02:00
|
|
|
# set loglevel
|
2020-07-09 20:12:49 +02:00
|
|
|
logger = logging.getLogger()
|
2020-09-04 19:58:23 +02:00
|
|
|
if not config['general']['loglevel'].lower() in ('critical', 'error',
|
|
|
|
'warning', 'info',
|
|
|
|
'debug'):
|
2020-07-09 20:12:49 +02:00
|
|
|
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())
|
2020-09-04 19:58:23 +02:00
|
|
|
# log config if level is debug
|
|
|
|
if config['general']['loglevel'].lower() == 'debug':
|
|
|
|
log_config(config)
|
|
|
|
|
|
|
|
# check certificates are readable
|
|
|
|
certs = (config['server']['cert'],
|
|
|
|
config['client']['cert'],
|
|
|
|
config['client']['key'])
|
|
|
|
if check_certs(certs) is False:
|
2020-09-07 15:19:07 +02:00
|
|
|
exit(1)
|
2020-09-04 19:58:23 +02:00
|
|
|
|
|
|
|
# check cli arguments
|
2019-09-19 09:44:52 +02:00
|
|
|
STATUS = check_arguments(argv)
|
2020-09-04 19:58:23 +02:00
|
|
|
if STATUS is None:
|
|
|
|
logging.error('No valid status given')
|
2020-09-07 15:19:07 +02:00
|
|
|
exit(2)
|
2019-07-26 21:33:40 +02:00
|
|
|
|
2020-09-04 19:58:23 +02:00
|
|
|
# create ssl context
|
2020-09-07 15:19:07 +02:00
|
|
|
context = create_ssl_context(config)
|
|
|
|
if context is False:
|
|
|
|
exit(3)
|
|
|
|
|
|
|
|
# get connection
|
|
|
|
conn = create_ssl_connection(config, context)
|
|
|
|
|
|
|
|
# send status
|
|
|
|
try:
|
|
|
|
logging.debug('Send new status: {}'.format(STATUS))
|
|
|
|
conn.send(STATUS)
|
|
|
|
except Exception as e:
|
|
|
|
logging.error('Error: {}'.format(e))
|
|
|
|
exit(6)
|
|
|
|
try:
|
|
|
|
RESPONSE = conn.recv(1)
|
|
|
|
logging.debug('Server returns: {}'.format(RESPONSE))
|
|
|
|
if RESPONSE == STATUS:
|
|
|
|
logging.info('Status sucessfull updated')
|
|
|
|
else:
|
|
|
|
logging.error('Failed to update status')
|
|
|
|
logging.debug('Disconnect from server')
|
|
|
|
except Exception as e:
|
|
|
|
logging.error('Error: {}'.format(e))
|
|
|
|
exit(7)
|
2019-07-26 21:33:40 +02:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|