or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

addons.mdcommands.mdconfiguration.mdconnections.mdcontent.mdflow-io.mdhttp-flows.mdindex.mdprotocols.md

configuration.mddocs/

0

# Configuration and Options

1

2

Comprehensive configuration system with type-safe options for proxy behavior, TLS settings, network configuration, and addon parameters. Provides both programmatic and file-based configuration management.

3

4

## Capabilities

5

6

### Options Class

7

8

Main configuration management class providing type-safe option handling and validation.

9

10

```python { .api }

11

class Options:

12

"""

13

Main configuration class for mitmproxy.

14

15

Manages all proxy settings with type validation and change notifications.

16

Supports loading from files, command-line arguments, and programmatic updates.

17

"""

18

def __init__(self, **kwargs) -> None:

19

"""

20

Initialize options with default values.

21

22

Parameters:

23

- **kwargs: Initial option values to override defaults

24

"""

25

26

def set(self, key: str, value: Any) -> None:

27

"""

28

Set an option value with validation.

29

30

Parameters:

31

- key: Option name

32

- value: New option value

33

34

Raises:

35

- OptionsError: If key is invalid or value type is wrong

36

"""

37

38

def get(self, key: str, default: Any = None) -> Any:

39

"""

40

Get an option value.

41

42

Parameters:

43

- key: Option name

44

- default: Default value if option not set

45

46

Returns:

47

- Current option value or default

48

"""

49

50

def update(self, **kwargs) -> None:

51

"""

52

Update multiple options at once.

53

54

Parameters:

55

- **kwargs: Option key-value pairs to update

56

"""

57

58

def load_paths(self, *paths: str) -> None:

59

"""

60

Load options from configuration files.

61

62

Parameters:

63

- *paths: Configuration file paths to load

64

"""

65

66

def save(self, path: str) -> None:

67

"""

68

Save current options to a configuration file.

69

70

Parameters:

71

- path: File path to save configuration

72

"""

73

74

def __getattr__(self, name: str) -> Any:

75

"""Access options as attributes."""

76

77

def __setattr__(self, name: str, value: Any) -> None:

78

"""Set options as attributes."""

79

```

80

81

### Configuration Constants

82

83

Key configuration constants and default values.

84

85

```python { .api }

86

# Default configuration directory

87

CONF_DIR: str = "~/.mitmproxy"

88

89

# Configuration file basename

90

CONF_BASENAME: str = "mitmproxy"

91

92

# Default key size for certificate generation

93

KEY_SIZE: int = 2048

94

95

# Content view line cutoff for performance

96

CONTENT_VIEW_LINES_CUTOFF: int = 512

97

98

# Default proxy ports

99

DEFAULT_PROXY_PORT: int = 8080

100

DEFAULT_WEB_PORT: int = 8081

101

102

# TLS configuration

103

DEFAULT_TLS_PORT: int = 443

104

```

105

106

### Common Option Categories

107

108

Key configuration options organized by category.

109

110

```python { .api }

111

# Network Options

112

class NetworkOptions:

113

"""Network-related configuration options."""

114

listen_host: str = "127.0.0.1"

115

listen_port: int = 8080

116

mode: str = "regular" # regular, transparent, socks5, reverse, upstream

117

upstream_cert: bool = True

118

119

# TLS/SSL Options

120

class TLSOptions:

121

"""TLS/SSL configuration options."""

122

certs: List[str] = []

123

cadir: str = "~/.mitmproxy"

124

ssl_insecure: bool = False

125

ssl_verify_upstream_trusted_ca: Optional[str] = None

126

ssl_verify_upstream_trusted_confdir: Optional[str] = None

127

128

# Proxy Behavior Options

129

class ProxyOptions:

130

"""Proxy behavior configuration options."""

131

allow_hosts: List[str] = []

132

ignore_hosts: List[str] = []

133

tcp_hosts: List[str] = []

134

intercept: Optional[str] = None

135

modify_body: List[str] = []

136

modify_headers: List[str] = []

137

138

# Interface Options

139

class InterfaceOptions:

140

"""User interface configuration options."""

141

console_eventlog: bool = False

142

console_focus_follow: bool = False

143

web_open_browser: bool = True

144

web_debug: bool = False

145

```

146

147

## Usage Examples

148

149

### Basic Configuration

150

151

```python

152

from mitmproxy import options

153

154

def setup_basic_proxy():

155

"""Set up basic proxy configuration."""

156

opts = options.Options()

157

158

# Set basic proxy options

159

opts.listen_host = "0.0.0.0" # Listen on all interfaces

160

opts.listen_port = 8080

161

opts.mode = "regular"

162

163

# Enable upstream certificate verification

164

opts.upstream_cert = True

165

166

# Set custom certificate authority directory

167

opts.cadir = "/path/to/custom/ca"

168

169

return opts

170

171

def setup_transparent_proxy():

172

"""Set up transparent proxy configuration."""

173

opts = options.Options()

174

175

# Configure for transparent mode

176

opts.mode = "transparent"

177

opts.listen_port = 8080

178

179

# Allow specific hosts only

180

opts.allow_hosts = ["*.example.com", "api.service.com"]

181

182

# Ignore certain hosts (don't proxy)

183

opts.ignore_hosts = ["localhost", "127.0.0.1", "*.local"]

184

185

return opts

186

187

def setup_reverse_proxy():

188

"""Set up reverse proxy configuration."""

189

opts = options.Options()

190

191

# Configure reverse proxy to specific upstream

192

opts.mode = "reverse:https://api.backend.com"

193

opts.listen_port = 8080

194

195

# Modify headers for backend

196

opts.modify_headers = [

197

"/~s/Host/api.backend.com", # Set Host header

198

"/~s/X-Forwarded-Proto/https" # Add forwarded protocol

199

]

200

201

return opts

202

```

203

204

### TLS/SSL Configuration

205

206

```python

207

from mitmproxy import options

208

import os

209

210

def setup_custom_tls():

211

"""Configure custom TLS settings."""

212

opts = options.Options()

213

214

# Custom certificate directory

215

ca_dir = os.path.expanduser("~/custom_mitmproxy_ca")

216

opts.cadir = ca_dir

217

218

# Custom certificates for specific domains

219

opts.certs = [

220

"example.com=/path/to/example.com.pem",

221

"*.api.com=/path/to/wildcard-api.pem"

222

]

223

224

# Disable upstream certificate verification (testing only!)

225

opts.ssl_insecure = True

226

227

# Custom trusted CA for upstream verification

228

opts.ssl_verify_upstream_trusted_ca = "/path/to/custom-ca.pem"

229

230

return opts

231

232

def setup_client_certificates():

233

"""Configure client certificate authentication."""

234

opts = options.Options()

235

236

# Client certificate for upstream authentication

237

opts.client_certs = [

238

"api.secure.com=/path/to/client-cert.pem"

239

]

240

241

# Configure TLS versions

242

opts.tls_version_client_min = "TLSv1.2"

243

opts.tls_version_server_min = "TLSv1.2"

244

245

return opts

246

```

247

248

### Advanced Configuration

249

250

```python

251

from mitmproxy import options

252

import yaml

253

254

def load_configuration_from_file():

255

"""Load configuration from YAML file."""

256

opts = options.Options()

257

258

# Load from custom configuration file

259

config_path = "mitmproxy_config.yaml"

260

261

try:

262

with open(config_path, 'r') as f:

263

config = yaml.safe_load(f)

264

265

# Apply configuration options

266

for key, value in config.items():

267

if hasattr(opts, key):

268

setattr(opts, key, value)

269

270

print(f"Loaded configuration from {config_path}")

271

272

except FileNotFoundError:

273

print(f"Configuration file {config_path} not found, using defaults")

274

275

return opts

276

277

def setup_development_proxy():

278

"""Configuration optimized for development work."""

279

opts = options.Options()

280

281

# Development-friendly settings

282

opts.listen_host = "0.0.0.0"

283

opts.listen_port = 8080

284

opts.web_open_browser = True

285

opts.web_debug = True

286

287

# Enable console event logging

288

opts.console_eventlog = True

289

opts.console_focus_follow = True

290

291

# Ignore common development URLs

292

opts.ignore_hosts = [

293

"localhost:*",

294

"127.0.0.1:*",

295

"*.local",

296

"webpack-dev-server",

297

"hot-reload"

298

]

299

300

# Intercept API calls for debugging

301

opts.intercept = "~u /api/"

302

303

# Modify CORS headers for development

304

opts.modify_headers = [

305

"/~s/Access-Control-Allow-Origin/*",

306

"/~s/Access-Control-Allow-Methods/GET,POST,PUT,DELETE,OPTIONS",

307

"/~s/Access-Control-Allow-Headers/Content-Type,Authorization"

308

]

309

310

return opts

311

312

def setup_security_testing():

313

"""Configuration for security testing and analysis."""

314

opts = options.Options()

315

316

# Security testing configuration

317

opts.listen_port = 8080

318

opts.ssl_insecure = True # Allow invalid certificates

319

320

# Save all flows for analysis

321

opts.save_stream_file = "security_test_flows.mitm"

322

323

# Enable detailed logging

324

opts.verbosity = 2

325

326

# Don't ignore any hosts

327

opts.ignore_hosts = []

328

329

# Intercept all HTTPS traffic

330

opts.intercept = "~secure"

331

332

# Add security headers for testing

333

opts.modify_headers = [

334

"/~s/X-Security-Test/enabled"

335

]

336

337

return opts

338

```

339

340

### Dynamic Configuration Updates

341

342

```python

343

from mitmproxy import options

344

import threading

345

import time

346

347

class ConfigurationManager:

348

"""Manages dynamic configuration updates."""

349

350

def __init__(self, initial_opts=None):

351

self.opts = initial_opts or options.Options()

352

self.lock = threading.Lock()

353

354

def update_proxy_mode(self, new_mode):

355

"""Dynamically update proxy mode."""

356

with self.lock:

357

old_mode = self.opts.mode

358

self.opts.mode = new_mode

359

print(f"Proxy mode changed from {old_mode} to {new_mode}")

360

361

def toggle_interception(self, pattern=None):

362

"""Toggle request interception on/off."""

363

with self.lock:

364

if self.opts.intercept:

365

# Turn off interception

366

old_pattern = self.opts.intercept

367

self.opts.intercept = None

368

print(f"Interception disabled (was: {old_pattern})")

369

else:

370

# Turn on interception

371

self.opts.intercept = pattern or "~all"

372

print(f"Interception enabled: {self.opts.intercept}")

373

374

def add_ignore_host(self, host_pattern):

375

"""Add host to ignore list."""

376

with self.lock:

377

if host_pattern not in self.opts.ignore_hosts:

378

self.opts.ignore_hosts.append(host_pattern)

379

print(f"Added {host_pattern} to ignore list")

380

381

def remove_ignore_host(self, host_pattern):

382

"""Remove host from ignore list."""

383

with self.lock:

384

if host_pattern in self.opts.ignore_hosts:

385

self.opts.ignore_hosts.remove(host_pattern)

386

print(f"Removed {host_pattern} from ignore list")

387

388

def update_upstream_proxy(self, upstream_url):

389

"""Update upstream proxy configuration."""

390

with self.lock:

391

if upstream_url:

392

self.opts.mode = f"upstream:{upstream_url}"

393

print(f"Upstream proxy set to: {upstream_url}")

394

else:

395

self.opts.mode = "regular"

396

print("Upstream proxy disabled")

397

398

# Usage example

399

config_manager = ConfigurationManager()

400

401

# Dynamic updates

402

config_manager.update_proxy_mode("transparent")

403

config_manager.toggle_interception("~u /api/")

404

config_manager.add_ignore_host("*.cdn.com")

405

```

406

407

### Configuration Validation

408

409

```python

410

from mitmproxy import options

411

from mitmproxy.exceptions import OptionsError

412

413

def validate_proxy_configuration(opts):

414

"""Validate proxy configuration for common issues."""

415

issues = []

416

417

# Check port conflicts

418

if opts.listen_port == opts.web_port:

419

issues.append("Proxy and web interface ports cannot be the same")

420

421

# Validate mode-specific settings

422

if opts.mode.startswith("reverse:"):

423

upstream_url = opts.mode.split(":", 1)[1]

424

if not upstream_url.startswith(("http://", "https://")):

425

issues.append("Reverse proxy upstream must be a valid URL")

426

427

# Check certificate paths

428

for cert_spec in opts.certs:

429

if "=" in cert_spec:

430

domain, cert_path = cert_spec.split("=", 1)

431

if not os.path.exists(cert_path):

432

issues.append(f"Certificate file not found: {cert_path}")

433

434

# Validate TLS settings

435

if opts.ssl_insecure and not opts.upstream_cert:

436

issues.append("ssl_insecure=True with upstream_cert=False may cause issues")

437

438

# Check host patterns

439

for pattern in opts.allow_hosts + opts.ignore_hosts:

440

if not pattern:

441

issues.append("Empty host pattern found")

442

443

return issues

444

445

def apply_safe_configuration(opts):

446

"""Apply configuration with validation and error handling."""

447

try:

448

# Validate configuration

449

issues = validate_proxy_configuration(opts)

450

451

if issues:

452

print("Configuration issues found:")

453

for issue in issues:

454

print(f" - {issue}")

455

456

response = input("Continue anyway? (y/N): ")

457

if response.lower() != 'y':

458

return False

459

460

# Apply configuration (this would typically be done by the master)

461

print("Configuration applied successfully")

462

return True

463

464

except OptionsError as e:

465

print(f"Configuration error: {e}")

466

return False

467

except Exception as e:

468

print(f"Unexpected error applying configuration: {e}")

469

return False

470

471

# Usage

472

opts = options.Options()

473

opts.listen_port = 8080

474

opts.web_port = 8081

475

opts.mode = "reverse:https://api.example.com"

476

477

if apply_safe_configuration(opts):

478

print("Proxy configured and ready")

479

else:

480

print("Configuration failed")

481

```