3 # implement samba_tool gpo commands
5 # Copyright Andrew Tridgell 2010
6 # Copyright Giampaolo Lauria 2011 <lauria2@yahoo.com>
7 # Copyright Amitay Isaacs 2011 <amitay@gmail.com>
9 # based on C implementation by Guenther Deschner and Wilco Baan Hofman
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with this program. If not, see <http://www.gnu.org/licenses/>.
26 import samba.getopt as options
29 from samba.auth import system_session
30 from samba.netcmd import (
36 from samba.samdb import SamDB
37 from samba import drs_utils, nttime2string, dsdb, dcerpc
38 from samba.dcerpc import misc
39 from samba.ndr import ndr_unpack
42 from samba.auth import AUTH_SESSION_INFO_DEFAULT_GROUPS, AUTH_SESSION_INFO_AUTHENTICATED, AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
43 from samba.netcmd.common import netcmd_finddc
47 def samdb_connect(ctx):
48 '''make a ldap connection to the server'''
50 ctx.samdb = SamDB(url=ctx.url,
51 session_info=system_session(),
52 credentials=ctx.creds, lp=ctx.lp)
54 raise CommandError("LDAP connection to %s failed " % ctx.url, e)
57 def attr_default(msg, attrname, default):
58 '''get an attribute from a ldap msg with a default'''
60 return msg[attrname][0]
64 def flags_string(flags, value):
65 '''return a set of flags as a string'''
69 for (str, val) in flags:
74 ret += '0x%08x' % value
78 def parse_gplink(gplink):
79 '''parse a gPLink into an array of dn and options'''
86 if len(d) != 2 or not d[0].startswith("[LDAP://"):
87 raise RuntimeError("Badly formed gPLink '%s'" % g)
88 ret.append({ 'dn' : d[0][8:], 'options' : int(d[1])})
92 def encode_gplink(gplist):
93 '''Encode an array of dn and options into gPLink string'''
96 ret += "[LDAP://%s;%d]" % (g['dn'], g['options'])
100 def dc_url(lp, creds, url=None, dc=None):
101 '''If URL is not specified, return URL for writable DC.
102 If dc is provided, use that to construct ldap URL'''
107 dc = netcmd_finddc(lp, creds)
109 raise RunTimeError("Could not find a DC for domain", e)
114 def get_gpo_dn(samdb, gpo):
115 '''Construct the DN for gpo'''
117 dn = samdb.get_default_basedn()
118 dn.add_child(ldb.Dn(samdb, "CN=Policies,DC=System"))
119 dn.add_child(ldb.Dn(samdb, "CN=%s" % gpo))
123 def get_gpo_info(samdb, gpo=None, displayname=None, dn=None):
124 '''Get GPO information using gpo, displayname or dn'''
126 policies_dn = samdb.get_default_basedn()
127 policies_dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
129 base_dn = policies_dn
130 search_expr = "(objectClass=groupPolicyContainer)"
131 search_scope = ldb.SCOPE_ONELEVEL
134 search_expr = "(&(objectClass=groupPolicyContainer)(name=%s))" % gpo
136 if displayname is not None:
137 search_expr = "(&(objectClass=groupPolicyContainer)(displayname=%s))" % displayname
141 search_scope = ldb.SCOPE_BASE
144 msg = samdb.search(base=base_dn, scope=search_scope,
145 expression=search_expr,
146 attrs=['nTSecurityDescriptor',
154 mesg = "Cannot get information for GPO %s" % gpo
156 mesg = "Cannot get information for GPOs"
157 raise CommandError(mesg, e)
163 '''Parse UNC string into a hostname, a service, and a filepath'''
164 if unc.startswith('\\\\') and unc.startswith('//'):
166 tmp = unc[2:].split('/', 2)
169 tmp = unc[2:].split('\\', 2)
175 def copy_directory_recurse(conn, remotedir, localdir):
176 if not os.path.isdir(localdir):
178 r_dirs = [ remotedir ]
179 l_dirs = [ localdir ]
184 dirlist = conn.list(r_dir)
186 r_name = r_dir + '\\' + e['name']
187 l_name = l_dir + os.path.sep + e['name']
189 if e['attrib'] & smb.FILE_ATTRIBUTE_DIRECTORY:
190 r_dirs.append(r_name)
191 l_dirs.append(l_name)
193 elif e['attrib'] & smb.FILE_ATTRIBUTE_ARCHIVE:
194 data = conn.loadfile(r_name)
195 file(l_name, 'w').write(data)
198 class cmd_listall(Command):
201 synopsis = "%prog gpo listall [options]"
204 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
205 metavar="URL", dest="H")
208 def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
210 self.lp = sambaopts.get_loadparm()
211 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
213 self.url = dc_url(self.lp, self.creds, H)
218 ("GPO_FLAG_USER_DISABLE", dsdb.GPO_FLAG_USER_DISABLE ),
219 ( "GPO_FLAG_MACHINE_DISABLE", dsdb.GPO_FLAG_MACHINE_DISABLE ) ]
221 msg = get_gpo_info(self.samdb, None)
224 print("GPO : %s" % m['name'][0])
225 print("display name : %s" % m['displayName'][0])
226 print("path : %s" % m['gPCFileSysPath'][0])
227 print("dn : %s" % m.dn)
228 print("version : %s" % attr_default(m, 'versionNumber', '0'))
229 print("flags : %s" % flags_string(gpo_flags, int(attr_default(m, 'flags', 0))))
233 class cmd_list(Command):
234 """list GPOs for an account"""
236 synopsis = "%prog gpo list <username> [options]"
238 takes_args = [ 'username' ]
241 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
242 metavar="URL", dest="H")
245 def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None):
247 self.lp = sambaopts.get_loadparm()
248 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
250 self.url = dc_url(self.lp, self.creds, H)
255 msg = self.samdb.search(expression='(&(|(samAccountName=%s)(samAccountName=%s$))(objectClass=User))' %
259 raise CommandError("Failed to find account %s" % username, e)
261 # check if its a computer account
263 msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
264 is_computer = 'computer' in msg['objectClass']
266 raise CommandError("Failed to find objectClass for user %s" % username, e)
268 session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS |
269 AUTH_SESSION_INFO_AUTHENTICATED )
271 # When connecting to a remote server, don't look up the local privilege DB
272 if self.url is not None and self.url.startswith('ldap'):
273 session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
275 session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
276 session_info_flags=session_info_flags)
278 token = session.security_token
283 dn = ldb.Dn(self.samdb, str(user_dn)).parent()
285 msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
287 glist = parse_gplink(msg['gPLink'][0])
289 if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
291 if g['options'] & dsdb.GPLINK_OPT_DISABLE:
295 gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
296 attrs=['name', 'displayName', 'flags',
297 'ntSecurityDescriptor'])
299 print("Failed to fetch gpo object %s" % g['dn'])
302 secdesc_ndr = gmsg[0]['ntSecurityDescriptor'][0]
303 secdesc = ndr_unpack(dcerpc.security.descriptor, secdesc_ndr)
306 samba.security.access_check(secdesc, token,
307 dcerpc.security.SEC_STD_READ_CONTROL |
308 dcerpc.security.SEC_ADS_LIST |
309 dcerpc.security.SEC_ADS_READ_PROP)
311 print("Failed access check on %s" % msg.dn)
314 # check the flags on the GPO
315 flags = int(attr_default(gmsg[0], 'flags', 0))
316 if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
318 if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
320 gpos.append((gmsg[0]['displayName'][0], gmsg[0]['name'][0]))
322 # check if this blocks inheritance
323 gpoptions = int(attr_default(msg, 'gPOptions', 0))
324 if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
327 if dn == self.samdb.get_default_basedn():
336 print("GPOs for %s %s" % (msg_str, username))
338 print(" %s %s" % (g[0], g[1]))
341 class cmd_show(Command):
342 """Show information for a GPO"""
344 synopsis = "%prog gpo show <gpo> [options]"
346 takes_optiongroups = {
347 "sambaopts": options.SambaOptions,
348 "versionopts": options.VersionOptions,
349 "credopts": options.CredentialsOptions,
352 takes_args = [ 'gpo' ]
355 Option("-H", help="LDB URL for database or target server", type=str)
358 def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
360 self.lp = sambaopts.get_loadparm()
361 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
363 self.url = dc_url(self.lp, self.creds, H)
368 ("GPO_FLAG_USER_DISABLE", dsdb.GPO_FLAG_USER_DISABLE ),
369 ( "GPO_FLAG_MACHINE_DISABLE", dsdb.GPO_FLAG_MACHINE_DISABLE ) ]
372 msg = get_gpo_info(self.samdb, gpo)[0]
374 raise CommandError("GPO %s does not exist" % gpo, e)
376 secdesc_ndr = msg['ntSecurityDescriptor'][0]
377 secdesc = ndr_unpack(dcerpc.security.descriptor, secdesc_ndr)
379 print("GPO : %s" % msg['name'][0])
380 print("display name : %s" % msg['displayName'][0])
381 print("path : %s" % msg['gPCFileSysPath'][0])
382 print("dn : %s" % msg.dn)
383 print("version : %s" % attr_default(msg, 'versionNumber', '0'))
384 print("flags : %s" % flags_string(gpo_flags, int(attr_default(msg, 'flags', 0))))
385 print("ACL : %s" % secdesc.as_sddl())
389 class cmd_getlink(Command):
390 """List GPO Links for a container"""
392 synopsis = "%prog gpo getlink <container_dn> [options]"
394 takes_optiongroups = {
395 "sambaopts": options.SambaOptions,
396 "versionopts": options.VersionOptions,
397 "credopts": options.CredentialsOptions,
400 takes_args = [ 'container_dn' ]
403 Option("-H", help="LDB URL for database or target server", type=str)
406 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
409 self.lp = sambaopts.get_loadparm()
410 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
412 self.url = dc_url(self.lp, self.creds, H)
417 ("GPLINK_OPT_DISABLE", dsdb.GPLINK_OPT_DISABLE),
418 ("GPLINK_OPT_ENFORCE", dsdb.GPLINK_OPT_ENFORCE),
422 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
423 expression="(objectClass=*)",
426 raise CommandError("Could not find Container DN %s (%s)" % container_dn, e)
429 print("GPO(s) linked to DN %s" % container_dn)
430 gplist = parse_gplink(msg['gPLink'][0])
432 msg = get_gpo_info(self.samdb, dn=g['dn'])
433 print(" GPO : %s" % msg[0]['name'][0])
434 print(" Name : %s" % msg[0]['displayName'][0])
435 print(" Options : %s" % flags_string(gplink_options, g['options']))
438 print("No GPO(s) linked to DN=%s" % container_dn)
441 class cmd_setlink(Command):
442 """Add or Update a GPO link to a container"""
444 synopsis = "%prog gpo setlink <container_dn> <gpo> [options]"
446 takes_optiongroups = {
447 "sambaopts": options.SambaOptions,
448 "versionopts": options.VersionOptions,
449 "credopts": options.CredentialsOptions,
452 takes_args = [ 'container_dn', 'gpo' ]
455 Option("-H", help="LDB URL for database or target server", type=str),
456 Option("--disable", dest="disabled", default=False, action='store_true',
457 help="Disable policy"),
458 Option("--enforce", dest="enforced", default=False, action='store_true',
459 help="Enforce policy")
462 def run(self, container_dn, gpo, H=None, disabled=False, enforced=False,
463 sambaopts=None, credopts=None, versionopts=None):
465 self.lp = sambaopts.get_loadparm()
466 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
468 self.url = dc_url(self.lp, self.creds, H)
474 gplink_options |= dsdb.GPLINK_OPT_DISABLE
476 gplink_options |= dsdb.GPLINK_OPT_ENFORCE
478 # Check if valid GPO DN
480 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
482 raise CommandError("GPO %s does not exist" % gpo_dn, e)
483 gpo_dn = get_gpo_dn(self.samdb, gpo)
485 # Check if valid Container DN
487 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
488 expression="(objectClass=*)",
491 raise CommandError("Could not find container DN %s" % container_dn, e)
493 # Update existing GPlinks or Add new one
494 existing_gplink = False
496 gplist = parse_gplink(msg['gPLink'][0])
497 existing_gplink = True
500 if g['dn'].lower() == gpo_dn.lower():
501 g['options'] = gplink_options
505 gplist.insert(0, { 'dn' : gpo_dn, 'options' : gplink_options })
508 gplist.append({ 'dn' : gpo_dn, 'options' : gplink_options })
510 gplink_str = encode_gplink(gplist)
513 m.dn = ldb.Dn(self.samdb, container_dn)
516 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
518 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_ADD, 'gPLink')
523 raise CommandError("Error adding GPO Link", e)
525 print("Added/Updated GPO link")
526 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
529 class cmd_dellink(Command):
530 """Delete GPO link from a container"""
532 synopsis = "%prog gpo dellink <container_dn> <gpo> [options]"
534 takes_optiongroups = {
535 "sambaopts": options.SambaOptions,
536 "versionopts": options.VersionOptions,
537 "credopts": options.CredentialsOptions,
540 takes_args = [ 'container_dn', 'gpo' ]
543 Option("-H", help="LDB URL for database or target server", type=str),
546 def run(self, container_dn, gpo_dn, H=None, sambaopts=None, credopts=None,
549 self.lp = sambaopts.get_loadparm()
550 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
552 self.url = dc_url(self.lp, self.creds, H)
558 msg = get_gpo_info(self.sambdb, gpo=gpo)[0]
560 raise CommandError("GPO %s does not exist" % gpo, e)
561 gpo_dn = get_gpo_dn(self.samdb, gpo)
563 # Check if valid Container DN and get existing GPlinks
565 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
566 expression="(objectClass=*)",
569 raise CommandError("Could not find container DN %s" % dn, e)
572 gplist = parse_gplink(msg['gPLink'][0])
574 if g['dn'].lower() == gpo_dn.lower():
578 raise CommandError("Specified GPO is not linked to this container");
581 m.dn = ldb.Dn(self.samdb, container_dn)
584 gplink_str = encode_gplink(gplist)
585 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
587 m['new_value'] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, 'gPLink')
592 raise CommandError("Error Removing GPO Link (%s)" % e)
594 print("Deleted GPO link.")
595 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
598 class cmd_getinheritance(Command):
599 """Get inheritance flag for a container"""
601 synopsis = "%prog gpo getinheritance <container_dn> [options]"
603 takes_optiongroups = {
604 "sambaopts": options.SambaOptions,
605 "versionopts": options.VersionOptions,
606 "credopts": options.CredentialsOptions,
609 takes_args = [ 'container_dn' ]
612 Option("-H", help="LDB URL for database or target server", type=str)
615 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
619 self.lp = sambaopts.get_loadparm()
621 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
626 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
627 expression="(objectClass=*)",
628 attrs=['gPOptions'])[0]
630 raise CommandError("Could not find Container DN %s" % container_dn, e)
633 if 'gPOptions' in msg:
634 inheritance = int(msg['gPOptions'][0]);
636 if inheritance == dsdb.GPO_BLOCK_INHERITANCE:
637 print("Container has GPO_BLOCK_INHERITANCE")
639 print("Container has GPO_INHERIT")
642 class cmd_setinheritance(Command):
643 """Set inheritance flag on a container"""
645 synopsis = "%prog gpo setinheritance <container_dn> <block|inherit> [options]"
647 takes_optiongroups = {
648 "sambaopts": options.SambaOptions,
649 "versionopts": options.VersionOptions,
650 "credopts": options.CredentialsOptions,
653 takes_args = [ 'container_dn', 'inherit_state' ]
656 Option("-H", help="LDB URL for database or target server", type=str)
659 def run(self, container_dn, inherit_state, H=None, sambaopts=None, credopts=None,
662 if inherit_state.lower() == 'block':
663 inheritance = dsdb.GPO_BLOCK_INHERITANCE
664 elif inherit_state.lower() == 'inherit':
665 inheritance = dsdb.GPO_INHERIT
667 raise CommandError("Unknown inheritance state (%s)" % inherit_state)
670 self.lp = sambaopts.get_loadparm()
672 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
677 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
678 expression="(objectClass=*)",
679 attrs=['gPOptions'])[0]
681 raise CommandError("Could not find Container DN %s" % container_dn, e)
684 m.dn = ldb.Dn(self.samdb, container_dn)
686 if 'gPOptions' in msg:
687 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_REPLACE, 'gPOptions')
689 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_ADD, 'gPOptions');
694 raise CommandError("Error setting inheritance state %s" % inherit_state, e)
697 class cmd_fetch(Command):
700 synopsis = "%prog gpo fetch <gpo> [options]"
702 takes_optiongroups = {
703 "sambaopts": options.SambaOptions,
704 "versionopts": options.VersionOptions,
705 "credopts": options.CredentialsOptions,
708 takes_args = [ 'gpo' ]
711 Option("-H", help="LDB URL for database or target server", type=str),
712 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
715 def run(self, gpo, H=None, tmpdir=None, sambaopts=None, credopts=None, versionopts=None):
717 self.lp = sambaopts.get_loadparm()
718 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
720 dc_hostname = netcmd_finddc(self.lp, self.creds)
721 self.url = dc_url(self.lp, self.creds, H, dc=dc_hostname)
725 msg = get_gpo_info(self.samdb, gpo)[0]
727 raise CommandError("GPO %s does not exist" % gpo)
729 unc = msg['gPCFileSysPath'][0]
731 [dom_name, service, sharepath] = parse_unc(unc)
733 raise CommandError("Invalid GPO path (%s)" % unc)
736 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
738 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
744 localdir = tmpdir + os.path.sep + "policy"
745 if not os.path.isdir(localdir):
747 gpodir = localdir + os.path.sep + gpo
748 if not os.path.isdir(gpodir):
750 copy_directory_recurse(conn, sharepath, gpodir)
752 raise CommandError("Error copying GPO", e)
753 print('GPO copied to %s' % gpodir)
756 class cmd_create(Command):
759 class cmd_setacl(Command):
760 """Set ACL on a GPO"""
763 class cmd_gpo(SuperCommand):
764 """Group Policy Object (GPO) commands"""
767 subcommands["listall"] = cmd_listall()
768 subcommands["list"] = cmd_list()
769 subcommands["show"] = cmd_show()
770 subcommands["getlink"] = cmd_getlink()
771 subcommands["setlink"] = cmd_setlink()
772 subcommands["dellink"] = cmd_dellink()
773 subcommands["getinheritance"] = cmd_getinheritance()
774 subcommands["setinheritance"] = cmd_setinheritance()
775 subcommands["fetch"] = cmd_fetch()
776 subcommands["create"] = cmd_create()
777 subcommands["setacl"] = cmd_setacl()