myldapsync 1.0.3__py2.py3-none-any.whl

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.

Potentially problematic release.


This version of myldapsync might be problematic. Click here for more details.

myldapsync/__init__.py ADDED
@@ -0,0 +1,292 @@
1
+ ###############################################################################
2
+ #
3
+ # myldapsync - adopted for MySQL fork of pgldapsync by EnterpriseDB Corporation
4
+ #
5
+ # Synchronise MySQL users with users in an LDAP directory.
6
+ #
7
+ ###############################################################################
8
+
9
+ """myldapsync main entry point."""
10
+
11
+ # FIX THIS!
12
+ # pylint: disable=too-many-branches,too-many-locals,too-many-statements
13
+
14
+ import argparse
15
+ import os
16
+
17
+ import configparser
18
+
19
+ from myldapsync.ldaputils.connection import connect_ldap_server
20
+ from myldapsync.ldaputils.users import *
21
+ from myldapsync.myutils.users import *
22
+
23
+
24
+ def read_command_line():
25
+ """Read the command line arguments.
26
+
27
+ Returns:
28
+ ArgumentParser: The parsed arguments object
29
+ """
30
+ parser = argparse.ArgumentParser(
31
+ description='Synchronise users and groups from LDAP/AD to MySQL.')
32
+ parser.add_argument("--dry-run", "-d", action='store_true',
33
+ help="don't apply changes to the database server, "
34
+ "dump the SQL to stdout instead")
35
+ parser.add_argument("config", metavar="CONFIG_FILE",
36
+ help="the configuration file to read")
37
+
38
+ args = parser.parse_args()
39
+
40
+ return args
41
+
42
+
43
+ def read_config(file):
44
+ """Read the config file.
45
+
46
+ Args:
47
+ file (str): The config file to read
48
+ my_user (str[]): A list of users in MySQL
49
+
50
+ Returns:
51
+ ConfigParser: The config object
52
+ """
53
+ config = configparser.ConfigParser()
54
+
55
+ # Read the default config
56
+ defaults = os.path.join(os.path.dirname(os.path.realpath(__file__)),
57
+ 'config_default.ini')
58
+
59
+ try:
60
+ config.read(defaults)
61
+ except configparser.Error as exception:
62
+ sys.stderr.write(
63
+ "Error reading default configuration file (%s): %s\n" %
64
+ (defaults, exception))
65
+ sys.exit(1)
66
+
67
+ try:
68
+ config.read(file)
69
+ except configparser.Error as exception:
70
+ sys.stderr.write(
71
+ "Error reading user configuration file (%s): %s\n" %
72
+ (file, exception))
73
+ sys.exit(1)
74
+
75
+ return config
76
+
77
+
78
+ def main():
79
+ """The core structure of the app."""
80
+
81
+ # Read the command line options
82
+ args = read_command_line()
83
+
84
+ # Read the config file
85
+ config = read_config(args.config)
86
+
87
+ # MySQL connection dictionary
88
+ connection_string_params = {}
89
+
90
+ if (host := config.get('mysql', 'host')) != '':
91
+ connection_string_params = dict(connection_string_params, host=host)
92
+
93
+ if (user := config.get('mysql', 'user')) != '':
94
+ connection_string_params = dict(connection_string_params, user=user)
95
+
96
+ if (password := config.get('mysql', 'password')) != '':
97
+ connection_string_params = dict(connection_string_params, password=password)
98
+
99
+ if (db := config.get('mysql', 'db')) != '':
100
+ connection_string_params = dict(connection_string_params, db=db)
101
+
102
+ if (auth_plugin := config.get('mysql', 'auth_plugin')) != '':
103
+ connection_string_params = dict(connection_string_params, auth_plugin=auth_plugin)
104
+
105
+ if (ssl_ca := config.get('mysql', 'ssl_ca')) != '':
106
+ connection_string_params = dict(connection_string_params, ssl_ca=ssl_ca)
107
+
108
+ if (ssl_cert := config.get('mysql', 'ssl_cert')) != '':
109
+ connection_string_params = dict(connection_string_params, ssl_cert=ssl_cert)
110
+
111
+ if (ssl_key := config.get('mysql', 'ssl_key')) != '':
112
+ connection_string_params = dict(connection_string_params, ssl_key=ssl_key)
113
+
114
+ if (ssl_verify_identity := config.get('mysql', 'ssl_verify_identity')) != '':
115
+ connection_string_params = dict(connection_string_params, ssl_verify_identity=ssl_verify_identity)
116
+
117
+ if (ssl_verify_cert := config.get('mysql', 'ssl_verify_cert')) != '':
118
+ connection_string_params = dict(connection_string_params, ssl_verify_cert=ssl_verify_cert)
119
+
120
+ if (use_pure := config.get('mysql', 'use_pure')) != '':
121
+ connection_string_params = dict(connection_string_params, use_pure=use_pure)
122
+
123
+ if (SERVICE_NAME := config.get('mysql', 'SERVICE_NAME')) and (LDAP_SERVER_IP := config.get('mysql', 'LDAP_SERVER_IP')) != '':
124
+ connection_string_params = dict(connection_string_params, krb_service_principal=f"{SERVICE_NAME}/{LDAP_SERVER_IP}")
125
+
126
+ # Connect to LDAP and get the users we care about
127
+ ldap_conn = connect_ldap_server(config)
128
+ if ldap_conn is None:
129
+ sys.exit(1)
130
+
131
+ ldap_users = get_filtered_ldap_users(config, ldap_conn, False)
132
+ if ldap_users is None:
133
+ sys.exit(1)
134
+
135
+ # Get the LDAP admin users, if the base DN and filter are configured
136
+ if config.get('ldap', 'admin_base_dn') == '' or \
137
+ config.get('ldap', 'admin_filter_string') == '':
138
+ ldap_admin_users = []
139
+ else:
140
+ ldap_admin_users = get_ldap_users(config, ldap_conn, True)
141
+ if ldap_admin_users is None:
142
+ sys.exit(1)
143
+
144
+ # Connect to MySQL and get the users we care about
145
+ my_conn = mysql.connector.connect(**connection_string_params)
146
+ if my_conn is None:
147
+ sys.exit(1)
148
+
149
+ my_users = get_filtered_my_users(config, my_conn)
150
+ if my_users is None:
151
+ sys.exit(1)
152
+
153
+ # Compare the LDAP and MySQL users and get the lists of users
154
+ # to add and drop.
155
+ users_to_create = get_create_users(ldap_users, my_users)
156
+ users_to_drop = get_drop_users(ldap_users, my_users)
157
+
158
+ # Create/drop users if required
159
+ have_work = ((config.getboolean('general',
160
+ 'add_ldap_users_to_mysql') and
161
+ len(users_to_create) > 0) or
162
+ (config.getboolean('general',
163
+ 'remove_users_from_mysql') and
164
+ len(users_to_drop) > 0))
165
+
166
+ # Initialise the counters for operations/errors
167
+ users_added = 0
168
+ users_dropped = 0
169
+ users_add_errors = 0
170
+ users_drop_errors = 0
171
+
172
+ # Warn the user we're in dry run mode
173
+ if args.dry_run:
174
+ print("-- This is an LDAP sync dry run.")
175
+ print("-- The commands below can be manually executed if required.")
176
+
177
+ cur = None
178
+ if have_work:
179
+
180
+ # Begin the transaction
181
+ if args.dry_run:
182
+ print("START TRANSACTION;")
183
+ else:
184
+ cur = my_conn.cursor()
185
+ cur.execute("START TRANSACTION;")
186
+
187
+ # Set authentication plugin
188
+ auth_plugin = config.get('general', 'auth_plugin')
189
+ if auth_plugin == 'simple':
190
+ identified = 'WITH authentication_ldap_simple'
191
+ elif auth_plugin == 'sasl':
192
+ identified = 'WITH authentication_ldap_sasl'
193
+ elif auth_plugin == 'pam':
194
+ dbms = config.get('general', 'dbms')
195
+ if dbms == 'mysql':
196
+ identified = 'WITH authentication_pam'
197
+ elif dbms == 'psms':
198
+ compat = config.get('general', 'compat')
199
+ if compat:
200
+ identified = 'WITH auth_pam_compat'
201
+ else:
202
+ identified = 'WITH auth_pam'
203
+ elif dbms == 'mariadb':
204
+ identified = 'VIA pam'
205
+
206
+ # If we need to add users to MySQL, then do so
207
+ if config.getboolean('general', 'add_ldap_users_to_mysql'):
208
+
209
+ # For each user, get the required attributes and SQL snippets
210
+ for user in users_to_create:
211
+ user_name = user.replace('\'', '\\\'')
212
+ user_grants = get_user_grants(config, user_name)
213
+ user_admin_grants = get_user_grants(config, user_name,
214
+ (user in ldap_admin_users))
215
+ privilege_list = get_user_privileges(config, user_name,
216
+ (user in ldap_admin_users))
217
+
218
+ if args.dry_run:
219
+
220
+ # It's a dry run, so just print the output
221
+ print('CREATE USER "%s" IDENTIFIED %s; %s %s %s' %
222
+ (user_name, identified, privilege_list, user_grants, user_admin_grants))
223
+ else:
224
+
225
+ # This is a live run, so directly execute the SQL generated.
226
+ # For each statement, create a savepoint so we can rollback
227
+ # to it if there's an error. That allows us to fail only
228
+ # a single user rather than all of them.
229
+ try:
230
+ # We can't use a real parameterised query here as we're
231
+ # working with an object, not data.
232
+ cur.execute('CREATE USER "%s" IDENTIFIED %s;' %
233
+ (user_name, identified))
234
+ cur.execute('%s' % privilege_list)
235
+ cur.execute('%s' % user_grants)
236
+ cur.execute('%s' % user_admin_grants)
237
+ users_added = users_added + 1
238
+ except mysql.connector.Error as exception:
239
+ sys.stderr.write("Error creating user %s: %s" % (user,
240
+ exception))
241
+ users_add_errors = users_add_errors + 1
242
+ cur.execute('ROLLBACK;')
243
+
244
+ # If we need to drop users from MySQL, then do so
245
+ if config.getboolean('general', 'remove_users_from_mysql'):
246
+
247
+ # For each user to drop, just run the DROP statement
248
+ for user in users_to_drop:
249
+
250
+ user_name = user.replace('\'', '\\\'')
251
+
252
+ if args.dry_run:
253
+
254
+ # It's a dry run, so just print the output
255
+ print('DROP USER "%s";' % user_name)
256
+ else:
257
+
258
+ # This is a live run, so directly execute the SQL generated.
259
+ # For each statement, create a savepoint so we can rollback
260
+ # to it if there's an error. That allows us to fail only
261
+ # a single user rather than all of them.
262
+ try:
263
+ # We can't use a real parameterised query here as we're
264
+ # working with an object, not data.
265
+ cur.execute('DROP USER "%s";' % user_name)
266
+ users_dropped = users_dropped + 1
267
+ except mysql.connector.Error as exception:
268
+ sys.stderr.write("Error dropping user %s: %s" % (user,
269
+ exception))
270
+ users_drop_errors = users_drop_errors + 1
271
+ cur.execute('ROLLBACK;')
272
+
273
+ if have_work:
274
+
275
+ # Commit the transaction
276
+ if args.dry_run:
277
+ print("COMMIT;")
278
+ else:
279
+ cur.execute("COMMIT;")
280
+ cur.close()
281
+
282
+ # Print the summary of work completed
283
+ print("Users added to MySQL: %d" % users_added)
284
+ print("Users dropped from MySQL: %d" % users_dropped)
285
+ if users_add_errors > 0:
286
+ print("Errors adding users: %d" %
287
+ users_add_errors)
288
+ if users_drop_errors > 0:
289
+ print("Errors dropping users: %d" %
290
+ users_drop_errors)
291
+ else:
292
+ print("No users were added or dropped.")
@@ -0,0 +1,144 @@
1
+ ##########################################################################
2
+ #
3
+ # config.ini.example
4
+ #
5
+ # This file is a template for your site-specific configuration. Copy it,
6
+ # and modify to suit your requirements.
7
+ #
8
+ # Some values have defaults which are specified in config_default.ini.
9
+ # Others *must* be set in your configuration file.
10
+ #
11
+ ##########################################################################
12
+
13
+ ##########################################################################
14
+ # LDAP access configuration
15
+ ##########################################################################
16
+
17
+ [ldap]
18
+
19
+ # Debug LDAP connections?
20
+ debug = false
21
+
22
+ # LDAP server connection details (REQUIRED)
23
+ server_uri = ldap://ldap.example.com
24
+
25
+ # User to bind to the directory as. Leave empty for anonymous binding.
26
+ bind_username =
27
+ bind_password =
28
+
29
+ # Use TLS? If the URI scheme is ldaps://, this is ignored.
30
+ use_starttls = false
31
+
32
+ # TLS/SSL certificates. Specify if required, otherwise leave empty
33
+ ca_cert_file =
34
+ cert_file =
35
+ key_file =
36
+
37
+ # Search scope for users (one of BASE, LEVEL or SUBTREE)
38
+ search_scope = LEVEL
39
+
40
+ # The base DN for the user search (REQUIRED)
41
+ base_dn = CN=Users,dc=example,dc=com
42
+
43
+ # Filter string for the user search. For OpenLDAP, '(cn=*)' may well be enough.
44
+ # For AD, you might use '(objectClass=user)' (REQUIRED)
45
+ filter_string = (objectClass=user)
46
+
47
+ # The base DN for the admin user search. This may be the same as the base_dn, or
48
+ # may point to an alternate OU. If empty, no search will be performed.
49
+ admin_base_dn = CN=Users,dc=example,dc=com
50
+
51
+ # The filter string for users that should be created as superusers regardless of
52
+ # the [general]/role_attribute_superuser setting. With AD you might use a filter
53
+ # such as: (&(objectClass=user)(memberof=CN=MYGROUP,CN=Users,dc=example,dc=com))
54
+ # If, for example on OpenLDAP, your admin users are members of an alternate OU,
55
+ # then a filter of (cn=*) may suffice.
56
+ # If empty, no search will be performed.
57
+ admin_filter_string = (&(objectClass=user)(memberof=CN=MYGROUP,CN=Users,dc=example,dc=com))
58
+
59
+ # The LDAP attribute containing user names. In OpenLDAP, this may be 'uid'
60
+ # whilst in AD, 'sAMAccountName' might be appropriate. (REQUIRED)
61
+ username_attribute = uid
62
+
63
+ # A command delimited list of users to ignore
64
+ ignore_users = Manager,ldap.sync
65
+
66
+ # Kerberos authentication parameters
67
+ use_kerberos =
68
+ SERVICE_NAME =
69
+ LDAP_SERVER_IP =
70
+
71
+
72
+ ##########################################################################
73
+ # MySQL access configuration
74
+ ##########################################################################
75
+
76
+ [mysql]
77
+
78
+ # A comma delimited list of users to ignore
79
+ ignore_users = root
80
+
81
+ # Connection parameters
82
+ host = localhost
83
+ db = mysql
84
+ user = root
85
+ password =
86
+ auth_plugin = mysql_native_password
87
+ ssl_ca =
88
+ ssl_cert =
89
+ ssl_key =
90
+ ssl_verify_identity =
91
+ ssl_verify_cert =
92
+ use_pure =
93
+ SERVICE_NAME =
94
+
95
+ ##########################################################################
96
+ # General configuration
97
+ ##########################################################################
98
+
99
+ [general]
100
+
101
+ # Authentication plugin (one of simple, sasl or pam)
102
+ auth_plugin = pam
103
+
104
+ # Oracle-compatible PAM
105
+ compat = false
106
+
107
+ # Database management system - one of mysql, psms (Percona Server for MySQL) or mariadb.
108
+ dbms = psms
109
+
110
+ # Add LDAP users to MySQL if they don't exist, or ignore them?
111
+ add_ldap_users_to_mysql = true
112
+
113
+ # Remove MySQL users if they don't exist in LDAP, or ignore them?
114
+ remove_users_from_mysql = true
115
+
116
+ # Database for privileges granting. If empty privileges will be granted for everything i.e. *.*.
117
+ # Wildcard could be used like "db%" so grants will be applied for every database with "db" name prefix.
118
+ database =
119
+
120
+ # Privileges to grant to users in MySQL.
121
+ # Note these privileges are only applied to users when created. Existing users are unaffected.
122
+ user_privilege_all = false
123
+ user_privilege_create = false
124
+ user_privilege_create_role = false
125
+ user_privilege_alter = false
126
+ user_privilege_create_user = false
127
+ user_privilege_alter_rename = false
128
+ user_privilege_event = false
129
+ user_privilege_execute = false
130
+ user_privilege_trigger = false
131
+ user_privilege_insert = false
132
+ user_privilege_update = false
133
+ user_privilege_delete = false
134
+ user_privilege_drop = false
135
+
136
+ # A comma delimited list of roles to grant membership to when creating
137
+ # users. Note that existing users will not be modified. Roles specified
138
+ # here must already exist in MySQL. Supported in MySQL 8+ and MariaDB 10+.
139
+ roles_to_grant = group1,group2
140
+
141
+ # A comma delimited list of roles to grant membership to with ADMIN when
142
+ # creating users. Note that existing users will not be modified. Roles
143
+ # specified here must already exist in MySQL. Supported in MySQL 8+ and MariaDB 10+.
144
+ roles_to_grant_with_admin = group3
@@ -0,0 +1,62 @@
1
+ ##########################################################################
2
+ # This config file is read before the user config and is present to
3
+ # supply default values for optional parameters.
4
+ ##########################################################################
5
+
6
+ [ldap]
7
+ debug = false
8
+ server_uri =
9
+ bind_username =
10
+ bind_password =
11
+ filter_string = (objectClass=user)
12
+ username_attribute = sAMAccountName
13
+ use_starttls = false
14
+ ca_cert_file =
15
+ cert_file =
16
+ key_file =
17
+ search_scope = LEVEL
18
+ base_dn =
19
+ admin_base_dn =
20
+ admin_filter_string =
21
+ use_kerberos =
22
+ SERVICE_NAME =
23
+ LDAP_SERVER_IP =
24
+ ignore_users =
25
+
26
+ [mysql]
27
+ ignore_users = root
28
+ host = localhost
29
+ db = mysql
30
+ user = root
31
+ password =
32
+ auth_plugin = mysql_native_password
33
+ ssl_ca =
34
+ ssl_cert =
35
+ ssl_key =
36
+ ssl_verify_identity =
37
+ ssl_verify_cert =
38
+ use_pure =
39
+ SERVICE_NAME =
40
+
41
+ [general]
42
+ auth_plugin = pam
43
+ compat = false
44
+ dbms = psms
45
+ add_ldap_users_to_mysql = true
46
+ remove_users_from_mysql = true
47
+ database =
48
+ user_privilege_all = false
49
+ user_privilege_create = false
50
+ user_privilege_create_role = false
51
+ user_privilege_alter = false
52
+ user_privilege_create_user = false
53
+ user_privilege_alter_rename = false
54
+ user_privilege_event = false
55
+ user_privilege_execute = false
56
+ user_privilege_trigger = false
57
+ user_privilege_insert = false
58
+ user_privilege_update = false
59
+ user_privilege_delete = false
60
+ user_privilege_drop = false
61
+ roles_to_grant =
62
+ roles_to_grant_with_admin =
@@ -0,0 +1,7 @@
1
+ ###############################################################################
2
+ #
3
+ # myldapsync - adopted for MySQL fork of pgldapsync by EnterpriseDB Corporation
4
+ #
5
+ # Synchronise MySQL users with users in an LDAP directory.
6
+ #
7
+ ###############################################################################
@@ -0,0 +1,128 @@
1
+ ###############################################################################
2
+ #
3
+ # myldapsync - adopted for MySQL fork of pgldapsync by EnterpriseDB Corporation
4
+ #
5
+ # Synchronise MySQL users with users in an LDAP directory.
6
+ #
7
+ ###############################################################################
8
+
9
+ """LDAP connection functions."""
10
+
11
+ # FIX THIS!
12
+ # pylint: disable=too-many-branches
13
+
14
+ import ssl
15
+ import sys
16
+
17
+ from ldap3 import Connection, Server, Tls, SASL, KERBEROS
18
+ from ldap3.core.exceptions import LDAPBindError, LDAPSocketOpenError, \
19
+ LDAPStartTLSError, LDAPSASLBindInProgressError, LDAPSASLPrepError, \
20
+ LDAPSASLMechanismNotSupportedError
21
+
22
+
23
+ try:
24
+ from urllib.parse import urlparse
25
+ except ImportError:
26
+ from urlparse import urlparse
27
+
28
+
29
+ def connect_ldap_server(config):
30
+ """Setup the connection to the LDAP server.
31
+
32
+ Args:
33
+ config (ConfigParser): The application configuration
34
+
35
+ Returns:
36
+ ldap3.core.connection.Connection: The LDAP connection object
37
+ """
38
+ # Parse the server URI
39
+ uri = urlparse(config.get('ldap', 'server_uri'))
40
+
41
+ # Create the TLS configuration object if required
42
+ tls = None
43
+
44
+ if uri.scheme == 'ldaps' or config.getboolean('ldap', 'use_starttls'):
45
+
46
+ if (ca_cert_file := config.get('ldap', 'ca_cert_file')) != '':
47
+ pass
48
+ else:
49
+ ca_cert_file = None
50
+
51
+ if (cert_file := config.get('ldap', 'cert_file')) != '':
52
+ pass
53
+ else:
54
+ cert_file = None
55
+
56
+ if (key_file := config.get('ldap', 'key_file')) != '':
57
+ pass
58
+ else:
59
+ key_file = None
60
+
61
+ tls = Tls(
62
+ local_private_key_file=key_file,
63
+ local_certificate_file=cert_file,
64
+ validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1,
65
+ ca_certs_file=ca_cert_file)
66
+
67
+ # Debug
68
+ if config.getboolean('ldap', 'debug'):
69
+ sys.stderr.write("TLS/SSL configuration: %s\n" % tls)
70
+
71
+ # Create the server object
72
+ server = Server(uri.hostname,
73
+ port=uri.port,
74
+ tls=tls,
75
+ use_ssl=uri.scheme == 'ldaps')
76
+
77
+ # Debug
78
+ if config.getboolean('ldap', 'debug'):
79
+ sys.stderr.write("LDAP server config: %s\n" % server)
80
+
81
+ # Create the connection
82
+ conn = None
83
+ try:
84
+ if config.get('ldap', 'bind_username') == '' and config.get('ldap', 'use_krb') == '':
85
+ conn = Connection(server, auto_bind=True)
86
+ elif config.get('ldap', 'use_krb') != '':
87
+ if (SERVICE_NAME := config.get('ldap', 'SERVICE_NAME')) and (LDAP_SERVER_IP := config.get('ldap', 'LDAP_SERVER_IP')) != '':
88
+ SPN = f"{SERVICE_NAME}/{LDAP_SERVER_IP}"
89
+ conn = Connection(server, user=SPN, authentication=SASL, sasl_mechanism=KERBEROS)
90
+ else:
91
+ conn = Connection(server, authentication=SASL, sasl_mechanism=KERBEROS)
92
+ else:
93
+ conn = Connection(server,
94
+ config.get('ldap', 'bind_username'),
95
+ config.get('ldap', 'bind_password'),
96
+ auto_bind=True)
97
+ except LDAPSocketOpenError as exception:
98
+ sys.stderr.write("Error connecting to the LDAP server: %s\n" %
99
+ exception)
100
+ except LDAPBindError as exception:
101
+ sys.stderr.write("Error binding to the LDAP server: %s\n" % exception)
102
+
103
+ except LDAPSASLBindInProgressError as exception:
104
+ sys.stderr.write("SASL bind in progress error: %s\n" % exception)
105
+
106
+ except LDAPSASLPrepError as exception:
107
+ sys.stderr.write("SASL prep error: %s\n" % exception)
108
+
109
+ except LDAPSASLMechanismNotSupportedError as exception:
110
+ sys.stderr.write("SASL mechanism not supported error: %s\n" % exception)
111
+
112
+ # Debug
113
+ if config.getboolean('ldap', 'debug'):
114
+ sys.stderr.write("Initial LDAP connection: %s\n" % conn)
115
+
116
+ # Enable TLS if STARTTLS is configured
117
+ if uri.scheme != 'ldaps' and config.getboolean('ldap', 'use_starttls'):
118
+ try:
119
+ conn.start_tls()
120
+ except LDAPStartTLSError as exception:
121
+ sys.stderr.write("Error starting TLS: %s\n" % exception)
122
+ return None
123
+
124
+ # Debug
125
+ if config.getboolean('ldap', 'debug'):
126
+ sys.stderr.write("Final LDAP connection: %s\n" % conn)
127
+
128
+ return conn
@@ -0,0 +1,80 @@
1
+ ###############################################################################
2
+ #
3
+ # myldapsync - adopted for MySQL fork of pgldapsync by EnterpriseDB Corporation
4
+ #
5
+ # Synchronise MySQL users with users in an LDAP directory.
6
+ #
7
+ ###############################################################################
8
+
9
+ """LDAP user functions."""
10
+
11
+ import sys
12
+
13
+ from ldap3.core.exceptions import LDAPInvalidFilterError, \
14
+ LDAPInvalidScopeError, LDAPAttributeError
15
+
16
+
17
+ def get_ldap_users(config, conn, admin):
18
+ """Get a list of users from the LDAP server.
19
+
20
+ Args:
21
+ config (ConfigParser): The application configuration
22
+ conn (ldap3.core.connection.Connection): The LDAP connection object
23
+ admin (bool): Return users in the admin group?
24
+ Returns:
25
+ str[]: A list of user names
26
+ """
27
+ users = []
28
+
29
+ if admin:
30
+ base_dn = config.get('ldap', 'admin_base_dn')
31
+ search_filter = config.get('ldap', 'admin_filter_string')
32
+ else:
33
+ base_dn = config.get('ldap', 'base_dn')
34
+ search_filter = config.get('ldap', 'filter_string')
35
+
36
+ try:
37
+ conn.search(base_dn,
38
+ search_filter,
39
+ config.get('ldap', 'search_scope'),
40
+ attributes=[config.get('ldap', 'username_attribute')]
41
+ )
42
+ except LDAPInvalidScopeError as exception:
43
+ sys.stderr.write("Error searching the LDAP directory: %s\n" % exception)
44
+ sys.exit(1)
45
+ except LDAPAttributeError as exception:
46
+ sys.stderr.write("Error searching the LDAP directory: %s\n" % exception)
47
+ sys.exit(1)
48
+ except LDAPInvalidFilterError as exception:
49
+ sys.stderr.write("Error searching the LDAP directory: %s\n" % exception)
50
+ sys.exit(1)
51
+
52
+ for entry in conn.entries:
53
+ users.append(entry[config.get('ldap', 'username_attribute')].value)
54
+
55
+ return users
56
+
57
+
58
+ def get_filtered_ldap_users(config, conn, admin):
59
+ """Get a filtered list of users from the LDAP server, having removed users
60
+ to be ignored.
61
+
62
+ Args:
63
+ config (ConfigParser): The application configuration
64
+ conn (ldap3.core.connection.Connection): The LDAP connection object
65
+ admin (bool): Return users in the admin group?
66
+ Returns:
67
+ str[]: A filtered list of user names
68
+ """
69
+ users = get_ldap_users(config, conn, admin)
70
+ if users is None:
71
+ return None
72
+
73
+ # Remove ignored users
74
+ for user in config.get('ldap', 'ignore_users').split(','):
75
+ try:
76
+ users.remove(user)
77
+ except ValueError:
78
+ pass
79
+
80
+ return users
@@ -0,0 +1,7 @@
1
+ ###############################################################################
2
+ #
3
+ # myldapsync - adopted for MySQL fork of pgldapsync by EnterpriseDB Corporation
4
+ #
5
+ # Synchronise MySQL users with users in an LDAP directory.
6
+ #
7
+ ###############################################################################
@@ -0,0 +1,215 @@
1
+ ###############################################################################
2
+ #
3
+ # myldapsync - adopted for MySQL fork of pgldapsync by EnterpriseDB Corporation
4
+ #
5
+ # Synchronise MySQL users with users in an LDAP directory.
6
+ #
7
+ ###############################################################################
8
+
9
+ """MySQL user functions."""
10
+
11
+ import sys
12
+
13
+ import mysql.connector
14
+
15
+
16
+ def get_my_users(conn):
17
+ """Get a list of user from the MySQL server.
18
+
19
+ Args:
20
+ conn (connection): The MySQL connection object
21
+ Returns:
22
+ str[]: A list of user names
23
+ """
24
+ cur = conn.cursor()
25
+
26
+ try:
27
+ cur.execute("SELECT user FROM mysql.user\n"
28
+ "WHERE account_locked='N'\n"
29
+ "AND password_expired='N'\n"
30
+ "AND authentication_string IS NOT NULL;")
31
+ rows = cur.fetchall()
32
+ except mysql.connector.Error as exception:
33
+ sys.stderr.write("Error retrieving MySQL users: %s\n" %
34
+ exception)
35
+ return None
36
+
37
+ users = []
38
+
39
+ for row in rows:
40
+ users.append(row[0])
41
+
42
+ cur.close()
43
+
44
+ return users
45
+
46
+
47
+ def get_filtered_my_users(config, conn):
48
+ """Get a filtered list of users from the MySQL server, having
49
+ removed users to be ignored.
50
+
51
+ Args:
52
+ config (ConfigParser): The application configuration
53
+ conn (connection): The MySQL connection object
54
+ Returns:
55
+ str[]: A filtered list of users
56
+ """
57
+ users = get_my_users(conn)
58
+ if users is None:
59
+ return None
60
+
61
+ # Remove ignored users
62
+ for user in config.get('mysql', 'ignore_users').split(','):
63
+ try:
64
+ users = [members for members in users if user != members]
65
+ except ValueError:
66
+ pass
67
+
68
+ return users
69
+
70
+
71
+ def get_user_privileges(config, user, with_admin=False):
72
+ """Generate a list of user privileges to use when creating users
73
+
74
+ Args:
75
+ config (ConfigParser): The application configuration
76
+ user (str): The user name to be granted privileges
77
+ with_admin (bool): Generate a list of privileges that will have the WITH
78
+ GRANT OPTION specified, if True
79
+ Returns:
80
+ str: A SQL snippet listing the user privileges
81
+ """
82
+
83
+ privilege_list = ''
84
+ sql = ''
85
+
86
+ if (database := config.get('general', 'database')) != '':
87
+ database = '`' + database + '`'
88
+ else:
89
+ database = '*'
90
+
91
+ if config.getboolean('general', 'user_privilege_all') or with_admin:
92
+ privilege_list = privilege_list + 'ALL' + ', '
93
+ else:
94
+ if config.getboolean('general', 'user_privilege_create'):
95
+ privilege_list = privilege_list + 'CREATE'+ ', '
96
+
97
+ if config.getboolean('general', 'user_privilege_create_role'):
98
+ privilege_list = privilege_list + 'CREATE ROLE'+ ', '
99
+
100
+ if config.getboolean('general', 'user_privilege_alter'):
101
+ privilege_list = privilege_list + 'CREATE, INSERT, ALTER'+ ', '
102
+
103
+ if config.getboolean('general', 'user_privilege_create_user'):
104
+ privilege_list = privilege_list + 'CREATE USER'+ ', '
105
+
106
+ if config.getboolean('general', 'user_privilege_alter_rename'):
107
+ privilege_list = privilege_list + 'CREATE, INSERT, ALTER, DROP'+ ', '
108
+
109
+ if config.getboolean('general', 'user_privilege_event'):
110
+ privilege_list = privilege_list + 'EVENT'+ ', '
111
+
112
+ if config.getboolean('general', 'user_privilege_execute'):
113
+ privilege_list = privilege_list + 'EXECUTE'+ ', '
114
+
115
+ if config.getboolean('general', 'user_privilege_trigger'):
116
+ privilege_list = privilege_list + 'TRIGGER'+ ', '
117
+
118
+ if config.getboolean('general', 'user_privilege_insert'):
119
+ privilege_list = privilege_list + 'INSERT'+ ', '
120
+
121
+ if config.getboolean('general', 'user_privilege_update'):
122
+ privilege_list = privilege_list + 'UPDATE'+ ', '
123
+
124
+ if config.getboolean('general', 'user_privilege_delete'):
125
+ privilege_list = privilege_list + 'DELETE'+ ', '
126
+
127
+ if config.getboolean('general', 'user_privilege_drop'):
128
+ privilege_list = privilege_list + 'DROP'+ ', '
129
+
130
+ if privilege_list.endswith(', '):
131
+ privilege_list = privilege_list[:-2]
132
+
133
+ if privilege_list != '':
134
+ sql = 'GRANT %s ON %s.* TO "%s"' % (privilege_list, database, user)
135
+ if with_admin:
136
+ sql = sql + " WITH GRANT OPTION"
137
+ sql = sql + ';'
138
+
139
+ return sql
140
+
141
+
142
+ def get_user_grants(config, user, with_admin=False):
143
+ """Get a SQL string to GRANT membership to the configured roles when
144
+ creating a new user.
145
+
146
+ Args:
147
+ config (ConfigParser): The application configuration
148
+ user (str): The user name to be granted roles
149
+ with_admin (bool): Generate a list of roles that will have the WITH
150
+ ADMIN OPTION specified, if True
151
+ Returns:
152
+ str: A SQL snippet listing the user roles
153
+ """
154
+ roles = ''
155
+ sql = ''
156
+
157
+ if with_admin:
158
+ roles_to_grant = config.get('general',
159
+ 'roles_to_grant_with_admin').split(',')
160
+ else:
161
+ roles_to_grant = config.get('general', 'roles_to_grant').split(',')
162
+
163
+ if roles_to_grant != ['']:
164
+ for role_to_grant in roles_to_grant:
165
+ roles = roles + '"' + role_to_grant + '", '
166
+
167
+ if roles.endswith(', '):
168
+ roles = roles[:-2]
169
+
170
+ if roles != '':
171
+ sql = 'GRANT %s TO "%s"' % (roles, user)
172
+
173
+ if with_admin:
174
+ sql = sql + " WITH ADMIN OPTION"
175
+
176
+ sql = sql + ';'
177
+
178
+ return sql
179
+
180
+ def get_create_users(ldap_users, my_users):
181
+ """Get a filtered list of users to create.
182
+
183
+ Args:
184
+ ldap_users (str[]): A list of users in LDAP
185
+ my_users (str[]): A list of users in MySQL
186
+
187
+ Returns:
188
+ str[]: A list of users that exist in LDAP but not in MySQL
189
+ """
190
+ users = []
191
+
192
+ for user in ldap_users:
193
+ if user not in my_users:
194
+ users.append(user)
195
+
196
+ return users
197
+
198
+
199
+ def get_drop_users(ldap_users, my_users):
200
+ """Get a filtered list of users to drop.
201
+
202
+ Args:
203
+ ldap_users (str[]): A list of users in LDAP
204
+ my_users (str[]): A list of users in MySQL
205
+
206
+ Returns:
207
+ str[]: A list of users that exist in MySQL but not in LDAP
208
+ """
209
+ users = []
210
+
211
+ for user in my_users:
212
+ if user not in ldap_users:
213
+ users.append(user)
214
+
215
+ return users
@@ -0,0 +1,23 @@
1
+ myldapsync - adopted for MySQL fork of pgldapsync by EnterpriseDB Corporation
2
+
3
+ GNU General Public License (GPL)
4
+
5
+ Copyright (c) 2024, Artur Lebedev
6
+
7
+ Copyright (C) 2018 - 2023, EnterpriseDB Corporation
8
+
9
+ Permission to use, copy, modify, and distribute this software and its
10
+ documentation for any purpose, without fee, and without a written agreement is
11
+ hereby granted, provided that the above copyright notice and this paragraph and
12
+ the following two paragraphs appear in all copies.
13
+
14
+ IN NO EVENT SHALL ENTERPRISEDB CORPORATION BE LIABLE TO ANY PARTY FOR DIRECT,
15
+ INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
16
+ ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
17
+ ENTERPRISEDB CORPORATION HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
18
+
19
+ ENTERPRISEDB CORPORATION SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT
20
+ NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND
22
+ ENTERPRISEDB CORPORATION HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
23
+ UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.1
2
+ Name: myldapsync
3
+ Version: 1.0.3
4
+ Summary: Synchronise LDAP users to MySQL and MariaDB
5
+ Home-page: https://github.com/6eh01der/myldapsync
6
+ Author: Artur Lebedev
7
+ Author-email: ras_atari@mail.ru
8
+ License: MySQL
9
+ Platform: UNKNOWN
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.8
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: License :: OSI Approved :: GNU General Public License (GPL)
16
+ Classifier: Operating System :: OS Independent
17
+ Requires-Python: >=3.8
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: ldap3>=2.9.1
21
+ Requires-Dist: mysql-connector-python>=8.0.31
22
+ Requires-Dist: pyasn1>=0.4.8
23
+
24
+ # myldapsync - fork of [pgldapsync](https://github.com/EnterpriseDB/pgldapsync) by [EnterpriseDB Corporation](https://www.enterprisedb.com/) adopted for MySQL and MariaDB
25
+
26
+ This Python module allows you to synchronise MySQL or MariaDB users
27
+ with users in an LDAP directory.
28
+
29
+ Require MySQL 8 with installed and configured simple or sasl LDAP Authentication Plugin or PAM plugin (pam also supported in MySQL 5.7 and MariaDB).
30
+
31
+ Percona Server for MySQL:
32
+
33
+ https://docs.percona.com/percona-server/8.0/ldap-authentication
34
+
35
+ https://docs.percona.com/percona-server/8.0/pam-plugin.html
36
+
37
+ MySQL:
38
+
39
+ https://dev.mysql.com/doc/refman/8.0/en/ldap-pluggable-authentication.html
40
+
41
+ https://dev.mysql.com/doc/refman/8.0/en/pam-pluggable-authentication.html
42
+
43
+ MariaDB:
44
+
45
+ https://mariadb.com/kb/en/authentication-plugin-pam/
46
+
47
+ *myldapsync is supported on Python 3.8 or later.*
48
+
49
+ In order to use it, you will need to create a _config.ini_
50
+ file containing the site-specific configuration you require.
51
+ See _config.ini.example_ for a complete list of all the
52
+ available configuration options. This file should be copied to
53
+ create your own configuration.
54
+
55
+ Once configured, simply run myldapsync like so:
56
+
57
+ python3 myldapsync.py /path/to/config.ini
58
+
59
+ In order to test the configuration (and dump the SQL that would
60
+ be executed to stdout), run it like this:
61
+
62
+ python3 myldapsync.py --dry-run /path/to/config.ini
63
+
64
+ ## Creating a virtual environment for dev/test
65
+
66
+ python3 -m venv /path/to/myldapsync
67
+ source /path/to/myldapsync/bin/activate
68
+ pip install -r requirements.txt
69
+
70
+ Adapt the first command as required for your environment/Python
71
+ version.
72
+
73
+ ## Creating a package
74
+
75
+ To create a package (wheel), run the following in your virtual
76
+ environment:
77
+
78
+ python3 setup.py sdist bdist_wheel
79
+
80
+
@@ -0,0 +1,14 @@
1
+ myldapsync/__init__.py,sha256=RnE0no2RtC-0MLfIyNvNcRlAwzdvtvj1XxekWcvJmak,10964
2
+ myldapsync/config.ini.example,sha256=MmH_3hcwbIXnu1QgTfahabeEvt1AVwjlG4JeZcRTnmk,4696
3
+ myldapsync/config_default.ini,sha256=cCv_cgZd9hryCJqnm95tI_HRdmHzoLTY0riReH6ceeI,1383
4
+ myldapsync/ldaputils/__init__.py,sha256=pLf1RRFyZfISuyqFVjYiIb8OHiG81zENLqt19mj3Jz8,305
5
+ myldapsync/ldaputils/connection.py,sha256=4b2ToP9Jan9IqLX2FaZaY0ZsYqq4E4c_FddnK6QZum8,4340
6
+ myldapsync/ldaputils/users.py,sha256=AAEXcOEanu6Ts7qjI_pl-6xW3cdM3gwnWdZgWW5QCdo,2578
7
+ myldapsync/myutils/__init__.py,sha256=pLf1RRFyZfISuyqFVjYiIb8OHiG81zENLqt19mj3Jz8,305
8
+ myldapsync/myutils/users.py,sha256=WHuvVzEBf1qAhBCE3sGUAoRbV_0ogdKsuWJdXVUaSh0,6318
9
+ myldapsync-1.0.3.dist-info/LICENSE,sha256=90fR_JG7Ho4afLDvgFo9Fcp4mpHm67KcKojdlf5HfII,1143
10
+ myldapsync-1.0.3.dist-info/METADATA,sha256=hQ2P3PukIuJWOrgys2DtZ-w8PQDFkyy4PEHRnlPpl-0,2580
11
+ myldapsync-1.0.3.dist-info/WHEEL,sha256=fS9sRbCBHs7VFcwJLnLXN1MZRR0_TVTxvXKzOnaSFs8,110
12
+ myldapsync-1.0.3.dist-info/entry_points.txt,sha256=K9EakG5jitn-fWZr5_nwSKN8E74beN-TrSMEsyhBNX4,57
13
+ myldapsync-1.0.3.dist-info/top_level.txt,sha256=YeTlOnBYF59HhVmWNbMQGaUXB_iVb9FuRadPXQDtytE,11
14
+ myldapsync-1.0.3.dist-info/RECORD,,
@@ -0,0 +1,6 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.44.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ myldapsync = myldapsync.__init__:main
3
+
@@ -0,0 +1 @@
1
+ myldapsync