236
195
.replace(b"\n", b"\\n")
237
196
.replace(b"\0", b"\\x00"))
240
199
def encrypt(self, data, password):
241
200
passphrase = self.password_encode(password)
242
201
with tempfile.NamedTemporaryFile(
243
202
dir=self.tempdir) as passfile:
244
203
passfile.write(passphrase)
246
proc = subprocess.Popen([self.gpg, '--symmetric',
205
proc = subprocess.Popen(['gpg', '--symmetric',
247
206
'--passphrase-file',
249
208
+ self.gnupgargs,
250
stdin=subprocess.PIPE,
251
stdout=subprocess.PIPE,
252
stderr=subprocess.PIPE)
253
ciphertext, err = proc.communicate(input=data)
209
stdin = subprocess.PIPE,
210
stdout = subprocess.PIPE,
211
stderr = subprocess.PIPE)
212
ciphertext, err = proc.communicate(input = data)
254
213
if proc.returncode != 0:
255
214
raise PGPError(err)
256
215
return ciphertext
258
217
def decrypt(self, data, password):
259
218
passphrase = self.password_encode(password)
260
219
with tempfile.NamedTemporaryFile(
261
dir=self.tempdir) as passfile:
220
dir = self.tempdir) as passfile:
262
221
passfile.write(passphrase)
264
proc = subprocess.Popen([self.gpg, '--decrypt',
223
proc = subprocess.Popen(['gpg', '--decrypt',
265
224
'--passphrase-file',
267
226
+ self.gnupgargs,
268
stdin=subprocess.PIPE,
269
stdout=subprocess.PIPE,
270
stderr=subprocess.PIPE)
271
decrypted_plaintext, err = proc.communicate(input=data)
227
stdin = subprocess.PIPE,
228
stdout = subprocess.PIPE,
229
stderr = subprocess.PIPE)
230
decrypted_plaintext, err = proc.communicate(input = data)
272
231
if proc.returncode != 0:
273
232
raise PGPError(err)
274
233
return decrypted_plaintext
277
# Pretend that we have an Avahi module
279
"""This isn't so much a class as it is a module-like namespace."""
280
IF_UNSPEC = -1 # avahi-common/address.h
281
PROTO_UNSPEC = -1 # avahi-common/address.h
282
PROTO_INET = 0 # avahi-common/address.h
283
PROTO_INET6 = 1 # avahi-common/address.h
284
DBUS_NAME = "org.freedesktop.Avahi"
285
DBUS_INTERFACE_ENTRY_GROUP = DBUS_NAME + ".EntryGroup"
286
DBUS_INTERFACE_SERVER = DBUS_NAME + ".Server"
287
DBUS_PATH_SERVER = "/"
290
def string_array_to_txt_array(t):
291
return dbus.Array((dbus.ByteArray(s.encode("utf-8"))
292
for s in t), signature="ay")
293
ENTRY_GROUP_ESTABLISHED = 2 # avahi-common/defs.h
294
ENTRY_GROUP_COLLISION = 3 # avahi-common/defs.h
295
ENTRY_GROUP_FAILURE = 4 # avahi-common/defs.h
296
SERVER_INVALID = 0 # avahi-common/defs.h
297
SERVER_REGISTERING = 1 # avahi-common/defs.h
298
SERVER_RUNNING = 2 # avahi-common/defs.h
299
SERVER_COLLISION = 3 # avahi-common/defs.h
300
SERVER_FAILURE = 4 # avahi-common/defs.h
303
236
class AvahiError(Exception):
304
237
def __init__(self, value, *args, **kwargs):
305
238
self.value = value
495
428
class AvahiServiceToSyslog(AvahiService):
496
429
def rename(self, *args, **kwargs):
497
430
"""Add the new name to the syslog messages"""
498
ret = super(AvahiServiceToSyslog, self).rename(*args, **kwargs)
431
ret = AvahiService.rename(self, *args, **kwargs)
499
432
syslogger.setFormatter(logging.Formatter(
500
433
'Mandos ({}) [%(process)d]: %(levelname)s: %(message)s'
501
434
.format(self.name)))
505
# Pretend that we have a GnuTLS module
506
class gnutls(object):
507
"""This isn't so much a class as it is a module-like namespace."""
509
library = ctypes.util.find_library("gnutls")
511
library = ctypes.util.find_library("gnutls-deb0")
512
_library = ctypes.cdll.LoadLibrary(library)
515
# Unless otherwise indicated, the constants and types below are
516
# all from the gnutls/gnutls.h C header file.
527
E_NO_CERTIFICATE_FOUND = -49
532
KEYID_USE_SHA256 = 1 # gnutls/x509.h
533
OPENPGP_FMT_RAW = 0 # gnutls/openpgp.h
536
class session_int(ctypes.Structure):
538
session_t = ctypes.POINTER(session_int)
540
class certificate_credentials_st(ctypes.Structure):
542
certificate_credentials_t = ctypes.POINTER(
543
certificate_credentials_st)
544
certificate_type_t = ctypes.c_int
546
class datum_t(ctypes.Structure):
547
_fields_ = [('data', ctypes.POINTER(ctypes.c_ubyte)),
548
('size', ctypes.c_uint)]
550
class openpgp_crt_int(ctypes.Structure):
552
openpgp_crt_t = ctypes.POINTER(openpgp_crt_int)
553
openpgp_crt_fmt_t = ctypes.c_int # gnutls/openpgp.h
554
log_func = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
555
credentials_type_t = ctypes.c_int
556
transport_ptr_t = ctypes.c_void_p
557
close_request_t = ctypes.c_int
560
class Error(Exception):
561
def __init__(self, message=None, code=None, args=()):
562
# Default usage is by a message string, but if a return
563
# code is passed, convert it to a string with
566
if message is None and code is not None:
567
message = gnutls.strerror(code)
568
return super(gnutls.Error, self).__init__(
571
class CertificateSecurityError(Error):
575
class Credentials(object):
577
self._c_object = gnutls.certificate_credentials_t()
578
gnutls.certificate_allocate_credentials(
579
ctypes.byref(self._c_object))
580
self.type = gnutls.CRD_CERTIFICATE
583
gnutls.certificate_free_credentials(self._c_object)
585
class ClientSession(object):
586
def __init__(self, socket, credentials=None):
587
self._c_object = gnutls.session_t()
588
gnutls_flags = gnutls.CLIENT
589
if gnutls.check_version(b"3.5.6"):
590
gnutls_flags |= gnutls.NO_TICKETS
592
gnutls_flags |= gnutls.ENABLE_RAWPK
593
gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
595
gnutls.set_default_priority(self._c_object)
596
gnutls.transport_set_ptr(self._c_object, socket.fileno())
597
gnutls.handshake_set_private_extensions(self._c_object,
600
if credentials is None:
601
credentials = gnutls.Credentials()
602
gnutls.credentials_set(self._c_object, credentials.type,
603
ctypes.cast(credentials._c_object,
605
self.credentials = credentials
608
gnutls.deinit(self._c_object)
611
return gnutls.handshake(self._c_object)
613
def send(self, data):
617
data_len -= gnutls.record_send(self._c_object,
622
return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
624
# Error handling functions
625
def _error_code(result):
626
"""A function to raise exceptions on errors, suitable
627
for the 'restype' attribute on ctypes functions"""
630
if result == gnutls.E_NO_CERTIFICATE_FOUND:
631
raise gnutls.CertificateSecurityError(code=result)
632
raise gnutls.Error(code=result)
634
def _retry_on_error(result, func, arguments):
635
"""A function to retry on some errors, suitable
636
for the 'errcheck' attribute on ctypes functions"""
638
if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
639
return _error_code(result)
640
result = func(*arguments)
643
# Unless otherwise indicated, the function declarations below are
644
# all from the gnutls/gnutls.h C header file.
647
priority_set_direct = _library.gnutls_priority_set_direct
648
priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
649
ctypes.POINTER(ctypes.c_char_p)]
650
priority_set_direct.restype = _error_code
652
init = _library.gnutls_init
653
init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
654
init.restype = _error_code
656
set_default_priority = _library.gnutls_set_default_priority
657
set_default_priority.argtypes = [session_t]
658
set_default_priority.restype = _error_code
660
record_send = _library.gnutls_record_send
661
record_send.argtypes = [session_t, ctypes.c_void_p,
663
record_send.restype = ctypes.c_ssize_t
664
record_send.errcheck = _retry_on_error
666
certificate_allocate_credentials = (
667
_library.gnutls_certificate_allocate_credentials)
668
certificate_allocate_credentials.argtypes = [
669
ctypes.POINTER(certificate_credentials_t)]
670
certificate_allocate_credentials.restype = _error_code
672
certificate_free_credentials = (
673
_library.gnutls_certificate_free_credentials)
674
certificate_free_credentials.argtypes = [
675
certificate_credentials_t]
676
certificate_free_credentials.restype = None
678
handshake_set_private_extensions = (
679
_library.gnutls_handshake_set_private_extensions)
680
handshake_set_private_extensions.argtypes = [session_t,
682
handshake_set_private_extensions.restype = None
684
credentials_set = _library.gnutls_credentials_set
685
credentials_set.argtypes = [session_t, credentials_type_t,
687
credentials_set.restype = _error_code
689
strerror = _library.gnutls_strerror
690
strerror.argtypes = [ctypes.c_int]
691
strerror.restype = ctypes.c_char_p
693
certificate_type_get = _library.gnutls_certificate_type_get
694
certificate_type_get.argtypes = [session_t]
695
certificate_type_get.restype = _error_code
697
certificate_get_peers = _library.gnutls_certificate_get_peers
698
certificate_get_peers.argtypes = [session_t,
699
ctypes.POINTER(ctypes.c_uint)]
700
certificate_get_peers.restype = ctypes.POINTER(datum_t)
702
global_set_log_level = _library.gnutls_global_set_log_level
703
global_set_log_level.argtypes = [ctypes.c_int]
704
global_set_log_level.restype = None
706
global_set_log_function = _library.gnutls_global_set_log_function
707
global_set_log_function.argtypes = [log_func]
708
global_set_log_function.restype = None
710
deinit = _library.gnutls_deinit
711
deinit.argtypes = [session_t]
712
deinit.restype = None
714
handshake = _library.gnutls_handshake
715
handshake.argtypes = [session_t]
716
handshake.restype = _error_code
717
handshake.errcheck = _retry_on_error
719
transport_set_ptr = _library.gnutls_transport_set_ptr
720
transport_set_ptr.argtypes = [session_t, transport_ptr_t]
721
transport_set_ptr.restype = None
723
bye = _library.gnutls_bye
724
bye.argtypes = [session_t, close_request_t]
725
bye.restype = _error_code
726
bye.errcheck = _retry_on_error
728
check_version = _library.gnutls_check_version
729
check_version.argtypes = [ctypes.c_char_p]
730
check_version.restype = ctypes.c_char_p
732
_need_version = b"3.3.0"
733
if check_version(_need_version) is None:
734
raise self.Error("Needs GnuTLS {} or later"
735
.format(_need_version))
737
_tls_rawpk_version = b"3.6.6"
738
has_rawpk = bool(check_version(_tls_rawpk_version))
742
class pubkey_st(ctypes.Structure):
744
pubkey_t = ctypes.POINTER(pubkey_st)
746
x509_crt_fmt_t = ctypes.c_int
748
# All the function declarations below are from gnutls/abstract.h
749
pubkey_init = _library.gnutls_pubkey_init
750
pubkey_init.argtypes = [ctypes.POINTER(pubkey_t)]
751
pubkey_init.restype = _error_code
753
pubkey_import = _library.gnutls_pubkey_import
754
pubkey_import.argtypes = [pubkey_t, ctypes.POINTER(datum_t),
756
pubkey_import.restype = _error_code
758
pubkey_get_key_id = _library.gnutls_pubkey_get_key_id
759
pubkey_get_key_id.argtypes = [pubkey_t, ctypes.c_int,
760
ctypes.POINTER(ctypes.c_ubyte),
761
ctypes.POINTER(ctypes.c_size_t)]
762
pubkey_get_key_id.restype = _error_code
764
pubkey_deinit = _library.gnutls_pubkey_deinit
765
pubkey_deinit.argtypes = [pubkey_t]
766
pubkey_deinit.restype = None
768
# All the function declarations below are from gnutls/openpgp.h
770
openpgp_crt_init = _library.gnutls_openpgp_crt_init
771
openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)]
772
openpgp_crt_init.restype = _error_code
774
openpgp_crt_import = _library.gnutls_openpgp_crt_import
775
openpgp_crt_import.argtypes = [openpgp_crt_t,
776
ctypes.POINTER(datum_t),
778
openpgp_crt_import.restype = _error_code
780
openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self
781
openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint,
782
ctypes.POINTER(ctypes.c_uint)]
783
openpgp_crt_verify_self.restype = _error_code
785
openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit
786
openpgp_crt_deinit.argtypes = [openpgp_crt_t]
787
openpgp_crt_deinit.restype = None
789
openpgp_crt_get_fingerprint = (
790
_library.gnutls_openpgp_crt_get_fingerprint)
791
openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t,
795
openpgp_crt_get_fingerprint.restype = _error_code
797
if check_version(b"3.6.4"):
798
certificate_type_get2 = _library.gnutls_certificate_type_get2
799
certificate_type_get2.argtypes = [session_t, ctypes.c_int]
800
certificate_type_get2.restype = _error_code
802
# Remove non-public functions
803
del _error_code, _retry_on_error
806
437
def call_pipe(connection, # : multiprocessing.Connection
807
438
func, *args, **kwargs):
808
439
"""This function is meant to be called by multiprocessing.Process
810
441
This function runs func(*args, **kwargs), and writes the resulting
811
442
return value on the provided multiprocessing.Connection.
813
444
connection.send(func(*args, **kwargs))
814
445
connection.close()
817
447
class Client(object):
818
448
"""A representation of a client host served by this server.
821
451
approved: bool(); 'None' if not yet approved/disapproved
822
452
approval_delay: datetime.timedelta(); Time to wait for approval
823
453
approval_duration: datetime.timedelta(); Duration of one approval
824
checker: multiprocessing.Process(); a running checker process used
825
to see if the client lives. 'None' if no process is
827
checker_callback_tag: a GLib event source tag, or None
454
checker: subprocess.Popen(); a running checker process used
455
to see if the client lives.
456
'None' if no process is running.
457
checker_callback_tag: a gobject event source tag, or None
828
458
checker_command: string; External command which is run to check
829
459
if client lives. %() expansions are done at
830
460
runtime with vars(self) as dict, so that for
831
461
instance %(name)s can be used in the command.
832
checker_initiator_tag: a GLib event source tag, or None
462
checker_initiator_tag: a gobject event source tag, or None
833
463
created: datetime.datetime(); (UTC) object creation
834
464
client_structure: Object describing what attributes a client has
835
465
and is used for storing the client at exit
836
466
current_checker_command: string; current running checker_command
837
disable_initiator_tag: a GLib event source tag, or None
467
disable_initiator_tag: a gobject event source tag, or None
839
469
fingerprint: string (40 or 32 hexadecimal digits); used to
840
uniquely identify an OpenPGP client
841
key_id: string (64 hexadecimal digits); used to uniquely identify
842
a client using raw public keys
470
uniquely identify the client
843
471
host: string; available for use by the checker command
844
472
interval: datetime.timedelta(); How often to start a new checker
845
473
last_approval_request: datetime.datetime(); (UTC) or None
2367
1990
delay -= time2 - time
2370
session.send(client.secret)
2371
except gnutls.Error as error:
2372
logger.warning("gnutls send failed",
1993
while sent_size < len(client.secret):
1995
sent = session.send(client.secret[sent_size:])
1996
except gnutls.errors.GNUTLSError as error:
1997
logger.warning("gnutls send failed",
2000
logger.debug("Sent: %d, remaining: %d", sent,
2001
len(client.secret) - (sent_size
2376
2005
logger.info("Sending secret to %s", client.name)
2377
2006
# bump the timeout using extended_timeout
2378
2007
client.bump_timeout(client.extended_timeout)
2379
2008
if self.server.use_dbus:
2380
2009
# Emit D-Bus signal
2381
2010
client.GotSecret()
2384
2013
if approval_required:
2385
2014
client.approvals_pending -= 1
2388
except gnutls.Error as error:
2017
except gnutls.errors.GNUTLSError as error:
2389
2018
logger.warning("GnuTLS bye failed",
2390
2019
exc_info=error)
2393
2022
def peer_certificate(session):
2394
"Return the peer's certificate as a bytestring"
2396
cert_type = gnutls.certificate_type_get2(session._c_object,
2398
except AttributeError:
2399
cert_type = gnutls.certificate_type_get(session._c_object)
2400
if gnutls.has_rawpk:
2401
valid_cert_types = frozenset((gnutls.CRT_RAWPK,))
2403
valid_cert_types = frozenset((gnutls.CRT_OPENPGP,))
2404
# If not a valid certificate type...
2405
if cert_type not in valid_cert_types:
2406
logger.info("Cert type %r not in %r", cert_type,
2408
# ...return invalid data
2023
"Return the peer's OpenPGP certificate as a bytestring"
2024
# If not an OpenPGP certificate...
2025
if (gnutls.library.functions.gnutls_certificate_type_get(
2027
!= gnutls.library.constants.GNUTLS_CRT_OPENPGP):
2028
# ...do the normal thing
2029
return session.peer_certificate
2410
2030
list_size = ctypes.c_uint(1)
2411
cert_list = (gnutls.certificate_get_peers
2031
cert_list = (gnutls.library.functions
2032
.gnutls_certificate_get_peers
2412
2033
(session._c_object, ctypes.byref(list_size)))
2413
2034
if not bool(cert_list) and list_size.value != 0:
2414
raise gnutls.Error("error getting peer certificate")
2035
raise gnutls.errors.GNUTLSError("error getting peer"
2415
2037
if list_size.value == 0:
2417
2039
cert = cert_list[0]
2418
2040
return ctypes.string_at(cert.data, cert.size)
2421
def key_id(certificate):
2422
"Convert a certificate bytestring to a hexdigit key ID"
2423
# New GnuTLS "datum" with the public key
2424
datum = gnutls.datum_t(
2425
ctypes.cast(ctypes.c_char_p(certificate),
2426
ctypes.POINTER(ctypes.c_ubyte)),
2427
ctypes.c_uint(len(certificate)))
2428
# XXX all these need to be created in the gnutls "module"
2429
# New empty GnuTLS certificate
2430
pubkey = gnutls.pubkey_t()
2431
gnutls.pubkey_init(ctypes.byref(pubkey))
2432
# Import the raw public key into the certificate
2433
gnutls.pubkey_import(pubkey,
2434
ctypes.byref(datum),
2435
gnutls.X509_FMT_DER)
2436
# New buffer for the key ID
2437
buf = ctypes.create_string_buffer(32)
2438
buf_len = ctypes.c_size_t(len(buf))
2439
# Get the key ID from the raw public key into the buffer
2440
gnutls.pubkey_get_key_id(pubkey,
2441
gnutls.KEYID_USE_SHA256,
2442
ctypes.cast(ctypes.byref(buf),
2443
ctypes.POINTER(ctypes.c_ubyte)),
2444
ctypes.byref(buf_len))
2445
# Deinit the certificate
2446
gnutls.pubkey_deinit(pubkey)
2448
# Convert the buffer to a Python bytestring
2449
key_id = ctypes.string_at(buf, buf_len.value)
2450
# Convert the bytestring to hexadecimal notation
2451
hex_key_id = binascii.hexlify(key_id).upper()
2455
2043
def fingerprint(openpgp):
2456
2044
"Convert an OpenPGP bytestring to a hexdigit fingerprint"
2457
2045
# New GnuTLS "datum" with the OpenPGP public key
2458
datum = gnutls.datum_t(
2046
datum = gnutls.library.types.gnutls_datum_t(
2459
2047
ctypes.cast(ctypes.c_char_p(openpgp),
2460
2048
ctypes.POINTER(ctypes.c_ubyte)),
2461
2049
ctypes.c_uint(len(openpgp)))
2462
2050
# New empty GnuTLS certificate
2463
crt = gnutls.openpgp_crt_t()
2464
gnutls.openpgp_crt_init(ctypes.byref(crt))
2051
crt = gnutls.library.types.gnutls_openpgp_crt_t()
2052
gnutls.library.functions.gnutls_openpgp_crt_init(
2465
2054
# Import the OpenPGP public key into the certificate
2466
gnutls.openpgp_crt_import(crt, ctypes.byref(datum),
2467
gnutls.OPENPGP_FMT_RAW)
2055
gnutls.library.functions.gnutls_openpgp_crt_import(
2056
crt, ctypes.byref(datum),
2057
gnutls.library.constants.GNUTLS_OPENPGP_FMT_RAW)
2468
2058
# Verify the self signature in the key
2469
2059
crtverify = ctypes.c_uint()
2470
gnutls.openpgp_crt_verify_self(crt, 0,
2471
ctypes.byref(crtverify))
2060
gnutls.library.functions.gnutls_openpgp_crt_verify_self(
2061
crt, 0, ctypes.byref(crtverify))
2472
2062
if crtverify.value != 0:
2473
gnutls.openpgp_crt_deinit(crt)
2474
raise gnutls.CertificateSecurityError(code
2063
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2064
raise gnutls.errors.CertificateSecurityError(
2476
2066
# New buffer for the fingerprint
2477
2067
buf = ctypes.create_string_buffer(20)
2478
2068
buf_len = ctypes.c_size_t()
2479
2069
# Get the fingerprint from the certificate into the buffer
2480
gnutls.openpgp_crt_get_fingerprint(crt, ctypes.byref(buf),
2481
ctypes.byref(buf_len))
2070
gnutls.library.functions.gnutls_openpgp_crt_get_fingerprint(
2071
crt, ctypes.byref(buf), ctypes.byref(buf_len))
2482
2072
# Deinit the certificate
2483
gnutls.openpgp_crt_deinit(crt)
2073
gnutls.library.functions.gnutls_openpgp_crt_deinit(crt)
2484
2074
# Convert the buffer to a Python bytestring
2485
2075
fpr = ctypes.string_at(buf, buf_len.value)
2486
2076
# Convert the bytestring to hexadecimal notation
2575
2164
# socket_wrapper(), if socketfd was set.
2576
2165
socketserver.TCPServer.__init__(self, server_address,
2577
2166
RequestHandlerClass)
2579
2168
def server_bind(self):
2580
2169
"""This overrides the normal server_bind() function
2581
2170
to bind to an interface if one was specified, and also NOT to
2582
2171
bind to an address or port if they were not specified."""
2583
global SO_BINDTODEVICE
2584
2172
if self.interface is not None:
2585
2173
if SO_BINDTODEVICE is None:
2586
# Fall back to a hard-coded value which seems to be
2588
logger.warning("SO_BINDTODEVICE not found, trying 25")
2589
SO_BINDTODEVICE = 25
2591
self.socket.setsockopt(
2592
socket.SOL_SOCKET, SO_BINDTODEVICE,
2593
(self.interface + "\0").encode("utf-8"))
2594
except socket.error as error:
2595
if error.errno == errno.EPERM:
2596
logger.error("No permission to bind to"
2597
" interface %s", self.interface)
2598
elif error.errno == errno.ENOPROTOOPT:
2599
logger.error("SO_BINDTODEVICE not available;"
2600
" cannot bind to interface %s",
2602
elif error.errno == errno.ENODEV:
2603
logger.error("Interface %s does not exist,"
2604
" cannot bind", self.interface)
2174
logger.error("SO_BINDTODEVICE does not exist;"
2175
" cannot bind to interface %s",
2179
self.socket.setsockopt(
2180
socket.SOL_SOCKET, SO_BINDTODEVICE,
2181
(self.interface + "\0").encode("utf-8"))
2182
except socket.error as error:
2183
if error.errno == errno.EPERM:
2184
logger.error("No permission to bind to"
2185
" interface %s", self.interface)
2186
elif error.errno == errno.ENOPROTOOPT:
2187
logger.error("SO_BINDTODEVICE not available;"
2188
" cannot bind to interface %s",
2190
elif error.errno == errno.ENODEV:
2191
logger.error("Interface %s does not exist,"
2192
" cannot bind", self.interface)
2607
2195
# Only bind(2) the socket if we really need to.
2608
2196
if self.server_address[0] or self.server_address[1]:
2609
if self.server_address[1]:
2610
self.allow_reuse_address = True
2611
2197
if not self.server_address[0]:
2612
2198
if self.address_family == socket.AF_INET6:
2613
any_address = "::" # in6addr_any
2199
any_address = "::" # in6addr_any
2615
any_address = "0.0.0.0" # INADDR_ANY
2201
any_address = "0.0.0.0" # INADDR_ANY
2616
2202
self.server_address = (any_address,
2617
2203
self.server_address[1])
2618
2204
elif not self.server_address[1]:
3184
2749
protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
3185
2750
service = AvahiServiceToSyslog(
3186
name=server_settings["servicename"],
3187
servicetype="_mandos._tcp",
2751
name = server_settings["servicename"],
2752
servicetype = "_mandos._tcp",
2753
protocol = protocol,
3190
2755
if server_settings["interface"]:
3191
2756
service.interface = if_nametoindex(
3192
2757
server_settings["interface"].encode("utf-8"))
3194
2759
global multiprocessing_manager
3195
2760
multiprocessing_manager = multiprocessing.Manager()
3197
2762
client_class = Client
3199
client_class = functools.partial(ClientDBus, bus=bus)
2764
client_class = functools.partial(ClientDBus, bus = bus)
3201
2766
client_settings = Client.config_parser(client_config)
3202
2767
old_client_settings = {}
3203
2768
clients_data = {}
3205
2770
# This is used to redirect stdout and stderr for checker processes
3207
wnull = open(os.devnull, "w") # A writable /dev/null
2772
wnull = open(os.devnull, "w") # A writable /dev/null
3208
2773
# Only used if server is running in foreground but not in debug
3210
2775
if debug or not foreground:
3213
2778
# Get client data and settings from last running state.
3214
2779
if server_settings["restore"]:
3216
2781
with open(stored_state_path, "rb") as stored_state:
3217
if sys.version_info.major == 2:
3218
clients_data, old_client_settings = pickle.load(
3221
bytes_clients_data, bytes_old_client_settings = (
3222
pickle.load(stored_state, encoding="bytes"))
3223
# Fix bytes to strings
3226
clients_data = {(key.decode("utf-8")
3227
if isinstance(key, bytes)
3230
bytes_clients_data.items()}
3231
del bytes_clients_data
3232
for key in clients_data:
3233
value = {(k.decode("utf-8")
3234
if isinstance(k, bytes) else k): v
3236
clients_data[key].items()}
3237
clients_data[key] = value
3239
value["client_structure"] = [
3241
if isinstance(s, bytes)
3243
value["client_structure"]]
3245
for k in ("name", "host"):
3246
if isinstance(value[k], bytes):
3247
value[k] = value[k].decode("utf-8")
3248
if "key_id" not in value:
3249
value["key_id"] = ""
3250
elif "fingerprint" not in value:
3251
value["fingerprint"] = ""
3252
# old_client_settings
3254
old_client_settings = {
3255
(key.decode("utf-8")
3256
if isinstance(key, bytes)
3259
bytes_old_client_settings.items()}
3260
del bytes_old_client_settings
3262
for value in old_client_settings.values():
3263
if isinstance(value["host"], bytes):
3264
value["host"] = (value["host"]
2782
clients_data, old_client_settings = pickle.load(
3266
2784
os.remove(stored_state_path)
3267
2785
except IOError as e:
3268
2786
if e.errno == errno.ENOENT: