-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapproval_server.py
More file actions
executable file
·708 lines (575 loc) · 21 KB
/
approval_server.py
File metadata and controls
executable file
·708 lines (575 loc) · 21 KB
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
#!/usr/bin/env python3
"""
PAM SSH 2FA - Approval Server
=============================
A lightweight HTTP server that handles link-based authentication approvals.
Users click an approval link in their push notification instead of typing a code.
OVERVIEW
--------
When a user authenticates via SSH with auth_method=link or auth_method=both:
1. PAM module creates an approval request file with a unique token
2. PAM sends notification containing approval link
3. User clicks link on their phone
4. This server marks the approval as granted
5. PAM module detects approval and grants SSH access
INSTALLATION
------------
This server runs as a systemd service. Install with:
sudo ./install.sh
Or manually:
sudo cp approval_server.py /etc/pam-ssh-2fa/
sudo cp pam-ssh-2fa-server.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable pam-ssh-2fa-server
sudo systemctl start pam-ssh-2fa-server
CONFIGURATION
-------------
Server settings are in /etc/pam-ssh-2fa/config.ini under [server]:
port = 9110
url = http://your-server.example.com:9110
The 'url' is what appears in notification links. It must be reachable
from the user's phone (public IP, hostname, or Tailscale address).
SECURITY CONSIDERATIONS
-----------------------
- Tokens are cryptographically random and single-use
- Approvals expire after the configured timeout (default 5 minutes)
- Server binds to 0.0.0.0 by default (all interfaces)
- Consider firewall rules to limit access if needed
- For production, consider adding HTTPS via reverse proxy
ENDPOINTS
---------
GET /approve/<token> - Approve an authentication request
GET /health - Health check endpoint
AUTHOR
------
Generated by Claude (Anthropic) for SSH 2FA push notification authentication.
LICENSE
-------
MIT License - Use and modify freely.
"""
# =============================================================================
# IMPORTS
# =============================================================================
import os
import sys
import json
import time
import logging
import argparse
import configparser
from pathlib import Path
from datetime import datetime, timezone
from typing import Optional, Tuple
# Use built-in http.server for minimal dependencies
# No Flask required - keeps it simple and dependency-free
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import threading
# =============================================================================
# CONFIGURATION
# =============================================================================
# Default paths
DEFAULT_CONFIG_FILE = "/etc/pam-ssh-2fa/config.ini"
DEFAULT_APPROVALS_DIR = "/var/run/pam-ssh-2fa/approvals"
DEFAULT_PORT = 9110
DEFAULT_BIND_ADDRESS = "0.0.0.0"
# HTML templates (minimal, accessible)
HTML_SUCCESS = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSH Access Approved</title>
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
text-align: center;
}}
.success {{
color: #22863a;
font-size: 24px;
margin-bottom: 20px;
}}
.details {{
color: #666;
margin-top: 20px;
}}
</style>
</head>
<body>
<div class="success">[OK] Access Approved</div>
<p>SSH authentication for <strong>{user}</strong> has been approved.</p>
<p>You can close this page and return to your terminal.</p>
<div class="details">
<p>Host: {host}</p>
<p>From: {rhost}</p>
<p>Time: {time}</p>
</div>
</body>
</html>
"""
HTML_ERROR = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSH Approval Error</title>
<style>
body {{
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
text-align: center;
}}
.error {{
color: #cb2431;
font-size: 24px;
margin-bottom: 20px;
}}
</style>
</head>
<body>
<div class="error">[ERROR] {title}</div>
<p>{message}</p>
</body>
</html>
"""
HTML_HEALTH = """{"status": "ok", "timestamp": "{timestamp}"}"""
# =============================================================================
# LOGGING SETUP
# =============================================================================
def setup_logging(debug: bool = False, log_file: Optional[str] = None):
"""
Configure logging for the approval server.
Args:
debug: Enable debug level logging
log_file: Optional path to log file (also logs to stdout)
"""
level = logging.DEBUG if debug else logging.INFO
format_str = "%(asctime)s [%(levelname)s] %(message)s"
handlers = [logging.StreamHandler(sys.stdout)]
if log_file:
try:
log_dir = os.path.dirname(log_file)
if log_dir and not os.path.exists(log_dir):
os.makedirs(log_dir, mode=0o750)
handlers.append(logging.FileHandler(log_file))
except OSError as e:
print(f"Warning: Could not create log file: {e}")
logging.basicConfig(level=level, format=format_str, handlers=handlers)
# =============================================================================
# CONFIGURATION LOADER
# =============================================================================
class ServerConfig:
"""
Configuration manager for the approval server.
Loads settings from the main PAM 2FA config file.
Attributes:
port (int): Port to listen on
bind_address (str): Address to bind to (default 0.0.0.0)
approvals_dir (str): Directory for approval request files
debug (bool): Enable debug logging
log_file (str): Path to log file
"""
def __init__(self, config_file: str = DEFAULT_CONFIG_FILE):
"""
Initialize server configuration.
Args:
config_file: Path to the main config.ini file
"""
self.port = DEFAULT_PORT
self.bind_address = DEFAULT_BIND_ADDRESS
self.approvals_dir = DEFAULT_APPROVALS_DIR
self.debug = False
self.log_file = "/var/log/pam-ssh-2fa-server.log"
self._load_config(config_file)
def _load_config(self, config_file: str):
"""Load configuration from INI file."""
if not os.path.exists(config_file):
return
parser = configparser.ConfigParser()
try:
parser.read(config_file)
except configparser.Error:
return
# Server settings
if parser.has_option("server", "port"):
try:
self.port = int(parser.get("server", "port"))
except ValueError:
pass
if parser.has_option("server", "bind_address"):
self.bind_address = parser.get("server", "bind_address")
# General settings
if parser.has_option("general", "debug"):
self.debug = parser.get("general", "debug").lower() in ("true", "yes", "1")
if parser.has_option("server", "log_file"):
self.log_file = parser.get("server", "log_file")
# Approvals directory (derived from code storage dir)
if parser.has_option("codes", "storage_dir"):
storage_dir = parser.get("codes", "storage_dir")
self.approvals_dir = os.path.join(storage_dir, "approvals")
# =============================================================================
# APPROVAL MANAGER
# =============================================================================
class ApprovalManager:
"""
Manages approval request files.
Approval files are JSON with structure:
{
"token": "abc123...",
"user": "username",
"rhost": "192.168.1.1",
"host": "servername",
"created": 1234567890.123,
"expires": 1234567890.123,
"approved": false,
"approved_at": null
}
Attributes:
approvals_dir (str): Directory containing approval files
"""
def __init__(self, approvals_dir: str):
"""
Initialize the approval manager.
Args:
approvals_dir: Directory for approval request files
"""
self.approvals_dir = approvals_dir
self._ensure_dir()
def _ensure_dir(self):
"""Create approvals directory if it doesn't exist."""
if not os.path.exists(self.approvals_dir):
try:
os.makedirs(self.approvals_dir, mode=0o700)
except OSError:
pass
def get_approval_file(self, token: str) -> str:
"""
Get the path to an approval file by token.
Args:
token: The approval token
Returns:
Full path to the approval file
"""
# Sanitize token to prevent directory traversal
safe_token = "".join(c for c in token if c.isalnum())
return os.path.join(self.approvals_dir, f"{safe_token}.json")
def get_approval(self, token: str) -> Optional[dict]:
"""
Load an approval request by token.
Args:
token: The approval token
Returns:
Approval data dict, or None if not found/invalid
"""
filepath = self.get_approval_file(token)
if not os.path.exists(filepath):
return None
try:
with open(filepath, "r") as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
return None
def mark_approved(self, token: str) -> Tuple[bool, Optional[dict]]:
"""
Mark an approval request as approved.
Args:
token: The approval token
Returns:
Tuple of (success, approval_data)
- success: True if approval was successful
- approval_data: The approval data dict (for display)
"""
approval = self.get_approval(token)
if approval is None:
logging.warning(f"Approval not found: {token[:8]}...")
return False, None
# Check if already approved
if approval.get("approved"):
logging.info(f"Approval already granted: {token[:8]}...")
return True, approval
# Check if expired
if time.time() > approval.get("expires", 0):
logging.warning(f"Approval expired: {token[:8]}...")
return False, None
# Mark as approved
approval["approved"] = True
approval["approved_at"] = time.time()
# Write back
filepath = self.get_approval_file(token)
try:
with open(filepath, "w") as f:
json.dump(approval, f)
logging.info(
f"Approval granted: user={approval.get('user')}, "
f"rhost={approval.get('rhost')}, token={token[:8]}..."
)
return True, approval
except IOError as e:
logging.error(f"Failed to write approval: {e}")
return False, None
def cleanup_expired(self):
"""Remove expired approval files."""
if not os.path.exists(self.approvals_dir):
return
now = time.time()
cleaned = 0
for filename in os.listdir(self.approvals_dir):
if not filename.endswith(".json"):
continue
filepath = os.path.join(self.approvals_dir, filename)
try:
with open(filepath, "r") as f:
data = json.load(f)
if now > data.get("expires", 0):
os.unlink(filepath)
cleaned += 1
except (json.JSONDecodeError, IOError, OSError):
# Remove corrupt files
try:
os.unlink(filepath)
cleaned += 1
except OSError:
pass
if cleaned > 0:
logging.debug(f"Cleaned up {cleaned} expired approval(s)")
# =============================================================================
# HTTP REQUEST HANDLER
# =============================================================================
class ApprovalRequestHandler(BaseHTTPRequestHandler):
"""
HTTP request handler for approval endpoints.
Endpoints:
GET /approve/<token> - Approve an authentication request
GET /health - Health check
The handler accesses the ApprovalManager via server.approval_manager.
"""
# Suppress default logging (we do our own)
def log_message(self, format, *args):
logging.debug(f"HTTP: {args[0]}")
def _send_html(self, status: int, html: str):
"""Send an HTML response."""
self.send_response(status)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(html.encode("utf-8"))
def _send_json(self, status: int, data: str):
"""Send a JSON response."""
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(data.encode("utf-8"))
def do_GET(self):
"""Handle GET requests."""
parsed = urlparse(self.path)
path = parsed.path
# Health check endpoint
if path == "/health":
self._handle_health()
return
# Approval endpoint: /approve/<token>
if path.startswith("/approve/"):
token = path[9:] # Remove "/approve/" prefix
self._handle_approve(token)
return
# Root path - simple info
if path == "/":
self._handle_root()
return
# 404 for anything else
self._send_html(
404,
HTML_ERROR.format(
title="Not Found", message="The requested page was not found."
),
)
def _handle_root(self):
"""Handle requests to root path."""
html = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PAM SSH 2FA Approval Server</title>
</head>
<body>
<h1>PAM SSH 2FA Approval Server</h1>
<p>This server handles SSH authentication approvals.</p>
<p>Approval links are sent via push notification.</p>
</body>
</html>"""
self._send_html(200, html)
def _handle_health(self):
"""Handle health check requests."""
timestamp = datetime.now(timezone.utc).isoformat()
self._send_json(200, HTML_HEALTH.format(timestamp=timestamp))
def _handle_approve(self, token: str):
"""
Handle approval requests.
Args:
token: The approval token from the URL
"""
if not token:
self._send_html(
400,
HTML_ERROR.format(
title="Invalid Request", message="No approval token provided."
),
)
return
# Get the approval manager from the server
manager = self.server.approval_manager
# Attempt to mark as approved
success, approval = manager.mark_approved(token)
if success and approval:
# Format the response with approval details
approved_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self._send_html(
200,
HTML_SUCCESS.format(
user=approval.get("user", "unknown"),
host=approval.get("host", "unknown"),
rhost=approval.get("rhost", "unknown"),
time=approved_time,
),
)
else:
# Check why it failed
approval_data = manager.get_approval(token)
if approval_data is None:
self._send_html(
404,
HTML_ERROR.format(
title="Invalid Link",
message="This approval link is invalid or has already been used.",
),
)
elif time.time() > approval_data.get("expires", 0):
self._send_html(
410,
HTML_ERROR.format(
title="Link Expired",
message="This approval link has expired. Please try connecting again.",
),
)
else:
self._send_html(
500,
HTML_ERROR.format(
title="Server Error",
message="An error occurred processing your request. Please try again.",
),
)
# =============================================================================
# APPROVAL SERVER
# =============================================================================
class ApprovalServer(HTTPServer):
"""
HTTP server for handling approval requests.
Extends HTTPServer to include the ApprovalManager instance.
"""
def __init__(self, bind_address: str, port: int, approval_manager: ApprovalManager):
"""
Initialize the approval server.
Args:
bind_address: Address to bind to (e.g., "0.0.0.0")
port: Port to listen on
approval_manager: ApprovalManager instance for handling approvals
"""
super().__init__((bind_address, port), ApprovalRequestHandler)
self.approval_manager = approval_manager
# =============================================================================
# CLEANUP THREAD
# =============================================================================
class CleanupThread(threading.Thread):
"""
Background thread that periodically cleans up expired approvals.
Runs every 60 seconds to remove expired approval files.
"""
def __init__(self, approval_manager: ApprovalManager):
super().__init__(daemon=True)
self.approval_manager = approval_manager
self.running = True
def run(self):
"""Run the cleanup loop."""
while self.running:
try:
self.approval_manager.cleanup_expired()
except Exception as e:
logging.error(f"Cleanup error: {e}")
# Sleep for 60 seconds, checking for stop every second
for _ in range(60):
if not self.running:
break
time.sleep(1)
def stop(self):
"""Stop the cleanup thread."""
self.running = False
# =============================================================================
# MAIN
# =============================================================================
def main():
"""Main entry point for the approval server."""
parser = argparse.ArgumentParser(
description="PAM SSH 2FA Approval Server",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
This server handles link-based SSH authentication approvals.
Run as a systemd service for production use.
Examples:
%(prog)s Run with default settings
%(prog)s --port 9110 Run on specific port
%(prog)s --debug Enable debug logging
""",
)
parser.add_argument(
"--config",
"-c",
default=DEFAULT_CONFIG_FILE,
help=f"Path to config file (default: {DEFAULT_CONFIG_FILE})",
)
parser.add_argument(
"--port", "-p", type=int, help="Port to listen on (overrides config file)"
)
parser.add_argument("--bind", "-b", help="Address to bind to (default: 0.0.0.0)")
parser.add_argument(
"--debug", "-d", action="store_true", help="Enable debug logging"
)
args = parser.parse_args()
# Load configuration
config = ServerConfig(args.config)
# Command line overrides
if args.port:
config.port = args.port
if args.bind:
config.bind_address = args.bind
if args.debug:
config.debug = True
# Setup logging
setup_logging(debug=config.debug, log_file=config.log_file)
# Create approval manager
approval_manager = ApprovalManager(config.approvals_dir)
# Start cleanup thread
cleanup_thread = CleanupThread(approval_manager)
cleanup_thread.start()
# Create and start server
server = ApprovalServer(config.bind_address, config.port, approval_manager)
logging.info(f"PAM SSH 2FA Approval Server starting")
logging.info(f"Listening on {config.bind_address}:{config.port}")
logging.info(f"Approvals directory: {config.approvals_dir}")
try:
server.serve_forever()
except KeyboardInterrupt:
logging.info("Shutting down...")
finally:
cleanup_thread.stop()
server.shutdown()
logging.info("Server stopped")
if __name__ == "__main__":
main()