1 # implement samba_tool gpo commands
3 # Copyright Andrew Tridgell 2010
4 # Copyright Amitay Isaacs 2011-2012 <amitay@gmail.com>
6 # based on C implementation by Guenther Deschner and Wilco Baan Hofman
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
23 import samba.getopt as options
26 from samba.auth import system_session
27 from samba.netcmd import (
33 from samba.samdb import SamDB
34 from samba import dsdb
35 from samba.dcerpc import security
36 from samba.ndr import ndr_unpack
39 from samba.auth import AUTH_SESSION_INFO_DEFAULT_GROUPS, AUTH_SESSION_INFO_AUTHENTICATED, AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
40 from samba.netcmd.common import netcmd_finddc
41 from samba import policy
44 from samba.ntacls import dsacl2fsacl
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 gpo_flags_string(value):
65 '''return gpo flags string'''
66 flags = policy.get_gpo_flags(value)
74 def gplink_options_string(value):
75 '''return gplink options string'''
76 options = policy.get_gplink_options(value)
80 ret = ' '.join(options)
84 def parse_gplink(gplink):
85 '''parse a gPLink into an array of dn and options'''
92 if len(d) != 2 or not d[0].startswith("[LDAP://"):
93 raise RuntimeError("Badly formed gPLink '%s'" % g)
94 ret.append({ 'dn' : d[0][8:], 'options' : int(d[1])})
98 def encode_gplink(gplist):
99 '''Encode an array of dn and options into gPLink string'''
102 ret += "[LDAP://%s;%d]" % (g['dn'], g['options'])
106 def dc_url(lp, creds, url=None, dc=None):
107 '''If URL is not specified, return URL for writable DC.
108 If dc is provided, use that to construct ldap URL'''
113 dc = netcmd_finddc(lp, creds)
115 raise RuntimeError("Could not find a DC for domain", e)
120 def get_gpo_dn(samdb, gpo):
121 '''Construct the DN for gpo'''
123 dn = samdb.get_default_basedn()
124 dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
125 dn.add_child(ldb.Dn(samdb, "CN=%s" % gpo))
129 def get_gpo_info(samdb, gpo=None, displayname=None, dn=None,
130 sd_flags=security.SECINFO_OWNER|security.SECINFO_GROUP|security.SECINFO_DACL|security.SECINFO_SACL):
131 '''Get GPO information using gpo, displayname or dn'''
133 policies_dn = samdb.get_default_basedn()
134 policies_dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
136 base_dn = policies_dn
137 search_expr = "(objectClass=groupPolicyContainer)"
138 search_scope = ldb.SCOPE_ONELEVEL
141 search_expr = "(&(objectClass=groupPolicyContainer)(name=%s))" % ldb.binary_encode(gpo)
143 if displayname is not None:
144 search_expr = "(&(objectClass=groupPolicyContainer)(displayname=%s))" % ldb.binary_encode(displayname)
148 search_scope = ldb.SCOPE_BASE
151 msg = samdb.search(base=base_dn, scope=search_scope,
152 expression=search_expr,
153 attrs=['nTSecurityDescriptor',
159 controls=['sd_flags:1:%d' % sd_flags])
162 mesg = "Cannot get information for GPO %s" % gpo
164 mesg = "Cannot get information for GPOs"
165 raise CommandError(mesg, e)
170 def get_gpo_containers(samdb, gpo):
171 '''lists dn of containers for a GPO'''
173 search_expr = "(&(objectClass=*)(gPLink=*%s*))" % gpo
175 msg = samdb.search(expression=search_expr, attrs=['gPLink'])
177 raise CommandError("Could not find container(s) with GPO %s" % gpo, e)
182 def del_gpo_link(samdb, container_dn, gpo):
183 '''delete GPO link for the container'''
184 # Check if valid Container DN and get existing GPlinks
186 msg = samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
187 expression="(objectClass=*)",
190 raise CommandError("Container '%s' does not exist" % container_dn, e)
193 gpo_dn = str(get_gpo_dn(samdb, gpo))
195 gplist = parse_gplink(msg['gPLink'][0])
197 if g['dn'].lower() == gpo_dn.lower():
202 raise CommandError("No GPO(s) linked to this container")
205 raise CommandError("GPO '%s' not linked to this container" % gpo)
210 gplink_str = encode_gplink(gplist)
211 m['r0'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
213 m['d0'] = ldb.MessageElement(msg['gPLink'][0], ldb.FLAG_MOD_DELETE, 'gPLink')
217 raise CommandError("Error removing GPO from container", e)
221 '''Parse UNC string into a hostname, a service, and a filepath'''
222 if unc.startswith('\\\\') and unc.startswith('//'):
223 raise ValueError("UNC doesn't start with \\\\ or //")
224 tmp = unc[2:].split('/', 2)
227 tmp = unc[2:].split('\\', 2)
230 raise ValueError("Invalid UNC string: %s" % unc)
233 def copy_directory_remote_to_local(conn, remotedir, localdir):
234 if not os.path.isdir(localdir):
236 r_dirs = [ remotedir ]
237 l_dirs = [ localdir ]
242 dirlist = conn.list(r_dir)
244 r_name = r_dir + '\\' + e['name']
245 l_name = os.path.join(l_dir, e['name'])
247 if e['attrib'] & smb.FILE_ATTRIBUTE_DIRECTORY:
248 r_dirs.append(r_name)
249 l_dirs.append(l_name)
252 data = conn.loadfile(r_name)
253 file(l_name, 'w').write(data)
256 def copy_directory_local_to_remote(conn, localdir, remotedir):
257 if not conn.chkpath(remotedir):
258 conn.mkdir(remotedir)
259 l_dirs = [ localdir ]
260 r_dirs = [ remotedir ]
265 dirlist = os.listdir(l_dir)
267 l_name = os.path.join(l_dir, e)
268 r_name = r_dir + '\\' + e
270 if os.path.isdir(l_name):
271 l_dirs.append(l_name)
272 r_dirs.append(r_name)
275 data = file(l_name, 'r').read()
276 conn.savefile(r_name, data)
279 def create_directory_hier(conn, remotedir):
280 elems = remotedir.replace('/', '\\').split('\\')
283 path = path + '\\' + e
284 if not conn.chkpath(path):
288 class cmd_listall(Command):
291 synopsis = "%prog [options]"
293 takes_optiongroups = {
294 "sambaopts": options.SambaOptions,
295 "versionopts": options.VersionOptions,
296 "credopts": options.CredentialsOptions,
300 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
301 metavar="URL", dest="H")
304 def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
306 self.lp = sambaopts.get_loadparm()
307 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
309 self.url = dc_url(self.lp, self.creds, H)
313 msg = get_gpo_info(self.samdb, None)
316 self.outf.write("GPO : %s\n" % m['name'][0])
317 self.outf.write("display name : %s\n" % m['displayName'][0])
318 self.outf.write("path : %s\n" % m['gPCFileSysPath'][0])
319 self.outf.write("dn : %s\n" % m.dn)
320 self.outf.write("version : %s\n" % attr_default(m, 'versionNumber', '0'))
321 self.outf.write("flags : %s\n" % gpo_flags_string(int(attr_default(m, 'flags', 0))))
322 self.outf.write("\n")
325 class cmd_list(Command):
326 """List GPOs for an account."""
328 synopsis = "%prog <username> [options]"
330 takes_args = ['username']
331 takes_optiongroups = {
332 "sambaopts": options.SambaOptions,
333 "versionopts": options.VersionOptions,
334 "credopts": options.CredentialsOptions,
338 Option("-H", "--URL", help="LDB URL for database or target server",
339 type=str, metavar="URL", dest="H")
342 def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None):
344 self.lp = sambaopts.get_loadparm()
345 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
347 self.url = dc_url(self.lp, self.creds, H)
352 msg = self.samdb.search(expression='(&(|(samAccountName=%s)(samAccountName=%s$))(objectClass=User))' %
353 (ldb.binary_encode(username),ldb.binary_encode(username)))
356 raise CommandError("Failed to find account %s" % username)
358 # check if its a computer account
360 msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
361 is_computer = 'computer' in msg['objectClass']
363 raise CommandError("Failed to find objectClass for user %s" % username)
365 session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS |
366 AUTH_SESSION_INFO_AUTHENTICATED )
368 # When connecting to a remote server, don't look up the local privilege DB
369 if self.url is not None and self.url.startswith('ldap'):
370 session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
372 session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
373 session_info_flags=session_info_flags)
375 token = session.security_token
380 dn = ldb.Dn(self.samdb, str(user_dn)).parent()
382 msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
384 glist = parse_gplink(msg['gPLink'][0])
386 if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
388 if g['options'] & dsdb.GPLINK_OPT_DISABLE:
392 sd_flags=security.SECINFO_OWNER|security.SECINFO_GROUP|security.SECINFO_DACL
393 gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
394 attrs=['name', 'displayName', 'flags',
395 'nTSecurityDescriptor'],
396 controls=['sd_flags:1:%d' % sd_flags])
397 secdesc_ndr = gmsg[0]['nTSecurityDescriptor'][0]
398 secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
400 self.outf.write("Failed to fetch gpo object with nTSecurityDescriptor %s\n" %
405 samba.security.access_check(secdesc, token,
406 security.SEC_STD_READ_CONTROL |
407 security.SEC_ADS_LIST |
408 security.SEC_ADS_READ_PROP)
410 self.outf.write("Failed access check on %s\n" % msg.dn)
413 # check the flags on the GPO
414 flags = int(attr_default(gmsg[0], 'flags', 0))
415 if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
417 if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
419 gpos.append((gmsg[0]['displayName'][0], gmsg[0]['name'][0]))
421 # check if this blocks inheritance
422 gpoptions = int(attr_default(msg, 'gPOptions', 0))
423 if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
426 if dn == self.samdb.get_default_basedn():
435 self.outf.write("GPOs for %s %s\n" % (msg_str, username))
437 self.outf.write(" %s %s\n" % (g[0], g[1]))
440 class cmd_show(Command):
441 """Show information for a GPO."""
443 synopsis = "%prog <gpo> [options]"
445 takes_optiongroups = {
446 "sambaopts": options.SambaOptions,
447 "versionopts": options.VersionOptions,
448 "credopts": options.CredentialsOptions,
454 Option("-H", help="LDB URL for database or target server", type=str)
457 def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
459 self.lp = sambaopts.get_loadparm()
460 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
462 self.url = dc_url(self.lp, self.creds, H)
467 msg = get_gpo_info(self.samdb, gpo)[0]
469 raise CommandError("GPO '%s' does not exist" % gpo)
472 secdesc_ndr = msg['nTSecurityDescriptor'][0]
473 secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
474 secdesc_sddl = secdesc.as_sddl()
476 secdesc_sddl = "<hidden>"
478 self.outf.write("GPO : %s\n" % msg['name'][0])
479 self.outf.write("display name : %s\n" % msg['displayName'][0])
480 self.outf.write("path : %s\n" % msg['gPCFileSysPath'][0])
481 self.outf.write("dn : %s\n" % msg.dn)
482 self.outf.write("version : %s\n" % attr_default(msg, 'versionNumber', '0'))
483 self.outf.write("flags : %s\n" % gpo_flags_string(int(attr_default(msg, 'flags', 0))))
484 self.outf.write("ACL : %s\n" % secdesc_sddl)
485 self.outf.write("\n")
488 class cmd_getlink(Command):
489 """List GPO Links for a container."""
491 synopsis = "%prog <container_dn> [options]"
493 takes_optiongroups = {
494 "sambaopts": options.SambaOptions,
495 "versionopts": options.VersionOptions,
496 "credopts": options.CredentialsOptions,
499 takes_args = ['container_dn']
502 Option("-H", help="LDB URL for database or target server", type=str)
505 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
508 self.lp = sambaopts.get_loadparm()
509 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
511 self.url = dc_url(self.lp, self.creds, H)
516 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
517 expression="(objectClass=*)",
520 raise CommandError("Container '%s' does not exist" % container_dn)
523 self.outf.write("GPO(s) linked to DN %s\n" % container_dn)
524 gplist = parse_gplink(msg['gPLink'][0])
526 msg = get_gpo_info(self.samdb, dn=g['dn'])
527 self.outf.write(" GPO : %s\n" % msg[0]['name'][0])
528 self.outf.write(" Name : %s\n" % msg[0]['displayName'][0])
529 self.outf.write(" Options : %s\n" % gplink_options_string(g['options']))
530 self.outf.write("\n")
532 self.outf.write("No GPO(s) linked to DN=%s\n" % container_dn)
535 class cmd_setlink(Command):
536 """Add or update a GPO link to a container."""
538 synopsis = "%prog <container_dn> <gpo> [options]"
540 takes_optiongroups = {
541 "sambaopts": options.SambaOptions,
542 "versionopts": options.VersionOptions,
543 "credopts": options.CredentialsOptions,
546 takes_args = ['container_dn', 'gpo']
549 Option("-H", help="LDB URL for database or target server", type=str),
550 Option("--disable", dest="disabled", default=False, action='store_true',
551 help="Disable policy"),
552 Option("--enforce", dest="enforced", default=False, action='store_true',
553 help="Enforce policy")
556 def run(self, container_dn, gpo, H=None, disabled=False, enforced=False,
557 sambaopts=None, credopts=None, versionopts=None):
559 self.lp = sambaopts.get_loadparm()
560 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
562 self.url = dc_url(self.lp, self.creds, H)
568 gplink_options |= dsdb.GPLINK_OPT_DISABLE
570 gplink_options |= dsdb.GPLINK_OPT_ENFORCE
572 # Check if valid GPO DN
574 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
576 raise CommandError("GPO '%s' does not exist" % gpo)
577 gpo_dn = str(get_gpo_dn(self.samdb, gpo))
579 # Check if valid Container DN
581 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
582 expression="(objectClass=*)",
585 raise CommandError("Container '%s' does not exist" % container_dn)
587 # Update existing GPlinks or Add new one
588 existing_gplink = False
590 gplist = parse_gplink(msg['gPLink'][0])
591 existing_gplink = True
594 if g['dn'].lower() == gpo_dn.lower():
595 g['options'] = gplink_options
599 raise CommandError("GPO '%s' already linked to this container" % gpo)
601 gplist.insert(0, { 'dn' : gpo_dn, 'options' : gplink_options })
604 gplist.append({ 'dn' : gpo_dn, 'options' : gplink_options })
606 gplink_str = encode_gplink(gplist)
609 m.dn = ldb.Dn(self.samdb, container_dn)
612 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
614 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_ADD, 'gPLink')
619 raise CommandError("Error adding GPO Link", e)
621 self.outf.write("Added/Updated GPO link\n")
622 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
625 class cmd_dellink(Command):
626 """Delete GPO link from a container."""
628 synopsis = "%prog <container_dn> <gpo> [options]"
630 takes_optiongroups = {
631 "sambaopts": options.SambaOptions,
632 "versionopts": options.VersionOptions,
633 "credopts": options.CredentialsOptions,
636 takes_args = ['container', 'gpo']
639 Option("-H", help="LDB URL for database or target server", type=str),
642 def run(self, container, gpo, H=None, sambaopts=None, credopts=None,
645 self.lp = sambaopts.get_loadparm()
646 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
648 self.url = dc_url(self.lp, self.creds, H)
654 get_gpo_info(self.samdb, gpo=gpo)[0]
656 raise CommandError("GPO '%s' does not exist" % gpo)
658 container_dn = ldb.Dn(self.samdb, container)
659 del_gpo_link(self.samdb, container_dn, gpo)
660 self.outf.write("Deleted GPO link.\n")
661 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
664 class cmd_listcontainers(Command):
665 """List all linked containers for a GPO."""
667 synopsis = "%prog <gpo> [options]"
669 takes_optiongroups = {
670 "sambaopts": options.SambaOptions,
671 "versionopts": options.VersionOptions,
672 "credopts": options.CredentialsOptions,
678 Option("-H", help="LDB URL for database or target server", type=str)
681 def run(self, gpo, H=None, sambaopts=None, credopts=None,
684 self.lp = sambaopts.get_loadparm()
685 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
687 self.url = dc_url(self.lp, self.creds, H)
691 msg = get_gpo_containers(self.samdb, gpo)
693 self.outf.write("Container(s) using GPO %s\n" % gpo)
695 self.outf.write(" DN: %s\n" % m['dn'])
697 self.outf.write("No Containers using GPO %s\n" % gpo)
700 class cmd_getinheritance(Command):
701 """Get inheritance flag for a container."""
703 synopsis = "%prog <container_dn> [options]"
705 takes_optiongroups = {
706 "sambaopts": options.SambaOptions,
707 "versionopts": options.VersionOptions,
708 "credopts": options.CredentialsOptions,
711 takes_args = ['container_dn']
714 Option("-H", help="LDB URL for database or target server", type=str)
717 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
720 self.lp = sambaopts.get_loadparm()
721 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
723 self.url = dc_url(self.lp, self.creds, H)
728 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
729 expression="(objectClass=*)",
730 attrs=['gPOptions'])[0]
732 raise CommandError("Container '%s' does not exist" % container_dn)
735 if 'gPOptions' in msg:
736 inheritance = int(msg['gPOptions'][0])
738 if inheritance == dsdb.GPO_BLOCK_INHERITANCE:
739 self.outf.write("Container has GPO_BLOCK_INHERITANCE\n")
741 self.outf.write("Container has GPO_INHERIT\n")
744 class cmd_setinheritance(Command):
745 """Set inheritance flag on a container."""
747 synopsis = "%prog <container_dn> <block|inherit> [options]"
749 takes_optiongroups = {
750 "sambaopts": options.SambaOptions,
751 "versionopts": options.VersionOptions,
752 "credopts": options.CredentialsOptions,
755 takes_args = [ 'container_dn', 'inherit_state' ]
758 Option("-H", help="LDB URL for database or target server", type=str)
761 def run(self, container_dn, inherit_state, H=None, sambaopts=None, credopts=None,
764 if inherit_state.lower() == 'block':
765 inheritance = dsdb.GPO_BLOCK_INHERITANCE
766 elif inherit_state.lower() == 'inherit':
767 inheritance = dsdb.GPO_INHERIT
769 raise CommandError("Unknown inheritance state (%s)" % inherit_state)
771 self.lp = sambaopts.get_loadparm()
772 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
774 self.url = dc_url(self.lp, self.creds, H)
778 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
779 expression="(objectClass=*)",
780 attrs=['gPOptions'])[0]
782 raise CommandError("Container '%s' does not exist" % container_dn)
785 m.dn = ldb.Dn(self.samdb, container_dn)
787 if 'gPOptions' in msg:
788 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_REPLACE, 'gPOptions')
790 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_ADD, 'gPOptions')
795 raise CommandError("Error setting inheritance state %s" % inherit_state, e)
798 class cmd_fetch(Command):
799 """Download a GPO."""
801 synopsis = "%prog <gpo> [options]"
803 takes_optiongroups = {
804 "sambaopts": options.SambaOptions,
805 "versionopts": options.VersionOptions,
806 "credopts": options.CredentialsOptions,
812 Option("-H", help="LDB URL for database or target server", type=str),
813 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
816 def run(self, gpo, H=None, tmpdir=None, sambaopts=None, credopts=None, versionopts=None):
818 self.lp = sambaopts.get_loadparm()
819 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
821 # We need to know writable DC to setup SMB connection
822 if H and H.startswith('ldap://'):
826 dc_hostname = netcmd_finddc(self.lp, self.creds)
827 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
831 msg = get_gpo_info(self.samdb, gpo)[0]
833 raise CommandError("GPO '%s' does not exist" % gpo)
836 unc = msg['gPCFileSysPath'][0]
838 [dom_name, service, sharepath] = parse_unc(unc)
840 raise CommandError("Invalid GPO path (%s)" % unc)
844 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
846 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname)
851 if not os.path.isdir(tmpdir):
852 raise CommandError("Temoprary directory '%s' does not exist" % tmpdir)
854 localdir = os.path.join(tmpdir, "policy")
855 if not os.path.isdir(localdir):
858 gpodir = os.path.join(localdir, gpo)
859 if os.path.isdir(gpodir):
860 raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
864 copy_directory_remote_to_local(conn, sharepath, gpodir)
866 # FIXME: Catch more specific exception
867 raise CommandError("Error copying GPO from DC", e)
868 self.outf.write('GPO copied to %s\n' % gpodir)
871 class cmd_create(Command):
872 """Create an empty GPO."""
874 synopsis = "%prog <displayname> [options]"
876 takes_optiongroups = {
877 "sambaopts": options.SambaOptions,
878 "versionopts": options.VersionOptions,
879 "credopts": options.CredentialsOptions,
882 takes_args = ['displayname']
885 Option("-H", help="LDB URL for database or target server", type=str),
886 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
889 def run(self, displayname, H=None, tmpdir=None, sambaopts=None, credopts=None,
892 self.lp = sambaopts.get_loadparm()
893 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
895 # We need to know writable DC to setup SMB connection
896 if H and H.startswith('ldap://'):
900 dc_hostname = netcmd_finddc(self.lp, self.creds)
901 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
905 msg = get_gpo_info(self.samdb, displayname=displayname)
907 raise CommandError("A GPO already existing with name '%s'" % displayname)
910 guid = str(uuid.uuid4())
911 gpo = "{%s}" % guid.upper()
912 realm = self.lp.get('realm')
913 unc_path = "\\\\%s\\sysvol\\%s\\Policies\\%s" % (realm, realm, gpo)
918 if not os.path.isdir(tmpdir):
919 raise CommandError("Temporary directory '%s' does not exist" % tmpdir)
921 localdir = os.path.join(tmpdir, "policy")
922 if not os.path.isdir(localdir):
925 gpodir = os.path.join(localdir, gpo)
926 if os.path.isdir(gpodir):
927 raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
931 os.mkdir(os.path.join(gpodir, "Machine"))
932 os.mkdir(os.path.join(gpodir, "User"))
933 gpt_contents = "[General]\r\nVersion=0\r\n"
934 file(os.path.join(gpodir, "GPT.INI"), "w").write(gpt_contents)
936 raise CommandError("Error Creating GPO files", e)
938 # Connect to DC over SMB
939 [dom_name, service, sharepath] = parse_unc(unc_path)
941 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
943 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
945 self.samdb.transaction_start()
948 gpo_dn = get_gpo_dn(self.samdb, gpo)
952 m['a01'] = ldb.MessageElement("groupPolicyContainer", ldb.FLAG_MOD_ADD, "objectClass")
953 m['a02'] = ldb.MessageElement(displayname, ldb.FLAG_MOD_ADD, "displayName")
954 m['a03'] = ldb.MessageElement(unc_path, ldb.FLAG_MOD_ADD, "gPCFileSysPath")
955 m['a04'] = ldb.MessageElement("0", ldb.FLAG_MOD_ADD, "flags")
956 m['a05'] = ldb.MessageElement("0", ldb.FLAG_MOD_ADD, "versionNumber")
957 m['a06'] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_ADD, "showInAdvancedViewOnly")
958 m['a07'] = ldb.MessageElement("2", ldb.FLAG_MOD_ADD, "gpcFunctionalityVersion")
961 # Add cn=User,cn=<guid>
963 m.dn = ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn))
964 m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
965 m['a02'] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_ADD, "showInAdvancedViewOnly")
968 # Add cn=Machine,cn=<guid>
970 m.dn = ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn))
971 m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
972 m['a02'] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_ADD, "showInAdvancedViewOnly")
975 # Copy GPO files over SMB
976 create_directory_hier(conn, sharepath)
977 copy_directory_local_to_remote(conn, gpodir, sharepath)
979 # Get new security descriptor
980 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
981 ds_sd_ndr = msg['nTSecurityDescriptor'][0]
982 ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
984 # Create a file system security descriptor
985 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
986 sddl = dsacl2fsacl(ds_sd, domain_sid)
987 fs_sd = security.descriptor.from_sddl(sddl, domain_sid)
990 sio = ( security.SECINFO_OWNER |
991 security.SECINFO_GROUP |
992 security.SECINFO_DACL |
993 security.SECINFO_PROTECTED_DACL )
994 conn.set_acl(sharepath, fs_sd, sio)
996 self.samdb.transaction_cancel()
999 self.samdb.transaction_commit()
1001 self.outf.write("GPO '%s' created as %s\n" % (displayname, gpo))
1004 class cmd_del(Command):
1007 synopsis = "%prog <gpo> [options]"
1009 takes_optiongroups = {
1010 "sambaopts": options.SambaOptions,
1011 "versionopts": options.VersionOptions,
1012 "credopts": options.CredentialsOptions,
1015 takes_args = ['gpo']
1018 Option("-H", help="LDB URL for database or target server", type=str),
1021 def run(self, gpo, H=None, sambaopts=None, credopts=None,
1024 self.lp = sambaopts.get_loadparm()
1025 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1027 # We need to know writable DC to setup SMB connection
1028 if H and H.startswith('ldap://'):
1032 dc_hostname = netcmd_finddc(self.lp, self.creds)
1033 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1037 # Check if valid GPO
1039 get_gpo_info(self.samdb, gpo=gpo)[0]
1041 raise CommandError("GPO '%s' does not exist" % gpo)
1043 realm = self.lp.get('realm')
1044 unc_path = "\\\\%s\\sysvol\\%s\\Policies\\%s" % (realm, realm, gpo)
1046 # Connect to DC over SMB
1047 [dom_name, service, sharepath] = parse_unc(unc_path)
1049 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
1050 except Exception, e:
1051 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
1053 self.samdb.transaction_start()
1055 # Check for existing links
1056 msg = get_gpo_containers(self.samdb, gpo)
1059 self.outf.write("GPO %s is linked to containers\n" % gpo)
1061 del_gpo_link(self.samdb, m['dn'], gpo)
1062 self.outf.write(" Removed link from %s.\n" % m['dn'])
1064 # Remove LDAP entries
1065 gpo_dn = get_gpo_dn(self.samdb, gpo)
1066 self.samdb.delete(ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn)))
1067 self.samdb.delete(ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn)))
1068 self.samdb.delete(gpo_dn)
1071 conn.deltree(sharepath)
1074 self.samdb.transaction_cancel()
1077 self.samdb.transaction_commit()
1079 self.outf.write("GPO %s deleted.\n" % gpo)
1082 class cmd_aclcheck(Command):
1083 """Check all GPOs have matching LDAP and DS ACLs."""
1085 synopsis = "%prog [options]"
1087 takes_optiongroups = {
1088 "sambaopts": options.SambaOptions,
1089 "versionopts": options.VersionOptions,
1090 "credopts": options.CredentialsOptions,
1094 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
1095 metavar="URL", dest="H")
1098 def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
1100 self.lp = sambaopts.get_loadparm()
1101 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1103 self.url = dc_url(self.lp, self.creds, H)
1105 # We need to know writable DC to setup SMB connection
1106 if H and H.startswith('ldap://'):
1110 dc_hostname = netcmd_finddc(self.lp, self.creds)
1111 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1115 msg = get_gpo_info(self.samdb, None)
1119 unc = m['gPCFileSysPath'][0]
1121 [dom_name, service, sharepath] = parse_unc(unc)
1123 raise CommandError("Invalid GPO path (%s)" % unc)
1127 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
1129 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname)
1131 fs_sd = conn.get_acl(sharepath, security.SECINFO_OWNER | security.SECINFO_GROUP | security.SECINFO_DACL, security.SEC_FLAG_MAXIMUM_ALLOWED)
1133 ds_sd_ndr = m['nTSecurityDescriptor'][0]
1134 ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
1136 # Create a file system security descriptor
1137 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
1138 expected_fs_sddl = dsacl2fsacl(ds_sd, domain_sid)
1140 if (fs_sd.as_sddl(domain_sid) != expected_fs_sddl):
1141 raise CommandError("Invalid GPO ACL %s on path (%s), should be %s" % (fs_sd.as_sddl(domain_sid), sharepath, expected_fs_sddl))
1144 class cmd_gpo(SuperCommand):
1145 """Group Policy Object (GPO) management."""
1148 subcommands["listall"] = cmd_listall()
1149 subcommands["list"] = cmd_list()
1150 subcommands["show"] = cmd_show()
1151 subcommands["getlink"] = cmd_getlink()
1152 subcommands["setlink"] = cmd_setlink()
1153 subcommands["dellink"] = cmd_dellink()
1154 subcommands["listcontainers"] = cmd_listcontainers()
1155 subcommands["getinheritance"] = cmd_getinheritance()
1156 subcommands["setinheritance"] = cmd_setinheritance()
1157 subcommands["fetch"] = cmd_fetch()
1158 subcommands["create"] = cmd_create()
1159 subcommands["del"] = cmd_del()
1160 subcommands["aclcheck"] = cmd_aclcheck()