-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_notify.py
More file actions
executable file
·317 lines (257 loc) · 9.53 KB
/
test_notify.py
File metadata and controls
executable file
·317 lines (257 loc) · 9.53 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
#!/usr/bin/env python3
"""
PAM SSH 2FA - Notification Test Utility
=======================================
This utility allows you to test notification delivery without going through
the full PAM authentication flow. Use it to verify your Apprise URLs are
correct before enabling the PAM module.
USAGE:
./test_notify.py # Use global config URLs
./test_notify.py --user doug # Test doug's personal config
./test_notify.py --url "ntfy://..." # Test a specific URL
./test_notify.py --list-services # Show supported services
EXAMPLES:
# Test with your configured URLs
sudo ./test_notify.py
# Test a specific user's configuration
sudo ./test_notify.py --user doug
# Test a specific ntfy topic
./test_notify.py --url "ntfy://ntfy.sh/my-topic"
# Test Pushover
./test_notify.py --url "pover://USERKEY@APPTOKEN"
# Test multiple URLs
./test_notify.py --url "ntfy://ntfy.sh/topic1" --url "pover://user@token"
"""
import argparse
import sys
import os
import configparser
# Try to import apprise
try:
import apprise
APPRISE_AVAILABLE = True
except ImportError:
APPRISE_AVAILABLE = False
print("ERROR: Apprise not installed.")
print("Install with: pip3 install apprise --break-system-packages")
sys.exit(1)
def list_services():
"""
List all notification services supported by Apprise.
This prints a formatted list of services with their URL prefixes.
"""
print("Supported Notification Services")
print("=" * 60)
print()
print("Apprise supports 80+ services. Common ones include:")
print()
services = [
("ntfy", "ntfy://topic or ntfy://server/topic", "Free, open source"),
("Pushover", "pover://user@token", "$5 one-time"),
("Telegram", "tgram://bot_token/chat_id", "Free, needs bot"),
("Slack", "slack://token_a/token_b/token_c/#channel", "Free tier available"),
("Discord", "discord://webhook_id/webhook_token", "Free"),
("Email", "mailto://user:pass@smtp.server?to=addr", "Any SMTP"),
("Gotify", "gotify://server/token", "Self-hosted"),
("Pushbullet", "pbul://access_token", "Free tier"),
("Join", "join://apikey/device", "Android"),
("Simplepush", "spush://apikey", "iOS/Android"),
("Prowl", "prowl://apikey", "iOS"),
("Matrix", "matrix://user:pass@server/#room", "Self-hosted"),
("Rocket.Chat", "rocket://user:pass@server/#channel", "Self-hosted"),
("XMPP/Jabber", "xmpp://user:pass@server", "Various"),
("SMS (Twilio)", "twilio://sid:token@from/to", "Paid"),
("SMS (AWS SNS)", "sns://access_key/secret_key/region/phone", "Paid"),
]
for name, url_format, note in services:
print(f" {name:15} {url_format}")
print(f" {' ':15} ({note})")
print()
print("For complete list and documentation:")
print(" https://github.com/caronc/apprise/wiki")
print()
def load_config_urls(config_path="/etc/pam-ssh-2fa/config.ini", user=None):
"""
Load notification URLs from the config file.
Args:
config_path: Path to the main config INI file
user: Optional username to load user-specific config
Returns:
Tuple of (urls_list, source_description)
"""
urls = []
source = "defaults"
# Load global config
if os.path.exists(config_path):
parser = configparser.ConfigParser()
try:
parser.read(config_path)
urls_str = parser.get("notifications", "apprise_urls", fallback="")
if urls_str:
urls = [url.strip() for url in urls_str.split(",") if url.strip()]
source = config_path
except Exception as e:
print(f"Warning: Could not parse config: {e}")
# Check for user-specific config
if user:
config_dir = os.path.dirname(config_path) or "/etc/pam-ssh-2fa"
user_config_dir = os.path.join(config_dir, "users")
# Sanitize username
safe_user = "".join(c for c in user if c.isalnum() or c in "-_.")
if safe_user != user:
print(f"Warning: Invalid characters in username, using: {safe_user}")
user = safe_user
# Try to find user config
for ext in [".conf", ".ini", ""]:
user_config_file = os.path.join(user_config_dir, f"{user}{ext}")
if os.path.exists(user_config_file):
parser = configparser.ConfigParser()
try:
parser.read(user_config_file)
urls_str = parser.get("notifications", "apprise_urls", fallback="")
if urls_str:
urls = [
url.strip() for url in urls_str.split(",") if url.strip()
]
source = user_config_file
except Exception as e:
print(f"Warning: Could not parse user config: {e}")
break
else:
if user:
print(
f"Note: No config file found for user '{user}', using global config"
)
return urls, source
def send_test_notification(urls, code="1234"):
"""
Send a test notification to the specified URLs.
Args:
urls: List of Apprise notification URLs
code: Test code to include in the message
Returns:
True if at least one notification succeeded
"""
if not urls:
print("ERROR: No notification URLs provided.")
print()
print("Either:")
print(" 1. Configure URLs in /etc/pam-ssh-2fa/config.ini")
print(" 2. Create per-user config in /etc/pam-ssh-2fa/users/<username>.conf")
print(" 3. Use --url to specify URLs directly")
print()
return False
# Get hostname
try:
hostname = os.uname().nodename
except:
hostname = "test-host"
# Create notification content
title = "SSH 2FA Test Notification"
body = f"""This is a test notification from PAM SSH 2FA.
If you received this, your notification setup is working!
Test code: {code}
Host: {hostname}
User: test
From: 127.0.0.1
This code would expire in 5 minutes during real authentication."""
# Create Apprise instance
apobj = apprise.Apprise()
print(f"Testing {len(urls)} notification URL(s)...")
print()
for url in urls:
# Mask sensitive parts of URL for display
display_url = url
if "@" in url:
# Hide credentials
parts = url.split("@")
if len(parts) >= 2:
prefix = parts[0].split("://")[0] if "://" in parts[0] else parts[0]
display_url = f"{prefix}://***@{parts[-1]}"
print(f" Adding: {display_url}")
apobj.add(url)
print()
print("Sending notification...")
# Send
result = apobj.notify(title=title, body=body, notify_type=apprise.NotifyType.INFO)
print()
if result:
print("[OK] SUCCESS: Notification sent!")
print()
print("Check your device - you should have received a message.")
return True
else:
print("[FAIL] FAILED: Could not send notification.")
print()
print("Troubleshooting:")
print(" - Verify your URL format is correct")
print(" - Check that API keys/tokens are valid")
print(" - Ensure outbound HTTPS (port 443) is allowed")
print(" - Try with --debug for more details")
return False
def main():
parser = argparse.ArgumentParser(
description="Test PAM SSH 2FA push notifications",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s Test with global config URLs
%(prog)s --user doug Test doug's personal config
%(prog)s --url "ntfy://ntfy.sh/my-topic" Test specific URL
%(prog)s --list-services Show supported services
""",
)
parser.add_argument(
"--url",
"-u",
action="append",
dest="urls",
help="Apprise notification URL (can be specified multiple times)",
)
parser.add_argument("--user", help="Username to load per-user config for")
parser.add_argument(
"--config",
"-c",
default="/etc/pam-ssh-2fa/config.ini",
help="Path to config file (default: /etc/pam-ssh-2fa/config.ini)",
)
parser.add_argument(
"--code",
default="1234",
help="Test code to include in notification (default: 1234)",
)
parser.add_argument(
"--list-services",
"-l",
action="store_true",
help="List supported notification services",
)
parser.add_argument("--debug", action="store_true", help="Enable debug output")
args = parser.parse_args()
# Handle --list-services
if args.list_services:
list_services()
return 0
# Enable debug logging if requested
if args.debug:
import logging
logging.basicConfig(level=logging.DEBUG)
print()
print("PAM SSH 2FA - Notification Test")
print("=" * 40)
print()
# Get URLs from args or config
urls = args.urls or []
source = "command line"
if not urls:
print(f"Loading URLs from config...")
if args.user:
print(f"Looking for user-specific config for: {args.user}")
urls, source = load_config_urls(args.config, args.user)
print(f"Using config: {source}")
print()
# Send test
success = send_test_notification(urls, args.code)
return 0 if success else 1
if __name__ == "__main__":
sys.exit(main())