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 dsdb
38 from samba.dcerpc import security
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
44 from samba import policy
47 from samba.ntacls import dsacl2fsacl
50 def samdb_connect(ctx):
51 '''make a ldap connection to the server'''
53 ctx.samdb = SamDB(url=ctx.url,
54 session_info=system_session(),
55 credentials=ctx.creds, lp=ctx.lp)
57 raise CommandError("LDAP connection to %s failed " % ctx.url, e)
60 def attr_default(msg, attrname, default):
61 '''get an attribute from a ldap msg with a default'''
63 return msg[attrname][0]
67 def gpo_flags_string(value):
68 '''return gpo flags string'''
69 flags = policy.get_gpo_flags(value)
77 def gplink_options_string(value):
78 '''return gplink options string'''
79 options = policy.get_gplink_options(value)
83 ret = ' '.join(options)
87 def parse_gplink(gplink):
88 '''parse a gPLink into an array of dn and options'''
95 if len(d) != 2 or not d[0].startswith("[LDAP://"):
96 raise RuntimeError("Badly formed gPLink '%s'" % g)
97 ret.append({ 'dn' : d[0][8:], 'options' : int(d[1])})
101 def encode_gplink(gplist):
102 '''Encode an array of dn and options into gPLink string'''
105 ret += "[LDAP://%s;%d]" % (g['dn'], g['options'])
109 def dc_url(lp, creds, url=None, dc=None):
110 '''If URL is not specified, return URL for writable DC.
111 If dc is provided, use that to construct ldap URL'''
116 dc = netcmd_finddc(lp, creds)
118 raise RunTimeError("Could not find a DC for domain", e)
123 def get_gpo_dn(samdb, gpo):
124 '''Construct the DN for gpo'''
126 dn = samdb.get_default_basedn()
127 dn.add_child(ldb.Dn(samdb, "CN=Policies,DC=System"))
128 dn.add_child(ldb.Dn(samdb, "CN=%s" % gpo))
132 def get_gpo_info(samdb, gpo=None, displayname=None, dn=None):
133 '''Get GPO information using gpo, displayname or dn'''
135 policies_dn = samdb.get_default_basedn()
136 policies_dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
138 base_dn = policies_dn
139 search_expr = "(objectClass=groupPolicyContainer)"
140 search_scope = ldb.SCOPE_ONELEVEL
143 search_expr = "(&(objectClass=groupPolicyContainer)(name=%s))" % ldb.binary_encode(gpo)
145 if displayname is not None:
146 search_expr = "(&(objectClass=groupPolicyContainer)(displayname=%s))" % ldb.binary_encode(displayname)
150 search_scope = ldb.SCOPE_BASE
153 msg = samdb.search(base=base_dn, scope=search_scope,
154 expression=search_expr,
155 attrs=['nTSecurityDescriptor',
163 mesg = "Cannot get information for GPO %s" % gpo
165 mesg = "Cannot get information for GPOs"
166 raise CommandError(mesg, e)
172 '''Parse UNC string into a hostname, a service, and a filepath'''
173 if unc.startswith('\\\\') and unc.startswith('//'):
174 raise ValueError("UNC doesn't start with \\\\ or //")
175 tmp = unc[2:].split('/', 2)
178 tmp = unc[2:].split('\\', 2)
181 raise ValueError("Invalid UNC string: %s" % unc)
184 def copy_directory_remote_to_local(conn, remotedir, localdir):
185 if not os.path.isdir(localdir):
187 r_dirs = [ remotedir ]
188 l_dirs = [ localdir ]
193 dirlist = conn.list(r_dir)
195 r_name = r_dir + '\\' + e['name']
196 l_name = os.path.join(l_dir, e['name'])
198 if e['attrib'] & smb.FILE_ATTRIBUTE_DIRECTORY:
199 r_dirs.append(r_name)
200 l_dirs.append(l_name)
203 data = conn.loadfile(r_name)
204 file(l_name, 'w').write(data)
207 def copy_directory_local_to_remote(conn, localdir, remotedir):
208 if not conn.chkpath(remotedir):
209 conn.mkdir(remotedir)
210 l_dirs = [ localdir ]
211 r_dirs = [ remotedir ]
216 dirlist = os.listdir(l_dir)
218 l_name = os.path.join(l_dir, e)
219 r_name = r_dir + '\\' + e
221 if os.path.isdir(l_name):
222 l_dirs.append(l_name)
223 r_dirs.append(r_name)
226 data = file(l_name, 'r').read()
227 conn.savefile(r_name, data)
230 def create_directory_hier(conn, remotedir):
231 elems = remotedir.replace('/', '\\').split('\\')
234 path = path + '\\' + e
235 if not conn.chkpath(path):
239 class cmd_listall(Command):
242 synopsis = "%prog [options]"
245 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
246 metavar="URL", dest="H")
249 def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
251 self.lp = sambaopts.get_loadparm()
252 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
254 self.url = dc_url(self.lp, self.creds, H)
258 msg = get_gpo_info(self.samdb, None)
261 self.outf.write("GPO : %s\n" % m['name'][0])
262 self.outf.write("display name : %s\n" % m['displayName'][0])
263 self.outf.write("path : %s\n" % m['gPCFileSysPath'][0])
264 self.outf.write("dn : %s\n" % m.dn)
265 self.outf.write("version : %s\n" % attr_default(m, 'versionNumber', '0'))
266 self.outf.write("flags : %s\n" % gpo_flags_string(int(attr_default(m, 'flags', 0))))
267 self.outf.write("\n")
270 class cmd_list(Command):
271 """list GPOs for an account"""
273 synopsis = "%prog <username> [options]"
275 takes_args = ['username']
278 Option("-H", "--URL", help="LDB URL for database or target server",
279 type=str, metavar="URL", dest="H")
282 def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None):
284 self.lp = sambaopts.get_loadparm()
285 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
287 self.url = dc_url(self.lp, self.creds, H)
292 msg = self.samdb.search(expression='(&(|(samAccountName=%s)(samAccountName=%s$))(objectClass=User))' %
293 (ldb.binary_encode(username),ldb.binary_encode(username)))
296 raise CommandError("Failed to find account %s" % username, e)
298 # check if its a computer account
300 msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
301 is_computer = 'computer' in msg['objectClass']
303 raise CommandError("Failed to find objectClass for user %s" % username, e)
305 session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS |
306 AUTH_SESSION_INFO_AUTHENTICATED )
308 # When connecting to a remote server, don't look up the local privilege DB
309 if self.url is not None and self.url.startswith('ldap'):
310 session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
312 session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
313 session_info_flags=session_info_flags)
315 token = session.security_token
320 dn = ldb.Dn(self.samdb, str(user_dn)).parent()
322 msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
324 glist = parse_gplink(msg['gPLink'][0])
326 if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
328 if g['options'] & dsdb.GPLINK_OPT_DISABLE:
332 gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
333 attrs=['name', 'displayName', 'flags',
334 'ntSecurityDescriptor'])
336 self.outf.write("Failed to fetch gpo object %s\n" %
340 secdesc_ndr = gmsg[0]['ntSecurityDescriptor'][0]
341 secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
344 samba.security.access_check(secdesc, token,
345 security.SEC_STD_READ_CONTROL |
346 security.SEC_ADS_LIST |
347 security.SEC_ADS_READ_PROP)
349 self.outf.write("Failed access check on %s\n" % msg.dn)
352 # check the flags on the GPO
353 flags = int(attr_default(gmsg[0], 'flags', 0))
354 if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
356 if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
358 gpos.append((gmsg[0]['displayName'][0], gmsg[0]['name'][0]))
360 # check if this blocks inheritance
361 gpoptions = int(attr_default(msg, 'gPOptions', 0))
362 if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
365 if dn == self.samdb.get_default_basedn():
374 self.outf.write("GPOs for %s %s\n" % (msg_str, username))
376 self.outf.write(" %s %s\n" % (g[0], g[1]))
379 class cmd_show(Command):
380 """Show information for a GPO"""
382 synopsis = "%prog <gpo> [options]"
384 takes_optiongroups = {
385 "sambaopts": options.SambaOptions,
386 "versionopts": options.VersionOptions,
387 "credopts": options.CredentialsOptions,
393 Option("-H", help="LDB URL for database or target server", type=str)
396 def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
398 self.lp = sambaopts.get_loadparm()
399 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
401 self.url = dc_url(self.lp, self.creds, H)
406 msg = get_gpo_info(self.samdb, gpo)[0]
408 raise CommandError("GPO %s does not exist" % gpo, e)
410 secdesc_ndr = msg['ntSecurityDescriptor'][0]
411 secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
413 self.outf.write("GPO : %s\n" % msg['name'][0])
414 self.outf.write("display name : %s\n" % msg['displayName'][0])
415 self.outf.write("path : %s\n" % msg['gPCFileSysPath'][0])
416 self.outf.write("dn : %s\n" % msg.dn)
417 self.outf.write("version : %s\n" % attr_default(msg, 'versionNumber', '0'))
418 self.outf.write("flags : %s\n" % gpo_flags_string(int(attr_default(msg, 'flags', 0))))
419 self.outf.write("ACL : %s\n" % secdesc.as_sddl())
420 self.outf.write("\n")
423 class cmd_getlink(Command):
424 """List GPO Links for a container"""
426 synopsis = "%prog <container_dn> [options]"
428 takes_optiongroups = {
429 "sambaopts": options.SambaOptions,
430 "versionopts": options.VersionOptions,
431 "credopts": options.CredentialsOptions,
434 takes_args = ['container_dn']
437 Option("-H", help="LDB URL for database or target server", type=str)
440 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
443 self.lp = sambaopts.get_loadparm()
444 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
446 self.url = dc_url(self.lp, self.creds, H)
451 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
452 expression="(objectClass=*)",
455 raise CommandError("Could not find Container DN %s (%s)" % container_dn, e)
458 self.outf.write("GPO(s) linked to DN %s\n" % container_dn)
459 gplist = parse_gplink(msg['gPLink'][0])
461 msg = get_gpo_info(self.samdb, dn=g['dn'])
462 self.outf.write(" GPO : %s\n" % msg[0]['name'][0])
463 self.outf.write(" Name : %s\n" % msg[0]['displayName'][0])
464 self.outf.write(" Options : %s\n" % gplink_options_string(g['options']))
465 self.outf.write("\n")
467 self.outf.write("No GPO(s) linked to DN=%s\n" % container_dn)
470 class cmd_setlink(Command):
471 """Add or Update a GPO link to a container"""
473 synopsis = "%prog <container_dn> <gpo> [options]"
475 takes_optiongroups = {
476 "sambaopts": options.SambaOptions,
477 "versionopts": options.VersionOptions,
478 "credopts": options.CredentialsOptions,
481 takes_args = ['container_dn', 'gpo']
484 Option("-H", help="LDB URL for database or target server", type=str),
485 Option("--disable", dest="disabled", default=False, action='store_true',
486 help="Disable policy"),
487 Option("--enforce", dest="enforced", default=False, action='store_true',
488 help="Enforce policy")
491 def run(self, container_dn, gpo, H=None, disabled=False, enforced=False,
492 sambaopts=None, credopts=None, versionopts=None):
494 self.lp = sambaopts.get_loadparm()
495 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
497 self.url = dc_url(self.lp, self.creds, H)
503 gplink_options |= dsdb.GPLINK_OPT_DISABLE
505 gplink_options |= dsdb.GPLINK_OPT_ENFORCE
507 # Check if valid GPO DN
509 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
511 raise CommandError("GPO %s does not exist" % gpo_dn, e)
512 gpo_dn = get_gpo_dn(self.samdb, gpo)
514 # Check if valid Container DN
516 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
517 expression="(objectClass=*)",
520 raise CommandError("Could not find container DN %s" % container_dn, e)
522 # Update existing GPlinks or Add new one
523 existing_gplink = False
525 gplist = parse_gplink(msg['gPLink'][0])
526 existing_gplink = True
529 if g['dn'].lower() == gpo_dn.lower():
530 g['options'] = gplink_options
534 gplist.insert(0, { 'dn' : gpo_dn, 'options' : gplink_options })
537 gplist.append({ 'dn' : gpo_dn, 'options' : gplink_options })
539 gplink_str = encode_gplink(gplist)
542 m.dn = ldb.Dn(self.samdb, container_dn)
545 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
547 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_ADD, 'gPLink')
552 raise CommandError("Error adding GPO Link", e)
554 self.outf.write("Added/Updated GPO link\n")
555 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
558 class cmd_dellink(Command):
559 """Delete GPO link from a container"""
561 synopsis = "%prog <container_dn> <gpo> [options]"
563 takes_optiongroups = {
564 "sambaopts": options.SambaOptions,
565 "versionopts": options.VersionOptions,
566 "credopts": options.CredentialsOptions,
569 takes_args = ['container_dn', 'gpo']
572 Option("-H", help="LDB URL for database or target server", type=str),
575 def run(self, container_dn, gpo_dn, H=None, sambaopts=None, credopts=None,
578 self.lp = sambaopts.get_loadparm()
579 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
581 self.url = dc_url(self.lp, self.creds, H)
587 msg = get_gpo_info(self.sambdb, gpo=gpo)[0]
589 raise CommandError("GPO %s does not exist" % gpo, e)
590 gpo_dn = get_gpo_dn(self.samdb, gpo)
592 # Check if valid Container DN and get existing GPlinks
594 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
595 expression="(objectClass=*)",
598 raise CommandError("Could not find container DN %s" % dn, e)
601 gplist = parse_gplink(msg['gPLink'][0])
603 if g['dn'].lower() == gpo_dn.lower():
607 raise CommandError("Specified GPO is not linked to this container")
610 m.dn = ldb.Dn(self.samdb, container_dn)
613 gplink_str = encode_gplink(gplist)
614 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
616 m['new_value'] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, 'gPLink')
621 raise CommandError("Error Removing GPO Link (%s)" % e)
623 self.outf.write("Deleted GPO link.\n")
624 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
627 class cmd_getinheritance(Command):
628 """Get inheritance flag for a container"""
630 synopsis = "%prog <container_dn> [options]"
632 takes_optiongroups = {
633 "sambaopts": options.SambaOptions,
634 "versionopts": options.VersionOptions,
635 "credopts": options.CredentialsOptions,
638 takes_args = ['container_dn']
641 Option("-H", help="LDB URL for database or target server", type=str)
644 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
648 self.lp = sambaopts.get_loadparm()
650 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
655 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
656 expression="(objectClass=*)",
657 attrs=['gPOptions'])[0]
659 raise CommandError("Could not find Container DN %s" % container_dn, e)
662 if 'gPOptions' in msg:
663 inheritance = int(msg['gPOptions'][0])
665 if inheritance == dsdb.GPO_BLOCK_INHERITANCE:
666 self.outf.write("Container has GPO_BLOCK_INHERITANCE\n")
668 self.outf.write("Container has GPO_INHERIT\n")
671 class cmd_setinheritance(Command):
672 """Set inheritance flag on a container"""
674 synopsis = "%prog <container_dn> <block|inherit> [options]"
676 takes_optiongroups = {
677 "sambaopts": options.SambaOptions,
678 "versionopts": options.VersionOptions,
679 "credopts": options.CredentialsOptions,
682 takes_args = [ 'container_dn', 'inherit_state' ]
685 Option("-H", help="LDB URL for database or target server", type=str)
688 def run(self, container_dn, inherit_state, H=None, sambaopts=None, credopts=None,
691 if inherit_state.lower() == 'block':
692 inheritance = dsdb.GPO_BLOCK_INHERITANCE
693 elif inherit_state.lower() == 'inherit':
694 inheritance = dsdb.GPO_INHERIT
696 raise CommandError("Unknown inheritance state (%s)" % inherit_state)
699 self.lp = sambaopts.get_loadparm()
701 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
706 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
707 expression="(objectClass=*)",
708 attrs=['gPOptions'])[0]
710 raise CommandError("Could not find Container DN %s" % container_dn, e)
713 m.dn = ldb.Dn(self.samdb, container_dn)
715 if 'gPOptions' in msg:
716 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_REPLACE, 'gPOptions')
718 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_ADD, 'gPOptions')
723 raise CommandError("Error setting inheritance state %s" % inherit_state, e)
726 class cmd_fetch(Command):
729 synopsis = "%prog <gpo> [options]"
731 takes_optiongroups = {
732 "sambaopts": options.SambaOptions,
733 "versionopts": options.VersionOptions,
734 "credopts": options.CredentialsOptions,
740 Option("-H", help="LDB URL for database or target server", type=str),
741 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
744 def run(self, gpo, H=None, tmpdir=None, sambaopts=None, credopts=None, versionopts=None):
746 self.lp = sambaopts.get_loadparm()
747 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
749 dc_hostname = netcmd_finddc(self.lp, self.creds)
750 self.url = dc_url(self.lp, self.creds, H, dc=dc_hostname)
754 msg = get_gpo_info(self.samdb, gpo)[0]
756 raise CommandError("GPO %s does not exist" % gpo)
759 unc = msg['gPCFileSysPath'][0]
761 [dom_name, service, sharepath] = parse_unc(unc)
763 raise CommandError("Invalid GPO path (%s)" % unc)
767 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
769 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
774 if not os.path.isdir(tmpdir):
775 raise CommandError("Temoprary directory '%s' does not exist" % tmpdir)
777 localdir = os.path.join(tmpdir, "policy")
778 if not os.path.isdir(localdir):
781 gpodir = os.path.join(localdir, gpo)
782 if os.path.isdir(gpodir):
783 raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
787 copy_directory_remote_to_local(conn, sharepath, gpodir)
789 # FIXME: Catch more specific exception
790 raise CommandError("Error copying GPO from DC", e)
791 self.outf.write('GPO copied to %s\n' % gpodir)
794 class cmd_create(Command):
795 """Create an empty GPO"""
797 synopsis = "%prog <displayname> [options]"
799 takes_optiongroups = {
800 "sambaopts": options.SambaOptions,
801 "versionopts": options.VersionOptions,
802 "credopts": options.CredentialsOptions,
805 takes_args = ['displayname']
808 Option("-H", help="LDB URL for database or target server", type=str),
809 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
812 def run(self, displayname, H=None, tmpdir=None, sambaopts=None, credopts=None,
815 self.lp = sambaopts.get_loadparm()
816 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
818 self.url = dc_url(self.lp, self.creds, H)
820 dc_hostname = netcmd_finddc(self.lp, self.creds)
823 msg = get_gpo_info(self.samdb, displayname=displayname)
825 raise CommandError("A GPO already existing with name '%s'" % displayname)
828 guid = str(uuid.uuid4())
829 gpo = "{%s}" % guid.upper()
830 realm = self.lp.get('realm')
831 unc_path = "\\\\%s\\sysvol\\%s\\Policies\\%s" % (realm, realm, gpo)
836 if not os.path.isdir(tmpdir):
837 raise CommandError("Temporary directory '%s' does not exist" % tmpdir)
839 localdir = os.path.join(tmpdir, "policy")
840 if not os.path.isdir(localdir):
843 gpodir = os.path.join(localdir, gpo)
844 if os.path.isdir(gpodir):
845 raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
849 os.mkdir(os.path.join(gpodir, "Machine"))
850 os.mkdir(os.path.join(gpodir, "User"))
851 gpt_contents = "[General]\r\nVersion=0\r\n"
852 file(os.path.join(gpodir, "GPT.INI"), "w").write(gpt_contents)
854 raise CommandError("Error Creating GPO files", e)
857 gpo_dn = self.samdb.get_default_basedn()
858 gpo_dn.add_child(ldb.Dn(self.samdb, "CN=Policies,CN=System"))
859 gpo_dn.add_child(ldb.Dn(self.samdb, "CN=%s" % gpo))
862 m.dn = ldb.Dn(self.samdb, gpo_dn.get_linearized())
863 m['a01'] = ldb.MessageElement("groupPolicyContainer", ldb.FLAG_MOD_ADD, "objectClass")
864 m['a02'] = ldb.MessageElement(displayname, ldb.FLAG_MOD_ADD, "displayName")
865 m['a03'] = ldb.MessageElement(unc_path, ldb.FLAG_MOD_ADD, "gPCFileSysPath")
866 m['a04'] = ldb.MessageElement("0", ldb.FLAG_MOD_ADD, "flags")
867 m['a05'] = ldb.MessageElement("0", ldb.FLAG_MOD_ADD, "versionNumber")
868 m['a06'] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_ADD, "showInAdvancedViewOnly")
869 m['a07'] = ldb.MessageElement("2", ldb.FLAG_MOD_ADD, "gpcFunctionalityVersion")
873 raise CommandError("Error adding GPO in AD", e)
875 # Add cn=User,cn=<guid>
877 m.dn = ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn))
878 m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
879 m['a02'] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_ADD, "showInAdvancedViewOnly")
883 raise CommandError("Error adding GPO in AD", e)
885 # Add cn=Machine,cn=<guid>
887 m.dn = ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn))
888 m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
889 m['a02'] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_ADD, "showInAdvancedViewOnly")
893 raise CommandError("Error adding GPO in AD", e)
895 # Copy GPO files over SMB
896 [dom_name, service, sharepath] = parse_unc(unc_path)
898 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
900 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
903 create_directory_hier(conn, sharepath)
904 copy_directory_local_to_remote(conn, gpodir, sharepath)
906 raise CommandError("Error Copying GPO to DC", e)
908 # Get new security descriptor
909 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
910 ds_sd_ndr = msg['ntSecurityDescriptor'][0]
911 ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
913 # Create a file system security descriptor
914 fs_sd = security.descriptor(dsacl2fsacl(ds_sd, self.samdb.get_domain_sid()))
918 conn.set_acl(sharepath, fs_sd)
920 raise CommandError("Error setting ACL on GPT", e)
922 self.outf.write("GPO '%s' created as %s\n" % (displayname, gpo))
925 class cmd_gpo(SuperCommand):
926 """Group Policy Object (GPO) management"""
929 subcommands["listall"] = cmd_listall()
930 subcommands["list"] = cmd_list()
931 subcommands["show"] = cmd_show()
932 subcommands["getlink"] = cmd_getlink()
933 subcommands["setlink"] = cmd_setlink()
934 subcommands["dellink"] = cmd_dellink()
935 subcommands["getinheritance"] = cmd_getinheritance()
936 subcommands["setinheritance"] = cmd_setinheritance()
937 subcommands["fetch"] = cmd_fetch()
938 subcommands["create"] = cmd_create()