Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

############################################################################# 

# 

# A collection of software-defined routers for Surrogate networking needs. 

# 

# Copyright (C) 2015-2016 Menlo Security, Inc. 

# All rights reserved. 

# 

############################################################################# 

import abc 

import atexit 

import functools 

import netifaces 

import os 

import socket 

import struct 

import subprocess 

 

import psutil 

import tornado.ioloop as ioloop 

import tornado.iostream as iostream 

import tornado.netutil 

from tornado.gen import coroutine 

from tornado.netutil import Resolver 

 

from subprocess import check_call, check_output 

from safly.config import config 

from safly.container import os_helpers 

from safly.logger import SafelyLoggerMixin, get_logger 

from safly.timex import alert_if_slow, monotonic 

 

log = get_logger('sm-net', auto_prefix=True) 

 

# Name of container bridge device (e.g., 'br0'). 

con_bridge_device = None 

 

Resolver.configure('tornado.netutil.ThreadedResolver') 

 

def get_default_gateway_device(): 

"""Returns the system-wide default-route gateway if there is one.""" 

return netifaces.gateways()['default'][netifaces.AF_INET][1] 

 

def _get_device_addr(dev): 

"""Returns the IP address assigned to the device @dev.""" 

return netifaces.ifaddresses(dev)[netifaces.AF_INET][0]['addr'] 

 

def _get_if_gateway(dev): 

"""Returns the gateway IP for device @dev, or None if device has no 

gateway IP.""" 

gw_by_if = {tup[1] : tup[0] for tup in 

netifaces.gateways()[netifaces.AF_INET]} 

return gw_by_if.get(dev, None) 

 

def get_container_host_ip(): 

return _get_device_addr(con_bridge_device) 

 

class LinkObserver(SafelyLoggerMixin): 

"""Watches for link changes and notifies interested parties. 

 

To keep this simple, we delegate responsibility of determining which 

links changed status, if any, to the class's client. 

 

This class does not provide any guarantees about notification (e.g., 

under memory pressure) speed because the underlying kernel link 

notification mechanism (NETLINK) does not. But eventual notification 

is guaranteed by periodic callbacks. 

 

Per netlink (7): 

 

"Only processes with an effective UID of 0 or the CAP_NET_ADMIN capability 

may send or listen to a netlink multicast group." 

""" 

RTMGRP_LINK = 0x001 # Link updates multicast group. 

RTMGRP_IPV4_IFADDR = 0x010 # IPv4 address changes (e.g., device aliases) 

RTMGRP_IPV6_IFADDR = 0x100 # IPv6 address changes (e.g., device aliases) 

# Format of NETLINK messages coming from the kernel. 

HEADER_FMT = 'IHHII' # See struct nlmsghdr in netlink(7) 

SOL_NETLINK = 270 

NETLINK_NO_ENOBUFS = 5 # Disable ENOBUFS errors. 

SYNC_INTERVAL_MS = config.getint('surrogate_manager', 

'link_observer_sync_interval_ms') 

 

def __init__(self, io_loop=None): 

super(LinkObserver, self).__init__('sm-link-observer', 

auto_prefix=True) 

self._io_loop = io_loop or ioloop.IOLoop.instance() 

self._hdr_len = struct.calcsize(self.HEADER_FMT) 

self._pc = ioloop.PeriodicCallback(self._on_periodic, 

self.SYNC_INTERVAL_MS) 

self._pc.start() 

self._observers = set() 

self._netlink_stream = None 

 

@staticmethod 

def instance(io_loop=None): 

if not hasattr(LinkObserver, '_instance'): 

LinkObserver._instance = LinkObserver(io_loop) 

LinkObserver._instance._connect() 

return LinkObserver._instance 

 

def _connect(self): 

try: 

s = socket.socket(socket.AF_NETLINK, 

# "NETLINK is a datagram oriented 

# service." 

socket.SOCK_DGRAM, 

socket.NETLINK_ROUTE) 

# Tornado's IOStream cannot recover from ENOBUFS returned by 

# NETLINK when the socket receive buffer is full. So disable it 

# as we do not need it: we need to know that link status changed 

# but not any further details. 

s.setsockopt(self.SOL_NETLINK, self.NETLINK_NO_ENOBUFS, 1) 

s.bind((os.getpid(), self.RTMGRP_LINK | self.RTMGRP_IPV4_IFADDR | 

self.RTMGRP_IPV6_IFADDR)) 

# FIXME: IOStream assumes a TCP-like socket, but that's not what 

# a netlink socket is. Despite the differences, this mostly works 

# because we do not use any TCP like features (e.g., connect). 

self._netlink_stream = iostream.IOStream(s, io_loop=self._io_loop) 

self._netlink_stream.set_close_callback(self._on_close) 

self._netlink_stream.read_bytes(self._hdr_len, self._on_header) 

except Exception: 

self.log.exception({}, event='netlink-connect-failed') 

else: 

# In case we missed events while disconnected. 

self._invoke_callbacks('netlink-connect') 

 

def register(self, func): 

self._observers.add(func) 

 

def deregister(self, func): 

self._observers.remove(func) 

 

def _invoke_callbacks(self, reason): 

for observer in self._observers: 

try: 

observer(reason) 

except Exception: 

self.log.exception({}, event='callback-exception') 

 

def _on_close(self): 

# This shouldn't happen, especially since we've disabled ENOBUFS. 

self.log.error({}, event='netlink-sock-closed') 

# Attempt to recover by reconnecting. 

self._netlink_stream = None 

self._connect() 

 

def _on_header(self, hdr): 

msg_len, msg_type, msg_flags = struct.unpack(self.HEADER_FMT, hdr)[0:3] 

self.log.debug({'nr_observers': len(self._observers), 

'msg_len': msg_len, 

'msg_type': msg_type, 

'msg_flags': '%x' % msg_flags}, 

event='link-event') 

self._invoke_callbacks('link-event') 

self._netlink_stream.read_bytes(msg_len - self._hdr_len, 

self._on_payload) 

 

def _on_payload(self, payload): 

# We don't care about the payload (and decoding it is more work). 

self._netlink_stream.read_bytes(self._hdr_len, self._on_header) 

 

def _on_periodic(self): 

if not self._netlink_stream: 

# Prior connection attempt failed; try again. 

self._connect() 

self._invoke_callbacks('periodic') 

 

 

class ContainerRouter(SafelyLoggerMixin): 

"""A logical packet router bound to a given Container.""" 

 

__metaclass__ = abc.ABCMeta 

 

def __init__(self, con): 

self._con = con 

super(ContainerRouter, self).__init__('sm-net', 

auto_prefix=True) 

 

def get_extra_logger_fields(self): 

"""Parent override.""" 

extra = super(ContainerRouter, self).get_extra_logger_fields() 

extra.append(('surrogate_id', self._con.safe_rid, 14)) 

if self._con.safe_bid: 

extra.append(('browser_id', self._con.safe_bid, 14)) 

if self._con._netns_handle: 

extra.append(('ip', self._con._netns_handle.addr, 14)) 

return extra 

 

@abc.abstractmethod 

def _update_rules(self, add): 

# Override me---this is where you work the IPTables magic. 

pass 

 

def _get_action(self, add): 

return (('-I', 'add') if add else ('-D', 'delete')) 

 

def start(self): 

self.log.info({}, event='started') 

try: 

self._update_rules(add=True) 

except Exception: 

self.log.exception({}, event='start-failed') 

 

def stop(self): 

try: 

self._update_rules(add=False) 

except Exception: 

self.log.exception({}, event='stop-failed') 

self.log.info({}, event='stopped') 

 

 

class GatewayRouter(ContainerRouter): 

"""Forwards outbound container traffic through a designated gateway device. 

 

Forwards all packets coming from the container and heading out of the host 

(i.e., outbound packets) through a designated network device (e.g., a 

bounce tunnel). This is done solely via Linux's source IP policy routing 

capabilities. 

""" 

 

# Our self-designated namespace for routing table ids. 

NAMESPACE_ID = 0xE5000000 

 

def __init__(self, con, device_pref_list, forwarded_ports, 

proxy_config=None, io_loop=None): 

super(GatewayRouter, self).__init__(con) 

self._io_loop = io_loop or ioloop.IOLoop.instance() 

self._con_ip = self._con._netns_handle.addr 

# ID Scheme: use the container process pid 

# 

# FIXME: despite the use of a namespace id, there is still a risk of 

# collision with other applications; would be best if the kernel just 

# gave us a unique id; keyspace is only 32-bits so random id 

# generation may not work well either. 

assert(self._con.pid < 2**16) 

self._table_id = str(self.NAMESPACE_ID + self._con.pid) 

self._pref_list = [get_default_gateway_device() if dev == 'default' 

else dev for dev in device_pref_list] 

self._gateway_device = None 

self._forwarded_ports = forwarded_ports 

self._link_observer = LinkObserver.instance(self._io_loop) 

self._helper_routers = {} 

if proxy_config: 

self._proxy_host, self._proxy_port = proxy_config.split(':') 

self._proxy_port = int(self._proxy_port) 

else: 

self._proxy_host = None 

self._proxy_port = None 

 

def get_logger_name(self): 

"""Parent override.""" 

return 'sm-gateway-router' 

 

def _stop_helper_routers(self): 

for name, router in self._helper_routers.items(): 

router.stop() 

self._helper_routers.pop(name) 

 

# FIXME: given the risk of these check_calls blocking (can we truly 

# guarantee that they do not block indefinitely?), we should really do this 

# in an Executor thread. 

@alert_if_slow(max_secs=1) # We shouldn't block the event loop for long. 

def _update_rules(self, gateway_device, add=True): 

ipt_action, ip_action = self._get_action(add) 

try: 

#### Bounce gateway setup 

# If no bounce device is given, then we do not install any bounce 

# rules, thus causing traffic to be routed via the default route. 

# 

# Set up the custom routing table: route packets via the 

# designated bounce gateway for this container. 

check_call(['ip', 'route', 'flush', 'table', self._table_id]) 

if add: 

cmd = ['ip', 'route', ip_action, 

# Safe to use 'default' since this rule 

# only applies to forwarded traffic. 

# 

# 'default' is equivalent to 0.0.0.0/0 . 

'default'] 

gateway = _get_if_gateway(gateway_device) 

if gateway: 

cmd += ['via', gateway] 

else: 

# The other end of a tunnel is usually a gateway that knows 

# how to forward packets, so this is not necessarily fatal. 

self.log.warning({'detail': 'No gateway IP, is it a tunnel or bridge?', 

'dev': gateway_device}, 

event='device-has-no-gateway') 

cmd += ['dev', gateway_device, 

# 'static' ==> ensure that routing daemons do not 

# remove this entry: see ip-route(8). 

'proto', 'static', 

'table', self._table_id] 

check_call(cmd) 

# Send container for processing to the custom routing table 

# @self._table_id (as opposed to the main routing table). 

check_call(['ip', 'rule', ip_action, 

# Priority must be higher (kernel gives priority to 

# lower values) than the main and default tables (32766 

# and 32767 respectively). 

'priority', '1000', 

# 'from' is not necessary given that fwmark is unique to 

# the container, but having this helps with debugging. 

'from', self._con_ip, 

# Route only container-initiated traffic (i.e., packets 

# with the mark set) through the gateway device (which 

# is possibly a bounce tunnel). All other packets 

# should use the default routing table. This is 

# especially important for resource requests---the 

# replies must be routed out via the default interface 

# or they will be lost thus resulting in resource load 

# failure. 

'fwmark', self._table_id, 

'table', self._table_id]) 

# Flush kernel cache to ensure that new rules take effect. 

# 

# FIXME: this is a system-wide flush; any way to do this more 

# selectively? 

check_call(['ip', 'route', 'flush', 'cache']) 

 

# Enable source-NAT on the device so that replies packets can find 

# their way back. 

# 

# NOTE on MASQUERADE vs. SNAT: they both do source-address NAT'ing, 

# but if the former is used, the kernel will take care of IP address 

# changes on the device, thus making it naturally more link/tunnel 

# failure tolerant. 

check_call(['iptables', 

'-t', 'nat', 

ipt_action, 

'SM-nat-postrouting-bf', 

'-s', self._con_ip, 

'-o', gateway_device, 

'-j', 'MASQUERADE']) 

 

#### Forwarding setup. 

# 

# Goal: allow container to initiate connections (e.g., for HTTP) and 

# send packets through its gateway device (AKA, bounce tunnel). 

# 

# There is no need to allow outbound packets on the default gateway 

# since the Surrogate should never make connections through it (it 

# will only receive connections from SurrogateRouters). Outgoing 

# packets related to SurrogateRouter-established connections are 

# allowed by the RELATED,ESTABLISHED rule we've installed. 

for proto, port in set(self._forwarded_ports): 

check_call(['iptables', ipt_action, 'SM-filter-forward', 

'-s', self._con_ip, 

'-p', proto, 

'-o', gateway_device, 

'--dport', str(port), 

'-j', 'ACCEPT']) 

 

# Mark all container-initiated traffic so that we can very precisely 

# route that traffic and only that traffic through the gateway 

# device. 

# 

# ASSUMPTION: We do not expect Surrogate-initiated connections to 

# create RELATED connections. Therefore, we needn't leverage 

# connection tracking state---it suffices to mark based on 

# destination port. 

for proto, port in set(self._forwarded_ports): 

check_call(['iptables', '-t', 'mangle', 

ipt_action, 

'SM-mangle-prerouting', 

'-s', self._con_ip, 

'-p', proto, 

'--dport', str(port), 

'-j', 'MARK', 

'--set-mark', self._table_id]) 

except subprocess.CalledProcessError as e: 

self.log.exception({'cmd': e.cmd, 'errcode': e.returncode}, 

event='rule-update-error') 

 

def _on_link_state_changed(self, reason): 

def get_if_stats(dev): 

"""Returns interface stats. Works with interface aliases too. 

 

Interface aliases share the stats of the parent interface.""" 

# psutil.net_if_stats() does not include device aliases. 

try: 

return psutil.net_if_stats()[dev.split(':')[0]] 

except Exception: 

return None 

 

def get_if_addrs(dev): 

try: 

return netifaces.ifaddresses(dev) 

except Exception: 

return None 

 

def is_dev_up(dev): 

"""Returns True iff @dev is up. 

 

Works with device aliases as well (e.g., eth0:0).""" 

try: 

return (dev in psutil.net_if_addrs() and get_if_stats(dev).isup) 

except Exception: 

return False 

 

usable_devices = [dev for dev in self._pref_list if is_dev_up(dev)] 

new_dev = usable_devices[0] if usable_devices else None 

if not new_dev: 

# Note that this could be a transient situation. 

self.log.error({'usable_devices': usable_devices, 

'pref_list': self._pref_list}, 

event='no-gateway-device') 

if new_dev == self._gateway_device: 

return # No change. 

dns_hosts_by_dev = config.getjson('surrogate_manager', 

'dns_hosts_by_device') 

dns_hosts = dns_hosts_by_dev.get(new_dev, None) 

self.log.info({'old_gateway': self._gateway_device, 

'new_gateway': new_dev, 

'new_gateway_info': (get_if_addrs(new_dev) if 

new_dev else None), 

'new_gateway_stats': (get_if_stats(new_dev) if new_dev 

else None), 

'usable_devices': usable_devices, 

'dns_hosts': dns_hosts, 

'proxy_host': self._proxy_host, 

'proxy_port': self._proxy_port, 

'reason': reason}, 

event='gateway-changed') 

if self._gateway_device: 

self._update_rules(self._gateway_device, add=False) 

self._stop_helper_routers() 

if new_dev: 

self._helper_routers['dns'] = VirtualIPForwarder(self._con, 

(dns_hosts or 

os_helpers.get_nameservers()), 

self._con.SURROGATE_DNS_HOSTS, 

{('udp', 53), ('tcp', 53)}, 

io_loop=self._io_loop) 

if self._proxy_host: 

self._helper_routers['proxy'] = VirtualIPForwarder(self._con, 

[self._proxy_host], 

[self._con.SURROGATE_PROXY_IP], 

{('tcp', self._proxy_port)}, 

io_loop=self._io_loop) 

for name, router in self._helper_routers.items(): 

router.start() 

self._update_rules(new_dev, add=True) 

self._gateway_device = new_dev 

 

def start(self): 

self.log.info({'gateway_pref_list': self._pref_list, 

'container_ip': self._con_ip, 

'table_id': self._table_id, 

'forwarded_ports': self._forwarded_ports}, 

event='started') 

# Preferred gateway may not be available on start, so watch for link 

# events and check gateways again. 

self._link_observer.register(self._on_link_state_changed) 

self._on_link_state_changed('start') 

 

def stop(self): 

self._link_observer.deregister(self._on_link_state_changed) 

self.log.info('stopping', event='stopped') 

if self._gateway_device: 

self._update_rules(self._gateway_device, add=False) 

self._stop_helper_routers() 

 

class VirtualIPForwarder(ContainerRouter): 

"""DNATs packets headed for virtual IPs to a set of real hosts. 

 

The number of real hosts may be smaller than the number of virtual IPs, so 

we use round-robin assignment of virtual-to-real IPs to ensure that all 

virtual IPs are mapped to a real host. 

 

Real hosts may be given as DNS names or IPs (or a mix of both). DNS names 

are periodically resolved to IP addresses and translation mappings are 

updated if there are any changes. 

 

To ensure packets get through our forwarding firewall, we make forwarding 

exceptions for destination ports. 

""" 

 

# Interval at which to check for real host IP address changes. 

IP_CHECK_INTERVAL_SECS = config.getint('surrogate_manager', 

'virt_ip_check_interval_secs') 

 

def __init__(self, con, real_hosts, virtual_ips, fw_ports, io_loop=None): 

"""Initializer. 

 

|real_hosts| can be a collection of FQDNs or IP addresses (or a mix). 

|virtual_ips| must be a collection of IP addresses. 

|fw_ports| must be a set of destination ports to which we will allow 

packets to be forwarded. 

""" 

super(VirtualIPForwarder, self).__init__(con) 

self._io_loop = io_loop or ioloop.IOLoop.instance() 

self._real_hosts = real_hosts 

self._real_ips = None # Computed dynamically. 

self._virtual_ips = virtual_ips 

self._fw_ports = fw_ports 

self._ip_map = {} # Computed dynamically. 

self._resolver = Resolver() 

self._refresh_timer = None 

 

def get_logger_name(self): 

"""Parent override.""" 

return 'sm-virt-ip-forwarder' 

 

@alert_if_slow(max_secs=1) # We shouldn't block the event loop for long. 

def _update_rules(self, add=True): 

ipt_action = self._get_action(add)[0] 

try: 

con_ip = self._con._netns_handle.addr 

for orig_dst_ip, new_dst_ip in self._ip_map.items(): 

check_call(['iptables', '-t', 'nat', 

ipt_action, 

'SM-nat-prerouting-virtip', 

'-s', con_ip, 

'-d', orig_dst_ip, 

'-j', 'DNAT', 

'--to-destination', new_dst_ip]) 

# Ensure that requests are forwarded even if the target IP is 

# in the statically initialized blocked set. 

for new_dst_ip in set(self._ip_map.values()): 

for proto, port in self._fw_ports: 

check_call(['iptables', '-t', 'filter', 

ipt_action, 

'SM-filter-fw-block-exemptdyn', 

'-s', con_ip, 

'-d', new_dst_ip, 

'-p', proto, 

'--dport', str(port), 

'-j', 'ACCEPT']) 

except subprocess.CalledProcessError as e: 

self.log.exception({'cmd': e.cmd, 'errcode': e.returncode}, 

event='rule-update-error') 

 

def _do_ip_check_work(self, new_real_ips): 

if not new_real_ips: 

# Can't do much but retry with the hope that at least one host 

# eventually resolves. 

self.log.error({'hosts': self._real_hosts, 

'ips': new_real_ips}, 

event='total-resolve-failure') 

return 

if len(new_real_ips) != len(self._real_hosts): 

self.log.warning({'ips': new_real_ips, 

'hosts': self._real_hosts}, 

event='partial-resolve-failure') 

if new_real_ips == self._real_ips: 

# No change, do nothing. 

return 

self._update_rules(add=False) 

self._real_ips = new_real_ips 

self._ip_map = {list(self._virtual_ips)[i]: list(self._real_ips)[i % len(self._real_ips)] 

for i in xrange(len(self._virtual_ips))} 

self._update_rules(add=True) 

self.log.info({'real_hosts': self._real_hosts, 

'real_ips': self._real_ips, 

'ip_map': self._ip_map, 

'check_interval': self.IP_CHECK_INTERVAL_SECS, 

'fw_ports': self._fw_ports}, 

event='mapping-updated') 

 

@coroutine 

def _on_check_for_ip_changes(self): 

"""Reconfigure in response to domain-to-IP mapping changes. 

 

This periodically monitors DNS hostnames and updates our DNAT tables 

if the corresponding IP addresses have changed.""" 

try: 

new_real_ips = set() 

for host in self._real_hosts: 

try: 

if self._resolver: 

# Don't perform dns resolution if host is a valid ipv4 address 

if tornado.netutil.is_valid_ip(host): 

new_real_ips.add(host) 

else: 

# host needs to be resolved 

dns_start = monotonic() 

response = yield self._resolver.resolve(host, 0, socket.AF_INET) 

if (monotonic() - dns_start) > 1: 

self.log.error({'host':host, 

'time': monotonic() - dns_start}, 

event='slow-resolution') 

# ThreadedResolver returns a list of (family, address) tuples 

# e.g. [(socket.AF_INET, ('1.2.3.4', 80))] 

new_real_ips.add(response[0][1][0]) 

except Exception as e: 

# Host resolution most likely failed. 

self.log.exception({'error': e}, event='change-check-failed') 

except Exception as e: 

self.log.exception({'error': e}, event='change-check-failed') 

if self._resolver: 

try: 

self._do_ip_check_work(new_real_ips) 

except Exception as e: 

self.log.exception({'error': e}, event='change-check-failed') 

self._refresh_timer = self._io_loop.call_later(self.IP_CHECK_INTERVAL_SECS, 

self._on_check_for_ip_changes) 

 

 

def start(self): 

super(VirtualIPForwarder, self).start() 

# Create the initial set of IP mappings, and keep checking for 

# host-to-IP mapping changes. 

self._on_check_for_ip_changes() 

 

def stop(self): 

try: 

self._resolver.close() 

except Exception as e: 

self.log.exception({'error': e}, event='resolver-close-failed') 

self._resolver = None 

if self._refresh_timer: 

self._io_loop.remove_timeout(self._refresh_timer) 

self._refresh_timer = None 

super(VirtualIPForwarder, self).stop() 

 

class HostInputFirewall(ContainerRouter): 

"""Firewall for container packets arriving at the host.""" 

 

def __init__(self, con, input_ports): 

super(HostInputFirewall, self).__init__(con) 

self._con_ip = con._netns_handle.addr 

self._input_ports = input_ports 

 

def get_logger_name(self): 

"""Parent override.""" 

return 'sm-host-firewall' 

 

@alert_if_slow(max_secs=1) # We shouldn't block the event loop for long. 

def _update_rules(self, add=True): 

ipt_action = self._get_action(add)[0] 

try: 

for proto, port in set(self._input_ports): 

check_call(['iptables', ipt_action, 'SM-filter-input', 

'-s', self._con_ip, 

'-p', proto, 

'--dport', str(port), 

'-j', 'ACCEPT']) 

except subprocess.CalledProcessError as e: 

self.log.exception({'cmd': e.cmd, 'errcode': e.returncode}, 

event='rule-update-error') 

 

def start(self): 

self.log.info({'container_ip': self._con_ip, 

'input_ports': self._input_ports}, 

event='started') 

self._update_rules(add=True) 

 

def stop(self): 

self._update_rules(add=False) 

self.log.info('stopping', event='stopped') 

 

def _destroy_custom_chains(): 

"""Removes all chains after clearing and removing references to them.""" 

log.info({'custom_chains': CUSTOM_CHAINS}, event='destroy-custom-chains') 

# First clear all chains and remove all refs to them. 

for table, root_chain, chain, dummy in CUSTOM_CHAINS: 

try: 

# Must remove all entries before removing the chain. 

check_output(['iptables', '-t', table, '-F', chain], 

stderr=subprocess.STDOUT) 

except subprocess.CalledProcessError: 

# No such chain: expected to happen on clean environments. 

pass 

# A custom chain cannot be removed/reset while there are references 

# to it. 

if root_chain: 

try: 

check_output(['iptables', '-t', table, '-D', root_chain, '-j', 

chain], stderr=subprocess.STDOUT) 

except subprocess.CalledProcessError: 

pass 

# The chains are now unref'd and thus safe to delete. 

for table, root_chain, chain, dummy in CUSTOM_CHAINS: 

try: 

# Now remove the chain. 

check_output(['iptables', '-t', table, '-X', chain], 

stderr=subprocess.STDOUT) 

except subprocess.CalledProcessError: 

# No such chain: expected to happen on clean environments. 

pass 

 

def _create_custom_chains(): 

"""Creates all chains and then initializes them. 

 

Invokes the chain-specific init function for each chain.""" 

log.info({'custom_chains': CUSTOM_CHAINS}, event='create-custom-chains') 

for table, root_chain, chain, dummy in CUSTOM_CHAINS: 

check_call(['iptables', '-t', table, '-N', chain]) 

check_call(['iptables', '-t', table, '-A', chain, '-j', 'RETURN']) 

if root_chain: 

check_call(['iptables', '-t', table, '-I', root_chain, '-j', chain]) 

for table, dummy, chain, init_func in CUSTOM_CHAINS: 

if init_func: 

init_func(table, chain) 

 

def _init_filter_input_pre(table, chain): 

# Allow inbound and outbound packets for related and established packets. 

for direction in ['-i', '-o']: 

check_call(['iptables', '-I', chain, 

'-m', 'state', 

'--state', 'RELATED,ESTABLISHED', 

direction, con_bridge_device, 

'-j', 'ACCEPT']) 

 

def _init_filter_input(table, chain): 

# By default, drop everything else coming from the container, 

# regardless of the root chain default INPUT policy action (drop or 

# accept). 

check_call(['iptables', '-I', chain, 

'-i', con_bridge_device, 

'-j', 'SM-input-drop']) 

 

def _init_filter_forward_pre(table, chain): 

# Allow related/established connections to and from anywhere: this is needed 

# to enable communication with SurrogateContainer clients (SurrogateRouters) 

# on other nodes in the cluster. 

for direction in ['-i', '-o']: 

check_call(['iptables', '-I', chain, 

'-m', 'state', 

'--state', 'RELATED,ESTABLISHED', 

direction, con_bridge_device, 

'-j', 'ACCEPT']) 

 

def _init_filter_forward_firewall(is_exception_chain, table, chain): 

"""Set up the static forwarding firewall rules. 

 

Dynamic rules (i.e., those that are Surrogate-specific) are added in a 

separate table. 

 

There are two tables for static rules: blocks go in the block chain 

(@is_exception_chain == False) and block exceptions go in the 

block-exceptions chain. 

""" 

 

def extract_elements(l, with_bang_prefix): 

res = [] 

for e in l: 

e = e.strip() 

if e.startswith('!') == with_bang_prefix: 

res.append(e[int(with_bang_prefix):]) 

return res 

 

never_forward_list = config.get('surrogate_manager', 

'never_forward').strip().split(',') 

processed_list = extract_elements(never_forward_list, is_exception_chain) 

tup_list = [tup.strip().split(':') for tup in processed_list if tup] 

log.info({'list': tup_list}, 

event=('init-forwarding-static-%s' % 

('block-exceptions' if is_exception_chain else 'block'))) 

for dst, proto, port in tup_list: 

cmd = ['iptables', '-I', chain, '-i', con_bridge_device, 

'-m', 'state', '--state', 'NEW'] 

if dst: 

cmd.extend(['-d', dst]) 

if proto: 

cmd.extend(['-p', proto]) 

if proto in ('tcp', 'udp') and port: 

cmd.extend(['--dport', str(port)]) 

if is_exception_chain: 

# Continue processing in the per-Surrogate forward chain. 

# 

# Goto semantics: processing will resume in the parent chain upon 

# return from the target chain. 

cmd.extend(['-g', 'SM-filter-forward']) 

else: 

cmd.extend(['-j', 'SM-forward-drop']) 

check_call(cmd) 

 

def _init_filter_forward(table, chain): 

# By default, do not forward anything coming from the container 

# network. Per container forwarding rules are expected to override this 

# in whitelist fashion. 

check_call(['iptables', '-I', chain, 

'-i', con_bridge_device, 

'-j', 'SM-forward-drop']) 

 

def _init_drop_chain(table, chain): 

check_call(['iptables', '-I', chain, 

'-j', 'DROP']) 

if chain.lower() in config.get('surrogate_manager', 'drop_chain_logging').strip().split(','): 

check_call(['iptables', '-I', chain, 

'-j', 'LOG', '--log-uid', 

'--log-prefix', chain.title() + ':']) 

 

# Rather than install rules in the root IPTables chains (e.g., INPUT, 

# FORWARD, etc.) we install our rules into SM-owned custom chains for better 

# isolation and clarity. These custom chains are referenced by their 

# corresponding root chain and get created upon SM startup and removed on SM 

# shutdown. 

# 

# The format here is: (table name, root chain, custom chain) . 

# 

# These are inserted at the top of the table in list order: i.e., later 

# entries takes precedence in matching. 

CUSTOM_CHAINS = [ 

('filter', None, 'SM-input-drop', _init_drop_chain), 

('filter', None, 'SM-forward-drop', _init_drop_chain), 

('filter', 'INPUT', 'SM-filter-input', _init_filter_input), 

('filter', 'INPUT', 'SM-filter-input-pre', _init_filter_input_pre), 

('filter', 'FORWARD', 'SM-filter-forward', _init_filter_forward), 

# Static block chain. 

('filter', 'FORWARD', 'SM-filter-fw-block', 

functools.partial(_init_filter_forward_firewall, False)), 

# Static exceptions to the static block chain. 

('filter', 'FORWARD', 'SM-filter-fw-block-exempt', 

functools.partial(_init_filter_forward_firewall, True)), 

# Dynamic exceptions to the static block chain (e.g., for Surrogate DNS). 

('filter', 'FORWARD', 'SM-filter-fw-block-exemptdyn', None), 

('filter', 'FORWARD', 'SM-filter-forward-pre', _init_filter_forward_pre), 

('mangle', 'PREROUTING', 'SM-mangle-prerouting', None), 

# Virtual IP to real IP mappings. 

('nat', 'PREROUTING', 'SM-nat-prerouting-virtip', None), 

('nat', 'POSTROUTING', 'SM-nat-postrouting-bf', None)] 

 

def _init_kernel_params(): 

sysctls = [ 

# Enable IP forwarding: the host needs to route container packets. 

('net.ipv4.ip_forward', '1'), 

# Optimization: disable ARP netfilter on the bridge; improves throughput 

# up 4x (2Gb/s) according to iperf experiments. 

('net.bridge.bridge-nf-call-arptables', '0'), 

('net.bridge.bridge-nf-call-ip6tables', '0'), 

# Layer 3 netfilter on the bridge is still needed to block 

# inter-container communication, so we must not disable that. 

('net.bridge.bridge-nf-call-iptables', '1'), 

# We don't need IPv6, and it may cause delays (e.g., during DNS lookup). 

('net.ipv6.conf.all.disable_ipv6', '1'), 

('net.ipv6.conf.default.disable_ipv6', '1'), 

('net.ipv6.conf.lo.disable_ipv6', '1') 

] 

log.info({'sysctls': sysctls}, event='init-kernel-params') 

for key, value in sysctls: 

# We should fail-stop on errors here, but some sysctls are not 

# available within our Docker test environment, thus we keep going. 

# This should not happen in production! 

try: 

check_output(['sysctl', '%s=%s' % (key, value)], 

stderr=subprocess.STDOUT) 

except Exception as e: 

log.error({'key': key, 'value': value, 'error': e}, 

event='init-sysctl-failure') 

 

def _init_bridge(dev, hw_addr='00:00:00:aa:bb:cc'): 

"""Create the container bridge with device name @dev. 

 

Bridge will be assigned MAC address @hw_addr.""" 

log.info({'dev': dev}, event='init-bridge') 

try: 

check_output(['ifconfig', dev, 'down'], stderr=subprocess.STDOUT) 

except Exception: 

# No such bridge: expected in clean environments. 

pass 

try: 

check_output(['brctl', 'delbr', dev], stderr=subprocess.STDOUT) 

except Exception: 

# No such bridge: expected in clean environments. 

pass 

check_call(['brctl', 'addbr', dev]) 

check_call(['brctl', 'setfd', dev, '0']) 

# Only one bridge in the network, so STP is not needed. 

check_call(['brctl', 'stp', dev, 'off']) 

# Tried this when debugging container networking problems. Doesn't 

# appear to be needed. 

#brctl setageing br0 3600 

#brctl setmaxage br0 3600 

check_call(['ifconfig', dev, '10.3.0.1', 'netmask', '255.255.0.0', 

'broadcast', '10.3.255.255', 'promisc', 'hw', 'ether', 

hw_addr, 'up']) 

 

def init(bridge_device): 

global con_bridge_device 

con_bridge_device = bridge_device 

_init_bridge(bridge_device) 

_init_kernel_params() 

_destroy_custom_chains() 

_create_custom_chains() 

 

@atexit.register 

def fini(): 

_destroy_custom_chains()