perun.proxy.utils 2.5.4__tar.gz → 2.7.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 (36) hide show
  1. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/PKG-INFO +56 -2
  2. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/README.md +50 -1
  3. perun.proxy.utils-2.7.0/perun/proxy/utils/nagios/check_oidc_login.py +341 -0
  4. perun.proxy.utils-2.7.0/perun/proxy/utils/oracle2postgresql.py +213 -0
  5. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun.proxy.utils.egg-info/PKG-INFO +56 -2
  6. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun.proxy.utils.egg-info/SOURCES.txt +2 -0
  7. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun.proxy.utils.egg-info/entry_points.txt +2 -0
  8. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun.proxy.utils.egg-info/requires.txt +6 -0
  9. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/setup.cfg +1 -1
  10. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/setup.py +8 -0
  11. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/LICENSE +0 -0
  12. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/__init__.py +0 -0
  13. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/metadata_expiration.py +0 -0
  14. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/__init__.py +0 -0
  15. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_custom_command.py +0 -0
  16. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_dockers.py +0 -0
  17. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_exabgp_propagation.py +0 -0
  18. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_ldap.py +0 -0
  19. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_ldap_syncrepl.py +0 -0
  20. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_mongodb.py +0 -0
  21. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_nginx.py +0 -0
  22. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_pgsql.py +0 -0
  23. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_php_syntax.py +0 -0
  24. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_privacyidea.py +0 -0
  25. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_rpc_status.py +0 -0
  26. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_saml.py +0 -0
  27. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/check_user_logins.py +0 -0
  28. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/nagios/webserver_availability.py +0 -0
  29. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/print_docker_versions.py +0 -0
  30. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/run_probes.py +0 -0
  31. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/run_version_script.py +0 -0
  32. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/separate_oidc_logs.py +0 -0
  33. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/separate_ssp_logs.py +0 -0
  34. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun/proxy/utils/sync_usable_token_types.py +0 -0
  35. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun.proxy.utils.egg-info/dependency_links.txt +0 -0
  36. {perun.proxy.utils-2.5.4 → perun.proxy.utils-2.7.0}/perun.proxy.utils.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: perun.proxy.utils
3
- Version: 2.5.4
3
+ Version: 2.7.0
4
4
  Summary: Utilities and monitoring probes for Perun ProxyIdP
5
5
  Home-page: https://gitlab.ics.muni.cz/perun/perun-proxyidp/perun-proxy-utils.git
6
6
  Requires-Python: >=3.9
@@ -17,11 +17,16 @@ Requires-Dist: check_nginx_status~=1.0
17
17
  Requires-Dist: pyotp~=2.9
18
18
  Requires-Dist: perun.connector~=3.8
19
19
  Requires-Dist: privacyidea~=3.9
20
+ Requires-Dist: flask~=1.1
21
+ Requires-Dist: idpyoidc~=2.1
22
+ Requires-Dist: sqlalchemy~=1.4
20
23
  Provides-Extra: ldap
21
24
  Requires-Dist: ldap3~=2.9.1; extra == "ldap"
22
25
  Requires-Dist: check_syncrepl_extended~=2020.13; extra == "ldap"
23
26
  Provides-Extra: postgresql
24
27
  Requires-Dist: psycopg2-binary~=2.9; extra == "postgresql"
28
+ Provides-Extra: oracle
29
+ Requires-Dist: cx-Oracle~=8.3; extra == "oracle"
25
30
 
26
31
  # Perun proxy utils
27
32
 
@@ -40,7 +45,8 @@ There are several extras which are required only for some scripts:
40
45
  - `[ldap]` for check_ldap and check_ldap_syncrepl
41
46
  - this also requires
42
47
  installing [build prerequisites of the python-ldap library](https://www.python-ldap.org/en/latest/installing.html#build-prerequisites)
43
- - `[postgresql]` for check_pgsql
48
+ - `[postgresql]` for check_pgsql and oracle2postgresql
49
+ - `[oracle]` for oracle2postgresql
44
50
 
45
51
  ## Scripts
46
52
 
@@ -136,6 +142,25 @@ python3 sync_usable_token_types.py
136
142
  --perun-connector-config-path "/path/to/file"
137
143
  ```
138
144
 
145
+ ### oracle2postgresql.py
146
+ Synchronizes data from Oracle db to PostgreSQL db.
147
+
148
+ Requires config file located at `/etc/oracle2postgresql_cfg.yaml` and [Oracle client](https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html).
149
+ #### Functionality
150
+ 1. Attribute Import:
151
+
152
+ Imports attributes from Oracle database tables to the PostgreSQL database, into a table compatible with [simplesamlphp-module-sqlattribs](https://github.com/tenet-ac-za/simplesamlphp-module-sqlattribs). Each attribute is specified with a corresponding SQL SELECT statement.
153
+
154
+ 2. Table Import:
155
+
156
+ Imports tables from the Oracle database to the PostgreSQL one. Supports both full and incremental synchronization.
157
+ For full synchronization, all records from the source table are imported.
158
+ For incremental synchronization, only records modified since the last synchronization are imported, based on designated change columns.
159
+ The full sync in turned off by default. Run with `-f` or `--full_sync` flag to turn it on.
160
+
161
+ Attributes and tables intended for import are stated in the config.
162
+ Target table names from PostgreSQL are hardcoded due to the possibility of needing to create them.
163
+
139
164
  ## Nagios probes
140
165
 
141
166
  All nagios scripts are located under `nagios` directory.
@@ -246,3 +271,32 @@ For usage instructions, run:
246
271
  ```sh
247
272
  check_pgsql --help
248
273
  ```
274
+
275
+ ### check_oidc_login
276
+
277
+ Check that OIDC auth process works by acting as an OIDC client (RP) attempting to
278
+ authenticate against an OIDC server (OP). Supports clients with PKCE and non-PKCE
279
+ authentication. Additional tag `-pkce` must be added to test PKCE log in. Using client
280
+ secret is always enforced since some clients might require it on top of PKCE.
281
+
282
+ Target OIDC server (OP) should **not** require authentication for this probe to
283
+ work. It **does not** test the credentials' validity but rather the OIDC auth process. This
284
+ can be achieved, for example, by setting up SATOSA's reflector backend.
285
+
286
+ For usage instructions, run:
287
+
288
+ ```sh
289
+ check_oidc_login --help
290
+ ```
291
+
292
+ Example:
293
+
294
+ ```sh
295
+ python3 check_oidc_login
296
+ --redirect-uri "http://localhost:44322/signin-oidc"
297
+ --client-id "my_oidc_client_id"
298
+ --client-secret "my_oidc_pkce_secret"
299
+ --issuer "https://id.muni.cz"
300
+ -vvv # verbose debug output
301
+ -pkce
302
+ ```
@@ -15,7 +15,8 @@ There are several extras which are required only for some scripts:
15
15
  - `[ldap]` for check_ldap and check_ldap_syncrepl
16
16
  - this also requires
17
17
  installing [build prerequisites of the python-ldap library](https://www.python-ldap.org/en/latest/installing.html#build-prerequisites)
18
- - `[postgresql]` for check_pgsql
18
+ - `[postgresql]` for check_pgsql and oracle2postgresql
19
+ - `[oracle]` for oracle2postgresql
19
20
 
20
21
  ## Scripts
21
22
 
@@ -111,6 +112,25 @@ python3 sync_usable_token_types.py
111
112
  --perun-connector-config-path "/path/to/file"
112
113
  ```
113
114
 
115
+ ### oracle2postgresql.py
116
+ Synchronizes data from Oracle db to PostgreSQL db.
117
+
118
+ Requires config file located at `/etc/oracle2postgresql_cfg.yaml` and [Oracle client](https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html).
119
+ #### Functionality
120
+ 1. Attribute Import:
121
+
122
+ Imports attributes from Oracle database tables to the PostgreSQL database, into a table compatible with [simplesamlphp-module-sqlattribs](https://github.com/tenet-ac-za/simplesamlphp-module-sqlattribs). Each attribute is specified with a corresponding SQL SELECT statement.
123
+
124
+ 2. Table Import:
125
+
126
+ Imports tables from the Oracle database to the PostgreSQL one. Supports both full and incremental synchronization.
127
+ For full synchronization, all records from the source table are imported.
128
+ For incremental synchronization, only records modified since the last synchronization are imported, based on designated change columns.
129
+ The full sync in turned off by default. Run with `-f` or `--full_sync` flag to turn it on.
130
+
131
+ Attributes and tables intended for import are stated in the config.
132
+ Target table names from PostgreSQL are hardcoded due to the possibility of needing to create them.
133
+
114
134
  ## Nagios probes
115
135
 
116
136
  All nagios scripts are located under `nagios` directory.
@@ -221,3 +241,32 @@ For usage instructions, run:
221
241
  ```sh
222
242
  check_pgsql --help
223
243
  ```
244
+
245
+ ### check_oidc_login
246
+
247
+ Check that OIDC auth process works by acting as an OIDC client (RP) attempting to
248
+ authenticate against an OIDC server (OP). Supports clients with PKCE and non-PKCE
249
+ authentication. Additional tag `-pkce` must be added to test PKCE log in. Using client
250
+ secret is always enforced since some clients might require it on top of PKCE.
251
+
252
+ Target OIDC server (OP) should **not** require authentication for this probe to
253
+ work. It **does not** test the credentials' validity but rather the OIDC auth process. This
254
+ can be achieved, for example, by setting up SATOSA's reflector backend.
255
+
256
+ For usage instructions, run:
257
+
258
+ ```sh
259
+ check_oidc_login --help
260
+ ```
261
+
262
+ Example:
263
+
264
+ ```sh
265
+ python3 check_oidc_login
266
+ --redirect-uri "http://localhost:44322/signin-oidc"
267
+ --client-id "my_oidc_client_id"
268
+ --client-secret "my_oidc_pkce_secret"
269
+ --issuer "https://id.muni.cz"
270
+ -vvv # verbose debug output
271
+ -pkce
272
+ ```
@@ -0,0 +1,341 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ make a full roundtrip test.yaml for SAML based SSO
5
+ """
6
+
7
+ import argparse
8
+ import http.cookiejar
9
+ import http.server
10
+ import json
11
+ import logging
12
+ import os
13
+ import threading
14
+ import time
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ from enum import Enum
19
+ from http.client import HTTPResponse
20
+ from typing import Dict, Any, List
21
+ from urllib.parse import urlparse
22
+
23
+ from flask import Flask, Response, request
24
+ from idpyoidc.client.oauth2.stand_alone_client import StandAloneClient
25
+
26
+ CALLBACK_ENDPOINT_CALLED = threading.Event()
27
+
28
+
29
+ class ClientConfigData:
30
+ def __init__(
31
+ self, client_id: str, client_secret: str, issuer: str, scopes: List[str]
32
+ ):
33
+ self.client_id = client_id
34
+ self.client_secret = client_secret
35
+ self.issuer = issuer
36
+ self.scopes = scopes
37
+
38
+
39
+ class Status(Enum):
40
+ OK = 0, "OK"
41
+ WARNING = 1, "WARNING"
42
+ CRITICAL = 2, "CRITICAL"
43
+ UNKNOWN = 3, "UNKNOWN"
44
+
45
+
46
+ class Evaluator:
47
+ def __init__(self):
48
+ self.start_time = None
49
+
50
+ def start_test(self):
51
+ self.start_time = time.time()
52
+
53
+ def finish_test(self, message: str, status: Status = Status.OK):
54
+ if not self.start_time:
55
+ raise ValueError("Test has not been started.")
56
+
57
+ auth_time = None
58
+ if status == Status.OK:
59
+ auth_time = round(time.time() - self.start_time, 2)
60
+
61
+ message = f"{message}|authtime={auth_time or ''};"
62
+ status_code, status_name = status.value
63
+
64
+ print(f"{status_name} - {message}")
65
+ os._exit(status_code)
66
+
67
+
68
+ def silence_flask_logs(app: Flask) -> None:
69
+ log = logging.getLogger("werkzeug")
70
+ log.setLevel(logging.ERROR)
71
+ app.logger.disabled = True
72
+ log.disabled = True
73
+
74
+
75
+ def get_flask_app(
76
+ client: StandAloneClient, evaluator: Evaluator, callback_path: str, verbose: int
77
+ ) -> Flask:
78
+ app = Flask(__name__)
79
+ app.config["client"] = client
80
+ app.config["evaluator"] = evaluator
81
+ silence_flask_logs(app)
82
+
83
+ @app.route(callback_path)
84
+ def signin_oidc():
85
+ CALLBACK_ENDPOINT_CALLED.set()
86
+ client: StandAloneClient = app.config["client"]
87
+ query_params = request.args.to_dict()
88
+
89
+ if verbose >= 3:
90
+ print(f"Parameters returned to callback after OIDC auth '{query_params}'")
91
+
92
+ auth_response = client.finalize(query_params)
93
+
94
+ if verbose >= 3:
95
+ print(
96
+ f"Final authentication response after exchange of code for token '"
97
+ f"{auth_response}'"
98
+ )
99
+
100
+ response = Response(status=200, headers={"Content-type": "text/plain"})
101
+
102
+ @response.call_on_close
103
+ def trigger_evaluation():
104
+ # trigger auth response evaluation after the flask response has been sent
105
+ if not auth_response.get("id_token"):
106
+ evaluator.finish_test(
107
+ "ID token was not found in OP's response.", Status.CRITICAL
108
+ )
109
+
110
+ if not auth_response.get("userinfo"):
111
+ evaluator.finish_test(
112
+ "User info was not found in OP's response.", Status.CRITICAL
113
+ )
114
+
115
+ evaluator.finish_test("Authentication was successful.", Status.OK)
116
+
117
+ return response
118
+
119
+ return app
120
+
121
+
122
+ def start_flask_app(
123
+ client: StandAloneClient, evaluator: Evaluator, redirect_uri: str, verbose: int
124
+ ):
125
+ parsed_redirect_uri = urlparse(redirect_uri)
126
+ app = get_flask_app(client, evaluator, parsed_redirect_uri.path, verbose)
127
+
128
+ app.run(host=parsed_redirect_uri.hostname, port=parsed_redirect_uri.port)
129
+
130
+
131
+ def get_args():
132
+ """
133
+ Supports the command-line arguments listed below.
134
+ """
135
+ parser = argparse.ArgumentParser(description="SAML authentication check")
136
+ parser._optionals.title = "Options"
137
+ parser.add_argument(
138
+ "--redirect-uri",
139
+ "-r",
140
+ required=True,
141
+ help="URI where OIDC callback will be redirected",
142
+ )
143
+ parser.add_argument(
144
+ "--client-id",
145
+ "-cid",
146
+ required=True,
147
+ help="ID of OIDC client registered with OP",
148
+ )
149
+ parser.add_argument(
150
+ "--client-secret",
151
+ "-cs",
152
+ required=True,
153
+ help="secret of OIDC client registered with OP",
154
+ )
155
+ parser.add_argument(
156
+ "--issuer",
157
+ "-i",
158
+ required=True,
159
+ help="Issuer used for OIDC auth",
160
+ )
161
+ parser.add_argument(
162
+ "--scopes",
163
+ "-s",
164
+ nargs="+",
165
+ help="List of scopes client will ask to access",
166
+ default=["openid", "email", "profile"],
167
+ )
168
+ parser.add_argument(
169
+ "--verbose",
170
+ "-v",
171
+ action="count",
172
+ default=0,
173
+ help="verbose mode (for debugging)",
174
+ )
175
+ parser.add_argument(
176
+ "--remember-me",
177
+ action="store_true",
178
+ help="check the Remember me option when logging in",
179
+ )
180
+ parser.add_argument(
181
+ "--use-pkce",
182
+ "-pkce",
183
+ action="store_true",
184
+ help="use pkce method for logging in",
185
+ )
186
+
187
+ return parser.parse_args()
188
+
189
+
190
+ class OIDCChecker:
191
+ def curl(self, url, data=None):
192
+ if self.args.verbose >= 1:
193
+ print("curl: {}".format(url))
194
+ req = urllib.request.Request(
195
+ url=url,
196
+ data=urllib.parse.urlencode(data).encode("ascii") if data else None,
197
+ )
198
+ response = None
199
+ try:
200
+ response: HTTPResponse = self.opener.open(req)
201
+ return response
202
+ except urllib.error.URLError as e:
203
+ if self.args.verbose >= 1:
204
+ print(e)
205
+ if self.args.verbose >= 2:
206
+ print(response)
207
+ self.evaluator.finish_test(e.reason, Status.CRITICAL)
208
+
209
+ def perform_oidc_auth(self, url: str) -> None:
210
+ # Reflector backend ensures that no additional information needs to be sent
211
+ # to the oidc auth endpoint and the auth should pass successfully
212
+ self.curl(url)
213
+
214
+ def main(self):
215
+ """
216
+ CMD Line tool
217
+ """
218
+
219
+ self.evaluator.start_test()
220
+
221
+ # 1. start the Flask endpoint which handles OIDC callback
222
+ if self.args.verbose >= 3:
223
+ print("STEP 1 - starting flask endpoint (callback)")
224
+
225
+ thread = threading.Thread(
226
+ target=start_flask_app,
227
+ args=[
228
+ self.client,
229
+ self.evaluator,
230
+ self.args.redirect_uri,
231
+ self.args.verbose,
232
+ ],
233
+ )
234
+ thread.start()
235
+
236
+ # 2. initiate auth process
237
+ if self.args.verbose >= 3:
238
+ print("STEP 2 - initiating OIDC auth process")
239
+
240
+ req_args = {"redirect_uri": self.args.redirect_uri}
241
+ login_url = self.client.init_authorization(req_args=req_args)
242
+ if self.args.verbose >= 3:
243
+ print(f"OIDC initiating url: '{login_url}'")
244
+
245
+ # 3. further proceed with auth
246
+ if self.args.verbose >= 3:
247
+ print("STEP 3 - proceeding with second OIDC auth step")
248
+
249
+ self.perform_oidc_auth(login_url)
250
+
251
+ # This point should not be reached if callback endpoint was called
252
+ if not CALLBACK_ENDPOINT_CALLED.is_set():
253
+ self.evaluator.finish_test(
254
+ "Callback endpoint was not called.", Status.CRITICAL
255
+ )
256
+
257
+ def get_issuer_info(self, issuer):
258
+ well_known_endpoint = f"{issuer}/.well-known/openid-configuration"
259
+ urllib.request.Request(well_known_endpoint)
260
+ response = self.curl(well_known_endpoint)
261
+ return json.loads(response.read().decode("utf-8"))
262
+
263
+ def get_non_pkce_client_cfg(
264
+ self, client_config_data: ClientConfigData
265
+ ) -> Dict[str, Any]:
266
+ return {
267
+ "provider_info": {
268
+ "issuer": client_config_data.issuer,
269
+ },
270
+ "client_id": client_config_data.client_id,
271
+ "client_secret": client_config_data.client_secret,
272
+ "scopes_supported": client_config_data.scopes,
273
+ "client_type": "oidc",
274
+ }
275
+
276
+ def get_pkce_client_cfg(
277
+ self, client_config_data: ClientConfigData
278
+ ) -> Dict[str, Any]:
279
+ base_config = self.get_non_pkce_client_cfg(client_config_data)
280
+ issuer_info = self.get_issuer_info(client_config_data.issuer)
281
+
282
+ additional_provider_info = {
283
+ "jwks_uri": issuer_info.get("jwks_uri"),
284
+ "userinfo_endpoint": issuer_info.get("userinfo_endpoint"),
285
+ "token_endpoint": issuer_info.get("token_endpoint"),
286
+ "authorization_endpoint": issuer_info.get("authorization_endpoint"),
287
+ }
288
+ base_config["provider_info"].update(additional_provider_info)
289
+
290
+ pkce_addon_info = {
291
+ "add_ons": {
292
+ "pkce": {
293
+ "function": "idpyoidc.client.oauth2.add_on.pkce.add_support",
294
+ "kwargs": {
295
+ "code_challenge_length": 64,
296
+ "code_challenge_method": "S256",
297
+ },
298
+ },
299
+ },
300
+ }
301
+ base_config.update(pkce_addon_info)
302
+
303
+ return base_config
304
+
305
+ def get_registered_client(
306
+ self, client_config_data: ClientConfigData
307
+ ) -> StandAloneClient:
308
+ if self.is_using_pkce:
309
+ client_cfg = self.get_pkce_client_cfg(client_config_data)
310
+ else:
311
+ client_cfg = self.get_non_pkce_client_cfg(client_config_data)
312
+
313
+ client = StandAloneClient(config=client_cfg)
314
+ client.do_provider_info() # get provider info based on issuer in client's
315
+ # config
316
+ client.do_client_registration() # client is configured statically if
317
+ # client_id is provided in the config
318
+
319
+ return client
320
+
321
+ def __init__(self, args):
322
+ self.args = args
323
+ self.cookiejar = http.cookiejar.CookieJar()
324
+ self.opener = urllib.request.build_opener(
325
+ urllib.request.HTTPCookieProcessor(self.cookiejar),
326
+ )
327
+ self.is_using_pkce = args.use_pkce
328
+ client_config_data = ClientConfigData(
329
+ args.client_id, args.client_secret, args.issuer, args.scopes
330
+ )
331
+ self.client = self.get_registered_client(client_config_data)
332
+ self.evaluator = Evaluator()
333
+
334
+
335
+ def main():
336
+ checker = OIDCChecker(get_args())
337
+ checker.main()
338
+
339
+
340
+ if __name__ == "__main__":
341
+ main()
@@ -0,0 +1,213 @@
1
+ import argparse
2
+ import yaml
3
+ from sys import stderr, exit
4
+ from sqlalchemy import (
5
+ create_engine,
6
+ Table,
7
+ Column,
8
+ MetaData,
9
+ UniqueConstraint,
10
+ Integer,
11
+ BigInteger,
12
+ String,
13
+ Text,
14
+ Date,
15
+ text,
16
+ )
17
+ from sqlalchemy.exc import SQLAlchemyError
18
+
19
+
20
+ class Oracle2PostgreSQL:
21
+ """
22
+ Import append-only attributes from Oracle DB to Postgresql.
23
+ For all IDs returned from the Oracle SQL, insert a predefined value into an attribute.
24
+ Currently, for all alumni insert alum into eduPersonAffiliation.
25
+ """
26
+
27
+ def __init__(self, full_sync):
28
+ self.table_for_imported_attributes = "AttributeFromSQLUnique"
29
+ self.imported_table_name = "w_exp_passwd_all"
30
+ self.__get_config()
31
+ self.full_sync = full_sync
32
+ self.oracle_engine = self.__get_oracle_engine()
33
+ self.postgresql_engine = self.__get_postgresql_engine()
34
+ self.__create_tables_if_they_dont_exist()
35
+
36
+ def run_sync(self):
37
+ self.__import_attributes(self.import_attributes)
38
+ self.__import_tables(self.import_tables, self.full_sync)
39
+
40
+ def __get_config(self):
41
+ filepath = "/etc/oracle2postgresql_cfg.yaml"
42
+ try:
43
+ with open(filepath, "r") as file:
44
+ conf = yaml.safe_load(file)
45
+ self.batch_size = conf["batch_size"]
46
+ self.oracle_con_string = conf["oracle_con_string"]
47
+ self.postgresql_con_string = conf["postgres_con_string"]
48
+ self.import_attributes = conf["import_attributes"]
49
+ self.import_tables = conf["import_table"]
50
+ except OSError as e:
51
+ print(
52
+ f"Cannot open config with path: {filepath}, error: {e.strerror}",
53
+ file=stderr,
54
+ )
55
+ exit(2)
56
+
57
+ def __get_oracle_engine(self):
58
+ return create_engine(self.oracle_con_string)
59
+
60
+ def __get_postgresql_engine(self):
61
+ return create_engine(self.postgresql_con_string)
62
+
63
+ def __create_tables_if_they_dont_exist(self):
64
+ metadata = MetaData()
65
+
66
+ Table(
67
+ self.table_for_imported_attributes,
68
+ metadata,
69
+ Column("id", Integer, primary_key=True, autoincrement=True),
70
+ Column("uid", String(100), nullable=False),
71
+ Column("sp", String(250), default="%"),
72
+ Column("attribute", String(30), nullable=False),
73
+ Column("value", Text),
74
+ Column("expires", Date, default="9999-12-31"),
75
+ UniqueConstraint("uid", "attribute", "sp", "expires"),
76
+ )
77
+
78
+ Table(
79
+ "w_exp_passwd_all",
80
+ metadata,
81
+ Column("people_id", BigInteger, primary_key=True),
82
+ Column("login", String(31), nullable=True),
83
+ Column("heslo_primarni", String(255), nullable=True),
84
+ Column("heslo_sekundarni", String(255), nullable=True),
85
+ Column("zmeneno_primarni", Date, nullable=True),
86
+ Column("zmeneno_sekundarni", Date, nullable=True),
87
+ )
88
+
89
+ try:
90
+ metadata.create_all(self.postgresql_engine)
91
+ except SQLAlchemyError as e:
92
+ print(f"Error creating tables: {e}")
93
+
94
+ def __run_oracle_statement(self, select, params={}):
95
+ with self.oracle_engine.connect() as conn:
96
+ stmt = text(select)
97
+ return conn.execute(stmt, params)
98
+
99
+ def __import_attributes(self, imports):
100
+ """
101
+ Import attributes.
102
+ imports -- array in the form:
103
+ 'select': {
104
+ 'attribute_name': 'value'
105
+ }
106
+ """
107
+ for select, attribute in imports.items():
108
+ stmt = self.__run_oracle_statement(select)
109
+ batch = []
110
+ for row in stmt:
111
+ batch.append(row[0])
112
+ if len(batch) >= self.batch_size:
113
+ self.__insert(batch, attribute)
114
+ batch = []
115
+ if len(batch) > 0:
116
+ self.__insert(batch, attribute)
117
+
118
+ def __import_tables(self, source_table_info, full_sync):
119
+ """
120
+ Import table.
121
+ source_table_info -- array in the form:
122
+ 'source_table': 'source_table_name',
123
+ 'columns': ['first', 'second'],
124
+ 'changed': ['timestamp_column']
125
+
126
+ """
127
+ columns = source_table_info["columns"] + source_table_info["changed"]
128
+ column_list_expr = source_table_info["columns"]
129
+ for change_column in source_table_info["changed"]:
130
+ column_list_expr.append(
131
+ f"TO_CHAR({change_column}, 'YYYY-MM-DD HH24:MI:SS') AS {change_column}"
132
+ )
133
+ column_list_expr = ",".join(column_list_expr)
134
+ params = {}
135
+ if full_sync:
136
+ select = f"SELECT {column_list_expr} FROM {source_table_info.get('source_table', self.imported_table_name)}"
137
+ else:
138
+ selects = []
139
+ with self.oracle_engine.connect() as conn:
140
+ for change_column in source_table_info["changed"]:
141
+ select = f"SELECT {column_list_expr} FROM {source_table_info.get('source_table', self.imported_table_name)}"
142
+ last_value = conn.execute(
143
+ text(
144
+ f"SELECT MAX({change_column}) FROM {self.imported_table_name}"
145
+ )
146
+ ).scalar()
147
+ select += f" WHERE {change_column} >= TO_TIMESTAMP(:{change_column}, 'YYYY-MM-DD HH24:MI:SS')"
148
+ selects.append(select)
149
+ params[change_column] = last_value
150
+ select = " UNION ".join(selects)
151
+ with self.oracle_engine.connect() as conn:
152
+ insert_data = conn.execute(text(select), params)
153
+
154
+ updates = [f"{column} = EXCLUDED.{column}" for column in columns]
155
+ placeholders = [f":{column}" for column in columns]
156
+ query = text(
157
+ f"INSERT INTO {self.imported_table_name} ({','.join(columns)}) VALUES ({','.join(placeholders)}) ON CONFLICT (people_id) DO UPDATE SET {','.join(updates)}"
158
+ )
159
+ row_count = 0
160
+ with self.postgresql_engine.begin() as conn:
161
+ for row in insert_data:
162
+ row_count += 1
163
+ params = {columns[i]: row[i] for i in range(len(columns))}
164
+ conn.execute(query, params)
165
+ print(f"Oracle2PostgreSQL.py - {row_count} account(s) were updated.")
166
+
167
+ def __insert(self, usernames, attribute):
168
+ if not usernames:
169
+ return
170
+
171
+ insert_text = text(
172
+ f'INSERT INTO "{self.table_for_imported_attributes}" (uid, attribute, value) '
173
+ "VALUES (:uid, :attribute, :value) "
174
+ "ON CONFLICT (id) DO UPDATE SET id = EXCLUDED.id"
175
+ )
176
+ with self.postgresql_engine.begin() as conn:
177
+ for username in usernames:
178
+ for name, value in attribute.items():
179
+ try:
180
+ with conn.begin_nested():
181
+ conn.execute(
182
+ insert_text,
183
+ {"uid": username, "attribute": name, "value": value},
184
+ )
185
+ except Exception as e:
186
+ print(
187
+ f"Oracle2PostgreSQL - Failed to insert/update, "
188
+ f"user {username}, attribute {name}, value {value}"
189
+ f"{e}"
190
+ )
191
+
192
+
193
+ def get_args():
194
+ parser = argparse.ArgumentParser()
195
+ parser.add_argument(
196
+ "-f",
197
+ "--full_sync",
198
+ action="store_true",
199
+ default=False,
200
+ help="Whether to do a full sync or not.",
201
+ )
202
+ return parser.parse_args()
203
+
204
+
205
+ def main():
206
+ args = get_args()
207
+
208
+ ora2postgresql = Oracle2PostgreSQL(args.full_sync)
209
+ ora2postgresql.run_sync()
210
+
211
+
212
+ if __name__ == "__main__":
213
+ main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: perun.proxy.utils
3
- Version: 2.5.4
3
+ Version: 2.7.0
4
4
  Summary: Utilities and monitoring probes for Perun ProxyIdP
5
5
  Home-page: https://gitlab.ics.muni.cz/perun/perun-proxyidp/perun-proxy-utils.git
6
6
  Requires-Python: >=3.9
@@ -17,11 +17,16 @@ Requires-Dist: check_nginx_status~=1.0
17
17
  Requires-Dist: pyotp~=2.9
18
18
  Requires-Dist: perun.connector~=3.8
19
19
  Requires-Dist: privacyidea~=3.9
20
+ Requires-Dist: flask~=1.1
21
+ Requires-Dist: idpyoidc~=2.1
22
+ Requires-Dist: sqlalchemy~=1.4
20
23
  Provides-Extra: ldap
21
24
  Requires-Dist: ldap3~=2.9.1; extra == "ldap"
22
25
  Requires-Dist: check_syncrepl_extended~=2020.13; extra == "ldap"
23
26
  Provides-Extra: postgresql
24
27
  Requires-Dist: psycopg2-binary~=2.9; extra == "postgresql"
28
+ Provides-Extra: oracle
29
+ Requires-Dist: cx-Oracle~=8.3; extra == "oracle"
25
30
 
26
31
  # Perun proxy utils
27
32
 
@@ -40,7 +45,8 @@ There are several extras which are required only for some scripts:
40
45
  - `[ldap]` for check_ldap and check_ldap_syncrepl
41
46
  - this also requires
42
47
  installing [build prerequisites of the python-ldap library](https://www.python-ldap.org/en/latest/installing.html#build-prerequisites)
43
- - `[postgresql]` for check_pgsql
48
+ - `[postgresql]` for check_pgsql and oracle2postgresql
49
+ - `[oracle]` for oracle2postgresql
44
50
 
45
51
  ## Scripts
46
52
 
@@ -136,6 +142,25 @@ python3 sync_usable_token_types.py
136
142
  --perun-connector-config-path "/path/to/file"
137
143
  ```
138
144
 
145
+ ### oracle2postgresql.py
146
+ Synchronizes data from Oracle db to PostgreSQL db.
147
+
148
+ Requires config file located at `/etc/oracle2postgresql_cfg.yaml` and [Oracle client](https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html).
149
+ #### Functionality
150
+ 1. Attribute Import:
151
+
152
+ Imports attributes from Oracle database tables to the PostgreSQL database, into a table compatible with [simplesamlphp-module-sqlattribs](https://github.com/tenet-ac-za/simplesamlphp-module-sqlattribs). Each attribute is specified with a corresponding SQL SELECT statement.
153
+
154
+ 2. Table Import:
155
+
156
+ Imports tables from the Oracle database to the PostgreSQL one. Supports both full and incremental synchronization.
157
+ For full synchronization, all records from the source table are imported.
158
+ For incremental synchronization, only records modified since the last synchronization are imported, based on designated change columns.
159
+ The full sync in turned off by default. Run with `-f` or `--full_sync` flag to turn it on.
160
+
161
+ Attributes and tables intended for import are stated in the config.
162
+ Target table names from PostgreSQL are hardcoded due to the possibility of needing to create them.
163
+
139
164
  ## Nagios probes
140
165
 
141
166
  All nagios scripts are located under `nagios` directory.
@@ -246,3 +271,32 @@ For usage instructions, run:
246
271
  ```sh
247
272
  check_pgsql --help
248
273
  ```
274
+
275
+ ### check_oidc_login
276
+
277
+ Check that OIDC auth process works by acting as an OIDC client (RP) attempting to
278
+ authenticate against an OIDC server (OP). Supports clients with PKCE and non-PKCE
279
+ authentication. Additional tag `-pkce` must be added to test PKCE log in. Using client
280
+ secret is always enforced since some clients might require it on top of PKCE.
281
+
282
+ Target OIDC server (OP) should **not** require authentication for this probe to
283
+ work. It **does not** test the credentials' validity but rather the OIDC auth process. This
284
+ can be achieved, for example, by setting up SATOSA's reflector backend.
285
+
286
+ For usage instructions, run:
287
+
288
+ ```sh
289
+ check_oidc_login --help
290
+ ```
291
+
292
+ Example:
293
+
294
+ ```sh
295
+ python3 check_oidc_login
296
+ --redirect-uri "http://localhost:44322/signin-oidc"
297
+ --client-id "my_oidc_client_id"
298
+ --client-secret "my_oidc_pkce_secret"
299
+ --issuer "https://id.muni.cz"
300
+ -vvv # verbose debug output
301
+ -pkce
302
+ ```
@@ -10,6 +10,7 @@ perun.proxy.utils.egg-info/requires.txt
10
10
  perun.proxy.utils.egg-info/top_level.txt
11
11
  perun/proxy/utils/__init__.py
12
12
  perun/proxy/utils/metadata_expiration.py
13
+ perun/proxy/utils/oracle2postgresql.py
13
14
  perun/proxy/utils/print_docker_versions.py
14
15
  perun/proxy/utils/run_probes.py
15
16
  perun/proxy/utils/run_version_script.py
@@ -24,6 +25,7 @@ perun/proxy/utils/nagios/check_ldap.py
24
25
  perun/proxy/utils/nagios/check_ldap_syncrepl.py
25
26
  perun/proxy/utils/nagios/check_mongodb.py
26
27
  perun/proxy/utils/nagios/check_nginx.py
28
+ perun/proxy/utils/nagios/check_oidc_login.py
27
29
  perun/proxy/utils/nagios/check_pgsql.py
28
30
  perun/proxy/utils/nagios/check_php_syntax.py
29
31
  perun/proxy/utils/nagios/check_privacyidea.py
@@ -6,6 +6,7 @@ check_ldap = perun.proxy.utils.nagios.check_ldap:main
6
6
  check_ldap_syncrepl = check_syncrepl_extended.check_syncrepl_extended:main
7
7
  check_mongodb = perun.proxy.utils.nagios.check_mongodb:main
8
8
  check_nginx = check_nginx_status.check_nginx_status:main
9
+ check_oidc_login = perun.proxy.utils.nagios.check_oidc_login:main
9
10
  check_pgsql = perun.proxy.utils.nagios.check_pgsql:main
10
11
  check_php_syntax = perun.proxy.utils.nagios.check_php_syntax:main
11
12
  check_privacyidea = perun.proxy.utils.nagios.check_privacyidea:main
@@ -14,6 +15,7 @@ check_saml = perun.proxy.utils.nagios.check_saml:main
14
15
  check_user_logins = perun.proxy.utils.nagios.check_user_logins:main
15
16
  check_webserver_availability = perun.proxy.utils.nagios.webserver_availability:main
16
17
  metadata_expiration = perun.proxy.utils.metadata_expiration:main
18
+ oracle2postgresql = perun.proxy.utils.oracle2postgresql:main
17
19
  print_docker_versions = perun.proxy.utils.print_docker_versions:main
18
20
  run_probes = perun.proxy.utils.run_probes:main
19
21
  run_version_script = perun.proxy.utils.run_version_script:main
@@ -9,10 +9,16 @@ check_nginx_status~=1.0
9
9
  pyotp~=2.9
10
10
  perun.connector~=3.8
11
11
  privacyidea~=3.9
12
+ flask~=1.1
13
+ idpyoidc~=2.1
14
+ sqlalchemy~=1.4
12
15
 
13
16
  [ldap]
14
17
  ldap3~=2.9.1
15
18
  check_syncrepl_extended~=2020.13
16
19
 
20
+ [oracle]
21
+ cx-Oracle~=8.3
22
+
17
23
  [postgresql]
18
24
  psycopg2-binary~=2.9
@@ -1,5 +1,5 @@
1
1
  [metadata]
2
- version = 2.5.4
2
+ version = 2.7.0
3
3
  license_files = LICENSE
4
4
  long_description = file: README.md
5
5
  long_description_content_type = text/markdown
@@ -19,6 +19,9 @@ setuptools.setup(
19
19
  "pyotp~=2.9",
20
20
  "perun.connector~=3.8",
21
21
  "privacyidea~=3.9",
22
+ "flask~=1.1",
23
+ "idpyoidc~=2.1",
24
+ "sqlalchemy~=1.4",
22
25
  ],
23
26
  extras_require={
24
27
  "ldap": [
@@ -28,6 +31,9 @@ setuptools.setup(
28
31
  "postgresql": [
29
32
  "psycopg2-binary~=2.9",
30
33
  ],
34
+ "oracle": [
35
+ "cx-Oracle~=8.3",
36
+ ],
31
37
  },
32
38
  entry_points={
33
39
  "console_scripts": [
@@ -40,6 +46,7 @@ setuptools.setup(
40
46
  "check_ldap_syncrepl=check_syncrepl_extended.check_syncrepl_extended:main",
41
47
  "check_mongodb=perun.proxy.utils.nagios.check_mongodb:main",
42
48
  "check_nginx=check_nginx_status.check_nginx_status:main",
49
+ "check_oidc_login=perun.proxy.utils.nagios.check_oidc_login:main",
43
50
  "check_rpc_status=perun.proxy.utils.nagios.check_rpc_status:main",
44
51
  "check_saml=perun.proxy.utils.nagios.check_saml:main",
45
52
  "check_user_logins=perun.proxy.utils.nagios.check_user_logins:main",
@@ -54,6 +61,7 @@ setuptools.setup(
54
61
  "separate_oidc_logs=perun.proxy.utils.separate_oidc_logs:main",
55
62
  "separate_ssp_logs=perun.proxy.utils.separate_ssp_logs:main",
56
63
  "sync_usable_token_types=perun.proxy.utils.sync_usable_token_types:main",
64
+ "oracle2postgresql=perun.proxy.utils.oracle2postgresql:main",
57
65
  ]
58
66
  },
59
67
  )