90
stored_state_file = "clients.pickle"
92
90
logger = logging.getLogger()
91
stored_state_path = "/var/lib/mandos/clients.pickle"
93
93
syslogger = (logging.handlers.SysLogHandler
94
94
(facility = logging.handlers.SysLogHandler.LOG_DAEMON,
95
95
address = str("/dev/log")))
98
if_nametoindex = (ctypes.cdll.LoadLibrary
99
(ctypes.util.find_library("c"))
101
except (OSError, AttributeError):
102
def if_nametoindex(interface):
103
"Get an interface index the hard way, i.e. using fcntl()"
104
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
105
with contextlib.closing(socket.socket()) as s:
106
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
107
struct.pack(str("16s16x"),
109
interface_index = struct.unpack(str("I"),
111
return interface_index
114
def initlogger(level=logging.WARNING):
115
"""init logger and add loglevel"""
117
syslogger.setFormatter(logging.Formatter
118
('Mandos [%(process)d]: %(levelname)s:'
120
logger.addHandler(syslogger)
122
console = logging.StreamHandler()
123
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
127
logger.addHandler(console)
128
logger.setLevel(level)
131
class CryptoError(Exception):
135
class Crypto(object):
136
"""A simple class for OpenPGP symmetric encryption & decryption"""
138
self.gnupg = GnuPGInterface.GnuPG()
139
self.tempdir = tempfile.mkdtemp(prefix="mandos-")
140
self.gnupg = GnuPGInterface.GnuPG()
141
self.gnupg.options.meta_interactive = False
142
self.gnupg.options.homedir = self.tempdir
143
self.gnupg.options.extra_args.extend(['--force-mdc',
149
def __exit__ (self, exc_type, exc_value, traceback):
157
if self.tempdir is not None:
158
# Delete contents of tempdir
159
for root, dirs, files in os.walk(self.tempdir,
161
for filename in files:
162
os.remove(os.path.join(root, filename))
164
os.rmdir(os.path.join(root, dirname))
166
os.rmdir(self.tempdir)
169
def password_encode(self, password):
170
# Passphrase can not be empty and can not contain newlines or
171
# NUL bytes. So we prefix it and hex encode it.
172
return b"mandos" + binascii.hexlify(password)
174
def encrypt(self, data, password):
175
self.gnupg.passphrase = self.password_encode(password)
176
with open(os.devnull) as devnull:
178
proc = self.gnupg.run(['--symmetric'],
179
create_fhs=['stdin', 'stdout'],
180
attach_fhs={'stderr': devnull})
181
with contextlib.closing(proc.handles['stdin']) as f:
183
with contextlib.closing(proc.handles['stdout']) as f:
184
ciphertext = f.read()
188
self.gnupg.passphrase = None
191
def decrypt(self, data, password):
192
self.gnupg.passphrase = self.password_encode(password)
193
with open(os.devnull) as devnull:
195
proc = self.gnupg.run(['--decrypt'],
196
create_fhs=['stdin', 'stdout'],
197
attach_fhs={'stderr': devnull})
198
with contextlib.closing(proc.handles['stdin'] ) as f:
200
with contextlib.closing(proc.handles['stdout']) as f:
201
decrypted_plaintext = f.read()
205
self.gnupg.passphrase = None
206
return decrypted_plaintext
96
syslogger.setFormatter(logging.Formatter
97
('Mandos [%(process)d]: %(levelname)s:'
99
logger.addHandler(syslogger)
101
console = logging.StreamHandler()
102
console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
106
logger.addHandler(console)
210
109
class AvahiError(Exception):
696
592
self.checker = None
594
# Encrypts a client secret and stores it in a varible encrypted_secret
595
def encrypt_secret(self, key):
596
# Encryption-key need to be of a specific size, so we hash inputed key
597
hasheng = hashlib.sha256()
599
encryptionkey = hasheng.digest()
601
# Create validation hash so we know at decryption if it was sucessful
602
hasheng = hashlib.sha256()
603
hasheng.update(self.secret)
604
validationhash = hasheng.digest()
607
iv = os.urandom(Crypto.Cipher.AES.block_size)
608
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
609
Crypto.Cipher.AES.MODE_CFB, iv)
610
ciphertext = ciphereng.encrypt(validationhash+self.secret)
611
self.encrypted_secret = (ciphertext, iv)
613
# Decrypt a encrypted client secret
614
def decrypt_secret(self, key):
615
# Decryption-key need to be of a specific size, so we hash inputed key
616
hasheng = hashlib.sha256()
618
encryptionkey = hasheng.digest()
620
# Decrypt encrypted secret
621
ciphertext, iv = self.encrypted_secret
622
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
623
Crypto.Cipher.AES.MODE_CFB, iv)
624
plain = ciphereng.decrypt(ciphertext)
626
# Validate decrypted secret to know if it was succesful
627
hasheng = hashlib.sha256()
628
validationhash = plain[:hasheng.digest_size]
629
secret = plain[hasheng.digest_size:]
630
hasheng.update(secret)
632
# if validation fails, we use key as new secret. Otherwhise, we use
633
# the decrypted secret
634
if hasheng.digest() == validationhash:
638
del self.encrypted_secret
699
641
def dbus_service_property(dbus_interface, signature="v",
700
642
access="readwrite", byte_arrays=False):
2183
2125
# with exceptions for any special settings as defined above
2184
2126
client_settings = dict((clientname,
2187
if setting not in special_settings
2188
else special_settings[setting]
2190
for setting, value in
2191
client_config.items(clientname)))
2128
(value if setting not in special_settings
2129
else special_settings[setting](clientname)))
2130
for setting, value in client_config.items(clientname)))
2192
2131
for clientname in client_config.sections())
2194
2133
old_client_settings = {}
2195
2134
clients_data = []
2197
# Get client data and settings from last running state.
2136
# Get client data and settings from last running state.
2198
2137
if server_settings["restore"]:
2200
2139
with open(stored_state_path, "rb") as stored_state:
2201
clients_data, old_client_settings = (pickle.load
2140
clients_data, old_client_settings = pickle.load(stored_state)
2203
2141
os.remove(stored_state_path)
2204
2142
except IOError as e:
2205
logger.warning("Could not load persistent state: {0}"
2143
logger.warning("Could not load persistant state: {0}".format(e))
2207
2144
if e.errno != errno.ENOENT:
2210
with Crypto() as crypt:
2211
for client in clients_data:
2212
client_name = client["name"]
2214
# Decide which value to use after restoring saved state.
2215
# We have three different values: Old config file,
2216
# new config file, and saved state.
2217
# New config value takes precedence if it differs from old
2218
# config value, otherwise use saved state.
2219
for name, value in client_settings[client_name].items():
2221
# For each value in new config, check if it
2222
# differs from the old config value (Except for
2223
# the "secret" attribute)
2224
if (name != "secret" and
2225
value != old_client_settings[client_name]
2227
setattr(client, name, value)
2231
# Clients who has passed its expire date can still be
2232
# enabled if its last checker was sucessful. Clients
2233
# whose checker failed before we stored its state is
2234
# assumed to have failed all checkers during downtime.
2235
if client["enabled"] and client["last_checked_ok"]:
2236
if ((datetime.datetime.utcnow()
2237
- client["last_checked_ok"])
2238
> client["interval"]):
2239
if client["last_checker_status"] != 0:
2240
client["enabled"] = False
2242
client["expires"] = (datetime.datetime
2244
+ client["timeout"])
2246
client["changedstate"] = (multiprocessing_manager
2248
(multiprocessing_manager
2251
new_client = (ClientDBusTransitional.__new__
2252
(ClientDBusTransitional))
2253
tcp_server.clients[client_name] = new_client
2254
new_client.bus = bus
2255
for name, value in client.iteritems():
2256
setattr(new_client, name, value)
2257
client_object_name = unicode(client_name).translate(
2258
{ord("."): ord("_"),
2259
ord("-"): ord("_")})
2260
new_client.dbus_object_path = (dbus.ObjectPath
2262
+ client_object_name))
2263
DBusObjectWithProperties.__init__(new_client,
2268
tcp_server.clients[client_name] = (Client.__new__
2270
for name, value in client.iteritems():
2271
setattr(tcp_server.clients[client_name],
2147
for client in clients_data:
2148
client_name = client["name"]
2150
# Decide which value to use after restoring saved state.
2151
# We have three different values: Old config file,
2152
# new config file, and saved state.
2153
# New config value takes precedence if it differs from old
2154
# config value, otherwise use saved state.
2155
for name, value in client_settings[client_name].items():
2275
tcp_server.clients[client_name].secret = (
2276
crypt.decrypt(tcp_server.clients[client_name]
2278
client_settings[client_name]
2281
# If decryption fails, we use secret from new settings
2282
tcp_server.clients[client_name].secret = (
2283
client_settings[client_name]["secret"])
2157
# For each value in new config, check if it differs
2158
# from the old config value (Except for the "secret"
2160
if name != "secret" and value != old_client_settings[client_name][name]:
2161
setattr(client, name, value)
2165
# Clients who has passed its expire date, can still be enabled if its
2166
# last checker was sucessful. Clients who checkers failed before we
2167
# stored it state is asumed to had failed checker during downtime.
2168
if client["enabled"] and client["last_checked_ok"]:
2169
if ((datetime.datetime.utcnow() - client["last_checked_ok"])
2170
> client["interval"]):
2171
if client["last_checker_status"] != 0:
2172
client["enabled"] = False
2174
client["expires"] = datetime.datetime.utcnow() + client["timeout"]
2176
client["changedstate"] = (multiprocessing_manager
2177
.Condition(multiprocessing_manager
2180
new_client = ClientDBusTransitional.__new__(ClientDBusTransitional)
2181
tcp_server.clients[client_name] = new_client
2182
new_client.bus = bus
2183
for name, value in client.iteritems():
2184
setattr(new_client, name, value)
2185
client_object_name = unicode(client_name).translate(
2186
{ord("."): ord("_"),
2187
ord("-"): ord("_")})
2188
new_client.dbus_object_path = (dbus.ObjectPath
2189
("/clients/" + client_object_name))
2190
DBusObjectWithProperties.__init__(new_client,
2192
new_client.dbus_object_path)
2194
tcp_server.clients[client_name] = Client.__new__(Client)
2195
for name, value in client.iteritems():
2196
setattr(tcp_server.clients[client_name], name, value)
2198
tcp_server.clients[client_name].decrypt_secret(
2199
client_settings[client_name]["secret"])
2285
2201
# Create/remove clients based on new changes made to config
2286
2202
for clientname in set(old_client_settings) - set(client_settings):
2287
2203
del tcp_server.clients[clientname]
2288
2204
for clientname in set(client_settings) - set(old_client_settings):
2289
tcp_server.clients[clientname] = (client_class(name
2205
tcp_server.clients[clientname] = (client_class(name = clientname,
2292
2207
client_settings
2295
2211
if not tcp_server.clients:
2296
2212
logger.warning("No clients defined")
2379
2295
multiprocessing.active_children()
2380
2296
if not (tcp_server.clients or client_settings):
2383
# Store client before exiting. Secrets are encrypted with key
2384
# based on what config file has. If config file is
2385
# removed/edited, old secret will thus be unrecovable.
2299
# Store client before exiting. Secrets are encrypted with key based
2300
# on what config file has. If config file is removed/edited, old
2301
# secret will thus be unrecovable.
2387
with Crypto() as crypt:
2388
for client in tcp_server.clients.itervalues():
2389
key = client_settings[client.name]["secret"]
2390
client.encrypted_secret = crypt.encrypt(client.secret,
2394
# A list of attributes that will not be stored when
2396
exclude = set(("bus", "changedstate", "secret"))
2397
for name, typ in (inspect.getmembers
2398
(dbus.service.Object)):
2401
client_dict["encrypted_secret"] = (client
2403
for attr in client.client_structure:
2404
if attr not in exclude:
2405
client_dict[attr] = getattr(client, attr)
2407
clients.append(client_dict)
2408
del client_settings[client.name]["secret"]
2303
for client in tcp_server.clients.itervalues():
2304
client.encrypt_secret(client_settings[client.name]["secret"])
2308
# A list of attributes that will not be stored when shuting down.
2309
exclude = set(("bus", "changedstate", "secret"))
2310
for name, typ in inspect.getmembers(dbus.service.Object):
2313
client_dict["encrypted_secret"] = client.encrypted_secret
2314
for attr in client.client_structure:
2315
if attr not in exclude:
2316
client_dict[attr] = getattr(client, attr)
2318
clients.append(client_dict)
2319
del client_settings[client.name]["secret"]
2411
with os.fdopen(os.open(stored_state_path,
2412
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2413
0600), "wb") as stored_state:
2322
with os.fdopen(os.open(stored_state_path, os.O_CREAT|os.O_WRONLY|os.O_TRUNC, 0600), "wb") as stored_state:
2414
2323
pickle.dump((clients, client_settings), stored_state)
2415
except (IOError, OSError) as e:
2416
logger.warning("Could not save persistent state: {0}"
2418
if e.errno not in (errno.ENOENT, errno.EACCES):
2324
except IOError as e:
2325
logger.warning("Could not save persistant state: {0}".format(e))
2326
if e.errno != errno.ENOENT:
2421
2329
# Delete all clients, and settings from config
2422
2330
while tcp_server.clients:
2423
2331
name, client = tcp_server.clients.popitem()