Debian Codegraph @

src/plugins/fd/kubernetes-backend/baculak8s/util/sslserver.py

raw
1 #
2 # Bacula(R) - The Network Backup Solution
3 #
4 # Copyright (C) 2000-2022 Kern Sibbald
5 #
6 # The original author of Bacula is Kern Sibbald, with contributions
7 # from many others, a complete list can be found in the file AUTHORS.
8 #
9 # You may use this file and others of this release according to the
10 # license defined in the LICENSE file, which includes the Affero General
11 # Public License, v3.0 ("AGPLv3") and some additional permissions and
12 # terms pursuant to its AGPLv3 Section 7.
13 #
14 # This notice must be preserved when any source code is
15 # conveyed and/or propagated.
16 #
17 # Bacula(R) is a registered trademark of Kern Sibbald.
18 #
19 # Copyright (c) 2019 by Inteos sp. z o.o.
20 # All rights reserved. IP transfered to Bacula Systems according to agreement.
21 # Author: RadosÅ‚aw Korzeniewski, [email protected], Inteos Sp. z o.o.
22 #
23
24 import os
25 import socket
26 import ssl
27 import time
28
29 from baculak8s.util.token import *
30
31 DEFAULTTIMEOUT = 600
32 DEFAULTCERTFILE = "/opt/bacula/etc/bacula-backup.cert"
33 DEFAULTKEYFILE = "/opt/bacula/etc/bacula-backup.key"
34 CONNECTIONSERVER_AUTHTOK_ERR1 = 'ConnectionServer: Authentication token receiving timeout!'
35 CONNECTIONSERVER_AUTHTOK_ERR2 = 'ConnectionServer: Authentication token error!'
36 CONNECTIONSERVER_AUTHTOK_ERR3 = '{ "message": "Cert files does not exist! Cannot prepare Connection Service!" }'
37 CONNECTIONSERVER_AUTHTOK_ERR4 = '{ "message": "ConnectionServer:Cannot bind to socket! Err={}" }'
38 CONNECTIONSERVER_AUTHTOK_ERR5 = 'ConnectionServer: Timeout waiting...'
39 CONNECTIONSERVER_AUTHTOK_ERR6 = 'ConnectionServer: Invalid Hello Data received!'
40 CONNECTIONSERVER_HELLO_ERR1 = 'ConnectionServer: Hello data receiving timeout!'
41 CONNECTIONSERVER_HELLO_ERR2 = 'ConnectionServer: Invalid Hello data packet: "{}"'
42 CONNECTIONSERVER_HELLO_ERR3 = 'ConnectionServer: Invalid Hello header: "{}"'
43
44
45 class ConnectionServer(object):
46
47 def __init__(self, host, port=9104, token=None, certfile=None, keyfile=None, timeout=DEFAULTTIMEOUT,
48 *args, **kwargs):
49 super(ConnectionServer, self).__init__(*args, **kwargs)
50 self.connstream = None
51 self.token = token if token is not None else generate_token()
52 self.timeout = timeout
53 try:
54 self.timeout = int(self.timeout)
55 except ValueError:
56 self.timeout = DEFAULTTIMEOUT
57 self.timeout = max(1, self.timeout)
58 socket.setdefaulttimeout(self.timeout)
59 self.bindsocket = socket.socket()
60 self.sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS)
61 self.host = host
62 self.port = port
63 self.certfile = certfile if certfile is not None else DEFAULTCERTFILE
64 self.keyfile = keyfile if keyfile is not None else DEFAULTKEYFILE
65
66 def streamrecv(self, size):
67 try:
68 data = self.connstream.recv(size)
69 except socket.timeout:
70 data = None
71 return data
72
73 def streamsend(self, data):
74 status = True
75 try:
76 self.connstream.send(data)
77 except socket.timeout:
78 status = False
79 finally:
80 return status
81
82 def authenticate(self):
83 hello = self.gethello()
84 if not isinstance(hello, dict) or 'error' in hello:
85 logging.debug(CONNECTIONSERVER_AUTHTOK_ERR6)
86 return {
87 'error': CONNECTIONSERVER_AUTHTOK_ERR6,
88 }
89 response = hello.get('response')
90 if response is not None and response[0] != 'Hello':
91 logging.debug(CONNECTIONSERVER_AUTHTOK_ERR6)
92 return {
93 'error': CONNECTIONSERVER_AUTHTOK_ERR6,
94 }
95
96 try:
97 data = self.connstream.recv(auth_data_length())
98 except socket.timeout:
99 logging.debug(CONNECTIONSERVER_AUTHTOK_ERR1)
100 return {
101 'error': CONNECTIONSERVER_AUTHTOK_ERR1,
102 }
103 if check_auth_data(self.token, data):
104 self.connstream.send(b'OK')
105 logging.debug('ConnectionServer:Authenticated')
106 return {}
107 else:
108 self.connstream.send(b'NO')
109 logging.error(CONNECTIONSERVER_AUTHTOK_ERR2)
110 return {
111 'error': CONNECTIONSERVER_AUTHTOK_ERR2,
112 }
113
114 def gethello(self) -> dict:
115 data = ""
116 try:
117 data = self.connstream.recv(4)
118 except socket.timeout:
119 logging.debug(CONNECTIONSERVER_HELLO_ERR1)
120 return {
121 'error': CONNECTIONSERVER_HELLO_ERR1,
122 }
123 ddata = data.decode()
124 if ddata[3] != ':':
125 logging.debug(CONNECTIONSERVER_HELLO_ERR3.format(ddata))
126 return {
127 'error': CONNECTIONSERVER_HELLO_ERR3.format(ddata),
128 }
129 ddata = ddata[:3]
130 try:
131 datalen = int(ddata)
132 except ValueError:
133 logging.debug(CONNECTIONSERVER_HELLO_ERR2.format(ddata))
134 return {
135 'error': CONNECTIONSERVER_HELLO_ERR2.format(ddata),
136 }
137 try:
138 data = self.connstream.recv(datalen)
139 except socket.timeout:
140 logging.debug(CONNECTIONSERVER_HELLO_ERR1)
141 return {
142 'error': CONNECTIONSERVER_HELLO_ERR1,
143 }
144 ddata = data.decode().split(':')
145 logging.debug(ddata)
146 return { 'response': ddata }
147
148 def close(self):
149 self.connstream.shutdown(socket.SHUT_RDWR)
150 self.connstream.close()
151
152 def shutdown(self):
153 self.bindsocket.close()
154
155 def listen(self):
156 if not os.path.exists(self.certfile) or not os.path.exists(self.keyfile):
157 logging.error(CONNECTIONSERVER_AUTHTOK_ERR3)
158 return {
159 'error': True,
160 'descr': CONNECTIONSERVER_AUTHTOK_ERR3,
161 }
162 self.sslcontext.load_cert_chain(certfile=self.certfile, keyfile=self.keyfile)
163 ops = 0
164 lastexcept = ""
165 for ops in range(self.timeout):
166 try:
167 self.bindsocket.bind((self.host, self.port))
168 except OSError as e:
169 logging.error(e)
170 lastexcept = str(e)
171 time.sleep(5)
172 else:
173 break
174 if ops == self.timeout - 1:
175 logging.error(CONNECTIONSERVER_AUTHTOK_ERR4.format(lastexcept))
176 return {
177 'error': True,
178 'descr': CONNECTIONSERVER_AUTHTOK_ERR4.format(lastexcept)
179 }
180 logging.debug('ConnectionServer:Listening...')
181 self.bindsocket.listen(5)
182 return {}
183
184 def handle_connection(self, process_client_data):
185 try:
186 newsocket, fromaddr = self.bindsocket.accept()
187 except socket.timeout:
188 logging.error(CONNECTIONSERVER_AUTHTOK_ERR5)
189 return {
190 'error': CONNECTIONSERVER_AUTHTOK_ERR5,
191 'should_remove_pod': 1,
192 }
193 logging.debug("ConnectionServer:Connection from: {}".format(fromaddr))
194 self.connstream = self.sslcontext.wrap_socket(newsocket, server_side=True)
195 try:
196 authresp = self.authenticate()
197 if 'error' in authresp:
198 return authresp
199 process_client_data(self.connstream)
200 finally:
201 logging.debug('ConnectionServer:Finish - disconnect.')
202 try:
203 self.connstream.shutdown(socket.SHUT_RDWR)
204 except Exception as e:
205 logging.debug('throw exception when disconnect.')
206 logging.error(e)
207 logging.debug('ConnectionServer:Finish - shutdown.')
208 self.connstream.close()
209 logging.debug('ConnectionServer:Finish - closed.')
210 return {}