forked from Yelp/paasta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
firewall.py
501 lines (422 loc) · 15.8 KB
/
firewall.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
import collections
import hashlib
import io
import ipaddress
import itertools
import json
import logging
import os.path
import re
from contextlib import contextmanager
from paasta_tools import iptables
from paasta_tools.cli.utils import get_instance_config
from paasta_tools.marathon_tools import get_all_namespaces_for_service
from paasta_tools.utils import get_running_mesos_docker_containers
from paasta_tools.utils import load_system_paasta_config
from paasta_tools.utils import NoConfigurationForServiceError
from paasta_tools.utils import timed_flock
PRIVATE_IP_RANGES = (
"127.0.0.0/255.0.0.0",
"10.0.0.0/255.0.0.0",
"172.16.0.0/255.240.0.0",
"192.168.0.0/255.255.0.0",
"169.254.0.0/255.255.0.0",
)
DEFAULT_SYNAPSE_SERVICE_DIR = "/var/run/synapse/services"
DEFAULT_FIREWALL_FLOCK_PATH = "/var/lib/paasta/firewall.flock"
DEFAULT_FIREWALL_FLOCK_TIMEOUT_SECS = 5
RESOLV_CONF = "/etc/resolv.conf"
# not exactly correct, but sufficient to filter out ipv6 or other weird things
IPV4_REGEX = re.compile(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$")
log = logging.getLogger(__name__)
class ServiceGroup(collections.namedtuple("ServiceGroup", ("service", "instance"))):
"""A service group.
:param service: service name
:param instance: instance name
"""
__slots__ = ()
@property
def chain_name(self):
"""Return iptables chain name.
Chain names are limited to 28 characters, so we have to trim quite a
bit. To attempt to ensure we don't have collisions due to shortening,
we append a hash to the end.
"""
chain = "PAASTA.{}".format(self.service[:10])
chain += "." + hashlib.sha256(json.dumps(self).encode("utf8")).hexdigest()[:10]
assert len(chain) <= 28, len(chain)
return chain
def get_rules(self, soa_dir, synapse_service_dir):
try:
conf = get_instance_config(
self.service,
self.instance,
load_system_paasta_config().get_cluster(),
load_deployments=False,
soa_dir=soa_dir,
)
except NotImplementedError:
# PAASTA-11414: new instance types may not provide this configuration information;
# we don't want to break all of the firewall infrastructure when that happens
return ()
except NoConfigurationForServiceError:
# PAASTA-12050: a deleted service may still have containers running on PaaSTA hosts
# for several minutes after the directory disappears from soa-configs.
return ()
if not conf.get_outbound_firewall():
return ()
rules = list(_default_rules(conf, self.log_prefix))
rules.extend(_well_known_rules(conf))
rules.extend(_smartstack_rules(conf, soa_dir, synapse_service_dir))
rules.extend(_cidr_rules(conf))
return tuple(rules)
def update_rules(self, soa_dir, synapse_service_dir):
iptables.ensure_chain(
self.chain_name, self.get_rules(soa_dir, synapse_service_dir)
)
iptables.reorder_chain(self.chain_name)
@property
def log_prefix(self):
# log-prefix is limited to 29 characters total
# space at the end is necessary to separate it from the rest of the line
# no restrictions on any particular characters afaict
return f"paasta.{self.service}"[:28] + " "
def _default_rules(conf, log_prefix):
log_rule = iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst="0.0.0.0/0.0.0.0",
target="LOG",
target_parameters=(("log-prefix", (log_prefix,)),),
matches=(("limit", (("limit", ("1/sec",)), ("limit-burst", ("1",)))),),
)
policy = conf.get_outbound_firewall()
if policy == "block":
return (
iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst="0.0.0.0/0.0.0.0",
target="REJECT",
matches=(),
target_parameters=((("reject-with", ("icmp-port-unreachable",))),),
),
log_rule,
)
elif policy == "monitor":
return (log_rule,)
else:
raise AssertionError(policy)
def _well_known_rules(conf):
# Allow access to certain resources for all services by default.
yield iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst="0.0.0.0/0.0.0.0",
target="PAASTA-COMMON",
matches=(),
target_parameters=(),
)
for dep in conf.get_dependencies() or ():
resource = dep.get("well-known")
if resource == "internet":
yield iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst="0.0.0.0/0.0.0.0",
target="PAASTA-INTERNET",
matches=(),
target_parameters=(),
)
elif resource is not None:
# TODO: handle better
raise AssertionError(resource)
def _synapse_backends(synapse_service_dir, namespace):
# Return the contents of the synapse JSON file for a particular service namespace
# e.g. /var/run/synapse/services/example_happyhour.main.json
with open(
os.path.join(synapse_service_dir, namespace + ".json")
) as synapse_backend_file:
synapse_backend_json = json.load(synapse_backend_file)
return synapse_backend_json
def _yocalhost_rule(port, comment, protocol="tcp"):
"""Return an iptables rule allowing access to a yocalhost port."""
return iptables.Rule(
protocol=protocol,
src="0.0.0.0/0.0.0.0",
dst="169.254.255.254/255.255.255.255",
target="ACCEPT",
matches=(
("comment", (("comment", (comment,)),)),
(protocol, (("dport", (str(port),)),)),
),
target_parameters=(),
)
def _smartstack_rules(conf, soa_dir, synapse_service_dir):
for dep in conf.get_dependencies() or ():
namespace = dep.get("smartstack")
if namespace is None:
continue
# TODO: support wildcards
# synapse backends
try:
backends = _synapse_backends(synapse_service_dir, namespace)
except (OSError, IOError, ValueError):
# Don't fatal if something goes wrong loading the synapse files
log.exception(f"Unable to load backend {namespace}")
backends = ()
for backend in backends:
yield iptables.Rule(
protocol="tcp",
src="0.0.0.0/0.0.0.0",
dst="{}/255.255.255.255".format(backend["host"]),
target="ACCEPT",
matches=(
("comment", (("comment", ("backend " + namespace,)),)),
("tcp", (("dport", (str(backend["port"]),)),)),
),
target_parameters=(),
)
# synapse-haproxy proxy_port
service, _ = namespace.split(".", 1)
service_namespaces = get_all_namespaces_for_service(service, soa_dir=soa_dir)
port = dict(service_namespaces)[namespace]["proxy_port"]
yield _yocalhost_rule(port, "proxy_port " + namespace)
def _ports_valid(ports):
for port in ports:
try:
port = int(port)
except ValueError:
log.exception(f"Unable to parse port: {port}")
return False
if not 1 <= port <= 65535:
log.error(f"Bogus port number: {port}")
return False
else:
return True
def _cidr_rules(conf):
for dep in conf.get_dependencies() or ():
cidr = dep.get("cidr")
port_str = dep.get("port")
if cidr is None:
continue
try:
network = ipaddress.IPv4Network(cidr)
except ipaddress.AddressValueError:
log.exception(f"Unable to parse IP network: {cidr}")
continue
if port_str is not None:
# port can be either a single port like "443" or a range like "1024:65535"
ports = str(port_str).split(":")
if len(ports) > 2:
log.error(
f'"port" must be either a single value or a range like "1024:65535": {port_str}'
)
continue
if not _ports_valid(ports):
continue
# Set up an ip rule if no port, or a tcp/udp rule if there is a port
dst = f"{network.network_address.exploded}/{network.netmask}"
if port_str is None:
yield iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst=dst,
target="ACCEPT",
matches=(("comment", (("comment", (f"allow {network}:*",)),)),),
target_parameters=(),
)
else:
for proto in ("tcp", "udp"):
yield iptables.Rule(
protocol=proto,
src="0.0.0.0/0.0.0.0",
dst=dst,
target="ACCEPT",
matches=(
("comment", (("comment", (f"allow {network}:{port_str}",)),)),
(proto, (("dport", (str(port_str),)),)),
),
target_parameters=(),
)
def services_running_here():
"""Generator helper that yields (service, instance, mac address) of both
marathon tasks.
"""
for container in get_running_mesos_docker_containers():
if container["HostConfig"]["NetworkMode"] != "bridge":
continue
service = container["Labels"].get("paasta_service")
instance = container["Labels"].get("paasta_instance")
if service is None or instance is None:
continue
network_info = container["NetworkSettings"]["Networks"]["bridge"]
mac = network_info["MacAddress"]
ip = network_info["IPAddress"]
yield service, instance, mac, ip
def active_service_groups():
"""Return active service groups."""
service_groups = collections.defaultdict(set)
for service, instance, mac, ip in services_running_here():
# TODO: only include macs that start with MAC_ADDRESS_PREFIX?
service_groups[ServiceGroup(service, instance)].add(mac)
return service_groups
def _dns_servers():
with io.open(RESOLV_CONF) as f:
for line in f:
parts = line.split()
if (
len(parts) == 2
and parts[0] == "nameserver"
and IPV4_REGEX.match(parts[1])
):
yield parts[1]
def ensure_shared_chains():
_ensure_dns_chain()
_ensure_internet_chain()
_ensure_common_chain()
def _ensure_common_chain():
"""The common chain allows access for all services to certain resources."""
iptables.ensure_chain(
"PAASTA-COMMON",
(
# Allow return traffic for incoming connections
iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst="0.0.0.0/0.0.0.0",
target="ACCEPT",
matches=(("conntrack", (("ctstate", ("ESTABLISHED",)),)),),
target_parameters=(),
),
_yocalhost_rule(1463, "scribed"),
_yocalhost_rule(8125, "metrics-relay", protocol="udp"),
_yocalhost_rule(3030, "sensu"),
iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst="0.0.0.0/0.0.0.0",
target="PAASTA-DNS",
matches=(),
target_parameters=(),
),
),
)
def _ensure_dns_chain():
iptables.ensure_chain(
"PAASTA-DNS",
tuple(
itertools.chain.from_iterable(
(
iptables.Rule(
protocol="udp",
src="0.0.0.0/0.0.0.0",
dst=f"{dns_server}/255.255.255.255",
target="ACCEPT",
matches=(("udp", (("dport", ("53",)),)),),
target_parameters=(),
),
# DNS goes over TCP sometimes, too!
iptables.Rule(
protocol="tcp",
src="0.0.0.0/0.0.0.0",
dst=f"{dns_server}/255.255.255.255",
target="ACCEPT",
matches=(("tcp", (("dport", ("53",)),)),),
target_parameters=(),
),
)
for dns_server in _dns_servers()
)
),
)
def _ensure_internet_chain():
iptables.ensure_chain(
"PAASTA-INTERNET",
(
iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst="0.0.0.0/0.0.0.0",
target="ACCEPT",
matches=(),
target_parameters=(),
),
)
+ tuple(
iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst=ip_range,
target="RETURN",
matches=(),
target_parameters=(),
)
for ip_range in PRIVATE_IP_RANGES
),
)
def ensure_service_chains(service_groups, soa_dir, synapse_service_dir):
"""Ensure service chains exist and have the right rules.
service_groups is a dict {ServiceGroup: set([mac_address..])}
Returns dictionary {[service chain] => [list of mac addresses]}.
"""
chains = {}
for service, macs in service_groups.items():
service.update_rules(soa_dir, synapse_service_dir)
chains[service.chain_name] = macs
return chains
def dispatch_rule(chain, mac):
return iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst="0.0.0.0/0.0.0.0",
target=chain,
matches=(("mac", (("mac-source", (mac.upper(),)),)),),
target_parameters=(),
)
def ensure_dispatch_chains(service_chains):
paasta_rules = set(
itertools.chain.from_iterable(
(dispatch_rule(chain, mac) for mac in macs)
for chain, macs in service_chains.items()
)
)
iptables.ensure_chain("PAASTA", paasta_rules)
jump_to_paasta = iptables.Rule(
protocol="ip",
src="0.0.0.0/0.0.0.0",
dst="0.0.0.0/0.0.0.0",
target="PAASTA",
matches=(),
target_parameters=(),
)
iptables.ensure_rule("INPUT", jump_to_paasta)
iptables.ensure_rule("FORWARD", jump_to_paasta)
def garbage_collect_old_service_chains(desired_chains):
current_paasta_chains = {
chain for chain in iptables.all_chains() if chain.startswith("PAASTA.")
}
for chain in current_paasta_chains - set(desired_chains):
iptables.delete_chain(chain)
def general_update(soa_dir, synapse_service_dir):
"""Update iptables to match the current PaaSTA state."""
ensure_shared_chains()
service_chains = ensure_service_chains(
active_service_groups(), soa_dir, synapse_service_dir
)
ensure_dispatch_chains(service_chains)
garbage_collect_old_service_chains(service_chains)
def prepare_new_container(soa_dir, synapse_service_dir, service, instance, mac):
"""Update iptables to include rules for a new (not yet running) MAC address
"""
ensure_shared_chains() # probably already set, but just to be safe
service_group = ServiceGroup(service, instance)
service_group.update_rules(soa_dir, synapse_service_dir)
iptables.insert_rule("PAASTA", dispatch_rule(service_group.chain_name, mac))
@contextmanager
def firewall_flock(flock_path=DEFAULT_FIREWALL_FLOCK_PATH):
""" Grab an exclusive flock to avoid concurrent iptables updates
"""
with io.FileIO(flock_path, "w") as f:
with timed_flock(f, seconds=DEFAULT_FIREWALL_FLOCK_TIMEOUT_SECS):
yield