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 import xml.etree.ElementTree as ET
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
46 from samba import NTSTATUSError
48 from samba.ntacls import dsacl2fsacl
49 from samba.dcerpc import nbt
50 from samba.net import Net
51 from samba.gp_parse import GPParser, GPNoParserException, GPGeneralizeException
52 from samba.gp_parse.gp_pol import GPPolParser
53 from samba.gp_parse.gp_ini import (
59 from samba.gp_parse.gp_csv import GPAuditCsvParser
60 from samba.gp_parse.gp_inf import GptTmplInfParser
61 from samba.gp_parse.gp_aas import GPAasParser
64 def samdb_connect(ctx):
65 '''make a ldap connection to the server'''
67 ctx.samdb = SamDB(url=ctx.url,
68 session_info=system_session(),
69 credentials=ctx.creds, lp=ctx.lp)
70 except Exception as e:
71 raise CommandError("LDAP connection to %s failed " % ctx.url, e)
74 def attr_default(msg, attrname, default):
75 '''get an attribute from a ldap msg with a default'''
77 return msg[attrname][0]
81 def gpo_flags_string(value):
82 '''return gpo flags string'''
83 flags = policy.get_gpo_flags(value)
91 def gplink_options_string(value):
92 '''return gplink options string'''
93 options = policy.get_gplink_options(value)
97 ret = ' '.join(options)
101 def parse_gplink(gplink):
102 '''parse a gPLink into an array of dn and options'''
104 a = gplink.split(']')
109 if len(d) != 2 or not d[0].startswith("[LDAP://"):
110 raise RuntimeError("Badly formed gPLink '%s'" % g)
111 ret.append({'dn': d[0][8:], 'options': int(d[1])})
115 def encode_gplink(gplist):
116 '''Encode an array of dn and options into gPLink string'''
119 ret += "[LDAP://%s;%d]" % (g['dn'], g['options'])
123 def dc_url(lp, creds, url=None, dc=None):
124 '''If URL is not specified, return URL for writable DC.
125 If dc is provided, use that to construct ldap URL'''
130 dc = netcmd_finddc(lp, creds)
131 except Exception as e:
132 raise RuntimeError("Could not find a DC for domain", e)
137 def get_gpo_dn(samdb, gpo):
138 '''Construct the DN for gpo'''
140 dn = samdb.get_default_basedn()
141 dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
142 dn.add_child(ldb.Dn(samdb, "CN=%s" % gpo))
146 def get_gpo_info(samdb, gpo=None, displayname=None, dn=None,
147 sd_flags=(security.SECINFO_OWNER |
148 security.SECINFO_GROUP |
149 security.SECINFO_DACL |
150 security.SECINFO_SACL)):
151 '''Get GPO information using gpo, displayname or dn'''
153 policies_dn = samdb.get_default_basedn()
154 policies_dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
156 base_dn = policies_dn
157 search_expr = "(objectClass=groupPolicyContainer)"
158 search_scope = ldb.SCOPE_ONELEVEL
161 search_expr = "(&(objectClass=groupPolicyContainer)(name=%s))" % ldb.binary_encode(gpo)
163 if displayname is not None:
164 search_expr = "(&(objectClass=groupPolicyContainer)(displayname=%s))" % ldb.binary_encode(displayname)
168 search_scope = ldb.SCOPE_BASE
171 msg = samdb.search(base=base_dn, scope=search_scope,
172 expression=search_expr,
173 attrs=['nTSecurityDescriptor',
179 controls=['sd_flags:1:%d' % sd_flags])
180 except Exception as e:
182 mesg = "Cannot get information for GPO %s" % gpo
184 mesg = "Cannot get information for GPOs"
185 raise CommandError(mesg, e)
190 def get_gpo_containers(samdb, gpo):
191 '''lists dn of containers for a GPO'''
193 search_expr = "(&(objectClass=*)(gPLink=*%s*))" % gpo
195 msg = samdb.search(expression=search_expr, attrs=['gPLink'])
196 except Exception as e:
197 raise CommandError("Could not find container(s) with GPO %s" % gpo, e)
202 def del_gpo_link(samdb, container_dn, gpo):
203 '''delete GPO link for the container'''
204 # Check if valid Container DN and get existing GPlinks
206 msg = samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
207 expression="(objectClass=*)",
209 except Exception as e:
210 raise CommandError("Container '%s' does not exist" % container_dn, e)
213 gpo_dn = str(get_gpo_dn(samdb, gpo))
215 gplist = parse_gplink(msg['gPLink'][0])
217 if g['dn'].lower() == gpo_dn.lower():
222 raise CommandError("No GPO(s) linked to this container")
225 raise CommandError("GPO '%s' not linked to this container" % gpo)
230 gplink_str = encode_gplink(gplist)
231 m['r0'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
233 m['d0'] = ldb.MessageElement(msg['gPLink'][0], ldb.FLAG_MOD_DELETE, 'gPLink')
236 except Exception as e:
237 raise CommandError("Error removing GPO from container", e)
241 '''Parse UNC string into a hostname, a service, and a filepath'''
242 if unc.startswith('\\\\') and unc.startswith('//'):
243 raise ValueError("UNC doesn't start with \\\\ or //")
244 tmp = unc[2:].split('/', 2)
247 tmp = unc[2:].split('\\', 2)
250 raise ValueError("Invalid UNC string: %s" % unc)
253 def find_parser(name, flags=re.IGNORECASE):
254 if re.match('fdeploy1\.ini$', name, flags=flags):
255 return GPFDeploy1IniParser()
256 if re.match('audit\.csv$', name, flags=flags):
257 return GPAuditCsvParser()
258 if re.match('GptTmpl\.inf$', name, flags=flags):
259 return GptTmplInfParser()
260 if re.match('GPT\.INI$', name, flags=flags):
261 return GPTIniParser()
262 if re.match('scripts.ini$', name, flags=flags):
263 return GPScriptsIniParser()
264 if re.match('psscripts.ini$', name, flags=flags):
265 return GPScriptsIniParser()
266 if re.match('.*\.ini$', name, flags=flags):
268 if re.match('.*\.pol$', name, flags=flags):
270 if re.match('.*\.aas$', name, flags=flags):
276 def backup_directory_remote_to_local(conn, remotedir, localdir):
277 SUFFIX = '.SAMBABACKUP'
278 if not os.path.isdir(localdir):
280 r_dirs = [ remotedir ]
281 l_dirs = [ localdir ]
286 dirlist = conn.list(r_dir, attribs=attr_flags)
289 r_name = r_dir + '\\' + e['name']
290 l_name = os.path.join(l_dir, e['name'])
292 if e['attrib'] & smb.FILE_ATTRIBUTE_DIRECTORY:
293 r_dirs.append(r_name)
294 l_dirs.append(l_name)
297 data = conn.loadfile(r_name)
298 with file(l_name + SUFFIX, 'w') as f:
301 parser = find_parser(e['name'])
303 parser.write_xml(l_name + '.xml')
306 attr_flags = smb.FILE_ATTRIBUTE_SYSTEM | \
307 smb.FILE_ATTRIBUTE_DIRECTORY | \
308 smb.FILE_ATTRIBUTE_ARCHIVE | \
309 smb.FILE_ATTRIBUTE_HIDDEN
312 def copy_directory_remote_to_local(conn, remotedir, localdir):
313 if not os.path.isdir(localdir):
321 dirlist = conn.list(r_dir, attribs=attr_flags)
324 r_name = r_dir + '\\' + e['name']
325 l_name = os.path.join(l_dir, e['name'])
327 if e['attrib'] & smb.FILE_ATTRIBUTE_DIRECTORY:
328 r_dirs.append(r_name)
329 l_dirs.append(l_name)
332 data = conn.loadfile(r_name)
333 open(l_name, 'w').write(data)
336 def copy_directory_local_to_remote(conn, localdir, remotedir,
337 ignore_existing=False):
338 if not conn.chkpath(remotedir):
339 conn.mkdir(remotedir)
346 dirlist = os.listdir(l_dir)
349 l_name = os.path.join(l_dir, e)
350 r_name = r_dir + '\\' + e
352 if os.path.isdir(l_name):
353 l_dirs.append(l_name)
354 r_dirs.append(r_name)
357 except NTSTATUSError:
358 if not ignore_existing:
361 data = open(l_name, 'r').read()
362 conn.savefile(r_name, data)
365 def create_directory_hier(conn, remotedir):
366 elems = remotedir.replace('/', '\\').split('\\')
369 path = path + '\\' + e
370 if not conn.chkpath(path):
374 class cmd_listall(Command):
377 synopsis = "%prog [options]"
379 takes_optiongroups = {
380 "sambaopts": options.SambaOptions,
381 "versionopts": options.VersionOptions,
382 "credopts": options.CredentialsOptions,
386 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
387 metavar="URL", dest="H")
390 def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
392 self.lp = sambaopts.get_loadparm()
393 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
395 self.url = dc_url(self.lp, self.creds, H)
399 msg = get_gpo_info(self.samdb, None)
402 self.outf.write("GPO : %s\n" % m['name'][0])
403 self.outf.write("display name : %s\n" % m['displayName'][0])
404 self.outf.write("path : %s\n" % m['gPCFileSysPath'][0])
405 self.outf.write("dn : %s\n" % m.dn)
406 self.outf.write("version : %s\n" % attr_default(m, 'versionNumber', '0'))
407 self.outf.write("flags : %s\n" % gpo_flags_string(int(attr_default(m, 'flags', 0))))
408 self.outf.write("\n")
411 class cmd_list(Command):
412 """List GPOs for an account."""
414 synopsis = "%prog <username> [options]"
416 takes_args = ['username']
417 takes_optiongroups = {
418 "sambaopts": options.SambaOptions,
419 "versionopts": options.VersionOptions,
420 "credopts": options.CredentialsOptions,
424 Option("-H", "--URL", help="LDB URL for database or target server",
425 type=str, metavar="URL", dest="H")
428 def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None):
430 self.lp = sambaopts.get_loadparm()
431 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
433 self.url = dc_url(self.lp, self.creds, H)
438 msg = self.samdb.search(expression='(&(|(samAccountName=%s)(samAccountName=%s$))(objectClass=User))' %
439 (ldb.binary_encode(username), ldb.binary_encode(username)))
442 raise CommandError("Failed to find account %s" % username)
444 # check if its a computer account
446 msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
447 is_computer = 'computer' in msg['objectClass']
449 raise CommandError("Failed to find objectClass for user %s" % username)
451 session_info_flags = (AUTH_SESSION_INFO_DEFAULT_GROUPS |
452 AUTH_SESSION_INFO_AUTHENTICATED)
454 # When connecting to a remote server, don't look up the local privilege DB
455 if self.url is not None and self.url.startswith('ldap'):
456 session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
458 session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
459 session_info_flags=session_info_flags)
461 token = session.security_token
466 dn = ldb.Dn(self.samdb, str(user_dn)).parent()
468 msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
470 glist = parse_gplink(msg['gPLink'][0])
472 if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
474 if g['options'] & dsdb.GPLINK_OPT_DISABLE:
478 sd_flags = (security.SECINFO_OWNER |
479 security.SECINFO_GROUP |
480 security.SECINFO_DACL)
481 gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
482 attrs=['name', 'displayName', 'flags',
483 'nTSecurityDescriptor'],
484 controls=['sd_flags:1:%d' % sd_flags])
485 secdesc_ndr = gmsg[0]['nTSecurityDescriptor'][0]
486 secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
488 self.outf.write("Failed to fetch gpo object with nTSecurityDescriptor %s\n" %
493 samba.security.access_check(secdesc, token,
494 security.SEC_STD_READ_CONTROL |
495 security.SEC_ADS_LIST |
496 security.SEC_ADS_READ_PROP)
498 self.outf.write("Failed access check on %s\n" % msg.dn)
501 # check the flags on the GPO
502 flags = int(attr_default(gmsg[0], 'flags', 0))
503 if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
505 if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
507 gpos.append((gmsg[0]['displayName'][0], gmsg[0]['name'][0]))
509 # check if this blocks inheritance
510 gpoptions = int(attr_default(msg, 'gPOptions', 0))
511 if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
514 if dn == self.samdb.get_default_basedn():
523 self.outf.write("GPOs for %s %s\n" % (msg_str, username))
525 self.outf.write(" %s %s\n" % (g[0], g[1]))
528 class cmd_show(Command):
529 """Show information for a GPO."""
531 synopsis = "%prog <gpo> [options]"
533 takes_optiongroups = {
534 "sambaopts": options.SambaOptions,
535 "versionopts": options.VersionOptions,
536 "credopts": options.CredentialsOptions,
542 Option("-H", help="LDB URL for database or target server", type=str)
545 def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
547 self.lp = sambaopts.get_loadparm()
548 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
550 self.url = dc_url(self.lp, self.creds, H)
555 msg = get_gpo_info(self.samdb, gpo)[0]
557 raise CommandError("GPO '%s' does not exist" % gpo)
560 secdesc_ndr = msg['nTSecurityDescriptor'][0]
561 secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
562 secdesc_sddl = secdesc.as_sddl()
564 secdesc_sddl = "<hidden>"
566 self.outf.write("GPO : %s\n" % msg['name'][0])
567 self.outf.write("display name : %s\n" % msg['displayName'][0])
568 self.outf.write("path : %s\n" % msg['gPCFileSysPath'][0])
569 self.outf.write("dn : %s\n" % msg.dn)
570 self.outf.write("version : %s\n" % attr_default(msg, 'versionNumber', '0'))
571 self.outf.write("flags : %s\n" % gpo_flags_string(int(attr_default(msg, 'flags', 0))))
572 self.outf.write("ACL : %s\n" % secdesc_sddl)
573 self.outf.write("\n")
576 class cmd_getlink(Command):
577 """List GPO Links for a container."""
579 synopsis = "%prog <container_dn> [options]"
581 takes_optiongroups = {
582 "sambaopts": options.SambaOptions,
583 "versionopts": options.VersionOptions,
584 "credopts": options.CredentialsOptions,
587 takes_args = ['container_dn']
590 Option("-H", help="LDB URL for database or target server", type=str)
593 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
596 self.lp = sambaopts.get_loadparm()
597 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
599 self.url = dc_url(self.lp, self.creds, H)
604 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
605 expression="(objectClass=*)",
608 raise CommandError("Container '%s' does not exist" % container_dn)
611 self.outf.write("GPO(s) linked to DN %s\n" % container_dn)
612 gplist = parse_gplink(msg['gPLink'][0])
614 msg = get_gpo_info(self.samdb, dn=g['dn'])
615 self.outf.write(" GPO : %s\n" % msg[0]['name'][0])
616 self.outf.write(" Name : %s\n" % msg[0]['displayName'][0])
617 self.outf.write(" Options : %s\n" % gplink_options_string(g['options']))
618 self.outf.write("\n")
620 self.outf.write("No GPO(s) linked to DN=%s\n" % container_dn)
623 class cmd_setlink(Command):
624 """Add or update a GPO link to a container."""
626 synopsis = "%prog <container_dn> <gpo> [options]"
628 takes_optiongroups = {
629 "sambaopts": options.SambaOptions,
630 "versionopts": options.VersionOptions,
631 "credopts": options.CredentialsOptions,
634 takes_args = ['container_dn', 'gpo']
637 Option("-H", help="LDB URL for database or target server", type=str),
638 Option("--disable", dest="disabled", default=False, action='store_true',
639 help="Disable policy"),
640 Option("--enforce", dest="enforced", default=False, action='store_true',
641 help="Enforce policy")
644 def run(self, container_dn, gpo, H=None, disabled=False, enforced=False,
645 sambaopts=None, credopts=None, versionopts=None):
647 self.lp = sambaopts.get_loadparm()
648 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
650 self.url = dc_url(self.lp, self.creds, H)
656 gplink_options |= dsdb.GPLINK_OPT_DISABLE
658 gplink_options |= dsdb.GPLINK_OPT_ENFORCE
660 # Check if valid GPO DN
662 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
664 raise CommandError("GPO '%s' does not exist" % gpo)
665 gpo_dn = str(get_gpo_dn(self.samdb, gpo))
667 # Check if valid Container DN
669 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
670 expression="(objectClass=*)",
673 raise CommandError("Container '%s' does not exist" % container_dn)
675 # Update existing GPlinks or Add new one
676 existing_gplink = False
678 gplist = parse_gplink(msg['gPLink'][0])
679 existing_gplink = True
682 if g['dn'].lower() == gpo_dn.lower():
683 g['options'] = gplink_options
687 raise CommandError("GPO '%s' already linked to this container" % gpo)
689 gplist.insert(0, {'dn': gpo_dn, 'options': gplink_options})
692 gplist.append({'dn': gpo_dn, 'options': gplink_options})
694 gplink_str = encode_gplink(gplist)
697 m.dn = ldb.Dn(self.samdb, container_dn)
700 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
702 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_ADD, 'gPLink')
706 except Exception as e:
707 raise CommandError("Error adding GPO Link", e)
709 self.outf.write("Added/Updated GPO link\n")
710 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
713 class cmd_dellink(Command):
714 """Delete GPO link from a container."""
716 synopsis = "%prog <container_dn> <gpo> [options]"
718 takes_optiongroups = {
719 "sambaopts": options.SambaOptions,
720 "versionopts": options.VersionOptions,
721 "credopts": options.CredentialsOptions,
724 takes_args = ['container', 'gpo']
727 Option("-H", help="LDB URL for database or target server", type=str),
730 def run(self, container, gpo, H=None, sambaopts=None, credopts=None,
733 self.lp = sambaopts.get_loadparm()
734 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
736 self.url = dc_url(self.lp, self.creds, H)
742 get_gpo_info(self.samdb, gpo=gpo)[0]
744 raise CommandError("GPO '%s' does not exist" % gpo)
746 container_dn = ldb.Dn(self.samdb, container)
747 del_gpo_link(self.samdb, container_dn, gpo)
748 self.outf.write("Deleted GPO link.\n")
749 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
752 class cmd_listcontainers(Command):
753 """List all linked containers for a GPO."""
755 synopsis = "%prog <gpo> [options]"
757 takes_optiongroups = {
758 "sambaopts": options.SambaOptions,
759 "versionopts": options.VersionOptions,
760 "credopts": options.CredentialsOptions,
766 Option("-H", help="LDB URL for database or target server", type=str)
769 def run(self, gpo, H=None, sambaopts=None, credopts=None,
772 self.lp = sambaopts.get_loadparm()
773 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
775 self.url = dc_url(self.lp, self.creds, H)
779 msg = get_gpo_containers(self.samdb, gpo)
781 self.outf.write("Container(s) using GPO %s\n" % gpo)
783 self.outf.write(" DN: %s\n" % m['dn'])
785 self.outf.write("No Containers using GPO %s\n" % gpo)
788 class cmd_getinheritance(Command):
789 """Get inheritance flag for a container."""
791 synopsis = "%prog <container_dn> [options]"
793 takes_optiongroups = {
794 "sambaopts": options.SambaOptions,
795 "versionopts": options.VersionOptions,
796 "credopts": options.CredentialsOptions,
799 takes_args = ['container_dn']
802 Option("-H", help="LDB URL for database or target server", type=str)
805 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
808 self.lp = sambaopts.get_loadparm()
809 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
811 self.url = dc_url(self.lp, self.creds, H)
816 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
817 expression="(objectClass=*)",
818 attrs=['gPOptions'])[0]
820 raise CommandError("Container '%s' does not exist" % container_dn)
823 if 'gPOptions' in msg:
824 inheritance = int(msg['gPOptions'][0])
826 if inheritance == dsdb.GPO_BLOCK_INHERITANCE:
827 self.outf.write("Container has GPO_BLOCK_INHERITANCE\n")
829 self.outf.write("Container has GPO_INHERIT\n")
832 class cmd_setinheritance(Command):
833 """Set inheritance flag on a container."""
835 synopsis = "%prog <container_dn> <block|inherit> [options]"
837 takes_optiongroups = {
838 "sambaopts": options.SambaOptions,
839 "versionopts": options.VersionOptions,
840 "credopts": options.CredentialsOptions,
843 takes_args = ['container_dn', 'inherit_state']
846 Option("-H", help="LDB URL for database or target server", type=str)
849 def run(self, container_dn, inherit_state, H=None, sambaopts=None, credopts=None,
852 if inherit_state.lower() == 'block':
853 inheritance = dsdb.GPO_BLOCK_INHERITANCE
854 elif inherit_state.lower() == 'inherit':
855 inheritance = dsdb.GPO_INHERIT
857 raise CommandError("Unknown inheritance state (%s)" % inherit_state)
859 self.lp = sambaopts.get_loadparm()
860 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
862 self.url = dc_url(self.lp, self.creds, H)
866 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
867 expression="(objectClass=*)",
868 attrs=['gPOptions'])[0]
870 raise CommandError("Container '%s' does not exist" % container_dn)
873 m.dn = ldb.Dn(self.samdb, container_dn)
875 if 'gPOptions' in msg:
876 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_REPLACE, 'gPOptions')
878 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_ADD, 'gPOptions')
882 except Exception as e:
883 raise CommandError("Error setting inheritance state %s" % inherit_state, e)
886 class cmd_fetch(Command):
887 """Download a GPO."""
889 synopsis = "%prog <gpo> [options]"
891 takes_optiongroups = {
892 "sambaopts": options.SambaOptions,
893 "versionopts": options.VersionOptions,
894 "credopts": options.CredentialsOptions,
900 Option("-H", help="LDB URL for database or target server", type=str),
901 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
904 def run(self, gpo, H=None, tmpdir=None, sambaopts=None, credopts=None, versionopts=None):
906 self.lp = sambaopts.get_loadparm()
907 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
909 # We need to know writable DC to setup SMB connection
910 if H and H.startswith('ldap://'):
914 dc_hostname = netcmd_finddc(self.lp, self.creds)
915 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
919 msg = get_gpo_info(self.samdb, gpo)[0]
921 raise CommandError("GPO '%s' does not exist" % gpo)
924 unc = msg['gPCFileSysPath'][0]
926 [dom_name, service, sharepath] = parse_unc(unc)
928 raise CommandError("Invalid GPO path (%s)" % unc)
932 conn = smb.SMB(dc_hostname,
938 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname)
943 if not os.path.isdir(tmpdir):
944 raise CommandError("Temoprary directory '%s' does not exist" % tmpdir)
946 localdir = os.path.join(tmpdir, "policy")
947 if not os.path.isdir(localdir):
950 gpodir = os.path.join(localdir, gpo)
951 if os.path.isdir(gpodir):
952 raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
956 copy_directory_remote_to_local(conn, sharepath, gpodir)
957 except Exception as e:
958 # FIXME: Catch more specific exception
959 raise CommandError("Error copying GPO from DC", e)
960 self.outf.write('GPO copied to %s\n' % gpodir)
963 class cmd_backup(Command):
966 synopsis = "%prog <gpo> [options]"
968 takes_optiongroups = {
969 "sambaopts": options.SambaOptions,
970 "versionopts": options.VersionOptions,
971 "credopts": options.CredentialsOptions,
977 Option("-H", help="LDB URL for database or target server", type=str),
978 Option("--tmpdir", help="Temporary directory for copying policy files", type=str),
979 Option("--generalize", help="Generalize XML entities to restore",
980 default=False, action='store_true'),
981 Option("--entities", help="File to export defining XML entities for the restore",
982 dest='ent_file', type=str)
985 def run(self, gpo, H=None, tmpdir=None, generalize=False, sambaopts=None,
986 credopts=None, versionopts=None, ent_file=None):
988 self.lp = sambaopts.get_loadparm()
989 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
991 # We need to know writable DC to setup SMB connection
992 if H and H.startswith('ldap://'):
996 dc_hostname = netcmd_finddc(self.lp, self.creds)
997 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1001 msg = get_gpo_info(self.samdb, gpo)[0]
1003 raise CommandError("GPO '%s' does not exist" % gpo)
1006 unc = msg['gPCFileSysPath'][0]
1008 [dom_name, service, sharepath] = parse_unc(unc)
1010 raise CommandError("Invalid GPO path (%s)" % unc)
1014 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
1016 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname)
1021 if not os.path.isdir(tmpdir):
1022 raise CommandError("Temoprary directory '%s' does not exist" % tmpdir)
1024 localdir = os.path.join(tmpdir, "policy")
1025 if not os.path.isdir(localdir):
1028 gpodir = os.path.join(localdir, gpo)
1029 if os.path.isdir(gpodir):
1030 raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
1034 backup_directory_remote_to_local(conn, sharepath, gpodir)
1035 except Exception as e:
1036 # FIXME: Catch more specific exception
1037 raise CommandError("Error copying GPO from DC", e)
1039 self.outf.write('GPO copied to %s\n' % gpodir)
1042 self.outf.write('\nAttempting to generalize XML entities:\n')
1043 entities = cmd_backup.generalize_xml_entities(self.outf, gpodir,
1047 for ent in sorted(entities.items(), key=operator.itemgetter(1)):
1048 ents += '<!ENTITY {} "{}">\n'.format(ent[1].strip('&;'), ent[0])
1051 with open(ent_file, 'w') as f:
1053 self.outf.write('Entities successfully written to %s\n' %
1056 self.outf.write('\nEntities:\n')
1057 self.outf.write(ents)
1060 def generalize_xml_entities(outf, sourcedir, targetdir):
1063 if not os.path.exists(targetdir):
1066 l_dirs = [ sourcedir ]
1067 r_dirs = [ targetdir ]
1069 l_dir = l_dirs.pop()
1070 r_dir = r_dirs.pop()
1072 dirlist = os.listdir(l_dir)
1075 l_name = os.path.join(l_dir, e)
1076 r_name = os.path.join(r_dir, e)
1078 if os.path.isdir(l_name):
1079 l_dirs.append(l_name)
1080 r_dirs.append(r_name)
1081 if not os.path.exists(r_name):
1084 if l_name.endswith('.xml'):
1085 # Restore the xml file if possible
1087 # Get the filename to find the parser
1088 to_parse = os.path.basename(l_name)[:-4]
1090 parser = find_parser(to_parse)
1092 with open(l_name, 'r') as ltemp:
1095 concrete_xml = ET.fromstring(data)
1096 found_entities = parser.generalize_xml(concrete_xml, r_name, entities)
1097 except GPGeneralizeException:
1098 outf.write('SKIPPING: Generalizing failed for %s\n' % to_parse)
1101 # No need to generalize non-xml files.
1103 # TODO This could be improved with xml files stored in
1104 # the renamed backup file (with custom extension) by
1105 # inlining them into the exported backups.
1106 if not os.path.samefile(l_name, r_name):
1107 shutil.copy2(l_name, r_name)
1112 class cmd_create(Command):
1113 """Create an empty GPO."""
1115 synopsis = "%prog <displayname> [options]"
1117 takes_optiongroups = {
1118 "sambaopts": options.SambaOptions,
1119 "versionopts": options.VersionOptions,
1120 "credopts": options.CredentialsOptions,
1123 takes_args = ['displayname']
1126 Option("-H", help="LDB URL for database or target server", type=str),
1127 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
1130 def run(self, displayname, H=None, tmpdir=None, sambaopts=None, credopts=None,
1133 self.lp = sambaopts.get_loadparm()
1134 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1136 net = Net(creds=self.creds, lp=self.lp)
1138 # We need to know writable DC to setup SMB connection
1139 if H and H.startswith('ldap://'):
1142 flags = (nbt.NBT_SERVER_LDAP |
1144 nbt.NBT_SERVER_WRITABLE)
1145 cldap_ret = net.finddc(address=dc_hostname, flags=flags)
1147 flags = (nbt.NBT_SERVER_LDAP |
1149 nbt.NBT_SERVER_WRITABLE)
1150 cldap_ret = net.finddc(domain=self.lp.get('realm'), flags=flags)
1151 dc_hostname = cldap_ret.pdc_dns_name
1152 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1156 msg = get_gpo_info(self.samdb, displayname=displayname)
1158 raise CommandError("A GPO already existing with name '%s'" % displayname)
1161 guid = str(uuid.uuid4())
1162 gpo = "{%s}" % guid.upper()
1166 realm = cldap_ret.dns_domain
1167 unc_path = "\\\\%s\\sysvol\\%s\\Policies\\%s" % (realm, realm, gpo)
1172 if not os.path.isdir(tmpdir):
1173 raise CommandError("Temporary directory '%s' does not exist" % tmpdir)
1174 self.tmpdir = tmpdir
1176 localdir = os.path.join(tmpdir, "policy")
1177 if not os.path.isdir(localdir):
1180 gpodir = os.path.join(localdir, gpo)
1181 self.gpodir = gpodir
1182 if os.path.isdir(gpodir):
1183 raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
1187 os.mkdir(os.path.join(gpodir, "Machine"))
1188 os.mkdir(os.path.join(gpodir, "User"))
1189 gpt_contents = "[General]\r\nVersion=0\r\n"
1190 open(os.path.join(gpodir, "GPT.INI"), "w").write(gpt_contents)
1191 except Exception as e:
1192 raise CommandError("Error Creating GPO files", e)
1194 # Connect to DC over SMB
1195 [dom_name, service, sharepath] = parse_unc(unc_path)
1196 self.sharepath = sharepath
1198 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
1199 except Exception as e:
1200 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
1204 self.samdb.transaction_start()
1207 gpo_dn = get_gpo_dn(self.samdb, gpo)
1211 m['a01'] = ldb.MessageElement("groupPolicyContainer", ldb.FLAG_MOD_ADD, "objectClass")
1214 # Add cn=User,cn=<guid>
1216 m.dn = ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn))
1217 m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
1220 # Add cn=Machine,cn=<guid>
1222 m.dn = ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn))
1223 m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
1226 # Get new security descriptor
1227 ds_sd_flags = (security.SECINFO_OWNER |
1228 security.SECINFO_GROUP |
1229 security.SECINFO_DACL)
1230 msg = get_gpo_info(self.samdb, gpo=gpo, sd_flags=ds_sd_flags)[0]
1231 ds_sd_ndr = msg['nTSecurityDescriptor'][0]
1232 ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
1234 # Create a file system security descriptor
1235 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
1236 sddl = dsacl2fsacl(ds_sd, domain_sid)
1237 fs_sd = security.descriptor.from_sddl(sddl, domain_sid)
1239 # Copy GPO directory
1240 create_directory_hier(conn, sharepath)
1243 sio = (security.SECINFO_OWNER |
1244 security.SECINFO_GROUP |
1245 security.SECINFO_DACL |
1246 security.SECINFO_PROTECTED_DACL)
1247 conn.set_acl(sharepath, fs_sd, sio)
1249 # Copy GPO files over SMB
1250 copy_directory_local_to_remote(conn, gpodir, sharepath)
1254 m['a02'] = ldb.MessageElement(displayname, ldb.FLAG_MOD_REPLACE, "displayName")
1255 m['a03'] = ldb.MessageElement(unc_path, ldb.FLAG_MOD_REPLACE, "gPCFileSysPath")
1256 m['a05'] = ldb.MessageElement("0", ldb.FLAG_MOD_REPLACE, "versionNumber")
1257 m['a07'] = ldb.MessageElement("2", ldb.FLAG_MOD_REPLACE, "gpcFunctionalityVersion")
1258 m['a04'] = ldb.MessageElement("0", ldb.FLAG_MOD_REPLACE, "flags")
1259 controls = ["permissive_modify:0"]
1260 self.samdb.modify(m, controls=controls)
1262 self.samdb.transaction_cancel()
1265 self.samdb.transaction_commit()
1267 self.outf.write("GPO '%s' created as %s\n" % (displayname, gpo))
1270 class cmd_restore(cmd_create):
1271 """Restore a GPO to a new container."""
1273 synopsis = "%prog <displayname> <backup location> [options]"
1275 takes_optiongroups = {
1276 "sambaopts": options.SambaOptions,
1277 "versionopts": options.VersionOptions,
1278 "credopts": options.CredentialsOptions,
1281 takes_args = ['displayname', 'backup']
1284 Option("-H", help="LDB URL for database or target server", type=str),
1285 Option("--tmpdir", help="Temporary directory for copying policy files", type=str),
1286 Option("--entities", help="File defining XML entities to insert into DOCTYPE header", type=str)
1289 def restore_from_backup_to_local_dir(self, sourcedir, targetdir, dtd_header=''):
1290 SUFFIX = '.SAMBABACKUP'
1292 if not os.path.exists(targetdir):
1295 l_dirs = [ sourcedir ]
1296 r_dirs = [ targetdir ]
1298 l_dir = l_dirs.pop()
1299 r_dir = r_dirs.pop()
1301 dirlist = os.listdir(l_dir)
1304 l_name = os.path.join(l_dir, e)
1305 r_name = os.path.join(r_dir, e)
1307 if os.path.isdir(l_name):
1308 l_dirs.append(l_name)
1309 r_dirs.append(r_name)
1310 if not os.path.exists(r_name):
1313 if l_name.endswith('.xml'):
1314 # Restore the xml file if possible
1316 # Get the filename to find the parser
1317 to_parse = os.path.basename(l_name)[:-4]
1319 parser = find_parser(to_parse)
1321 with open(l_name, 'r') as ltemp:
1323 xml_head = '<?xml version="1.0" encoding="utf-8"?>'
1325 if data.startswith(xml_head):
1326 # It appears that sometimes the DTD rejects
1327 # the xml header being after it.
1328 data = data[len(xml_head):]
1330 # Load the XML file with the DTD (entity) header
1331 parser.load_xml(ET.fromstring(xml_head + dtd_header + data))
1333 parser.load_xml(ET.fromstring(dtd_header + data))
1335 # Write out the substituted files in the output
1336 # location, ready to copy over.
1337 parser.write_binary(r_name[:-4])
1339 except GPNoParserException:
1340 # In the failure case, we fallback
1341 original_file = l_name[:-4] + SUFFIX
1342 shutil.copy2(original_file, r_name[:-4])
1344 self.outf.write('WARNING: No such parser for %s\n' % to_parse)
1345 self.outf.write('WARNING: Falling back to simple copy-restore.\n')
1348 traceback.print_exc()
1350 # In the failure case, we fallback
1351 original_file = l_name[:-4] + SUFFIX
1352 shutil.copy2(original_file, r_name[:-4])
1354 self.outf.write('WARNING: Error during parsing for %s\n' % l_name)
1355 self.outf.write('WARNING: Falling back to simple copy-restore.\n')
1357 def run(self, displayname, backup, H=None, tmpdir=None, entities=None, sambaopts=None, credopts=None,
1362 if not os.path.exists(backup):
1363 raise CommandError("Backup directory does not exist %s" % backup)
1365 if entities is not None:
1366 # DOCTYPE name is meant to match root element, but ElementTree does
1367 # not seem to care, so this seems to be enough.
1369 dtd_header = '<!DOCTYPE foobar [\n'
1371 if not os.path.exists(entities):
1372 raise CommandError("Entities file does not exist %s" %
1374 with open(entities, 'r') as entities_file:
1375 entities_content = entities_file.read()
1377 # Do a basic regex test of the entities file format
1378 if re.match('(\s*<!ENTITY\s*[a-zA-Z0-9_]+\s*.*?>)+\s*\Z',
1379 entities_content, flags=re.MULTILINE) is None:
1380 raise CommandError("Entities file does not appear to "
1381 "conform to format\n"
1382 'e.g. <!ENTITY entity "value">')
1383 dtd_header += entities_content.strip()
1385 dtd_header += '\n]>\n'
1387 super(cmd_restore, self).run(displayname, H, tmpdir, sambaopts,
1388 credopts, versionopts)
1391 # Iterate over backup files and restore with DTD
1392 self.restore_from_backup_to_local_dir(backup, self.gpodir,
1395 # Copy GPO files over SMB
1396 copy_directory_local_to_remote(self.conn, self.gpodir,
1398 ignore_existing=True)
1400 except Exception as e:
1402 traceback.print_exc()
1403 self.outf.write(str(e) + '\n')
1405 self.outf.write("Failed to restore GPO -- deleting...\n")
1407 cmd.run(self.gpo_name, H, sambaopts, credopts, versionopts)
1409 raise CommandError("Failed to restore: %s" % e)
1412 class cmd_del(Command):
1415 synopsis = "%prog <gpo> [options]"
1417 takes_optiongroups = {
1418 "sambaopts": options.SambaOptions,
1419 "versionopts": options.VersionOptions,
1420 "credopts": options.CredentialsOptions,
1423 takes_args = ['gpo']
1426 Option("-H", help="LDB URL for database or target server", type=str),
1429 def run(self, gpo, H=None, sambaopts=None, credopts=None,
1432 self.lp = sambaopts.get_loadparm()
1433 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1435 # We need to know writable DC to setup SMB connection
1436 if H and H.startswith('ldap://'):
1440 dc_hostname = netcmd_finddc(self.lp, self.creds)
1441 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1445 # Check if valid GPO
1447 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
1448 unc_path = msg['gPCFileSysPath'][0]
1450 raise CommandError("GPO '%s' does not exist" % gpo)
1452 # Connect to DC over SMB
1453 [dom_name, service, sharepath] = parse_unc(unc_path)
1455 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
1456 except Exception as e:
1457 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
1459 self.samdb.transaction_start()
1461 # Check for existing links
1462 msg = get_gpo_containers(self.samdb, gpo)
1465 self.outf.write("GPO %s is linked to containers\n" % gpo)
1467 del_gpo_link(self.samdb, m['dn'], gpo)
1468 self.outf.write(" Removed link from %s.\n" % m['dn'])
1470 # Remove LDAP entries
1471 gpo_dn = get_gpo_dn(self.samdb, gpo)
1472 self.samdb.delete(ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn)))
1473 self.samdb.delete(ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn)))
1474 self.samdb.delete(gpo_dn)
1477 conn.deltree(sharepath)
1480 self.samdb.transaction_cancel()
1483 self.samdb.transaction_commit()
1485 self.outf.write("GPO %s deleted.\n" % gpo)
1488 class cmd_aclcheck(Command):
1489 """Check all GPOs have matching LDAP and DS ACLs."""
1491 synopsis = "%prog [options]"
1493 takes_optiongroups = {
1494 "sambaopts": options.SambaOptions,
1495 "versionopts": options.VersionOptions,
1496 "credopts": options.CredentialsOptions,
1500 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
1501 metavar="URL", dest="H")
1504 def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
1506 self.lp = sambaopts.get_loadparm()
1507 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1509 self.url = dc_url(self.lp, self.creds, H)
1511 # We need to know writable DC to setup SMB connection
1512 if H and H.startswith('ldap://'):
1516 dc_hostname = netcmd_finddc(self.lp, self.creds)
1517 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1521 msg = get_gpo_info(self.samdb, None)
1525 unc = m['gPCFileSysPath'][0]
1527 [dom_name, service, sharepath] = parse_unc(unc)
1529 raise CommandError("Invalid GPO path (%s)" % unc)
1533 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
1535 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname)
1537 fs_sd = conn.get_acl(sharepath, security.SECINFO_OWNER | security.SECINFO_GROUP | security.SECINFO_DACL, security.SEC_FLAG_MAXIMUM_ALLOWED)
1539 ds_sd_ndr = m['nTSecurityDescriptor'][0]
1540 ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
1542 # Create a file system security descriptor
1543 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
1544 expected_fs_sddl = dsacl2fsacl(ds_sd, domain_sid)
1546 if (fs_sd.as_sddl(domain_sid) != expected_fs_sddl):
1547 raise CommandError("Invalid GPO ACL %s on path (%s), should be %s" % (fs_sd.as_sddl(domain_sid), sharepath, expected_fs_sddl))
1550 class cmd_gpo(SuperCommand):
1551 """Group Policy Object (GPO) management."""
1554 subcommands["listall"] = cmd_listall()
1555 subcommands["list"] = cmd_list()
1556 subcommands["show"] = cmd_show()
1557 subcommands["getlink"] = cmd_getlink()
1558 subcommands["setlink"] = cmd_setlink()
1559 subcommands["dellink"] = cmd_dellink()
1560 subcommands["listcontainers"] = cmd_listcontainers()
1561 subcommands["getinheritance"] = cmd_getinheritance()
1562 subcommands["setinheritance"] = cmd_setinheritance()
1563 subcommands["fetch"] = cmd_fetch()
1564 subcommands["create"] = cmd_create()
1565 subcommands["del"] = cmd_del()
1566 subcommands["aclcheck"] = cmd_aclcheck()
1567 subcommands["backup"] = cmd_backup()
1568 subcommands["restore"] = cmd_restore()