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
45 from samba.dcerpc import nbt
46 from samba.net import Net
49 def samdb_connect(ctx):
50 '''make a ldap connection to the server'''
52 ctx.samdb = SamDB(url=ctx.url,
53 session_info=system_session(),
54 credentials=ctx.creds, lp=ctx.lp)
55 except Exception as e:
56 raise CommandError("LDAP connection to %s failed " % ctx.url, e)
59 def attr_default(msg, attrname, default):
60 '''get an attribute from a ldap msg with a default'''
62 return msg[attrname][0]
66 def gpo_flags_string(value):
67 '''return gpo flags string'''
68 flags = policy.get_gpo_flags(value)
76 def gplink_options_string(value):
77 '''return gplink options string'''
78 options = policy.get_gplink_options(value)
82 ret = ' '.join(options)
86 def parse_gplink(gplink):
87 '''parse a gPLink into an array of dn and options'''
94 if len(d) != 2 or not d[0].startswith("[LDAP://"):
95 raise RuntimeError("Badly formed gPLink '%s'" % g)
96 ret.append({ 'dn' : d[0][8:], 'options' : int(d[1])})
100 def encode_gplink(gplist):
101 '''Encode an array of dn and options into gPLink string'''
104 ret += "[LDAP://%s;%d]" % (g['dn'], g['options'])
108 def dc_url(lp, creds, url=None, dc=None):
109 '''If URL is not specified, return URL for writable DC.
110 If dc is provided, use that to construct ldap URL'''
115 dc = netcmd_finddc(lp, creds)
116 except Exception as e:
117 raise RuntimeError("Could not find a DC for domain", e)
122 def get_gpo_dn(samdb, gpo):
123 '''Construct the DN for gpo'''
125 dn = samdb.get_default_basedn()
126 dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
127 dn.add_child(ldb.Dn(samdb, "CN=%s" % gpo))
131 def get_gpo_info(samdb, gpo=None, displayname=None, dn=None,
132 sd_flags=security.SECINFO_OWNER|security.SECINFO_GROUP|security.SECINFO_DACL|security.SECINFO_SACL):
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',
161 controls=['sd_flags:1:%d' % sd_flags])
162 except Exception as e:
164 mesg = "Cannot get information for GPO %s" % gpo
166 mesg = "Cannot get information for GPOs"
167 raise CommandError(mesg, e)
172 def get_gpo_containers(samdb, gpo):
173 '''lists dn of containers for a GPO'''
175 search_expr = "(&(objectClass=*)(gPLink=*%s*))" % gpo
177 msg = samdb.search(expression=search_expr, attrs=['gPLink'])
178 except Exception as e:
179 raise CommandError("Could not find container(s) with GPO %s" % gpo, e)
184 def del_gpo_link(samdb, container_dn, gpo):
185 '''delete GPO link for the container'''
186 # Check if valid Container DN and get existing GPlinks
188 msg = samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
189 expression="(objectClass=*)",
191 except Exception as e:
192 raise CommandError("Container '%s' does not exist" % container_dn, e)
195 gpo_dn = str(get_gpo_dn(samdb, gpo))
197 gplist = parse_gplink(msg['gPLink'][0])
199 if g['dn'].lower() == gpo_dn.lower():
204 raise CommandError("No GPO(s) linked to this container")
207 raise CommandError("GPO '%s' not linked to this container" % gpo)
212 gplink_str = encode_gplink(gplist)
213 m['r0'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
215 m['d0'] = ldb.MessageElement(msg['gPLink'][0], ldb.FLAG_MOD_DELETE, 'gPLink')
218 except Exception as e:
219 raise CommandError("Error removing GPO from container", e)
223 '''Parse UNC string into a hostname, a service, and a filepath'''
224 if unc.startswith('\\\\') and unc.startswith('//'):
225 raise ValueError("UNC doesn't start with \\\\ or //")
226 tmp = unc[2:].split('/', 2)
229 tmp = unc[2:].split('\\', 2)
232 raise ValueError("Invalid UNC string: %s" % unc)
234 attr_flags = smb.FILE_ATTRIBUTE_SYSTEM | \
235 smb.FILE_ATTRIBUTE_DIRECTORY | \
236 smb.FILE_ATTRIBUTE_ARCHIVE | \
237 smb.FILE_ATTRIBUTE_HIDDEN
239 def copy_directory_remote_to_local(conn, remotedir, localdir):
240 if not os.path.isdir(localdir):
242 r_dirs = [ remotedir ]
243 l_dirs = [ localdir ]
248 dirlist = conn.list(r_dir, attribs=attr_flags)
250 r_name = r_dir + '\\' + e['name']
251 l_name = os.path.join(l_dir, e['name'])
253 if e['attrib'] & smb.FILE_ATTRIBUTE_DIRECTORY:
254 r_dirs.append(r_name)
255 l_dirs.append(l_name)
258 data = conn.loadfile(r_name)
259 open(l_name, 'w').write(data)
262 def copy_directory_local_to_remote(conn, localdir, remotedir):
263 if not conn.chkpath(remotedir):
264 conn.mkdir(remotedir)
265 l_dirs = [ localdir ]
266 r_dirs = [ remotedir ]
271 dirlist = os.listdir(l_dir)
273 l_name = os.path.join(l_dir, e)
274 r_name = r_dir + '\\' + e
276 if os.path.isdir(l_name):
277 l_dirs.append(l_name)
278 r_dirs.append(r_name)
281 data = open(l_name, 'r').read()
282 conn.savefile(r_name, data)
285 def create_directory_hier(conn, remotedir):
286 elems = remotedir.replace('/', '\\').split('\\')
289 path = path + '\\' + e
290 if not conn.chkpath(path):
294 class cmd_listall(Command):
297 synopsis = "%prog [options]"
299 takes_optiongroups = {
300 "sambaopts": options.SambaOptions,
301 "versionopts": options.VersionOptions,
302 "credopts": options.CredentialsOptions,
306 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
307 metavar="URL", dest="H")
310 def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
312 self.lp = sambaopts.get_loadparm()
313 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
315 self.url = dc_url(self.lp, self.creds, H)
319 msg = get_gpo_info(self.samdb, None)
322 self.outf.write("GPO : %s\n" % m['name'][0])
323 self.outf.write("display name : %s\n" % m['displayName'][0])
324 self.outf.write("path : %s\n" % m['gPCFileSysPath'][0])
325 self.outf.write("dn : %s\n" % m.dn)
326 self.outf.write("version : %s\n" % attr_default(m, 'versionNumber', '0'))
327 self.outf.write("flags : %s\n" % gpo_flags_string(int(attr_default(m, 'flags', 0))))
328 self.outf.write("\n")
331 class cmd_list(Command):
332 """List GPOs for an account."""
334 synopsis = "%prog <username> [options]"
336 takes_args = ['username']
337 takes_optiongroups = {
338 "sambaopts": options.SambaOptions,
339 "versionopts": options.VersionOptions,
340 "credopts": options.CredentialsOptions,
344 Option("-H", "--URL", help="LDB URL for database or target server",
345 type=str, metavar="URL", dest="H")
348 def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None):
350 self.lp = sambaopts.get_loadparm()
351 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
353 self.url = dc_url(self.lp, self.creds, H)
358 msg = self.samdb.search(expression='(&(|(samAccountName=%s)(samAccountName=%s$))(objectClass=User))' %
359 (ldb.binary_encode(username),ldb.binary_encode(username)))
362 raise CommandError("Failed to find account %s" % username)
364 # check if its a computer account
366 msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
367 is_computer = 'computer' in msg['objectClass']
369 raise CommandError("Failed to find objectClass for user %s" % username)
371 session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS |
372 AUTH_SESSION_INFO_AUTHENTICATED )
374 # When connecting to a remote server, don't look up the local privilege DB
375 if self.url is not None and self.url.startswith('ldap'):
376 session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
378 session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
379 session_info_flags=session_info_flags)
381 token = session.security_token
386 dn = ldb.Dn(self.samdb, str(user_dn)).parent()
388 msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
390 glist = parse_gplink(msg['gPLink'][0])
392 if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
394 if g['options'] & dsdb.GPLINK_OPT_DISABLE:
398 sd_flags=security.SECINFO_OWNER|security.SECINFO_GROUP|security.SECINFO_DACL
399 gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
400 attrs=['name', 'displayName', 'flags',
401 'nTSecurityDescriptor'],
402 controls=['sd_flags:1:%d' % sd_flags])
403 secdesc_ndr = gmsg[0]['nTSecurityDescriptor'][0]
404 secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
406 self.outf.write("Failed to fetch gpo object with nTSecurityDescriptor %s\n" %
411 samba.security.access_check(secdesc, token,
412 security.SEC_STD_READ_CONTROL |
413 security.SEC_ADS_LIST |
414 security.SEC_ADS_READ_PROP)
416 self.outf.write("Failed access check on %s\n" % msg.dn)
419 # check the flags on the GPO
420 flags = int(attr_default(gmsg[0], 'flags', 0))
421 if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
423 if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
425 gpos.append((gmsg[0]['displayName'][0], gmsg[0]['name'][0]))
427 # check if this blocks inheritance
428 gpoptions = int(attr_default(msg, 'gPOptions', 0))
429 if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
432 if dn == self.samdb.get_default_basedn():
441 self.outf.write("GPOs for %s %s\n" % (msg_str, username))
443 self.outf.write(" %s %s\n" % (g[0], g[1]))
446 class cmd_show(Command):
447 """Show information for a GPO."""
449 synopsis = "%prog <gpo> [options]"
451 takes_optiongroups = {
452 "sambaopts": options.SambaOptions,
453 "versionopts": options.VersionOptions,
454 "credopts": options.CredentialsOptions,
460 Option("-H", help="LDB URL for database or target server", type=str)
463 def run(self, gpo, H=None, 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)
473 msg = get_gpo_info(self.samdb, gpo)[0]
475 raise CommandError("GPO '%s' does not exist" % gpo)
478 secdesc_ndr = msg['nTSecurityDescriptor'][0]
479 secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
480 secdesc_sddl = secdesc.as_sddl()
482 secdesc_sddl = "<hidden>"
484 self.outf.write("GPO : %s\n" % msg['name'][0])
485 self.outf.write("display name : %s\n" % msg['displayName'][0])
486 self.outf.write("path : %s\n" % msg['gPCFileSysPath'][0])
487 self.outf.write("dn : %s\n" % msg.dn)
488 self.outf.write("version : %s\n" % attr_default(msg, 'versionNumber', '0'))
489 self.outf.write("flags : %s\n" % gpo_flags_string(int(attr_default(msg, 'flags', 0))))
490 self.outf.write("ACL : %s\n" % secdesc_sddl)
491 self.outf.write("\n")
494 class cmd_getlink(Command):
495 """List GPO Links for a container."""
497 synopsis = "%prog <container_dn> [options]"
499 takes_optiongroups = {
500 "sambaopts": options.SambaOptions,
501 "versionopts": options.VersionOptions,
502 "credopts": options.CredentialsOptions,
505 takes_args = ['container_dn']
508 Option("-H", help="LDB URL for database or target server", type=str)
511 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
514 self.lp = sambaopts.get_loadparm()
515 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
517 self.url = dc_url(self.lp, self.creds, H)
522 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
523 expression="(objectClass=*)",
526 raise CommandError("Container '%s' does not exist" % container_dn)
529 self.outf.write("GPO(s) linked to DN %s\n" % container_dn)
530 gplist = parse_gplink(msg['gPLink'][0])
532 msg = get_gpo_info(self.samdb, dn=g['dn'])
533 self.outf.write(" GPO : %s\n" % msg[0]['name'][0])
534 self.outf.write(" Name : %s\n" % msg[0]['displayName'][0])
535 self.outf.write(" Options : %s\n" % gplink_options_string(g['options']))
536 self.outf.write("\n")
538 self.outf.write("No GPO(s) linked to DN=%s\n" % container_dn)
541 class cmd_setlink(Command):
542 """Add or update a GPO link to a container."""
544 synopsis = "%prog <container_dn> <gpo> [options]"
546 takes_optiongroups = {
547 "sambaopts": options.SambaOptions,
548 "versionopts": options.VersionOptions,
549 "credopts": options.CredentialsOptions,
552 takes_args = ['container_dn', 'gpo']
555 Option("-H", help="LDB URL for database or target server", type=str),
556 Option("--disable", dest="disabled", default=False, action='store_true',
557 help="Disable policy"),
558 Option("--enforce", dest="enforced", default=False, action='store_true',
559 help="Enforce policy")
562 def run(self, container_dn, gpo, H=None, disabled=False, enforced=False,
563 sambaopts=None, credopts=None, versionopts=None):
565 self.lp = sambaopts.get_loadparm()
566 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
568 self.url = dc_url(self.lp, self.creds, H)
574 gplink_options |= dsdb.GPLINK_OPT_DISABLE
576 gplink_options |= dsdb.GPLINK_OPT_ENFORCE
578 # Check if valid GPO DN
580 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
582 raise CommandError("GPO '%s' does not exist" % gpo)
583 gpo_dn = str(get_gpo_dn(self.samdb, gpo))
585 # Check if valid Container DN
587 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
588 expression="(objectClass=*)",
591 raise CommandError("Container '%s' does not exist" % container_dn)
593 # Update existing GPlinks or Add new one
594 existing_gplink = False
596 gplist = parse_gplink(msg['gPLink'][0])
597 existing_gplink = True
600 if g['dn'].lower() == gpo_dn.lower():
601 g['options'] = gplink_options
605 raise CommandError("GPO '%s' already linked to this container" % gpo)
607 gplist.insert(0, { 'dn' : gpo_dn, 'options' : gplink_options })
610 gplist.append({ 'dn' : gpo_dn, 'options' : gplink_options })
612 gplink_str = encode_gplink(gplist)
615 m.dn = ldb.Dn(self.samdb, container_dn)
618 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
620 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_ADD, 'gPLink')
624 except Exception as e:
625 raise CommandError("Error adding GPO Link", e)
627 self.outf.write("Added/Updated GPO link\n")
628 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
631 class cmd_dellink(Command):
632 """Delete GPO link from a container."""
634 synopsis = "%prog <container_dn> <gpo> [options]"
636 takes_optiongroups = {
637 "sambaopts": options.SambaOptions,
638 "versionopts": options.VersionOptions,
639 "credopts": options.CredentialsOptions,
642 takes_args = ['container', 'gpo']
645 Option("-H", help="LDB URL for database or target server", type=str),
648 def run(self, container, gpo, H=None, sambaopts=None, credopts=None,
651 self.lp = sambaopts.get_loadparm()
652 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
654 self.url = dc_url(self.lp, self.creds, H)
660 get_gpo_info(self.samdb, gpo=gpo)[0]
662 raise CommandError("GPO '%s' does not exist" % gpo)
664 container_dn = ldb.Dn(self.samdb, container)
665 del_gpo_link(self.samdb, container_dn, gpo)
666 self.outf.write("Deleted GPO link.\n")
667 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
670 class cmd_listcontainers(Command):
671 """List all linked containers for a GPO."""
673 synopsis = "%prog <gpo> [options]"
675 takes_optiongroups = {
676 "sambaopts": options.SambaOptions,
677 "versionopts": options.VersionOptions,
678 "credopts": options.CredentialsOptions,
684 Option("-H", help="LDB URL for database or target server", type=str)
687 def run(self, gpo, H=None, sambaopts=None, credopts=None,
690 self.lp = sambaopts.get_loadparm()
691 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
693 self.url = dc_url(self.lp, self.creds, H)
697 msg = get_gpo_containers(self.samdb, gpo)
699 self.outf.write("Container(s) using GPO %s\n" % gpo)
701 self.outf.write(" DN: %s\n" % m['dn'])
703 self.outf.write("No Containers using GPO %s\n" % gpo)
706 class cmd_getinheritance(Command):
707 """Get inheritance flag for a container."""
709 synopsis = "%prog <container_dn> [options]"
711 takes_optiongroups = {
712 "sambaopts": options.SambaOptions,
713 "versionopts": options.VersionOptions,
714 "credopts": options.CredentialsOptions,
717 takes_args = ['container_dn']
720 Option("-H", help="LDB URL for database or target server", type=str)
723 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
726 self.lp = sambaopts.get_loadparm()
727 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
729 self.url = dc_url(self.lp, self.creds, H)
734 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
735 expression="(objectClass=*)",
736 attrs=['gPOptions'])[0]
738 raise CommandError("Container '%s' does not exist" % container_dn)
741 if 'gPOptions' in msg:
742 inheritance = int(msg['gPOptions'][0])
744 if inheritance == dsdb.GPO_BLOCK_INHERITANCE:
745 self.outf.write("Container has GPO_BLOCK_INHERITANCE\n")
747 self.outf.write("Container has GPO_INHERIT\n")
750 class cmd_setinheritance(Command):
751 """Set inheritance flag on a container."""
753 synopsis = "%prog <container_dn> <block|inherit> [options]"
755 takes_optiongroups = {
756 "sambaopts": options.SambaOptions,
757 "versionopts": options.VersionOptions,
758 "credopts": options.CredentialsOptions,
761 takes_args = [ 'container_dn', 'inherit_state' ]
764 Option("-H", help="LDB URL for database or target server", type=str)
767 def run(self, container_dn, inherit_state, H=None, sambaopts=None, credopts=None,
770 if inherit_state.lower() == 'block':
771 inheritance = dsdb.GPO_BLOCK_INHERITANCE
772 elif inherit_state.lower() == 'inherit':
773 inheritance = dsdb.GPO_INHERIT
775 raise CommandError("Unknown inheritance state (%s)" % inherit_state)
777 self.lp = sambaopts.get_loadparm()
778 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
780 self.url = dc_url(self.lp, self.creds, H)
784 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
785 expression="(objectClass=*)",
786 attrs=['gPOptions'])[0]
788 raise CommandError("Container '%s' does not exist" % container_dn)
791 m.dn = ldb.Dn(self.samdb, container_dn)
793 if 'gPOptions' in msg:
794 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_REPLACE, 'gPOptions')
796 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_ADD, 'gPOptions')
800 except Exception as e:
801 raise CommandError("Error setting inheritance state %s" % inherit_state, e)
804 class cmd_fetch(Command):
805 """Download a GPO."""
807 synopsis = "%prog <gpo> [options]"
809 takes_optiongroups = {
810 "sambaopts": options.SambaOptions,
811 "versionopts": options.VersionOptions,
812 "credopts": options.CredentialsOptions,
818 Option("-H", help="LDB URL for database or target server", type=str),
819 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
822 def run(self, gpo, H=None, tmpdir=None, sambaopts=None, credopts=None, versionopts=None):
824 self.lp = sambaopts.get_loadparm()
825 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
827 # We need to know writable DC to setup SMB connection
828 if H and H.startswith('ldap://'):
832 dc_hostname = netcmd_finddc(self.lp, self.creds)
833 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
837 msg = get_gpo_info(self.samdb, gpo)[0]
839 raise CommandError("GPO '%s' does not exist" % gpo)
842 unc = msg['gPCFileSysPath'][0]
844 [dom_name, service, sharepath] = parse_unc(unc)
846 raise CommandError("Invalid GPO path (%s)" % unc)
850 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
852 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname)
857 if not os.path.isdir(tmpdir):
858 raise CommandError("Temoprary directory '%s' does not exist" % tmpdir)
860 localdir = os.path.join(tmpdir, "policy")
861 if not os.path.isdir(localdir):
864 gpodir = os.path.join(localdir, gpo)
865 if os.path.isdir(gpodir):
866 raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
870 copy_directory_remote_to_local(conn, sharepath, gpodir)
871 except Exception as e:
872 # FIXME: Catch more specific exception
873 raise CommandError("Error copying GPO from DC", e)
874 self.outf.write('GPO copied to %s\n' % gpodir)
877 class cmd_create(Command):
878 """Create an empty GPO."""
880 synopsis = "%prog <displayname> [options]"
882 takes_optiongroups = {
883 "sambaopts": options.SambaOptions,
884 "versionopts": options.VersionOptions,
885 "credopts": options.CredentialsOptions,
888 takes_args = ['displayname']
891 Option("-H", help="LDB URL for database or target server", type=str),
892 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
895 def run(self, displayname, H=None, tmpdir=None, sambaopts=None, credopts=None,
898 self.lp = sambaopts.get_loadparm()
899 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
901 net = Net(creds=self.creds, lp=self.lp)
903 # We need to know writable DC to setup SMB connection
904 if H and H.startswith('ldap://'):
907 flags = (nbt.NBT_SERVER_LDAP |
909 nbt.NBT_SERVER_WRITABLE)
910 cldap_ret = net.finddc(address=dc_hostname, flags=flags)
912 flags = (nbt.NBT_SERVER_LDAP |
914 nbt.NBT_SERVER_WRITABLE)
915 cldap_ret = net.finddc(domain=self.lp.get('realm'), flags=flags)
916 dc_hostname = cldap_ret.pdc_dns_name
917 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
921 msg = get_gpo_info(self.samdb, displayname=displayname)
923 raise CommandError("A GPO already existing with name '%s'" % displayname)
926 guid = str(uuid.uuid4())
927 gpo = "{%s}" % guid.upper()
928 realm = cldap_ret.dns_domain
929 unc_path = "\\\\%s\\sysvol\\%s\\Policies\\%s" % (realm, realm, gpo)
934 if not os.path.isdir(tmpdir):
935 raise CommandError("Temporary directory '%s' does not exist" % tmpdir)
937 localdir = os.path.join(tmpdir, "policy")
938 if not os.path.isdir(localdir):
941 gpodir = os.path.join(localdir, gpo)
942 if os.path.isdir(gpodir):
943 raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
947 os.mkdir(os.path.join(gpodir, "Machine"))
948 os.mkdir(os.path.join(gpodir, "User"))
949 gpt_contents = "[General]\r\nVersion=0\r\n"
950 open(os.path.join(gpodir, "GPT.INI"), "w").write(gpt_contents)
951 except Exception as e:
952 raise CommandError("Error Creating GPO files", e)
954 # Connect to DC over SMB
955 [dom_name, service, sharepath] = parse_unc(unc_path)
957 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
958 except Exception as e:
959 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
961 self.samdb.transaction_start()
964 gpo_dn = get_gpo_dn(self.samdb, gpo)
968 m['a01'] = ldb.MessageElement("groupPolicyContainer", ldb.FLAG_MOD_ADD, "objectClass")
971 # Add cn=User,cn=<guid>
973 m.dn = ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn))
974 m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
977 # Add cn=Machine,cn=<guid>
979 m.dn = ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn))
980 m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
983 # Get new security descriptor
984 ds_sd_flags = ( security.SECINFO_OWNER |
985 security.SECINFO_GROUP |
986 security.SECINFO_DACL )
987 msg = get_gpo_info(self.samdb, gpo=gpo, sd_flags=ds_sd_flags)[0]
988 ds_sd_ndr = msg['nTSecurityDescriptor'][0]
989 ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
991 # Create a file system security descriptor
992 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
993 sddl = dsacl2fsacl(ds_sd, domain_sid)
994 fs_sd = security.descriptor.from_sddl(sddl, domain_sid)
997 create_directory_hier(conn, sharepath)
1000 sio = ( security.SECINFO_OWNER |
1001 security.SECINFO_GROUP |
1002 security.SECINFO_DACL |
1003 security.SECINFO_PROTECTED_DACL )
1004 conn.set_acl(sharepath, fs_sd, sio)
1006 # Copy GPO files over SMB
1007 copy_directory_local_to_remote(conn, gpodir, sharepath)
1011 m['a02'] = ldb.MessageElement(displayname, ldb.FLAG_MOD_REPLACE, "displayName")
1012 m['a03'] = ldb.MessageElement(unc_path, ldb.FLAG_MOD_REPLACE, "gPCFileSysPath")
1013 m['a05'] = ldb.MessageElement("0", ldb.FLAG_MOD_REPLACE, "versionNumber")
1014 m['a07'] = ldb.MessageElement("2", ldb.FLAG_MOD_REPLACE, "gpcFunctionalityVersion")
1015 m['a04'] = ldb.MessageElement("0", ldb.FLAG_MOD_REPLACE, "flags")
1016 controls=["permissive_modify:0"]
1017 self.samdb.modify(m, controls=controls)
1019 self.samdb.transaction_cancel()
1022 self.samdb.transaction_commit()
1024 self.outf.write("GPO '%s' created as %s\n" % (displayname, gpo))
1027 class cmd_del(Command):
1030 synopsis = "%prog <gpo> [options]"
1032 takes_optiongroups = {
1033 "sambaopts": options.SambaOptions,
1034 "versionopts": options.VersionOptions,
1035 "credopts": options.CredentialsOptions,
1038 takes_args = ['gpo']
1041 Option("-H", help="LDB URL for database or target server", type=str),
1044 def run(self, gpo, H=None, sambaopts=None, credopts=None,
1047 self.lp = sambaopts.get_loadparm()
1048 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1050 # We need to know writable DC to setup SMB connection
1051 if H and H.startswith('ldap://'):
1055 dc_hostname = netcmd_finddc(self.lp, self.creds)
1056 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1060 # Check if valid GPO
1062 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
1063 unc_path = msg['gPCFileSysPath'][0]
1065 raise CommandError("GPO '%s' does not exist" % gpo)
1067 # Connect to DC over SMB
1068 [dom_name, service, sharepath] = parse_unc(unc_path)
1070 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
1071 except Exception as e:
1072 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
1074 self.samdb.transaction_start()
1076 # Check for existing links
1077 msg = get_gpo_containers(self.samdb, gpo)
1080 self.outf.write("GPO %s is linked to containers\n" % gpo)
1082 del_gpo_link(self.samdb, m['dn'], gpo)
1083 self.outf.write(" Removed link from %s.\n" % m['dn'])
1085 # Remove LDAP entries
1086 gpo_dn = get_gpo_dn(self.samdb, gpo)
1087 self.samdb.delete(ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn)))
1088 self.samdb.delete(ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn)))
1089 self.samdb.delete(gpo_dn)
1092 conn.deltree(sharepath)
1095 self.samdb.transaction_cancel()
1098 self.samdb.transaction_commit()
1100 self.outf.write("GPO %s deleted.\n" % gpo)
1103 class cmd_aclcheck(Command):
1104 """Check all GPOs have matching LDAP and DS ACLs."""
1106 synopsis = "%prog [options]"
1108 takes_optiongroups = {
1109 "sambaopts": options.SambaOptions,
1110 "versionopts": options.VersionOptions,
1111 "credopts": options.CredentialsOptions,
1115 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
1116 metavar="URL", dest="H")
1119 def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
1121 self.lp = sambaopts.get_loadparm()
1122 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1124 self.url = dc_url(self.lp, self.creds, H)
1126 # We need to know writable DC to setup SMB connection
1127 if H and H.startswith('ldap://'):
1131 dc_hostname = netcmd_finddc(self.lp, self.creds)
1132 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1136 msg = get_gpo_info(self.samdb, None)
1140 unc = m['gPCFileSysPath'][0]
1142 [dom_name, service, sharepath] = parse_unc(unc)
1144 raise CommandError("Invalid GPO path (%s)" % unc)
1148 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
1150 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname)
1152 fs_sd = conn.get_acl(sharepath, security.SECINFO_OWNER | security.SECINFO_GROUP | security.SECINFO_DACL, security.SEC_FLAG_MAXIMUM_ALLOWED)
1154 ds_sd_ndr = m['nTSecurityDescriptor'][0]
1155 ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
1157 # Create a file system security descriptor
1158 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
1159 expected_fs_sddl = dsacl2fsacl(ds_sd, domain_sid)
1161 if (fs_sd.as_sddl(domain_sid) != expected_fs_sddl):
1162 raise CommandError("Invalid GPO ACL %s on path (%s), should be %s" % (fs_sd.as_sddl(domain_sid), sharepath, expected_fs_sddl))
1165 class cmd_gpo(SuperCommand):
1166 """Group Policy Object (GPO) management."""
1169 subcommands["listall"] = cmd_listall()
1170 subcommands["list"] = cmd_list()
1171 subcommands["show"] = cmd_show()
1172 subcommands["getlink"] = cmd_getlink()
1173 subcommands["setlink"] = cmd_setlink()
1174 subcommands["dellink"] = cmd_dellink()
1175 subcommands["listcontainers"] = cmd_listcontainers()
1176 subcommands["getinheritance"] = cmd_getinheritance()
1177 subcommands["setinheritance"] = cmd_setinheritance()
1178 subcommands["fetch"] = cmd_fetch()
1179 subcommands["create"] = cmd_create()
1180 subcommands["del"] = cmd_del()
1181 subcommands["aclcheck"] = cmd_aclcheck()