90
stored_state_path = "/var/lib/mandos/clients.pickle"
90
92
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")))
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)
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
109
210
class AvahiError(Exception):
596
696
self.checker = None
598
# Encrypts a client secret and stores it in a varible
600
def encrypt_secret(self, key):
601
# Encryption-key need to be of a specific size, so we hash
603
hasheng = hashlib.sha256()
605
encryptionkey = hasheng.digest()
607
# Create validation hash so we know at decryption if it was
609
hasheng = hashlib.sha256()
610
hasheng.update(self.secret)
611
validationhash = hasheng.digest()
614
iv = os.urandom(Crypto.Cipher.AES.block_size)
615
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
616
Crypto.Cipher.AES.MODE_CFB, iv)
617
ciphertext = ciphereng.encrypt(validationhash+self.secret)
618
self.encrypted_secret = (ciphertext, iv)
620
# Decrypt a encrypted client secret
621
def decrypt_secret(self, key):
622
# Decryption-key need to be of a specific size, so we hash
624
hasheng = hashlib.sha256()
626
encryptionkey = hasheng.digest()
628
# Decrypt encrypted secret
629
ciphertext, iv = self.encrypted_secret
630
ciphereng = Crypto.Cipher.AES.new(encryptionkey,
631
Crypto.Cipher.AES.MODE_CFB, iv)
632
plain = ciphereng.decrypt(ciphertext)
634
# Validate decrypted secret to know if it was succesful
635
hasheng = hashlib.sha256()
636
validationhash = plain[:hasheng.digest_size]
637
secret = plain[hasheng.digest_size:]
638
hasheng.update(secret)
640
# If validation fails, we use key as new secret. Otherwise, we
641
# use the decrypted secret
642
if hasheng.digest() == validationhash:
646
del self.encrypted_secret
649
699
def dbus_service_property(dbus_interface, signature="v",
650
700
access="readwrite", byte_arrays=False):
1847
1910
return timevalue
1850
def if_nametoindex(interface):
1851
"""Call the C function if_nametoindex(), or equivalent
1853
Note: This function cannot accept a unicode string."""
1854
global if_nametoindex
1856
if_nametoindex = (ctypes.cdll.LoadLibrary
1857
(ctypes.util.find_library("c"))
1859
except (OSError, AttributeError):
1860
logger.warning("Doing if_nametoindex the hard way")
1861
def if_nametoindex(interface):
1862
"Get an interface index the hard way, i.e. using fcntl()"
1863
SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h
1864
with contextlib.closing(socket.socket()) as s:
1865
ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
1866
struct.pack(str("16s16x"),
1868
interface_index = struct.unpack(str("I"),
1870
return interface_index
1871
return if_nametoindex(interface)
1874
1913
def daemon(nochdir = False, noclose = False):
1875
1914
"""See daemon(3). Standard BSD Unix function.
2136
2176
# with exceptions for any special settings as defined above
2137
2177
client_settings = dict((clientname,
2140
setting not in special_settings
2180
if setting not in special_settings
2141
2181
else special_settings[setting]
2144
in client_config.items(clientname)))
2183
for setting, value in
2184
client_config.items(clientname)))
2145
2185
for clientname in client_config.sections())
2147
2187
old_client_settings = {}
2148
2188
clients_data = []
2150
# Get client data and settings from last running state.
2190
# Get client data and settings from last running state.
2151
2191
if server_settings["restore"]:
2153
2193
with open(stored_state_path, "rb") as stored_state:
2154
clients_data, old_client_settings = (
2155
pickle.load(stored_state))
2194
clients_data, old_client_settings = (pickle.load
2156
2196
os.remove(stored_state_path)
2157
2197
except IOError as e:
2158
logger.warning("Could not load persistant state: {0}"
2198
logger.warning("Could not load persistent state: {0}"
2160
2200
if e.errno != errno.ENOENT:
2163
for client in clients_data:
2164
client_name = client["name"]
2166
# Decide which value to use after restoring saved state.
2167
# We have three different values: Old config file,
2168
# new config file, and saved state.
2169
# New config value takes precedence if it differs from old
2170
# config value, otherwise use saved state.
2171
for name, value in client_settings[client_name].items():
2203
with Crypto() as crypt:
2204
for client in clients_data:
2205
client_name = client["name"]
2207
# Decide which value to use after restoring saved state.
2208
# We have three different values: Old config file,
2209
# new config file, and saved state.
2210
# New config value takes precedence if it differs from old
2211
# config value, otherwise use saved state.
2212
for name, value in client_settings[client_name].items():
2214
# For each value in new config, check if it
2215
# differs from the old config value (Except for
2216
# the "secret" attribute)
2217
if (name != "secret" and
2218
value != old_client_settings[client_name]
2220
setattr(client, name, value)
2224
# Clients who has passed its expire date can still be
2225
# enabled if its last checker was sucessful. Clients
2226
# whose checker failed before we stored its state is
2227
# assumed to have failed all checkers during downtime.
2228
if client["enabled"] and client["last_checked_ok"]:
2229
if ((datetime.datetime.utcnow()
2230
- client["last_checked_ok"])
2231
> client["interval"]):
2232
if client["last_checker_status"] != 0:
2233
client["enabled"] = False
2235
client["expires"] = (datetime.datetime
2237
+ client["timeout"])
2239
client["changedstate"] = (multiprocessing_manager
2241
(multiprocessing_manager
2244
new_client = (ClientDBusTransitional.__new__
2245
(ClientDBusTransitional))
2246
tcp_server.clients[client_name] = new_client
2247
new_client.bus = bus
2248
for name, value in client.iteritems():
2249
setattr(new_client, name, value)
2250
client_object_name = unicode(client_name).translate(
2251
{ord("."): ord("_"),
2252
ord("-"): ord("_")})
2253
new_client.dbus_object_path = (dbus.ObjectPath
2255
+ client_object_name))
2256
DBusObjectWithProperties.__init__(new_client,
2261
tcp_server.clients[client_name] = (Client.__new__
2263
for name, value in client.iteritems():
2264
setattr(tcp_server.clients[client_name],
2173
# For each value in new config, check if it differs
2174
# from the old config value (Except for the "secret"
2176
if (name != "secret" and
2177
value != old_client_settings[client_name][name]):
2178
setattr(client, name, value)
2182
# Clients who has passed its expire date, can still be enabled
2183
# if its last checker was sucessful. Clients who checkers
2184
# failed before we stored it state is asumed to had failed
2185
# checker during downtime.
2186
if client["enabled"] and client["last_checked_ok"]:
2187
if ((datetime.datetime.utcnow()
2188
- client["last_checked_ok"]) > client["interval"]):
2189
if client["last_checker_status"] != 0:
2190
client["enabled"] = False
2192
client["expires"] = (datetime.datetime.utcnow()
2193
+ client["timeout"])
2195
client["changedstate"] = (multiprocessing_manager
2196
.Condition(multiprocessing_manager
2199
new_client = ClientDBusTransitional.__new__(
2200
ClientDBusTransitional)
2201
tcp_server.clients[client_name] = new_client
2202
new_client.bus = bus
2203
for name, value in client.iteritems():
2204
setattr(new_client, name, value)
2205
new_client._approvals_pending = 0
2206
new_client.add_to_dbus()
2208
tcp_server.clients[client_name] = Client.__new__(Client)
2209
for name, value in client.iteritems():
2210
setattr(tcp_server.clients[client_name], name, value)
2212
tcp_server.clients[client_name].decrypt_secret(
2213
client_settings[client_name]["secret"])
2268
tcp_server.clients[client_name].secret = (
2269
crypt.decrypt(tcp_server.clients[client_name]
2271
client_settings[client_name]
2274
# If decryption fails, we use secret from new settings
2275
tcp_server.clients[client_name].secret = (
2276
client_settings[client_name]["secret"])
2215
2278
# Create/remove clients based on new changes made to config
2216
2279
for clientname in set(old_client_settings) - set(client_settings):
2217
2280
del tcp_server.clients[clientname]
2218
2281
for clientname in set(client_settings) - set(old_client_settings):
2219
tcp_server.clients[clientname] = client_class(name
2282
tcp_server.clients[clientname] = (client_class(name
2225
2288
if not tcp_server.clients:
2226
2289
logger.warning("No clients defined")
2309
2372
multiprocessing.active_children()
2310
2373
if not (tcp_server.clients or client_settings):
2313
2376
# Store client before exiting. Secrets are encrypted with key
2314
2377
# based on what config file has. If config file is
2315
2378
# removed/edited, old secret will thus be unrecovable.
2317
for client in tcp_server.clients.itervalues():
2318
client.encrypt_secret(
2319
client_settings[client.name]["secret"])
2323
# A list of attributes that will not be stored when
2325
exclude = set(("bus", "changedstate", "secret"))
2326
for name, typ in inspect.getmembers(dbus.service.Object):
2329
client_dict["encrypted_secret"] = client.encrypted_secret
2330
for attr in client.client_structure:
2331
if attr not in exclude:
2332
client_dict[attr] = getattr(client, attr)
2334
clients.append(client_dict)
2335
del client_settings[client.name]["secret"]
2380
with Crypto() as crypt:
2381
for client in tcp_server.clients.itervalues():
2382
key = client_settings[client.name]["secret"]
2383
client.encrypted_secret = crypt.encrypt(client.secret,
2387
# A list of attributes that will not be stored when
2389
exclude = set(("bus", "changedstate", "secret"))
2390
for name, typ in (inspect.getmembers
2391
(dbus.service.Object)):
2394
client_dict["encrypted_secret"] = (client
2396
for attr in client.client_structure:
2397
if attr not in exclude:
2398
client_dict[attr] = getattr(client, attr)
2400
clients.append(client_dict)
2401
del client_settings[client.name]["secret"]
2338
2404
with os.fdopen(os.open(stored_state_path,
2339
2405
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2340
stat.S_IRUSR | stat.S_IWUSR),
2341
"wb") as stored_state:
2406
0600), "wb") as stored_state:
2342
2407
pickle.dump((clients, client_settings), stored_state)
2343
except IOError as e:
2344
logger.warning("Could not save persistant state: {0}"
2408
except (IOError, OSError) as e:
2409
logger.warning("Could not save persistent state: {0}"
2346
if e.errno != errno.ENOENT:
2411
if e.errno not in (errno.ENOENT, errno.EACCES):
2349
2414
# Delete all clients, and settings from config
2350
2415
while tcp_server.clients:
2351
2416
name, client = tcp_server.clients.popitem()