perun.proxy.utils 1.0.0__tar.gz → 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (20) hide show
  1. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/PKG-INFO +1 -1
  2. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/README.md +31 -4
  3. perun.proxy.utils-1.1.0/perun/proxy/utils/nagios/check_saml.py +543 -0
  4. perun.proxy.utils-1.1.0/perun/proxy/utils/nagios/check_user_logins.py +118 -0
  5. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun.proxy.utils.egg-info/PKG-INFO +1 -1
  6. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun.proxy.utils.egg-info/SOURCES.txt +3 -1
  7. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/setup.cfg +1 -1
  8. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/LICENSE +0 -0
  9. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun/proxy/utils/__init__.py +0 -0
  10. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun/proxy/utils/metadata_expiration.py +0 -0
  11. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun/proxy/utils/nagios/__init__.py +0 -0
  12. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun/proxy/utils/nagios/check_mongodb.py +0 -0
  13. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun/proxy/utils/print_docker_versions.py +0 -0
  14. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun/proxy/utils/run_version_script.py +0 -0
  15. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun/proxy/utils/separate_oidc_logs.py +0 -0
  16. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun/proxy/utils/separate_ssp_logs.py +0 -0
  17. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun.proxy.utils.egg-info/dependency_links.txt +0 -0
  18. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun.proxy.utils.egg-info/requires.txt +0 -0
  19. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/perun.proxy.utils.egg-info/top_level.txt +0 -0
  20. {perun.proxy.utils-1.0.0 → perun.proxy.utils-1.1.0}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 1.2
2
2
  Name: perun.proxy.utils
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: Module with utilities and monitoring probes
5
5
  Home-page: https://gitlab.ics.muni.cz/perun-proxy-aai/proxyidp-scripts.git
6
6
  License: UNKNOWN
@@ -1,8 +1,6 @@
1
1
  # ProxyIdP scripts
2
2
 
3
- All nagios scripts are located under `nagios` directory.
4
-
5
- ## List scripts
3
+ ## Scripts
6
4
 
7
5
  ### separate_ssp_script.py
8
6
 
@@ -43,11 +41,40 @@ All nagios scripts are located under `nagios` directory.
43
41
  - Params:
44
42
  - 1... - machines to run the script on in the form of user@adress, the user needs root privileges to execute the script
45
43
 
44
+ ## Nagios probes
45
+
46
+ All nagios scripts are located under `nagios` directory.
47
+
46
48
  ### check_mongodb.py
47
49
 
48
50
  - nagios monitoring probe for mongodb
49
51
 
50
52
  - connect, connections, replication_lag, replset_state monitoring options are tested (some possible options may not work since there are constructs which are not supported by latest mongodb versions)
51
53
 
52
- - For usage run:
54
+ - for usage run:
53
55
  `python3 check_mongodb.py --help`
56
+
57
+ ### check_saml.py
58
+
59
+ - SAML authentication check
60
+
61
+ - for usage run:
62
+ `python3 check_saml.py --help`
63
+
64
+ ### check_user_logins.py
65
+
66
+ - check users which login in repeatedly more often than a specified threshold (logins per seconds)
67
+
68
+ - for usage run:
69
+ `python3 check_user_logins.py --help`
70
+
71
+ - example:
72
+
73
+ ```
74
+ python3 check_user_logins.py
75
+ -p /var/log/proxyaai/simplesamlphp/simplesamlphp/simplesamlphp.log
76
+ -l 5
77
+ -s 60
78
+ -r "^(?P<datetime>.{20}).*audit-login.* (?P<userid>[0-9]+)@muni\.cz$"
79
+ -d "%b %d %Y %H:%M:%S"
80
+ ```
@@ -0,0 +1,543 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ make a full roundtrip test for SAML based SSO
5
+ """
6
+
7
+ import base64
8
+ import hmac
9
+ import os
10
+ import struct
11
+ import argparse
12
+ import sys
13
+ import time
14
+ import urllib.request
15
+ import urllib.error
16
+ import urllib.parse
17
+ import ssl
18
+ import tempfile
19
+ import re
20
+ from html.parser import HTMLParser
21
+ import http.cookiejar
22
+
23
+ STATUS = {"OK": 0, "WARNING": 1, "CRITICAL": 2, "UNKNOWN": 3}
24
+
25
+ DEFAULT_HEADERS = {
26
+ "Accept": "text/html,application/xhtml+xml,"
27
+ + "application/xml;q=0.9,image/webp,*/*;q=0.8",
28
+ }
29
+
30
+ CACHE_REGEX = ".*_(OK|WARNING|CRITICAL|UNKNOWN)_.*"
31
+
32
+
33
+ # https://github.com/susam/mintotp/blob/master/mintotp.py
34
+ def hotp(key, counter, digits=6, digest="sha1"):
35
+ key = base64.b32decode(key.upper() + "=" * ((8 - len(key)) % 8))
36
+ counter = struct.pack(">Q", counter)
37
+ mac = hmac.new(key, counter, digest).digest()
38
+ offset = mac[-1] & 0x0F
39
+ endoffset = offset + 4
40
+ binary = struct.unpack(">L", mac[offset:endoffset])[0] & 0x7FFFFFFF
41
+ return str(binary)[-digits:].zfill(digits)
42
+
43
+
44
+ def totp(key, time_step=30, digits=6, digest="sha1"):
45
+ return hotp(key, int(time.time() / time_step), digits, digest)
46
+
47
+
48
+ class FormParser(HTMLParser):
49
+ form_action = None
50
+ form_data = {}
51
+ _form_in_progress = False
52
+
53
+ def __init__(self, *args, **kwargs):
54
+ self.form_action = None
55
+ self.form_data = {}
56
+ self._form_in_progress = False
57
+ super(FormParser, self).__init__(*args, **kwargs)
58
+
59
+ def handle_starttag(self, tag, attrs):
60
+ if tag.lower() == "form":
61
+ self._form_in_progress = True
62
+ for name, value in attrs:
63
+ if name.lower() == "action" and self.form_action is None:
64
+ self.form_action = value
65
+ elif tag.lower() == "input":
66
+ input_name = None
67
+ input_value = None
68
+ for name, value in attrs:
69
+ if name.lower() == "name":
70
+ input_name = value
71
+ elif name.lower() == "value":
72
+ input_value = value
73
+ if input_name and input_value:
74
+ self.form_data[input_name] = input_value
75
+
76
+ def handle_endtag(self, tag):
77
+ if tag.lower() == "form":
78
+ self._form_in_progress = False
79
+
80
+
81
+ def parse_form(html):
82
+ parser = FormParser()
83
+ parser.feed(html)
84
+ return parser.form_action, parser.form_data
85
+
86
+
87
+ def get_host_from_url(url):
88
+ return urllib.parse.urlparse(url).hostname
89
+
90
+
91
+ def get_args():
92
+ """
93
+ Supports the command-line arguments listed below.
94
+ """
95
+ parser = argparse.ArgumentParser(description="SAML authentication check")
96
+ parser._optionals.title = "Options"
97
+ parser.add_argument(
98
+ "--username",
99
+ required=True,
100
+ help="username for IdP",
101
+ )
102
+ parser.add_argument(
103
+ "--password",
104
+ required=True,
105
+ help="password for IdP",
106
+ )
107
+ parser.add_argument(
108
+ "--url",
109
+ help="URL that starts authentication",
110
+ default="https://inet.muni.cz/sys/servertest",
111
+ )
112
+ parser.add_argument(
113
+ "--string",
114
+ help="string to expect after successful authentication",
115
+ default="OSCIS",
116
+ )
117
+ parser.add_argument("--idp-host", help="hostname of IdP", default="id.muni.cz")
118
+ parser.add_argument(
119
+ "--hosts",
120
+ nargs="*",
121
+ default=[],
122
+ help="space separated list of hostname:ip or hostname:hostname pairs "
123
+ + "for replacing in all URLs",
124
+ )
125
+ """
126
+ parser.add_argument(
127
+ "--other-urls",
128
+ nargs="*",
129
+ default=[],
130
+ help="list of more services for testing single sign-on",
131
+ )
132
+ parser.add_argument(
133
+ "--other-urls-final",
134
+ nargs="*",
135
+ default=[],
136
+ help="list of final URLs of the other services for testing single sign-on",
137
+ )
138
+ """
139
+ parser.add_argument(
140
+ "--warn-time",
141
+ type=int,
142
+ help="warning threshold in seconds",
143
+ default=5,
144
+ )
145
+ parser.add_argument(
146
+ "--critical-time",
147
+ type=int,
148
+ help="critical threshold in seconds",
149
+ default=15,
150
+ )
151
+ parser.add_argument(
152
+ "--insecure",
153
+ action="store_true",
154
+ help="ignore server name in SSL/TLS certificates",
155
+ )
156
+ parser.add_argument(
157
+ "--username-field",
158
+ help="name of the username field on the login page",
159
+ default="username",
160
+ )
161
+ parser.add_argument(
162
+ "--password-field",
163
+ help="name of the password field on the login page",
164
+ default="password",
165
+ )
166
+ parser.add_argument(
167
+ "--totp",
168
+ help="secret key (seed) for TOTP in Base32 encoding",
169
+ default="ZYTYYE5FOAGW5ML7LRWUL4WTZLNJAMZS",
170
+ )
171
+ parser.add_argument(
172
+ "--verbose",
173
+ "-v",
174
+ action="count",
175
+ default=0,
176
+ help="verbose mode (for debugging)",
177
+ )
178
+ parser.add_argument(
179
+ "--remember-me",
180
+ action="store_true",
181
+ help="check the Remember me option when logging in",
182
+ )
183
+ parser.add_argument(
184
+ "--skip-security-image-check",
185
+ action="store_true",
186
+ help="skip security image check when remember me is used",
187
+ )
188
+ parser.add_argument(
189
+ "--cache-timeout",
190
+ type=int,
191
+ help="specify the time after which the cache will be wiped",
192
+ default=0,
193
+ )
194
+ parser.add_argument(
195
+ "--cache-file",
196
+ default="check_saml_cache",
197
+ help="name of the file used for the cache",
198
+ )
199
+
200
+ return parser.parse_args()
201
+
202
+
203
+ def replace_host_in_url(hosts, url, headers):
204
+ host = get_host_from_url(url)
205
+ headers["Host"] = host
206
+ if host in hosts:
207
+ parsed = urllib.parse.urlparse(url)
208
+ url = parsed._replace(netloc=hosts[host]).geturl()
209
+ headers["Host"] = host
210
+ return url, headers
211
+
212
+
213
+ class ResolvingHTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
214
+ def __init__(self, hosts, verbose=0):
215
+ self.hosts = hosts
216
+ self.verbose = verbose
217
+
218
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
219
+ """Check whether the host should be replaced with an IP"""
220
+ referrer = req.headers["Referer"] if "Referer" in req.headers else None
221
+ newurl, newheaders = replace_host_in_url(self.hosts, newurl, DEFAULT_HEADERS)
222
+ req.headers = newheaders
223
+ if referrer:
224
+ req.headers["Referer"] = referrer
225
+ if self.verbose >= 1:
226
+ print("Redirecting to {}".format(newurl))
227
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
228
+
229
+ def http_error_308(self, req, fp, code, msg, hdrs):
230
+ return self.http_error_301(req, fp, 301, msg, hdrs)
231
+
232
+
233
+ class SAMLChecker:
234
+ def curl(self, url, data=None, referrer=None):
235
+ url, headers = replace_host_in_url(self.hosts, url, DEFAULT_HEADERS)
236
+
237
+ if referrer:
238
+ headers["Referer"], _ = replace_host_in_url(
239
+ dict(map(reversed, self.hosts.items())),
240
+ urllib.parse.urlparse(referrer)
241
+ ._replace(fragment="")
242
+ ._replace(query="")
243
+ .geturl(),
244
+ {},
245
+ )
246
+ if self.args.verbose >= 1:
247
+ print("curl: {}".format(url))
248
+ if "Referer" in headers:
249
+ print("Referrer: {}".format(headers["Referer"]))
250
+ req = urllib.request.Request(
251
+ url=url,
252
+ data=urllib.parse.urlencode(data).encode("ascii") if data else None,
253
+ headers=headers,
254
+ )
255
+ if self.args.verbose >= 1:
256
+ print("")
257
+ response = None
258
+ try:
259
+ response = self.opener.open(req)
260
+ return response
261
+ except urllib.error.URLError as e:
262
+ if self.args.verbose >= 1:
263
+ print(e)
264
+ if self.args.verbose >= 2:
265
+ print(response)
266
+ self.finish(e.reason, "CRITICAL")
267
+
268
+ def js_form_redirect(self, html, url, force=False):
269
+ if (
270
+ force
271
+ or "document.forms[0].submit()" in html
272
+ or "javascript:DoSubmit();" in html
273
+ ):
274
+ form_action, form_data = parse_form(html)
275
+ return self.send_form(url, form_action, form_data)
276
+ return None, None
277
+
278
+ def initial_request(self, url):
279
+ response = self.curl(url)
280
+ response_html = response.read().decode("utf-8")
281
+ response_url = response.url
282
+ if get_host_from_url(response_url) != (
283
+ self.hosts[self.args.idp_host]
284
+ if self.args.idp_host in self.hosts
285
+ else self.args.idp_host
286
+ ):
287
+ response_html, response_url = self.js_form_redirect(
288
+ response_html, response_url
289
+ )
290
+ if response_html is None:
291
+ self.finish(
292
+ "Initial URL does not redirect to IdP and JS redirect not detected",
293
+ "CRITICAL",
294
+ )
295
+ return response_html, response_url
296
+
297
+ def send_form(self, url, action, data):
298
+ target_url = urllib.parse.urljoin(url, action)
299
+ response = self.curl(target_url, data, url)
300
+ return response.read().decode("utf-8"), response.url
301
+
302
+ def send_credentials(self, login_form_url, login_form_action, login_form_data):
303
+ login_form_data[self.args.username_field] = self.args.username
304
+ login_form_data[self.args.password_field] = self.args.password
305
+ if self.args.remember_me:
306
+ login_form_data["remember_me"] = "Yes"
307
+ response_html, response_url = self.send_form(
308
+ login_form_url, login_form_action, login_form_data
309
+ )
310
+
311
+ if self.args.verbose >= 1:
312
+ print(response_url)
313
+ if self.args.verbose >= 3:
314
+ print(response_html)
315
+
316
+ # MFA
317
+ if "TOTP" in response_html or "privacyIDEA" in response_html:
318
+ if self.args.verbose >= 1:
319
+ print("MFA is required")
320
+ totp_form_action, totp_form_data = parse_form(response_html)
321
+ totp_code = totp(self.args.totp)
322
+ totp_form_data["code"] = totp_code
323
+ totp_form_data["otp"] = totp_code
324
+ response_html, response_url = self.send_form(
325
+ response_url, totp_form_action, totp_form_data
326
+ )
327
+ if self.args.verbose >= 1:
328
+ print(response_url)
329
+ if "TOTP" in response_html or "privacyIDEA" in response_html:
330
+ if self.args.verbose >= 2:
331
+ print(response_html)
332
+ self.finish("TOTP MFA failed", "CRITICAL")
333
+ if self.args.verbose >= 3:
334
+ print(response_html)
335
+
336
+ if "consent" in response_html:
337
+ self.finish("Consent is required", "UNKNOWN")
338
+ elif "Wrong UČO or password" in response_html:
339
+ self.finish(
340
+ "Login was not successful, invalid username or password", "CRITICAL"
341
+ )
342
+ elif "Unhandled exception" in response_html:
343
+ self.finish(
344
+ "Login was not successful, unhandled exception occured", "CRITICAL"
345
+ )
346
+ elif "SAMLResponse" not in response_html:
347
+ self.finish("Login was not successful, unknown error", "CRITICAL")
348
+
349
+ form_action, form_data = parse_form(response_html)
350
+ if "SAMLResponse" not in form_data:
351
+ self.finish("Login was not successful, unknown error", "CRITICAL")
352
+ saml_response = base64.b64decode(form_data["SAMLResponse"]).decode("utf-8")
353
+
354
+ if (
355
+ '<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>'
356
+ not in saml_response
357
+ ):
358
+ self.finish("Login was not successful, non-success response", "CRITICAL")
359
+
360
+ return self.js_form_redirect(response_html, response_url, True)
361
+
362
+ def js_form_redirect_all(self, html, url):
363
+ for _ in range(10):
364
+ try_html, try_url = self.js_form_redirect(html, url)
365
+ if try_html is not None and try_url is not None:
366
+ html = try_html
367
+ url = try_url
368
+ else:
369
+ return (html, url)
370
+ return (html, url)
371
+
372
+ def finish(
373
+ self,
374
+ message,
375
+ status="OK",
376
+ cache_time=time.time(),
377
+ from_cache=False,
378
+ auth_time=None,
379
+ ):
380
+ if auth_time is not None and isinstance(auth_time, float):
381
+ message = "{}|authtime={:.2f};{};{};;".format(
382
+ message, auth_time, self.args.warn_time, self.args.critical_time
383
+ )
384
+ if auth_time is None and from_cache is False:
385
+ message = "{}|authtime=;{};{};;".format(
386
+ message, self.args.warn_time, self.args.critical_time
387
+ )
388
+ if self.args.cache_timeout > 0:
389
+ try:
390
+ file_path = tempfile.gettempdir() + "/" + args.cache_file
391
+ f = open(file_path, "w")
392
+ f.write("{}_{}_{}".format(cache_time, status, message))
393
+ f.close()
394
+ except (OSError, ValueError):
395
+ pass
396
+ if from_cache:
397
+ message = "Cached: " + message
398
+ print("{} - {}".format(status, message))
399
+ sys.exit(STATUS[status])
400
+
401
+ def check_cache(self):
402
+ try:
403
+ tempdir = tempfile.gettempdir()
404
+ file_path = tempdir + "/" + args.cache_file
405
+ if os.path.isfile(file_path):
406
+ with open(file_path, "r") as f:
407
+ res_b = f.read()
408
+ if not re.match(CACHE_REGEX, res_b):
409
+ raise ValueError("Bad cache content!")
410
+ res = res_b.split("_")
411
+ cached_time = float(res[0])
412
+ status = res[1]
413
+ message = res[2]
414
+ actual_time = time.time()
415
+ time_diff = actual_time - float(cached_time)
416
+ if time_diff < args.cache_timeout:
417
+ self.finish(
418
+ message=message,
419
+ status=status,
420
+ cache_time=cached_time,
421
+ from_cache=True,
422
+ )
423
+ except (OSError, ValueError):
424
+ pass
425
+
426
+ def main(self):
427
+ """
428
+ CMD Line tool
429
+ """
430
+
431
+ if self.args.cache_timeout > 0:
432
+ self.check_cache()
433
+
434
+ start_time = time.time()
435
+
436
+ # 1. start authentication
437
+ login_form_html, login_form_url = self.initial_request(self.args.url)
438
+ if self.args.verbose >= 3:
439
+ print(login_form_html)
440
+
441
+ # 2. log in and post response back
442
+ login_form_action, login_form_data = parse_form(login_form_html)
443
+ html, response_url = self.send_credentials(
444
+ login_form_url, login_form_action, login_form_data
445
+ )
446
+
447
+ # 3. follow all JS redirects
448
+ html, response_url = self.js_form_redirect_all(html, response_url)
449
+
450
+ if self.args.string not in html:
451
+ if self.args.verbose >= 2:
452
+ print(html)
453
+ self.finish(
454
+ "Missing the testing string {} in the response.".format(
455
+ self.args.string
456
+ ),
457
+ "CRITICAL",
458
+ )
459
+
460
+ if self.args.verbose >= 3:
461
+ print(html)
462
+
463
+ elapsed_seconds = time.time() - start_time
464
+ status = "OK"
465
+ if elapsed_seconds >= self.args.critical_time:
466
+ status = "CRITICAL"
467
+ if elapsed_seconds >= self.args.warn_time:
468
+ status = "WARNING"
469
+
470
+ # test whether security image is shown
471
+ if self.args.remember_me:
472
+ # logout from SP and IdP but keep username cookie
473
+ self.cookiejar.clear_session_cookies()
474
+ self.cookiejar.clear(get_host_from_url(self.args.url))
475
+ self.cookiejar.clear(
476
+ (
477
+ self.hosts[self.args.idp_host]
478
+ if self.args.idp_host in self.hosts
479
+ else self.args.idp_host
480
+ ),
481
+ "/",
482
+ "SimpleSAMLAuthToken",
483
+ )
484
+ self.cookiejar.clear(
485
+ (
486
+ self.hosts[self.args.idp_host]
487
+ if self.args.idp_host in self.hosts
488
+ else self.args.idp_host
489
+ ),
490
+ "/",
491
+ "SimpleSAMLSessionID",
492
+ )
493
+ login_form_html, login_form_url = self.initial_request(self.args.url)
494
+ if self.args.verbose >= 3:
495
+ print(login_form_html)
496
+ if (
497
+ not self.args.skip_security_image_check
498
+ and "class='antiphishing-img'" not in login_form_html
499
+ ):
500
+ self.finish(
501
+ "Missing security image on the login page.",
502
+ "CRITICAL",
503
+ )
504
+ if self.args.username not in login_form_html:
505
+ self.finish(
506
+ "Missing remembered username on the login page.",
507
+ "WARNING",
508
+ )
509
+
510
+ self.finish(
511
+ "Authentication took {:.2f} seconds".format(elapsed_seconds),
512
+ status,
513
+ auth_time=elapsed_seconds,
514
+ )
515
+
516
+ def __init__(self, args):
517
+ self.args = args
518
+ self.hosts = {
519
+ host.split(":", 1)[0]: host.split(":", 1)[1]
520
+ for host in (
521
+ self.args.hosts[0].strip("\"'").split(" ")
522
+ if self.args.hosts and " " in self.args.hosts[0]
523
+ else self.args.hosts
524
+ )
525
+ }
526
+ self.cookiejar = http.cookiejar.CookieJar()
527
+ if self.args.insecure:
528
+ self.opener = urllib.request.build_opener(
529
+ urllib.request.HTTPCookieProcessor(self.cookiejar),
530
+ ResolvingHTTPRedirectHandler(self.hosts, self.args.verbose),
531
+ urllib.request.HTTPSHandler(context=ssl.SSLContext()),
532
+ )
533
+ else:
534
+ self.opener = urllib.request.build_opener(
535
+ urllib.request.HTTPCookieProcessor(self.cookiejar),
536
+ ResolvingHTTPRedirectHandler(self.hosts, self.args.verbose),
537
+ )
538
+
539
+
540
+ if __name__ == "__main__":
541
+ args = get_args()
542
+ checker = SAMLChecker(args)
543
+ checker.main()
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import datetime
5
+ import sys
6
+ import re
7
+
8
+ # nagios return codes
9
+ UNKNOWN = -1
10
+ OK = 0
11
+ WARNING = 1
12
+ CRITICAL = 2
13
+
14
+
15
+ def parse_log_data(log_path, regex, date_format):
16
+ file = open(log_path, "r", encoding="utf-8")
17
+ lines = file.readlines()
18
+ user_dict = {}
19
+ for line in lines:
20
+ result = re.match(regex, line)
21
+ if result:
22
+ user_id = result.group("userid")
23
+ if user_id not in user_dict.keys():
24
+ user_dict[user_id] = [
25
+ datetime.datetime.strptime(
26
+ result.group("datetime"), date_format
27
+ ).timestamp()
28
+ ]
29
+ else:
30
+ user_dict[user_id].append(
31
+ datetime.datetime.strptime(
32
+ result.group("datetime"), date_format
33
+ ).timestamp()
34
+ )
35
+ return user_dict
36
+
37
+
38
+ def check_log_data(user_dict, limits, seconds):
39
+ warning = False
40
+ for user, date_times in user_dict.items():
41
+ final_count = 0
42
+ count = 0
43
+ date_times.sort()
44
+ for check_date_time in range(len(date_times)):
45
+ for i in range(len(date_times)):
46
+ if check_date_time <= i:
47
+ if date_times[i] - date_times[check_date_time] <= seconds:
48
+ count += 1
49
+ else:
50
+ break
51
+ if final_count < count:
52
+ final_count = count
53
+ count = 0
54
+
55
+ if final_count > limits:
56
+ print("WARNING - User: {} logins count: {}".format(user, final_count))
57
+ warning = True
58
+ if warning:
59
+ sys.exit(WARNING)
60
+
61
+
62
+ def check_positive(value):
63
+ ivalue = int(value)
64
+ if ivalue <= 0:
65
+ raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)
66
+ return ivalue
67
+
68
+
69
+ def command_line_validate(argv):
70
+ parser = argparse.ArgumentParser(description="frequent login check")
71
+ parser._optionals.title = "Options"
72
+ parser.add_argument(
73
+ "--path",
74
+ "-p",
75
+ required=True,
76
+ help="path to log file",
77
+ )
78
+ parser.add_argument(
79
+ "--regex",
80
+ "-r",
81
+ required=True,
82
+ help="parsing regex of logfile, must include groups userid and datetime",
83
+ )
84
+ parser.add_argument(
85
+ "--datetime_format",
86
+ "-d",
87
+ required=True,
88
+ help="datetime format of log file",
89
+ )
90
+ parser.add_argument(
91
+ "--logins",
92
+ "-l",
93
+ type=check_positive,
94
+ required=True,
95
+ help="maximal number of logins",
96
+ )
97
+ parser.add_argument(
98
+ "--seconds",
99
+ "-s",
100
+ type=check_positive,
101
+ required=True,
102
+ help="time interval for logins check",
103
+ )
104
+ args = parser.parse_args()
105
+ return args.path, args.regex, args.datetime_format, args.logins, args.seconds
106
+
107
+
108
+ def main():
109
+ argv = sys.argv[1:]
110
+ path, regex, datetime_format, logins, seconds = command_line_validate(argv)
111
+ user_dict = parse_log_data(path, regex, datetime_format)
112
+ check_log_data(user_dict, logins, seconds)
113
+ print("OK", logins, seconds)
114
+ return 0
115
+
116
+
117
+ if __name__ == "__main__":
118
+ main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 1.2
2
2
  Name: perun.proxy.utils
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: Module with utilities and monitoring probes
5
5
  Home-page: https://gitlab.ics.muni.cz/perun-proxy-aai/proxyidp-scripts.git
6
6
  License: UNKNOWN
@@ -14,4 +14,6 @@ perun/proxy/utils/run_version_script.py
14
14
  perun/proxy/utils/separate_oidc_logs.py
15
15
  perun/proxy/utils/separate_ssp_logs.py
16
16
  perun/proxy/utils/nagios/__init__.py
17
- perun/proxy/utils/nagios/check_mongodb.py
17
+ perun/proxy/utils/nagios/check_mongodb.py
18
+ perun/proxy/utils/nagios/check_saml.py
19
+ perun/proxy/utils/nagios/check_user_logins.py
@@ -1,5 +1,5 @@
1
1
  [metadata]
2
- version = 1.0.0
2
+ version = 1.1.0
3
3
  license_files = LICENSE
4
4
 
5
5
  [egg_info]