-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpam_ssh_2fa.py
More file actions
executable file
·2076 lines (1710 loc) · 69 KB
/
pam_ssh_2fa.py
File metadata and controls
executable file
·2076 lines (1710 loc) · 69 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
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
PAM SSH 2FA Module - Push Notification One-Time Password Authentication
========================================================================
This module provides two-factor authentication for SSH by generating a
random 4-digit code, sending it via push notification (using Apprise),
and prompting the user to enter the code.
OVERVIEW
--------
When a user attempts to authenticate via SSH, this module:
1. Generates a cryptographically secure 4-digit code
2. Sends that code to the user via configured notification service(s)
3. Prompts the user to enter the received code
4. Validates the entered code against the generated one
5. Allows or denies authentication based on the result
INSTALLATION
------------
This module requires:
- libpam-python (provides pam_python.so)
- apprise (Python library for notifications)
- Python 3.6+
Install via the provided install.sh script or manually:
apt install libpam-python python3-pip
pip3 install apprise --break-system-packages
CONFIGURATION
-------------
Configuration is stored in /etc/pam-ssh-2fa/config.ini
See config.ini for all available options.
PAM CONFIGURATION
-----------------
Add to /etc/pam.d/sshd (after @include common-auth or as needed):
auth required pam_python.so /etc/pam-ssh-2fa/pam_ssh_2fa.py
SSH CONFIGURATION
-----------------
In /etc/ssh/sshd_config:
UsePAM yes
KbdInteractiveAuthentication yes
AuthenticationMethods publickey,keyboard-interactive:pam
DEBUGGING
---------
- Set debug = true in config.ini to enable verbose logging
- Logs go to the configured log_file (default: /var/log/pam-ssh-2fa.log)
- Also logs to syslog under the AUTH facility
- Test with: pamtester sshd <username> authenticate
SECURITY CONSIDERATIONS
-----------------------
- Codes expire after a configurable timeout (default: 5 minutes)
- Codes are single-use and invalidated after successful authentication
- Failed attempts are logged with source IP
- Code storage uses secure file permissions (0600)
- Consider rate limiting at the firewall level for brute force protection
AUTHOR
------
Generated by Claude (Anthropic) for SSH 2FA push notification authentication.
LICENSE
-------
MIT License - Use and modify freely.
VERSION
-------
1.0.0 - Initial release
"""
# =============================================================================
# IMPORTS
# =============================================================================
import os
import sys
import time
import secrets
import configparser
import logging
import json
import hashlib
from pathlib import Path
from datetime import datetime, timedelta
from typing import Optional, Tuple, Dict, Any
# Apprise is imported conditionally to provide better error messages
# if it's not installed
try:
import apprise
APPRISE_AVAILABLE = True
except ImportError:
APPRISE_AVAILABLE = False
# =============================================================================
# CONSTANTS
# =============================================================================
# Default configuration file location
CONFIG_FILE = "/etc/pam-ssh-2fa/config.ini"
# Default values if config file is missing or incomplete
DEFAULTS = {
"code_length": 4, # Length of the OTP code
"code_timeout": 300, # Seconds before code expires (5 minutes)
"max_attempts": 3, # Maximum entry attempts before failure
"debug": False, # Enable debug logging
"log_file": "/var/log/pam-ssh-2fa.log",
"code_storage_dir": "/var/run/pam-ssh-2fa",
"apprise_urls": "", # Comma-separated Apprise notification URLs
"notification_title": "SSH Login Code",
"notification_body": "Your SSH verification code is: {code}\n\nHost: {host}\nUser: {user}\nFrom: {rhost}\n\nThis code expires in {timeout} minutes.",
"notification_body_link": "Click to approve SSH login:\n{link}\n\nHost: {host}\nUser: {user}\nFrom: {rhost}\n\nThis link expires in {timeout} minutes.",
"notification_body_both": "SSH Login for {user}@{host}\n\nClick to approve:\n{link}\n\nOr enter code: {code}\n\nFrom: {rhost}\nExpires in {timeout} minutes.",
"prompt_message": "Enter verification code: ",
"prompt_message_both": "Enter code OR press Enter after clicking link: ",
"success_message": "Verification successful.",
"failure_message": "Verification failed.",
"expired_message": "Code expired. Please reconnect to receive a new code.",
"bypass_users": "", # Comma-separated list of users to skip 2FA
"bypass_networks": "", # Comma-separated CIDR ranges to skip 2FA
"allow_unconfigured_users": False, # If True, users without config bypass 2FA
"auth_method": "code", # Default auth method: code, link, both, none
"server_port": 9110, # Approval server port
"server_url": "", # Approval server URL (e.g., http://myserver.com:9110)
}
# PAM return codes (defined here for clarity)
PAM_SUCCESS = 0
PAM_AUTH_ERR = 7
PAM_CRED_INSUFFICIENT = 8
PAM_AUTHINFO_UNAVAIL = 9
PAM_USER_UNKNOWN = 10
PAM_MAXTRIES = 11
PAM_IGNORE = 25
# =============================================================================
# LOGGING SETUP
# =============================================================================
class PAMLogger:
"""
Custom logger for PAM module that writes to both file and syslog.
This class provides a unified logging interface that:
- Writes to a dedicated log file for easy debugging
- Also logs to syslog for system integration
- Supports debug mode for verbose output
- Sanitizes sensitive data before logging
Attributes:
log_file (str): Path to the log file
debug (bool): Whether debug logging is enabled
logger (logging.Logger): The underlying Python logger instance
Usage:
logger = PAMLogger("/var/log/pam-ssh-2fa.log", debug=True)
logger.info("User authenticated", user="john", rhost="192.168.1.1")
logger.debug("Code generated", code_hash="abc123") # Only if debug=True
"""
def __init__(self, log_file: str, debug: bool = False):
"""
Initialize the PAM logger.
Args:
log_file: Path to the log file. Directory will be created if needed.
debug: If True, DEBUG level messages will be logged.
"""
self.log_file = log_file
self.debug = debug
self.logger = logging.getLogger("pam-ssh-2fa")
self.logger.setLevel(logging.DEBUG if debug else logging.INFO)
# Clear any existing handlers to avoid duplicates on module reload
self.logger.handlers.clear()
# Create log directory if it doesn't exist
log_dir = os.path.dirname(log_file)
if log_dir and not os.path.exists(log_dir):
try:
os.makedirs(log_dir, mode=0o750)
except OSError:
pass # Fall back to syslog only
# File handler with detailed format
try:
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(
logging.Formatter(
"%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
)
self.logger.addHandler(file_handler)
except (OSError, IOError):
pass # Fall back to syslog only
# Syslog handler for system integration
try:
from logging.handlers import SysLogHandler
syslog_handler = SysLogHandler(
address="/dev/log", facility=SysLogHandler.LOG_AUTH
)
syslog_handler.setFormatter(logging.Formatter("pam-ssh-2fa: %(message)s"))
self.logger.addHandler(syslog_handler)
except (OSError, IOError):
pass # Syslog not available
def _format_message(self, message: str, **kwargs) -> str:
"""
Format a log message with additional context.
Args:
message: The main log message
**kwargs: Additional key-value pairs to include
Returns:
Formatted message string with context appended
"""
if kwargs:
context = " | ".join(f"{k}={v}" for k, v in kwargs.items())
return f"{message} | {context}"
return message
def info(self, message: str, **kwargs):
"""Log an INFO level message."""
self.logger.info(self._format_message(message, **kwargs))
def warning(self, message: str, **kwargs):
"""Log a WARNING level message."""
self.logger.warning(self._format_message(message, **kwargs))
def error(self, message: str, **kwargs):
"""Log an ERROR level message."""
self.logger.error(self._format_message(message, **kwargs))
def debug(self, message: str, **kwargs):
"""Log a DEBUG level message (only if debug mode is enabled)."""
if self.debug:
self.logger.debug(self._format_message(message, **kwargs))
# =============================================================================
# CONFIGURATION MANAGEMENT
# =============================================================================
class Config:
"""
Configuration manager for the PAM 2FA module.
Loads configuration from an INI file and provides access to settings
with sensible defaults. Configuration is validated on load.
Supports per-user configuration files for notification settings,
allowing different users to receive codes via different services.
Configuration hierarchy (highest priority first):
1. Per-user config: /etc/pam-ssh-2fa/users/<username>.conf
2. Global config: /etc/pam-ssh-2fa/config.ini
3. Built-in defaults
The configuration file uses standard INI format:
[general]
debug = false
log_file = /var/log/pam-ssh-2fa.log
[codes]
length = 4
timeout = 300
[notifications]
apprise_urls = ntfy://ntfy.sh/my-topic,pover://...
Per-user config files only need the [notifications] section:
# /etc/pam-ssh-2fa/users/doug.conf
[notifications]
apprise_urls = pover://DOUG_USER_KEY@APP_TOKEN
Attributes:
config_file (str): Path to the main configuration file
user_config_dir (str): Path to per-user config directory
settings (dict): Parsed configuration settings
Usage:
config = Config("/etc/pam-ssh-2fa/config.ini")
timeout = config.get("code_timeout", 300)
urls = config.get_list("apprise_urls")
# Get user-specific config
user_config = config.get_user_config("doug")
doug_urls = user_config.get_list("apprise_urls")
"""
def __init__(self, config_file: str = CONFIG_FILE, user: str = None):
"""
Initialize configuration from file.
Args:
config_file: Path to the INI configuration file.
If file doesn't exist, defaults are used.
user: Optional username to load user-specific overrides.
"""
self.config_file = config_file
self.user = user
self.settings = DEFAULTS.copy()
# Derive user config directory from main config file location
config_dir = os.path.dirname(config_file) or "/etc/pam-ssh-2fa"
self.user_config_dir = os.path.join(config_dir, "users")
# Load global config first
self._load_config()
# Then overlay user-specific config if user provided
if user:
self._load_user_config(user)
def _load_config(self):
"""
Load and parse the main configuration file.
Reads the INI file and maps sections/keys to flat settings dict.
Missing values use defaults. Invalid values are logged and skipped.
"""
if not os.path.exists(self.config_file):
return # Use defaults
self._parse_config_file(self.config_file)
def _load_user_config(self, user: str):
"""
Load user-specific configuration overrides.
Looks for a config file named after the user in the users/ directory.
User config only overrides notification settings, not system settings.
Args:
user: Username to load config for
"""
# Sanitize username to prevent directory traversal
safe_user = "".join(c for c in user if c.isalnum() or c in "-_.")
if not safe_user or safe_user != user:
return # Invalid username, skip user config
# Try multiple file extensions
for ext in [".conf", ".ini", ""]:
user_config_file = os.path.join(self.user_config_dir, f"{safe_user}{ext}")
if os.path.exists(user_config_file):
self._parse_config_file(user_config_file, user_only=True)
return
def _parse_config_file(self, filepath: str, user_only: bool = False):
"""
Parse a configuration file and update settings.
Args:
filepath: Path to the config file
user_only: If True, only load user-customizable settings
(notifications section). This prevents users from
overriding system-wide security settings.
"""
parser = configparser.ConfigParser()
try:
parser.read(filepath)
except configparser.Error:
return # Skip on parse error
# Full mapping for system config
section_mapping = {
("general", "debug"): ("debug", self._parse_bool),
("general", "log_file"): ("log_file", str),
("codes", "length"): ("code_length", int),
("codes", "timeout"): ("code_timeout", int),
("codes", "max_attempts"): ("max_attempts", int),
("codes", "storage_dir"): ("code_storage_dir", str),
("notifications", "apprise_urls"): ("apprise_urls", str),
("notifications", "title"): ("notification_title", str),
("notifications", "body"): ("notification_body", str),
("notifications", "body_link"): ("notification_body_link", str),
("notifications", "body_both"): ("notification_body_both", str),
("messages", "prompt"): ("prompt_message", str),
("messages", "prompt_both"): ("prompt_message_both", str),
("messages", "success"): ("success_message", str),
("messages", "failure"): ("failure_message", str),
("messages", "expired"): ("expired_message", str),
("bypass", "users"): ("bypass_users", str),
("bypass", "networks"): ("bypass_networks", str),
("users", "allow_unconfigured_users"): (
"allow_unconfigured_users",
self._parse_bool,
),
("users", "auth_method"): ("auth_method", str),
("server", "port"): ("server_port", int),
("server", "url"): ("server_url", str),
}
# User configs can only override notification settings
# This prevents privilege escalation via user config files
if user_only:
section_mapping = {
("notifications", "apprise_urls"): ("apprise_urls", str),
("notifications", "title"): ("notification_title", str),
("notifications", "body"): ("notification_body", str),
("notifications", "body_link"): ("notification_body_link", str),
("notifications", "body_both"): ("notification_body_both", str),
("auth", "method"): ("auth_method", str),
}
for (section, key), (setting_name, converter) in section_mapping.items():
if parser.has_option(section, key):
try:
raw_value = parser.get(section, key)
self.settings[setting_name] = converter(raw_value)
except (ValueError, TypeError):
pass # Keep default on conversion error
def _parse_bool(self, value: str) -> bool:
"""
Parse a string to boolean.
Args:
value: String like "true", "yes", "1", "false", "no", "0"
Returns:
Boolean interpretation of the string
"""
return value.lower() in ("true", "yes", "1", "on", "enabled")
def get(self, key: str, default: Any = None) -> Any:
"""
Get a configuration value.
Args:
key: The setting name
default: Value to return if key not found
Returns:
The configuration value or default
"""
return self.settings.get(key, default)
def get_list(self, key: str, separator: str = ",") -> list:
"""
Get a configuration value as a list.
Splits the string value by separator and strips whitespace.
Args:
key: The setting name
separator: Character to split on (default: comma)
Returns:
List of strings, empty list if key not found or empty
"""
value = self.settings.get(key, "")
if not value:
return []
return [item.strip() for item in value.split(separator) if item.strip()]
def get_user_config(self, user: str) -> "Config":
"""
Get a new Config instance with user-specific overrides applied.
This is useful when you need to get settings for a specific user
after already loading the global config.
Args:
user: Username to load config for
Returns:
New Config instance with user overrides applied
"""
return Config(self.config_file, user=user)
def has_user_config(self, user: str) -> bool:
"""
Check if a user-specific configuration file exists.
Args:
user: Username to check
Returns:
True if user has a config file
"""
safe_user = "".join(c for c in user if c.isalnum() or c in "-_.")
if not safe_user or safe_user != user:
return False
for ext in [".conf", ".ini", ""]:
user_config_file = os.path.join(self.user_config_dir, f"{safe_user}{ext}")
if os.path.exists(user_config_file):
return True
return False
# =============================================================================
# CODE GENERATION AND STORAGE
# =============================================================================
class CodeManager:
"""
Manages generation, storage, and validation of one-time codes.
Codes are stored in individual files named by a hash of the username
and session info. This allows multiple pending codes for different
sessions while preventing enumeration of usernames.
File format is JSON with:
- code: The plaintext OTP code
- created: Unix timestamp of creation
- expires: Unix timestamp of expiration
- user: Username for verification
- rhost: Remote host IP
- attempts: Number of validation attempts made
Security features:
- Codes stored with 0600 permissions
- Storage directory has 0700 permissions
- Codes automatically expire
- Codes are deleted after successful use
- Failed attempts are tracked and limited
Attributes:
storage_dir (str): Directory for code storage files
code_length (int): Length of generated codes
timeout (int): Seconds until code expiration
max_attempts (int): Maximum validation attempts allowed
logger (PAMLogger): Logger instance for debugging
Usage:
manager = CodeManager("/var/run/pam-ssh-2fa", logger=logger)
code = manager.generate("john", "192.168.1.1")
is_valid = manager.validate("john", "192.168.1.1", "1234")
"""
def __init__(
self,
storage_dir: str,
code_length: int = 4,
timeout: int = 300,
max_attempts: int = 3,
logger: Optional[PAMLogger] = None,
):
"""
Initialize the code manager.
Args:
storage_dir: Directory to store code files
code_length: Number of digits in generated codes
timeout: Seconds until codes expire
max_attempts: Max validation attempts before lockout
logger: Optional logger for debug output
"""
self.storage_dir = storage_dir
self.code_length = code_length
self.timeout = timeout
self.max_attempts = max_attempts
self.logger = logger
# Ensure storage directory exists with secure permissions
self._ensure_storage_dir()
def _ensure_storage_dir(self):
"""
Create the storage directory if it doesn't exist.
Sets permissions to 0700 (owner read/write/execute only).
This prevents other users from accessing pending codes.
"""
if not os.path.exists(self.storage_dir):
try:
os.makedirs(self.storage_dir, mode=0o700)
except OSError as e:
if self.logger:
self.logger.error(f"Failed to create storage dir: {e}")
raise
else:
# Ensure correct permissions even if dir already exists
try:
os.chmod(self.storage_dir, 0o700)
except OSError:
pass
def _get_code_file(self, user: str, rhost: str) -> str:
"""
Get the path to the code file for a user/session.
Uses a hash of user and rhost to prevent username enumeration
while still allowing session-specific codes.
Args:
user: Username
rhost: Remote host IP address
Returns:
Full path to the code file
"""
# Create a hash of user+rhost for the filename
# This prevents enumeration of usernames from the filesystem
session_key = f"{user}:{rhost}"
file_hash = hashlib.sha256(session_key.encode()).hexdigest()[:16]
return os.path.join(self.storage_dir, f"code_{file_hash}.json")
def generate(self, user: str, rhost: str) -> str:
"""
Generate a new one-time code for a user session.
Creates a cryptographically secure random code and stores it
with metadata for later validation.
Args:
user: Username requesting authentication
rhost: Remote host IP address
Returns:
The generated code as a string (e.g., "1234")
Raises:
OSError: If unable to write the code file
"""
# Generate cryptographically secure random code
# Using secrets module for security-sensitive randomness
code = "".join(str(secrets.randbelow(10)) for _ in range(self.code_length))
# Calculate expiration time
now = time.time()
expires = now + self.timeout
# Prepare code data
code_data = {
"code": code,
"created": now,
"expires": expires,
"user": user,
"rhost": rhost,
"attempts": 0,
}
# Write to file with secure permissions
code_file = self._get_code_file(user, rhost)
# Create file with restricted permissions from the start
# Using os.open with mode flags to ensure atomic secure creation
fd = os.open(code_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
with os.fdopen(fd, "w") as f:
json.dump(code_data, f)
except Exception:
os.close(fd)
raise
if self.logger:
# Log code generation (hash the code for security in logs)
code_hash = hashlib.sha256(code.encode()).hexdigest()[:8]
self.logger.debug(
"Code generated",
user=user,
rhost=rhost,
code_hash=code_hash,
expires_in=f"{self.timeout}s",
)
return code
def validate(self, user: str, rhost: str, entered_code: str) -> Tuple[bool, str]:
"""
Validate an entered code against the stored code.
Checks if:
- A code exists for this user/session
- The code hasn't expired
- Maximum attempts haven't been exceeded
- The entered code matches
On successful validation, the code file is deleted.
On failure, the attempt counter is incremented.
Args:
user: Username
rhost: Remote host IP address
entered_code: The code entered by the user
Returns:
Tuple of (success: bool, message: str)
- success: True if code was valid
- message: Human-readable result message
"""
code_file = self._get_code_file(user, rhost)
# Check if code file exists
if not os.path.exists(code_file):
if self.logger:
self.logger.warning(
"No code found for validation", user=user, rhost=rhost
)
return False, "No pending code found. Please reconnect."
# Read and parse code data
try:
with open(code_file, "r") as f:
code_data = json.load(f)
except (json.JSONDecodeError, IOError) as e:
if self.logger:
self.logger.error(f"Failed to read code file: {e}")
self._cleanup_code(code_file)
return False, "Internal error. Please reconnect."
# Verify the code is for this user (defense in depth)
if code_data.get("user") != user:
if self.logger:
self.logger.warning(
"User mismatch in code validation",
expected=code_data.get("user"),
got=user,
)
return False, "Session mismatch. Please reconnect."
# Check if code has expired
if time.time() > code_data.get("expires", 0):
if self.logger:
self.logger.info("Code expired", user=user, rhost=rhost)
self._cleanup_code(code_file)
return False, "Code expired. Please reconnect to receive a new code."
# Check attempt count
attempts = code_data.get("attempts", 0)
if attempts >= self.max_attempts:
if self.logger:
self.logger.warning(
"Max attempts exceeded", user=user, rhost=rhost, attempts=attempts
)
self._cleanup_code(code_file)
return False, "Maximum attempts exceeded. Please reconnect."
# Validate the code using constant-time comparison
# This prevents timing attacks that could reveal code characters
stored_code = code_data.get("code", "")
if secrets.compare_digest(entered_code.strip(), stored_code):
# Success! Clean up the code file
if self.logger:
self.logger.info("Code validated successfully", user=user, rhost=rhost)
self._cleanup_code(code_file)
return True, "Verification successful."
# Invalid code - increment attempt counter
code_data["attempts"] = attempts + 1
remaining = self.max_attempts - code_data["attempts"]
try:
with open(code_file, "w") as f:
json.dump(code_data, f)
except IOError:
pass # Best effort to save attempts
if self.logger:
self.logger.warning(
"Invalid code entered",
user=user,
rhost=rhost,
attempts=code_data["attempts"],
remaining=remaining,
)
if remaining > 0:
return False, f"Invalid code. {remaining} attempts remaining."
else:
self._cleanup_code(code_file)
return False, "Invalid code. Maximum attempts exceeded."
def _cleanup_code(self, code_file: str):
"""
Securely remove a code file.
Args:
code_file: Path to the code file to remove
"""
try:
os.unlink(code_file)
except OSError:
pass # Best effort cleanup
def cleanup_expired(self):
"""
Remove all expired code files from storage.
This can be called periodically (e.g., via cron) to clean up
abandoned codes from interrupted sessions.
"""
if not os.path.exists(self.storage_dir):
return
now = time.time()
for filename in os.listdir(self.storage_dir):
if not filename.startswith("code_"):
continue
filepath = os.path.join(self.storage_dir, filename)
try:
with open(filepath, "r") as f:
code_data = json.load(f)
if now > code_data.get("expires", 0):
os.unlink(filepath)
if self.logger:
self.logger.debug(f"Cleaned up expired code: {filename}")
except (json.JSONDecodeError, IOError, OSError):
# Remove corrupt files
try:
os.unlink(filepath)
except OSError:
pass
# =============================================================================
# APPROVAL MANAGER (for link-based authentication)
# =============================================================================
class ApprovalManager:
"""
Manages link-based authentication approvals.
When auth_method is 'link' or 'both', this manager creates approval
request files that the approval server monitors. When a user clicks
the approval link, the server marks the file as approved.
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 for approval request files
timeout (int): Seconds until approval expires
server_url (str): Base URL for approval links
logger (PAMLogger): Optional logger for debugging
Usage:
manager = ApprovalManager(
approvals_dir="/var/run/pam-ssh-2fa/approvals",
timeout=300,
server_url="http://myserver.com:9110",
logger=logger
)
token, link = manager.create_approval("john", "192.168.1.1")
# Send link to user...
# Poll for approval:
while not manager.is_approved(token):
time.sleep(1)
"""
def __init__(
self,
approvals_dir: str,
timeout: int = 300,
server_url: str = "",
logger: Optional[PAMLogger] = None,
):
"""
Initialize the approval manager.
Args:
approvals_dir: Directory to store approval files
timeout: Seconds until approvals expire
server_url: Base URL for approval server (e.g., http://myserver:9110)
logger: Optional logger for debug output
"""
self.approvals_dir = approvals_dir
self.timeout = timeout
self.server_url = server_url.rstrip("/") if server_url else ""
self.logger = logger
# Ensure approvals directory exists
self._ensure_dir()
def _ensure_dir(self):
"""Create the 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 as e:
if self.logger:
self.logger.error(f"Failed to create approvals dir: {e}")
raise
else:
# Ensure correct permissions
try:
os.chmod(self.approvals_dir, 0o700)
except OSError:
pass
def _get_approval_file(self, token: str) -> str:
"""Get the path to an approval file by token."""
# Sanitize token to prevent directory traversal
safe_token = "".join(c for c in token if c.isalnum() or c in '-_')
return os.path.join(self.approvals_dir, f"{safe_token}.json")
def create_approval(self, user: str, rhost: str) -> Tuple[str, str]:
"""
Create a new approval request.
Args:
user: Username requesting authentication
rhost: Remote host IP address
Returns:
Tuple of (token, approval_link)
Raises:
OSError: If unable to write the approval file
ValueError: If server_url is not configured
"""
if not self.server_url:
raise ValueError("server_url not configured - cannot create approval links")
# Generate cryptographically secure random token
token = secrets.token_urlsafe(32)
# Get hostname
try:
hostname = os.uname().nodename
except (AttributeError, OSError):
hostname = "unknown"
# Calculate expiration
now = time.time()
expires = now + self.timeout
# Prepare approval data
approval_data = {
"token": token,
"user": user,
"rhost": rhost,
"host": hostname,
"created": now,
"expires": expires,
"approved": False,
"approved_at": None,
}
# Write to file with secure permissions
approval_file = self._get_approval_file(token)
fd = os.open(approval_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
with os.fdopen(fd, "w") as f:
json.dump(approval_data, f)
except Exception:
os.close(fd)
raise
# Construct approval link
approval_link = f"{self.server_url}/approve/{token}"
if self.logger:
self.logger.debug(
"Approval request created",
user=user,
rhost=rhost,
token=token[:8] + "...",
expires_in=f"{self.timeout}s",
)
return token, approval_link
def is_approved(self, token: str) -> bool:
"""
Check if an approval has been granted.
Args:
token: The approval token
Returns:
True if approved, False otherwise
"""
approval_file = self._get_approval_file(token)
if not os.path.exists(approval_file):
return False