forked from tequir00t/hermes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hermes.py
executable file
·1512 lines (1142 loc) · 53.2 KB
/
hermes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright (C) 2016 Neagaru Daniel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
"""Manage users on our LDAP Server.
This script can be used to create, delete, modify, or just print
internal users, bots, or clients. At the moment, we use clients just for
the FTP server. Bots are like normal users, but which aren't used by any
person.
It will connect to our LDAP which resides in a docker container on our
server, by forwarding port 389 from the server, to port 3890 on your
localhost. A valid SSH account is required for this to work. As our
server doesn't expose its port 389 to the external world, that's the
easiest way to manage LDAP in our environment.
The SSH Forwarding code was heavily inspired by paramiko's demo at
https://github.com/paramiko/paramiko/blob/master/demos/forward.py
"""
import os
import argparse
import sys
import getpass
import select
import re
import multiprocessing
import time
import paramiko
import ldap3
from passlib.hash import ldap_salted_sha1 as ssha
try:
import SocketServer
except ImportError:
import socketserver as SocketServer
try:
import ConfigParser as configparser
except ImportError:
import configparser
__author__ = "Daniel Neagaru, [email protected]"
__copyright__ = "Copyright 2016, Toptranslation GmbH"
__credits__ = "Daniel Neagaru"
__license__ = "GPLv3 or later"
__version__ = "0.0.1"
__maintainer__ = "Daniel Neagaru"
__email__ = "[email protected]"
__status__ = "Prototype"
def _load_configuration():
"""Load configuration from a file.
Load configuration from a .ini file, to avoid private information
being used inside the script.
"""
# Initiate the config parser.
config = configparser.RawConfigParser()
# Get the .ini file path.
inipath = os.path.join(os.getcwd(), "hermes.ini")
# Raise exception if couldn't find the file.
if not config.read(inipath):
raise Exception("[ERROR] Could not find hermes.ini.")
return config
class ForwardServer(SocketServer.ThreadingTCPServer):
"""Handle forwarded ports.
Used in the SSH Forwarding code, and acts as a server, which handles
the port forwarding.
"""
daemon_threads = True
allow_reuse_address = True
class Handler(SocketServer.BaseRequestHandler):
"""Handle the data from the SSH tunnel."""
def handle(self):
"""Send and receive data from the SSH tunnel."""
# Try to connect to the SSH Server.
try:
chan = self.ssh_transport.open_channel(
"direct-tcpip",
(self.chain_host, self.chain_port),
self.request.getpeername())
# Server didn't respond.
except Exception as e:
print("[ERROR] Incoming request to %s:%d failed: %s" %
(self.chain_host, self.chain_port, repr(e)))
return
# Server rejected our request.
if chan is None:
print("[ERROR] Incoming request to %s:%d was rejected by \
the SSH server." % (self.chain_host, self.chain_port))
return
# Connection succeeded.
print("[INFO] Connected! Tunnel open %r -> %r -> %r" %
(self.request.getpeername(),
chan.getpeername(),
(self.chain_host, self.chain_port)))
# Send and receive the data, until manually interrupted.
while True:
r, w, x = select.select([self.request, chan], [], [])
if self.request in r:
data = self.request.recv(1024)
if len(data) == 0:
break
chan.send(data)
if chan in r:
data = chan.recv(1024)
if len(data) == 0:
break
self.request.send(data)
peername = self.request.getpeername()
chan.close()
self.request.close()
print("[INFO] Tunnel closed from %r" % (peername,))
def forward_tunnel(local_port, remote_host, remote_port, transport):
"""Create a tunnel over SSH.
Create a tunnel between the remote port on the server and the local
port on the computer running this script.
"""
class SubHander(Handler):
chain_host = remote_host
chain_port = remote_port
ssh_transport = transport
ForwardServer(("", local_port), SubHander).serve_forever()
def verbose(options):
"""Print the output just if -v or --verbose option was set."""
return print if options.verbose else lambda *a, **k: None
def parse_options(CONFIG):
"""Parse the command line options.
Parse the command line arguments supplied to this script. It uses
the argparse python library, and implements 5 different subparsers,
for subcommands "print", "forward", "create", "delete" and
"modify".
"""
# Creating the main parser.
parser = argparse.ArgumentParser()
##################################################################
# GLOBAL #
##################################################################
# Add the required parameter username, which will be used to bind
# to the LDAP server.
parser.add_argument("-E", "--environment",
help="Choose your environment (from hermes.ini)",
default="DEFAULT")
args, remaining_args = parser.parse_known_args()
defaults = dict(CONFIG.items(args.environment))
parser.set_defaults(**defaults)
parser.add_argument("-U", "--username",
help="LDAP Bind username")
# Add the optional server address.
parser.add_argument("-S", "--server",
help="LDAP Server IP or name")
# Add the optional LDAP SSL.
parser.add_argument("--ssl",
help="Enable SSL",
action="store_true",
default=CONFIG.getboolean(args.environment,
"ssl"))
# Add the optional LDAP port number.
parser.add_argument("-P", "--port",
help="LDAP port number",
type=int)
# Add the optional port number to bind to localhost.
parser.add_argument("-L", "--localport",
help="Localhost port number used for binding",
type=int)
# Add the optional LDAP base.
parser.add_argument("-B", "--base",
help="LDAP Base")
# Add the optional people DN.
parser.add_argument("--peopledn",
help="LDAP People DN")
# Add the optional former workers DN.
parser.add_argument("--formerdn",
help="LDAP Former Workers DN")
# Add the optional bots DN.
parser.add_argument("--botsdn",
help="LDAP Bots DN")
# Add the optional clients DN.
parser.add_argument("--clientsdn",
help="LDAP Clients DN")
# Add the optional groups DN.
parser.add_argument("--groupsdn",
help="LDAP Groups DN")
# Add the optional SSH port number.
parser.add_argument("-H", "--sshport",
help="SSH Port number",
type=int)
# Add the optional verbose flag.
parser.add_argument("-v", "--verbose",
help="Show verbose output",
action="store_true")
# Adding subparser, with their name stored inside COMMAND
# variable.
subparsers = parser.add_subparsers(help="Use hermes COMMAND --help \
to see the options available to \
that command.",
dest="COMMAND")
subparsers.required = True
##################################################################
# PRINT #
##################################################################
# The print subparser, used to display the users matching the
# user supplied name. Use -p for people, -b for bots or -c for
# clients.
parser_print = subparsers.add_parser("print",
help="Print users matching UID")
# Add a required positioned argument UID.
parser_print.add_argument("UID",
help="LDAP user. Use \"ALL\" to match \
all users")
# Add a group of mutually exclusive arguments: people, bots, or
# clients. Exactly one of them should be used at a time.
group_print = parser_print.add_mutually_exclusive_group(required=True)
group_print.add_argument("-p", "--people",
help="People (Our dear coworkers)",
action="store_true")
group_print.add_argument("-b", "--bots",
help="Bots",
action="store_true")
group_print.add_argument("-c", "--clients",
help="Clients (At the moment just for FTP)",
action="store_true")
##################################################################
# FORWARD #
##################################################################
# The forward subparser, used just to forward the connection. No
# other options available.
subparsers.add_parser("forward",
help="Just forward port, use with Apache \
Directory Studio, or other LDAP tools.")
##################################################################
# CREATE #
##################################################################
# The create subparser, used to create a new account with the
# supplied UID. Use -p for people, -b for bots or -c for clients.
parser_create = subparsers.add_parser("create",
help="Create a new user with \
uid=UID")
# Add a required positioned argument UID.
parser_create.add_argument("UID", help="LDAP user.")
# Add an optional argument for the password.
parser_create.add_argument("--password",
help="Set up user's password. By \
default, it's \"please_change!\"")
# Add an optional argument for the email.
parser_create.add_argument("-m", "--mail",
help="Add another email in addition to \
[email protected]. Use multiple \
times to add multiple emails",
action="append")
# Add an optional argument for the description.
parser_create.add_argument("-d", "--description",
help="Add a short description to the \
account")
# Add an optional argument for the mobile phone.
parser_create.add_argument("-M", "--mobile",
help="Add a mobile phone. Use multiple \
times to add multiple numbers",
action="append")
# Add an optional argument for the work phone.
parser_create.add_argument("-t", "--telephone",
help="Add a telephone phone. Use \
multiple times to add multiple numbers",
action="append")
# Add an optional argument for the department.
parser_create.add_argument("-D", "--department",
help="Coworker's department")
# Add an optional argument for the title.
parser_create.add_argument("-T", "--title",
help="Coworker's title")
# Add a group of mutually exclusive arguments: people, bots, or
# clients. Exactly one of them should be used at a time.
group_create = parser_create.add_mutually_exclusive_group(required=True)
group_create.add_argument("-p", "--people",
help="People (Our dear coworkers)",
action="store_true")
group_create.add_argument("-b", "--bots",
help="Bots",
action="store_true")
group_create.add_argument("-c", "--clients",
help="Clients (At the moment just for \
FTP)",
action="store_true")
##################################################################
# DELETE #
##################################################################
# The delete subparser, used to delete an existing account,
# matching the supplied UID. Use -p for people, -b for bots or -c
# for clients.
parser_delete = subparsers.add_parser("delete",
help="Delete user UID")
# Add the required positioned argument UID.
parser_delete.add_argument("UID",
help="LDAP user.")
# Add a group of mutually exclusive arguments: people, bots, or
# clients. Exactly one of them should be used at a time.
group_delete = parser_delete.add_mutually_exclusive_group(required=True)
group_delete.add_argument("-p", "--people",
help="People (Our dear coworkers)",
action="store_true")
group_delete.add_argument("-b", "--bots",
help="Bots",
action="store_true")
group_delete.add_argument("-c", "--clients",
help="Clients (At the moment just for \
FTP)",
action="store_true")
##################################################################
# MODIFY #
##################################################################
# The modify subparser, used to modify an existing account,
# matching the supplied UID. Use -p for people, -b for bots or -c
# for clients.
parser_modify = subparsers.add_parser("modify",
help="Modify user matching \
UID. The old parameters will \
be deleted automatically.")
parser_modify.add_argument("UID",
help="LDAP user.")
# Add an optional argument for the password.
parser_modify.add_argument("--password",
help="Set up user's password. By \
default, it's \"please_change!\"")
# Add an optional argument for the email.
parser_modify.add_argument("-m", "--mail",
help="Add another email in addition to \
[email protected]. Use multiple \
times to add multiple emails",
action="append")
# Add an optional argument for the description.
parser_modify.add_argument("-d", "--description",
help="Add a short description to the \
account")
# Add an optional argument for the mobile phone.
parser_modify.add_argument("-M", "--mobile",
help="Add a mobile phone. Use multiple \
times to add multiple numbers",
action="append")
# Add an optional argument for the work phone.
parser_modify.add_argument("-t", "--telephone",
help="Add a telephone phone. Use \
multiple times to add multiple numbers",
action="append")
# Add an optional argument for the department.
parser_modify.add_argument("-D", "--department",
help="Coworker's department")
# Add an optional argument for the title.
parser_modify.add_argument("-T", "--title",
help="Coworker's title")
# Add a group of mutually exclusive arguments: people, bots, or
# clients. Exactly one of them should be used at a time.
group_modify = parser_modify.add_mutually_exclusive_group(required=True)
group_modify.add_argument("-p", "--people",
help="People (Our dear coworkers)",
action="store_true")
group_modify.add_argument("-b", "--bots",
help="Bots",
action="store_true")
group_modify.add_argument("-c", "--clients",
help="Clients (At the moment just for FTP)",
action="store_true")
return parser.parse_args()
def daemon(options):
"""Forward the LDAP port over SSH.
Forward the LDAP remote port over SSH, to the local port and wait
for the client process to exit, or for the user to close the
connection with Ctrl-C
"""
# Create a SSH client.
client = paramiko.SSHClient()
# Load SSH keys from the host.
client.load_system_host_keys()
# Add the non-existing keys to the known_hosts file.
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
verbose(options)("[INFO] Connecting to SSH...")
# Connect to the SSH server.
try:
client.connect(options.server, options.sshport, username="root")
verbose(options)("[INFO] Forwarding LDAP Port")
except Exception as e:
print("[ERROR] Failed to connect to %s:%d: %r" % (options.server,
options.sshport, e))
sys.exit(0)
# Forward the tunnel.
try:
forward_tunnel(options.localport,
"127.0.0.1",
options.port,
client.get_transport())
except KeyboardInterrupt:
print("\n[INFO] Port forwarding stopped.")
sys.exit(0)
def client(options):
"""Call the appropiate LDAP function.
Call the appropiate LDAP function, according to which COMMAND the
user selected. Connect to the localhost on the port opened by the
daemon process, and send the requested LDAP instructions.
"""
# Creates the user DN from the supplied options.
user = ",".join(("uid=" + options.username,
options.peopledn,
options.base))
# Asks for the user password. Don't echo.
password = getpass.getpass("Password for the user " + user + ": ")
# Connects to the LDAP server forwarded to a localhost port.
try:
conn = ldap3.Connection(server=ldap3.Server("127.0.0.1",
port=options.localport,
use_ssl=options.ssl),
auto_bind=True,
user=user,
password=password)
if options.COMMAND == "print":
ldapprint(options, conn)
elif options.COMMAND == "forward":
# No function necessarily to forward the connection. Just
# let the daemon do its job.
pass
elif options.COMMAND == "create":
ldapcreate(options, conn)
ldapprint(options, conn)
elif options.COMMAND == "delete":
ldapdelete(options, conn)
elif options.COMMAND == "modify":
ldapmodify(options, conn)
ldapprint(options, conn)
except ldap3.core.exceptions.LDAPBindError:
print("[ERROR] Sorry, Invalid credentials...")
sys.exit(0)
def ldapprint(options, conn):
"""Print matching LDAP entries.
Print the matching LDAP entries, for either people, clients, or
bots. It works even for partial matches, and it accepts UID as
``ALL'', to display all valid users.
"""
if options.people:
# Join peopledn with the base.
search_base = ",".join((options.peopledn, options.base))
if options.UID == "ALL":
# This will search for all matching people.
search_filter = "(objectClass=inetOrgPerson)"
else:
# This filter will search for approximate matches in
# displayName, sn and givenName, or for exact match in
# uid parameter.
search_filter = "(&" + \
"(objectClass=inetOrgPerson)" + \
"(|" + \
"(displayName=*" + options.UID + "*)" + \
"(sn=*" + options.UID + "*)" + \
"(givenName=*" + options.UID + "*)" + \
"(uid=" + options.UID + ")))"
# One level should be enough for us.
search_scope = "LEVEL"
# List of attributes to get from the server.
attributes = ["displayName",
"mail",
"mobile",
"telephoneNumber",
"ou",
"title",
"uid",
"memberOf"]
verbose(options)("[INFO] LDAP Search:" +
"\n\tsearch_base = " + search_base +
"\n\tsearch_filter = " + search_filter +
"\n\tsearch_scope = " + search_scope +
"\n\tattributes = " + str(attributes))
# LDAP Search.
conn.search(search_base=search_base,
search_filter=search_filter,
search_scope=search_scope,
attributes=attributes)
verbose(options)("[INFO] " + str(conn.result))
# Now display all the data we obtained from the server. The
# lambda function sorts the dictionary alphabetically, based
# on the uid value. Using every entry from the sorted list,
# we display the relevant information if it exists. If not,
# the attribute is skipped.
for entry in sorted(conn.response,
key=lambda entry: entry["attributes"]["uid"]):
try:
print("\n" + entry["attributes"]["displayName"][0] + ":")
except KeyError:
print(entry["attributes"]["uid"][0] + ":")
try:
print("\tuid = " + entry["attributes"]["uid"][0])
except KeyError:
pass
try:
print("\tTitle = " + entry["attributes"]["title"][0])
except KeyError:
pass
try:
print("\tDepartment = " + entry["attributes"]["ou"][0])
except KeyError:
pass
try:
for i in entry["attributes"]["mail"]:
print("\tMail = " + i)
except KeyError:
pass
try:
for i in entry["attributes"]["mobile"]:
print("\tMobile = " + i)
except KeyError:
pass
try:
for i in entry["attributes"]["telephoneNumber"]:
print("\tPhone = " + i)
except KeyError:
pass
try:
for i in entry["attributes"]["memberOf"]:
print("\tGroup = " + i)
except KeyError:
pass
# Now for the bots.
elif options.bots:
# Join bots DN with the base.
search_base = ",".join((options.botsdn, options.base))
# Search for all bots.
if options.UID == "ALL":
search_filter = "(objectClass=inetOrgPerson)"
# Search for bots with approximate match for the displayName
# or an exact match with uid argument.
else:
search_filter = "(&" + \
"(objectClass=inetOrgPerson)" + \
"(|" + \
"(displayName=*" + options.UID + "*)" + \
"(uid=" + options.UID + ")))"
# One Level is enough.
search_scope = "LEVEL"
# Attributes to get from the server.
attributes = ["displayName", "description", "uid"]
verbose(options)("[INFO] LDAP Search:" +
"\n\tsearch_base = " + search_base +
"\n\tsearch_filter = " + search_filter +
"\n\tsearch_scope = " + search_scope +
"\n\tattributes = " + str(attributes))
# LDAP Search.
conn.search(search_base=search_base,
search_filter=search_filter,
search_scope=search_scope,
attributes=attributes)
verbose(options)("[INFO] " + str(conn.result))
# Now display all the data we obtained from the server. The
# lambda function sorts the dictionary alphabetically, based
# on the uid value. Using every entry from the sorted list,
# we display the relevant information if it exists. If not,
# the attribute is skipped.
for entry in sorted(conn.response,
key=lambda entry: entry["attributes"]["uid"]):
try:
print("\n" + entry["attributes"]["displayName"][0] + ":")
except KeyError:
print(entry["attributes"]["uid"][0] + ":")
try:
print("\tuid = " + entry["attributes"]["uid"][0])
except KeyError:
pass
try:
print("\tDescription = " +
entry["attributes"]["description"][0])
except KeyError:
pass
# Now search for clients.
elif options.clients:
# Join the clients DN with the base.
search_base = ",".join((options.clientsdn, options.base))
# Search for all Posix Accounts (necessarily for FTP).
if options.UID == "ALL":
search_filter = "(objectClass=posixAccount)"
# Search for clients with approximate match for description
# and displayName, or an exact match on uid.
else:
search_filter = "(&" + \
"(objectClass=posixAccount)" + \
"(|" + \
"(description=*" + options.UID + "*)" + \
"(displayName=*" + options.UID + "*)" + \
"(uid=" + options.UID + ")))"
# One level is enough.
search_scope = "LEVEL"
# We need just description and uid from the server.
attributes = ["description", "uid"]
verbose(options)("[INFO] LDAP Search:" +
"\n\tsearch_base = " + search_base +
"\n\tsearch_filter = " + search_filter +
"\n\tsearch_scope = " + search_scope +
"\n\tattributes = " + str(attributes))
# Perform the search.
conn.search(search_base=search_base,
search_filter=search_filter,
search_scope=search_scope,
attributes=attributes)
verbose(options)("[INFO] " + str(conn.result))
# Display the sorted entries.
for entry in sorted(conn.response,
key=lambda entry: entry["attributes"]["uid"]):
print("\n" + entry["attributes"]["uid"][0]+":")
try:
print("\tDescription = " +
entry["attributes"]["description"][0])
except KeyError:
pass
def ldapcreate(options, conn):
"""Create new LDAP entries.
Create new LDAP entries, for people, bots, or clients. By default
not much information is written. To add phone numbers, emails,
etc. use the appropiate command line arguments.
"""
if options.people:
# Check if a person with this name already exists.
if conn.search(search_base=",".join((options.peopledn, options.base)),
search_filter="(&" +
"(objectClass=inetOrgPerson)" +
"(uid=" + options.UID + "))"):
print("[WARN] User " + options.UID +
" already exists. Please use modify instead of create")
sys.exit(0)
# Proceeds just if the username has the form: firstname.lastname.
if re.match("[a-z]+.[a-z]+", options.UID):
# Gets the DN of the person to be created.
dn = ",".join(("uid=" + options.UID,
options.peopledn,
options.base))
object_class = "inetOrgPerson"
attributes = {}
attributes["uid"] = options.UID
# If the user supplied a password, it's used, otherwise
# "please_change!" is set up as a password.
if options.password:
attributes["userPassword"] = ssha.encrypt(options.password)
else:
attributes["userPassword"] = ssha.encrypt("please_change!")
# cn will be "Firstname Lastname".
attributes["cn"] = " ".join(options.UID.split(".")).title()
# displayName will be "Firstname Lastname".
attributes["displayName"] = (" ".join(options.UID.split("."))
.title())
# sn will be Lastname.
attributes["sn"] = options.UID.split(".")[1].capitalize()
# givenName will be Firstname.
attributes["givenName"] = options.UID.split(".")[0].capitalize()
# initials will be FL.
attributes["initials"] = (options.UID.split(".")[0][0] +
options.UID.split(".")[1][0])
# mail will be [email protected].
attributes["mail"] = [options.UID + "@toptranslation.com"]
# add information from the command line arguments.
if options.mail:
attributes["mail"] += options.mail
# Delete duplicates, otherwise an error will occur.
attributes["mail"] = list(set(attributes["mail"]))
if options.mobile:
attributes["mobile"] = options.mobile
if options.department:
attributes["ou"] = options.department
if options.telephone:
attributes["telephoneNumber"] = options.mobile
if options.title:
attributes["title"] = options.title
if options.description:
attributes["description"] = options.description
verbose(options)("[INFO] LDAP add:" +
"\n\t" + dn +
"\n\tobject_class = " + object_class +
"\n\tattributes = " + str(attributes))
# Add the new entry.
conn.add(dn=dn,
object_class=object_class,
attributes=attributes)
verbose(options)("[INFO] " + str(conn.result))
verbose(options)("[INFO] LDAP modify_add:\n\t" +
",".join(("cn=owncloud",
options.groupsdn,
options.base)) +
"\n\tmember: " +
",".join(("uid=" + options.UID,
options.peopledn,
options.base)))
# Add the user to OwnCloud group.
conn.modify(",".join(("cn=owncloud",
options.groupsdn,
options.base)),
{"member": (ldap3.MODIFY_ADD,
[",".join(("uid=" + options.UID,
options.peopledn,
options.base))])})
verbose(options)("[INFO] " + str(conn.result))
verbose(options)("[INFO] LDAP modify_add:\n\t" +
",".join(("cn=redmine",
options.groupsdn,
options.base)) +
"\n\tmember: " +
",".join(("uid=" + options.UID,
options.peopledn,
options.base)))
# Add the user to Redmine group.
conn.modify(",".join(("cn=redmine",
options.groupsdn,
options.base)),
{"member": (ldap3.MODIFY_ADD,
[",".join(("uid=" + options.UID,
options.peopledn,
options.base))])})
verbose(options)("[INFO] " + str(conn.result))
else:
print("[ERROR] Please specify the UID for people as \
firstname.surname")
sys.exit(0)
# If the option -b was specified.
if options.bots:
# If user already exists.
if conn.search(search_base=",".join((options.botsdn,
options.base)),
search_filter="(&" +
"(objectClass=inetOrgPerson)" +
"(uid=" + options.UID+"))"):
print("[ERROR] User " + options.UID +
" already exists. Please use modify instead of create")
sys.exit(0)
# Create the bot UID.
dn = ",".join(("uid=" + options.UID,
options.botsdn,
options.base))
# Our bots use inetOrgPerson class.
object_class = "inetOrgPerson"
attributes = {}
attributes["uid"] = options.UID
# Set up bot's password. If not given, use "please_change!".
if options.password:
attributes["userPassword"] = ssha.encrypt(options.password)
else:
attributes["userPassword"] = ssha.encrypt("please_change!")
attributes["cn"] = options.UID
attributes["sn"] = options.UID
attributes["displayName"] = options.UID
attributes["givenName"] = options.UID
if options.mail:
attributes["mail"] = options.mail
if options.mobile:
attributes["mobile"] = options.mobile
if options.department:
attributes["ou"] = options.department
if options.telephone:
attributes["telephoneNumber"] = options.mobile
if options.title:
attributes["title"] = options.title
if options.description:
attributes["description"] = options.description
verbose(options)("[INFO] LDAP add:" +