cf047769f123e4bac9aab136ce5176ade74825f6
[garming/samba-autobuild/.git] / python / samba / netcmd / group.py
1 # Copyright Jelmer Vernooij 2008
2 #
3 # Based on the original in EJS:
4 # Copyright Andrew Tridgell 2005
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 import samba.getopt as options
20 from samba.netcmd import Command, SuperCommand, CommandError, Option
21 import ldb
22 from samba.ndr import ndr_unpack
23 from samba.dcerpc import security
24
25 from getpass import getpass
26 from samba.auth import system_session
27 from samba.samdb import SamDB
28 from samba.dsdb import (
29     ATYPE_SECURITY_GLOBAL_GROUP,
30     GTYPE_SECURITY_BUILTIN_LOCAL_GROUP,
31     GTYPE_SECURITY_DOMAIN_LOCAL_GROUP,
32     GTYPE_SECURITY_GLOBAL_GROUP,
33     GTYPE_SECURITY_UNIVERSAL_GROUP,
34     GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP,
35     GTYPE_DISTRIBUTION_GLOBAL_GROUP,
36     GTYPE_DISTRIBUTION_UNIVERSAL_GROUP,
37 )
38
39 security_group = dict({"Builtin": GTYPE_SECURITY_BUILTIN_LOCAL_GROUP,
40                        "Domain": GTYPE_SECURITY_DOMAIN_LOCAL_GROUP,
41                        "Global": GTYPE_SECURITY_GLOBAL_GROUP,
42                        "Universal": GTYPE_SECURITY_UNIVERSAL_GROUP})
43 distribution_group = dict({"Domain": GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP,
44                            "Global": GTYPE_DISTRIBUTION_GLOBAL_GROUP,
45                            "Universal": GTYPE_DISTRIBUTION_UNIVERSAL_GROUP})
46
47
48 class cmd_group_add(Command):
49     """Creates a new AD group.
50
51 This command creates a new Active Directory group.  The groupname specified on the command is a unique sAMAccountName.
52
53 An Active Directory group may contain user and computer accounts as well as other groups.  An administrator creates a group and adds members to that group so they can be managed as a single entity.  This helps to simplify security and system administration.
54
55 Groups may also be used to establish email distribution lists, using --group-type=Distribution.
56
57 Groups are located in domains in organizational units (OUs).  The group's scope is a characteristic of the group that designates the extent to which the group is applied within the domain tree or forest.
58
59 The group location (OU), type (security or distribution) and scope may all be specified on the samba-tool command when the group is created.
60
61 The command may be run from the root userid or another authorized userid.  The
62 -H or --URL= option can be used to execute the command on a remote server.
63
64 Example1:
65 samba-tool group add Group1 -H ldap://samba.samdom.example.com --description='Simple group'
66
67 Example1 adds a new group with the name Group1 added to the Users container on a remote LDAP server.  The -U parameter is used to pass the userid and password of a user that exists on the remote server and is authorized to issue the command on that server.  It defaults to the security type and global scope.
68
69 Example2:
70 sudo samba-tool group add Group2 --group-type=Distribution
71
72 Example2 adds a new distribution group to the local server.  The command is run under root using the sudo command.
73
74 Example3:
75 samba-tool group add Group3 --nis-domain=samdom --gid-number=12345
76
77 Example3 adds a new RFC2307 enabled group for NIS domain samdom and GID 12345 (both options are required to enable this feature).
78 """
79
80     synopsis = "%prog <groupname> [options]"
81
82     takes_optiongroups = {
83         "sambaopts": options.SambaOptions,
84         "versionopts": options.VersionOptions,
85         "credopts": options.CredentialsOptions,
86     }
87
88     takes_options = [
89         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
90                metavar="URL", dest="H"),
91         Option("--groupou",
92                help="Alternative location (without domainDN counterpart) to default CN=Users in which new user object will be created",
93                type=str),
94         Option("--group-scope", type="choice", choices=["Domain", "Global", "Universal"],
95                help="Group scope (Domain | Global | Universal)"),
96         Option("--group-type", type="choice", choices=["Security", "Distribution"],
97                help="Group type (Security | Distribution)"),
98         Option("--description", help="Group's description", type=str),
99         Option("--mail-address", help="Group's email address", type=str),
100         Option("--notes", help="Groups's notes", type=str),
101         Option("--gid-number", help="Group's Unix/RFC2307 GID number", type=int),
102         Option("--nis-domain", help="SFU30 NIS Domain", type=str),
103     ]
104
105     takes_args = ["groupname"]
106
107     def run(self, groupname, credopts=None, sambaopts=None,
108             versionopts=None, H=None, groupou=None, group_scope=None,
109             group_type=None, description=None, mail_address=None, notes=None, gid_number=None, nis_domain=None):
110
111         if (group_type or "Security") == "Security":
112             gtype = security_group.get(group_scope, GTYPE_SECURITY_GLOBAL_GROUP)
113         else:
114             gtype = distribution_group.get(group_scope, GTYPE_DISTRIBUTION_GLOBAL_GROUP)
115
116         if (gid_number is None and nis_domain is not None) or (gid_number is not None and nis_domain is None):
117             raise CommandError('Both --gid-number and --nis-domain have to be set for a RFC2307-enabled group. Operation cancelled.')
118
119         lp = sambaopts.get_loadparm()
120         creds = credopts.get_credentials(lp, fallback_machine=True)
121
122         try:
123             samdb = SamDB(url=H, session_info=system_session(),
124                           credentials=creds, lp=lp)
125             samdb.newgroup(groupname, groupou=groupou, grouptype = gtype,
126                            description=description, mailaddress=mail_address, notes=notes,
127                            gidnumber=gid_number, nisdomain=nis_domain)
128         except Exception as e:
129             # FIXME: catch more specific exception
130             raise CommandError('Failed to create group "%s"' % groupname, e)
131         self.outf.write("Added group %s\n" % groupname)
132
133
134 class cmd_group_delete(Command):
135     """Deletes an AD group.
136
137 The command deletes an existing AD group from the Active Directory domain.  The groupname specified on the command is the sAMAccountName.
138
139 Deleting a group is a permanent operation.  When a group is deleted, all permissions and rights that users in the group had inherited from the group account are deleted as well.
140
141 The command may be run from the root userid or another authorized userid.  The -H or --URL option can be used to execute the command on a remote server.
142
143 Example1:
144 samba-tool group delete Group1 -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
145
146 Example1 shows how to delete an AD group from a remote LDAP server.  The -U parameter is used to pass the userid and password of a user that exists on the remote server and is authorized to issue the command on that server.
147
148 Example2:
149 sudo samba-tool group delete Group2
150
151 Example2 deletes group Group2 from the local server.  The command is run under root using the sudo command.
152 """
153
154     synopsis = "%prog <groupname> [options]"
155
156     takes_optiongroups = {
157         "sambaopts": options.SambaOptions,
158         "versionopts": options.VersionOptions,
159         "credopts": options.CredentialsOptions,
160     }
161
162     takes_options = [
163         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
164                metavar="URL", dest="H"),
165     ]
166
167     takes_args = ["groupname"]
168
169     def run(self, groupname, credopts=None, sambaopts=None, versionopts=None, H=None):
170
171         lp = sambaopts.get_loadparm()
172         creds = credopts.get_credentials(lp, fallback_machine=True)
173         samdb = SamDB(url=H, session_info=system_session(),
174                       credentials=creds, lp=lp)
175
176         filter = ("(&(sAMAccountName=%s)(objectClass=group))" %
177                   groupname)
178
179         try:
180             res = samdb.search(base=samdb.domain_dn(),
181                                scope=ldb.SCOPE_SUBTREE,
182                                expression=filter,
183                                attrs=["dn"])
184             group_dn = res[0].dn
185         except IndexError:
186             raise CommandError('Unable to find group "%s"' % (groupname))
187
188         try:
189             samdb.delete(group_dn)
190         except Exception as e:
191             # FIXME: catch more specific exception
192             raise CommandError('Failed to remove group "%s"' % groupname, e)
193         self.outf.write("Deleted group %s\n" % groupname)
194
195
196 class cmd_group_add_members(Command):
197     """Add members to an AD group.
198
199 This command adds one or more members to an existing Active Directory group. The command accepts one or more group member names separated by commas.  A group member may be a user or computer account or another Active Directory group.
200
201 When a member is added to a group the member may inherit permissions and rights from the group.  Likewise, when permission or rights of a group are changed, the changes may reflect in the members through inheritance.
202
203 The member names specified on the command must be the sAMaccountName.
204
205 Example1:
206 samba-tool group addmembers supergroup Group1,Group2,User1 -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
207
208 Example1 shows how to add two groups, Group1 and Group2 and one user account, User1, to the existing AD group named supergroup.  The command will be run on a remote server specified with the -H.  The -U parameter is used to pass the userid and password of a user authorized to issue the command on the remote server.
209
210 Example2:
211 sudo samba-tool group addmembers supergroup User2
212
213 Example2 shows how to add a single user account, User2, to the supergroup AD group.  It uses the sudo command to run as root when issuing the command.
214 """
215
216     synopsis = "%prog <groupname> <listofmembers> [options]"
217
218     takes_optiongroups = {
219         "sambaopts": options.SambaOptions,
220         "versionopts": options.VersionOptions,
221         "credopts": options.CredentialsOptions,
222     }
223
224     takes_options = [
225         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
226                metavar="URL", dest="H"),
227     ]
228
229     takes_args = ["groupname", "listofmembers"]
230
231     def run(self, groupname, listofmembers, credopts=None, sambaopts=None,
232             versionopts=None, H=None):
233
234         lp = sambaopts.get_loadparm()
235         creds = credopts.get_credentials(lp, fallback_machine=True)
236
237         try:
238             samdb = SamDB(url=H, session_info=system_session(),
239                           credentials=creds, lp=lp)
240             groupmembers = listofmembers.split(',')
241             samdb.add_remove_group_members(groupname, groupmembers,
242                                            add_members_operation=True)
243         except Exception as e:
244             # FIXME: catch more specific exception
245             raise CommandError('Failed to add members "%s" to group "%s"' % (
246                 listofmembers, groupname), e)
247         self.outf.write("Added members to group %s\n" % groupname)
248
249
250 class cmd_group_remove_members(Command):
251     """Remove members from an AD group.
252
253 This command removes one or more members from an existing Active Directory group.  The command accepts one or more group member names separated by commas.  A group member may be a user or computer account or another Active Directory group that is a member of the group specified on the command.
254
255 When a member is removed from a group, inherited permissions and rights will no longer apply to the member.
256
257 Example1:
258 samba-tool group removemembers supergroup Group1 -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
259
260 Example1 shows how to remove Group1 from supergroup.  The command will run on the remote server specified on the -H parameter.  The -U parameter is used to pass the userid and password of a user authorized to issue the command on the remote server.
261
262 Example2:
263 sudo samba-tool group removemembers supergroup User1
264
265 Example2 shows how to remove a single user account, User2, from the supergroup AD group.  It uses the sudo command to run as root when issuing the command.
266 """
267
268     synopsis = "%prog <groupname> <listofmembers> [options]"
269
270     takes_optiongroups = {
271         "sambaopts": options.SambaOptions,
272         "versionopts": options.VersionOptions,
273         "credopts": options.CredentialsOptions,
274     }
275
276     takes_options = [
277         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
278                metavar="URL", dest="H"),
279     ]
280
281     takes_args = ["groupname", "listofmembers"]
282
283     def run(self, groupname, listofmembers, credopts=None, sambaopts=None,
284             versionopts=None, H=None):
285
286         lp = sambaopts.get_loadparm()
287         creds = credopts.get_credentials(lp, fallback_machine=True)
288
289         try:
290             samdb = SamDB(url=H, session_info=system_session(),
291                           credentials=creds, lp=lp)
292             samdb.add_remove_group_members(groupname, listofmembers.split(","),
293                                            add_members_operation=False)
294         except Exception as e:
295             # FIXME: Catch more specific exception
296             raise CommandError('Failed to remove members "%s" from group "%s"' % (listofmembers, groupname), e)
297         self.outf.write("Removed members from group %s\n" % groupname)
298
299
300 class cmd_group_list(Command):
301     """List all groups."""
302
303     synopsis = "%prog [options]"
304
305     takes_options = [
306         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
307                metavar="URL", dest="H"),
308         Option("-v", "--verbose",
309                help="Verbose output, showing group type and group scope.",
310                action="store_true"),
311
312     ]
313
314     takes_optiongroups = {
315         "sambaopts": options.SambaOptions,
316         "credopts": options.CredentialsOptions,
317         "versionopts": options.VersionOptions,
318     }
319
320     def run(self, sambaopts=None, credopts=None, versionopts=None, H=None,
321             verbose=False):
322         lp = sambaopts.get_loadparm()
323         creds = credopts.get_credentials(lp, fallback_machine=True)
324
325         samdb = SamDB(url=H, session_info=system_session(),
326                       credentials=creds, lp=lp)
327
328         domain_dn = samdb.domain_dn()
329         res = samdb.search(domain_dn, scope=ldb.SCOPE_SUBTREE,
330                            expression=("(objectClass=group)"),
331                            attrs=["samaccountname", "grouptype"])
332         if (len(res) == 0):
333             return
334
335         if verbose:
336             self.outf.write("Group Name                                  Group Type      Group Scope\n")
337             self.outf.write("-----------------------------------------------------------------------------\n")
338
339             for msg in res:
340                 self.outf.write("%-44s" % msg.get("samaccountname", idx=0))
341                 hgtype = hex(int("%s" % msg["grouptype"]) & 0x00000000FFFFFFFF)
342                 if (hgtype == hex(int(security_group.get("Builtin")))):
343                     self.outf.write("Security         Builtin\n")
344                 elif (hgtype == hex(int(security_group.get("Domain")))):
345                     self.outf.write("Security         Domain\n")
346                 elif (hgtype == hex(int(security_group.get("Global")))):
347                     self.outf.write("Security         Global\n")
348                 elif (hgtype == hex(int(security_group.get("Universal")))):
349                     self.outf.write("Security         Universal\n")
350                 elif (hgtype == hex(int(distribution_group.get("Global")))):
351                     self.outf.write("Distribution     Global\n")
352                 elif (hgtype == hex(int(distribution_group.get("Domain")))):
353                     self.outf.write("Distribution     Domain\n")
354                 elif (hgtype == hex(int(distribution_group.get("Universal")))):
355                     self.outf.write("Distribution     Universal\n")
356                 else:
357                     self.outf.write("\n")
358         else:
359             for msg in res:
360                 self.outf.write("%s\n" % msg.get("samaccountname", idx=0))
361
362 class cmd_group_list_members(Command):
363     """List all members of an AD group.
364
365 This command lists members from an existing Active Directory group. The command accepts one group name.
366
367 Example1:
368 samba-tool group listmembers \"Domain Users\" -H ldap://samba.samdom.example.com -Uadministrator%passw0rd
369 """
370
371     synopsis = "%prog <groupname> [options]"
372
373     takes_options = [
374         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
375                metavar="URL", dest="H"),
376     ]
377
378     takes_optiongroups = {
379         "sambaopts": options.SambaOptions,
380         "credopts": options.CredentialsOptions,
381         "versionopts": options.VersionOptions,
382     }
383
384     takes_args = ["groupname"]
385
386     def run(self, groupname, credopts=None, sambaopts=None, versionopts=None, H=None):
387         lp = sambaopts.get_loadparm()
388         creds = credopts.get_credentials(lp, fallback_machine=True)
389
390         try:
391             samdb = SamDB(url=H, session_info=system_session(),
392                           credentials=creds, lp=lp)
393
394             search_filter = "(&(objectClass=group)(samaccountname=%s))" % groupname
395             res = samdb.search(samdb.domain_dn(), scope=ldb.SCOPE_SUBTREE,
396                                expression=(search_filter),
397                                attrs=["objectSid"])
398
399             if (len(res) != 1):
400                 return
401
402             group_dn = res[0].get('dn', idx=0)
403             object_sid = res[0].get('objectSid', idx=0)
404
405             object_sid = ndr_unpack(security.dom_sid, object_sid)
406             (group_dom_sid, rid) = object_sid.split()
407
408             search_filter = "(|(primaryGroupID=%s)(memberOf=%s))" % (rid, group_dn)
409             res = samdb.search(samdb.domain_dn(), scope=ldb.SCOPE_SUBTREE,
410                                expression=(search_filter),
411                                attrs=["samAccountName", "cn"])
412
413             if (len(res) == 0):
414                 return
415
416             for msg in res:
417                 member_name = msg.get("samAccountName", idx=0)
418                 if member_name is None:
419                     member_name = msg.get("cn", idx=0)
420                 self.outf.write("%s\n" % member_name)
421
422         except Exception as e:
423             raise CommandError('Failed to list members of "%s" group ' % groupname, e)
424
425 class cmd_group_move(Command):
426     """Move a group to an organizational unit/container.
427
428     This command moves a group object into the specified organizational unit
429     or container.
430     The groupname specified on the command is the sAMAccountName.
431     The name of the organizational unit or container can be specified as a
432     full DN or without the domainDN component.
433
434     The command may be run from the root userid or another authorized userid.
435
436     The -H or --URL= option can be used to execute the command against a remote
437     server.
438
439     Example1:
440     samba-tool group move Group1 'OU=OrgUnit,DC=samdom.DC=example,DC=com' \
441         -H ldap://samba.samdom.example.com -U administrator
442
443     Example1 shows how to move a group Group1 into the 'OrgUnit' organizational
444     unit on a remote LDAP server.
445
446     The -H parameter is used to specify the remote target server.
447
448     Example2:
449     samba-tool group move Group1 CN=Users
450
451     Example2 shows how to move a group Group1 back into the CN=Users container
452     on the local server.
453     """
454
455     synopsis = "%prog <groupname> <new_parent_dn> [options]"
456
457     takes_options = [
458         Option("-H", "--URL", help="LDB URL for database or target server",
459                type=str, metavar="URL", dest="H"),
460     ]
461
462     takes_args = ["groupname", "new_parent_dn"]
463     takes_optiongroups = {
464         "sambaopts": options.SambaOptions,
465         "credopts": options.CredentialsOptions,
466         "versionopts": options.VersionOptions,
467     }
468
469     def run(self, groupname, new_parent_dn, credopts=None, sambaopts=None,
470             versionopts=None, H=None):
471         lp = sambaopts.get_loadparm()
472         creds = credopts.get_credentials(lp, fallback_machine=True)
473         samdb = SamDB(url=H, session_info=system_session(),
474                       credentials=creds, lp=lp)
475         domain_dn = ldb.Dn(samdb, samdb.domain_dn())
476
477         filter = ("(&(sAMAccountName=%s)(objectClass=group))" %
478                   groupname)
479         try:
480             res = samdb.search(base=domain_dn,
481                                expression=filter,
482                                scope=ldb.SCOPE_SUBTREE)
483             group_dn = res[0].dn
484         except IndexError:
485             raise CommandError('Unable to find group "%s"' % (groupname))
486
487         try:
488             full_new_parent_dn = samdb.normalize_dn_in_domain(new_parent_dn)
489         except Exception as e:
490             raise CommandError('Invalid new_parent_dn "%s": %s' %
491                                (new_parent_dn, e.message))
492
493         full_new_group_dn = ldb.Dn(samdb, str(group_dn))
494         full_new_group_dn.remove_base_components(len(group_dn) - 1)
495         full_new_group_dn.add_base(full_new_parent_dn)
496
497         try:
498             samdb.rename(group_dn, full_new_group_dn)
499         except Exception as e:
500             raise CommandError('Failed to move group "%s"' % groupname, e)
501         self.outf.write('Moved group "%s" into "%s"\n' %
502                         (groupname, full_new_parent_dn))
503
504 class cmd_group_show(Command):
505     """Display a group AD object.
506
507 This command displays a group object and it's attributes in the Active
508 Directory domain.
509 The group name specified on the command is the sAMAccountName of the group.
510
511 The command may be run from the root userid or another authorized userid.
512
513 The -H or --URL= option can be used to execute the command against a remote
514 server.
515
516 Example1:
517 samba-tool group show Group1 -H ldap://samba.samdom.example.com \
518 -U administrator --password=passw1rd
519
520 Example1 shows how to display a group's attributes in the domain against a remote
521 LDAP server.
522
523 The -H parameter is used to specify the remote target server.
524
525 Example2:
526 samba-tool group show Group2
527
528 Example2 shows how to display a group's attributes in the domain against a local
529 LDAP server.
530
531 Example3:
532 samba-tool group show Group3 --attributes=member,objectGUID
533
534 Example3 shows how to display a users objectGUID and member attributes.
535 """
536     synopsis = "%prog <group name> [options]"
537
538     takes_options = [
539         Option("-H", "--URL", help="LDB URL for database or target server",
540                type=str, metavar="URL", dest="H"),
541         Option("--attributes",
542                help=("Comma separated list of attributes, "
543                      "which will be printed."),
544                type=str, dest="group_attrs"),
545     ]
546
547     takes_args = ["groupname"]
548     takes_optiongroups = {
549         "sambaopts": options.SambaOptions,
550         "credopts": options.CredentialsOptions,
551         "versionopts": options.VersionOptions,
552     }
553
554     def run(self, groupname, credopts=None, sambaopts=None, versionopts=None,
555             H=None, group_attrs=None):
556
557         lp = sambaopts.get_loadparm()
558         creds = credopts.get_credentials(lp, fallback_machine=True)
559         samdb = SamDB(url=H, session_info=system_session(),
560                       credentials=creds, lp=lp)
561
562         attrs = None
563         if group_attrs:
564             attrs = group_attrs.split(",")
565
566         filter = ("(&(sAMAccountType=%d)(sAMAccountName=%s))" %
567                   (ATYPE_SECURITY_GLOBAL_GROUP,
568                     ldb.binary_encode(groupname)))
569
570         domaindn = samdb.domain_dn()
571
572         try:
573             res = samdb.search(base=domaindn, expression=filter,
574                                scope=ldb.SCOPE_SUBTREE, attrs=attrs)
575             user_dn = res[0].dn
576         except IndexError:
577             raise CommandError('Unable to find group "%s"' % (groupname))
578
579         for msg in res:
580             user_ldif = samdb.write_ldif(msg, ldb.CHANGETYPE_NONE)
581             self.outf.write(user_ldif)
582
583 class cmd_group(SuperCommand):
584     """Group management."""
585
586     subcommands = {}
587     subcommands["add"] = cmd_group_add()
588     subcommands["delete"] = cmd_group_delete()
589     subcommands["addmembers"] = cmd_group_add_members()
590     subcommands["removemembers"] = cmd_group_remove_members()
591     subcommands["list"] = cmd_group_list()
592     subcommands["listmembers"] = cmd_group_list_members()
593     subcommands["move"] = cmd_group_move()
594     subcommands["show"] = cmd_group_show()