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/>.
21 from __future__ import print_function
23 import samba.getopt as options
26 import xml.etree.ElementTree as ET
30 from samba.auth import system_session
31 from samba.netcmd import (
37 from samba.samdb import SamDB
38 from samba import dsdb
39 from samba.dcerpc import security
40 from samba.ndr import ndr_unpack
43 from samba.auth import AUTH_SESSION_INFO_DEFAULT_GROUPS, AUTH_SESSION_INFO_AUTHENTICATED, AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
44 from samba.netcmd.common import netcmd_finddc
45 from samba import policy
47 from samba.samba3 import libsmb_samba_internal as libsmb
48 from samba import NTSTATUSError
50 from samba.ntacls import dsacl2fsacl
51 from samba.dcerpc import nbt
52 from samba.net import Net
53 from samba.gp_parse import GPParser, GPNoParserException, GPGeneralizeException
54 from samba.gp_parse.gp_pol import GPPolParser
55 from samba.gp_parse.gp_ini import (
61 from samba.gp_parse.gp_csv import GPAuditCsvParser
62 from samba.gp_parse.gp_inf import GptTmplInfParser
63 from samba.gp_parse.gp_aas import GPAasParser
66 def attr_default(msg, attrname, default):
67 '''get an attribute from a ldap msg with a default'''
69 return msg[attrname][0]
73 def gpo_flags_string(value):
74 '''return gpo flags string'''
75 flags = policy.get_gpo_flags(value)
83 def gplink_options_string(value):
84 '''return gplink options string'''
85 options = policy.get_gplink_options(value)
89 ret = ' '.join(options)
93 def parse_gplink(gplink):
94 '''parse a gPLink into an array of dn and options'''
101 if len(d) != 2 or not d[0].startswith("[LDAP://"):
102 raise RuntimeError("Badly formed gPLink '%s'" % g)
103 ret.append({'dn': d[0][8:], 'options': int(d[1])})
107 def encode_gplink(gplist):
108 '''Encode an array of dn and options into gPLink string'''
111 ret += "[LDAP://%s;%d]" % (g['dn'], g['options'])
115 def dc_url(lp, creds, url=None, dc=None):
116 '''If URL is not specified, return URL for writable DC.
117 If dc is provided, use that to construct ldap URL'''
122 dc = netcmd_finddc(lp, creds)
123 except Exception as e:
124 raise RuntimeError("Could not find a DC for domain", e)
129 def get_gpo_dn(samdb, gpo):
130 '''Construct the DN for gpo'''
132 dn = samdb.get_default_basedn()
133 dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
134 dn.add_child(ldb.Dn(samdb, "CN=%s" % gpo))
138 def get_gpo_info(samdb, gpo=None, displayname=None, dn=None,
139 sd_flags=(security.SECINFO_OWNER |
140 security.SECINFO_GROUP |
141 security.SECINFO_DACL |
142 security.SECINFO_SACL)):
143 '''Get GPO information using gpo, displayname or dn'''
145 policies_dn = samdb.get_default_basedn()
146 policies_dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
148 base_dn = policies_dn
149 search_expr = "(objectClass=groupPolicyContainer)"
150 search_scope = ldb.SCOPE_ONELEVEL
153 search_expr = "(&(objectClass=groupPolicyContainer)(name=%s))" % ldb.binary_encode(gpo)
155 if displayname is not None:
156 search_expr = "(&(objectClass=groupPolicyContainer)(displayname=%s))" % ldb.binary_encode(displayname)
160 search_scope = ldb.SCOPE_BASE
163 msg = samdb.search(base=base_dn, scope=search_scope,
164 expression=search_expr,
165 attrs=['nTSecurityDescriptor',
171 controls=['sd_flags:1:%d' % sd_flags])
172 except Exception as e:
174 mesg = "Cannot get information for GPO %s" % gpo
176 mesg = "Cannot get information for GPOs"
177 raise CommandError(mesg, e)
182 def get_gpo_containers(samdb, gpo):
183 '''lists dn of containers for a GPO'''
185 search_expr = "(&(objectClass=*)(gPLink=*%s*))" % gpo
187 msg = samdb.search(expression=search_expr, attrs=['gPLink'])
188 except Exception as e:
189 raise CommandError("Could not find container(s) with GPO %s" % gpo, e)
194 def del_gpo_link(samdb, container_dn, gpo):
195 '''delete GPO link for the container'''
196 # Check if valid Container DN and get existing GPlinks
198 msg = samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
199 expression="(objectClass=*)",
201 except Exception as e:
202 raise CommandError("Container '%s' does not exist" % container_dn, e)
205 gpo_dn = str(get_gpo_dn(samdb, gpo))
207 gplist = parse_gplink(str(msg['gPLink'][0]))
209 if g['dn'].lower() == gpo_dn.lower():
214 raise CommandError("No GPO(s) linked to this container")
217 raise CommandError("GPO '%s' not linked to this container" % gpo)
222 gplink_str = encode_gplink(gplist)
223 m['r0'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
225 m['d0'] = ldb.MessageElement(msg['gPLink'][0], ldb.FLAG_MOD_DELETE, 'gPLink')
228 except Exception as e:
229 raise CommandError("Error removing GPO from container", e)
233 '''Parse UNC string into a hostname, a service, and a filepath'''
234 if unc.startswith('\\\\') and unc.startswith('//'):
235 raise ValueError("UNC doesn't start with \\\\ or //")
236 tmp = unc[2:].split('/', 2)
239 tmp = unc[2:].split('\\', 2)
242 raise ValueError("Invalid UNC string: %s" % unc)
245 def find_parser(name, flags=re.IGNORECASE):
246 if re.match('fdeploy1\.ini$', name, flags=flags):
247 return GPFDeploy1IniParser()
248 if re.match('audit\.csv$', name, flags=flags):
249 return GPAuditCsvParser()
250 if re.match('GptTmpl\.inf$', name, flags=flags):
251 return GptTmplInfParser()
252 if re.match('GPT\.INI$', name, flags=flags):
253 return GPTIniParser()
254 if re.match('scripts.ini$', name, flags=flags):
255 return GPScriptsIniParser()
256 if re.match('psscripts.ini$', name, flags=flags):
257 return GPScriptsIniParser()
258 if re.match('.*\.ini$', name, flags=flags):
260 if re.match('.*\.pol$', name, flags=flags):
262 if re.match('.*\.aas$', name, flags=flags):
268 def backup_directory_remote_to_local(conn, remotedir, localdir):
269 SUFFIX = '.SAMBABACKUP'
270 if not os.path.isdir(localdir):
272 r_dirs = [ remotedir ]
273 l_dirs = [ localdir ]
278 dirlist = conn.list(r_dir, attribs=attr_flags)
279 dirlist.sort(key=lambda x : x['name'])
281 r_name = r_dir + '\\' + e['name']
282 l_name = os.path.join(l_dir, e['name'])
284 if e['attrib'] & libsmb.FILE_ATTRIBUTE_DIRECTORY:
285 r_dirs.append(r_name)
286 l_dirs.append(l_name)
289 data = conn.loadfile(r_name)
290 with open(l_name + SUFFIX, 'wb') as f:
293 parser = find_parser(e['name'])
295 parser.write_xml(l_name + '.xml')
298 attr_flags = libsmb.FILE_ATTRIBUTE_SYSTEM | \
299 libsmb.FILE_ATTRIBUTE_DIRECTORY | \
300 libsmb.FILE_ATTRIBUTE_ARCHIVE | \
301 libsmb.FILE_ATTRIBUTE_HIDDEN
304 def copy_directory_remote_to_local(conn, remotedir, localdir):
305 if not os.path.isdir(localdir):
313 dirlist = conn.list(r_dir, attribs=attr_flags)
314 dirlist.sort(key=lambda x : x['name'])
316 r_name = r_dir + '\\' + e['name']
317 l_name = os.path.join(l_dir, e['name'])
319 if e['attrib'] & libsmb.FILE_ATTRIBUTE_DIRECTORY:
320 r_dirs.append(r_name)
321 l_dirs.append(l_name)
324 data = conn.loadfile(r_name)
325 open(l_name, 'wb').write(data)
328 def copy_directory_local_to_remote(conn, localdir, remotedir,
329 ignore_existing=False):
330 if not conn.chkpath(remotedir):
331 conn.mkdir(remotedir)
338 dirlist = os.listdir(l_dir)
341 l_name = os.path.join(l_dir, e)
342 r_name = r_dir + '\\' + e
344 if os.path.isdir(l_name):
345 l_dirs.append(l_name)
346 r_dirs.append(r_name)
349 except NTSTATUSError:
350 if not ignore_existing:
353 data = open(l_name, 'rb').read()
354 conn.savefile(r_name, data)
357 def create_directory_hier(conn, remotedir):
358 elems = remotedir.replace('/', '\\').split('\\')
361 path = path + '\\' + e
362 if not conn.chkpath(path):
365 def smb_connection(dc_hostname, service, lp, creds, sign=False):
368 conn = smb.SMB(dc_hostname, service, lp=lp, creds=creds, sign=sign)
370 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname)
374 class GPOCommand(Command):
375 def construct_tmpdir(self, tmpdir, gpo):
376 """Ensure that the temporary directory structure used in fetch,
377 backup, create, and restore is consistent.
379 If --tmpdir is used the named directory must be present, which may
380 contain a 'policy' subdirectory, but 'policy' must not itself have
381 a subdirectory with the gpo name. The policy and gpo directories
384 If --tmpdir is not used, a temporary directory is securely created.
387 tmpdir = tempfile.mkdtemp()
388 print("Using temporary directory %s (use --tmpdir to change)" % tmpdir,
391 if not os.path.isdir(tmpdir):
392 raise CommandError("Temporary directory '%s' does not exist" % tmpdir)
394 localdir = os.path.join(tmpdir, "policy")
395 if not os.path.isdir(localdir):
398 gpodir = os.path.join(localdir, gpo)
399 if os.path.isdir(gpodir):
401 "GPO directory '%s' already exists, refusing to overwrite" % gpodir)
405 except (IOError, OSError) as e:
406 raise CommandError("Error creating teporary GPO directory", e)
408 return tmpdir, gpodir
410 def samdb_connect(self):
411 '''make a ldap connection to the server'''
413 self.samdb = SamDB(url=self.url,
414 session_info=system_session(),
415 credentials=self.creds, lp=self.lp)
416 except Exception as e:
417 raise CommandError("LDAP connection to %s failed " % self.url, e)
420 class cmd_listall(GPOCommand):
423 synopsis = "%prog [options]"
425 takes_optiongroups = {
426 "sambaopts": options.SambaOptions,
427 "versionopts": options.VersionOptions,
428 "credopts": options.CredentialsOptions,
432 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
433 metavar="URL", dest="H")
436 def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
438 self.lp = sambaopts.get_loadparm()
439 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
441 self.url = dc_url(self.lp, self.creds, H)
445 msg = get_gpo_info(self.samdb, None)
448 self.outf.write("GPO : %s\n" % m['name'][0])
449 self.outf.write("display name : %s\n" % m['displayName'][0])
450 self.outf.write("path : %s\n" % m['gPCFileSysPath'][0])
451 self.outf.write("dn : %s\n" % m.dn)
452 self.outf.write("version : %s\n" % attr_default(m, 'versionNumber', '0'))
453 self.outf.write("flags : %s\n" % gpo_flags_string(int(attr_default(m, 'flags', 0))))
454 self.outf.write("\n")
457 class cmd_list(GPOCommand):
458 """List GPOs for an account."""
460 synopsis = "%prog <username> [options]"
462 takes_args = ['username']
463 takes_optiongroups = {
464 "sambaopts": options.SambaOptions,
465 "versionopts": options.VersionOptions,
466 "credopts": options.CredentialsOptions,
470 Option("-H", "--URL", help="LDB URL for database or target server",
471 type=str, metavar="URL", dest="H")
474 def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None):
476 self.lp = sambaopts.get_loadparm()
477 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
479 self.url = dc_url(self.lp, self.creds, H)
484 msg = self.samdb.search(expression='(&(|(samAccountName=%s)(samAccountName=%s$))(objectClass=User))' %
485 (ldb.binary_encode(username), ldb.binary_encode(username)))
488 raise CommandError("Failed to find account %s" % username)
490 # check if its a computer account
492 msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
493 is_computer = 'computer' in msg['objectClass']
495 raise CommandError("Failed to find objectClass for user %s" % username)
497 session_info_flags = (AUTH_SESSION_INFO_DEFAULT_GROUPS |
498 AUTH_SESSION_INFO_AUTHENTICATED)
500 # When connecting to a remote server, don't look up the local privilege DB
501 if self.url is not None and self.url.startswith('ldap'):
502 session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
504 session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
505 session_info_flags=session_info_flags)
507 token = session.security_token
512 dn = ldb.Dn(self.samdb, str(user_dn)).parent()
514 msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
516 glist = parse_gplink(str(msg['gPLink'][0]))
518 if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
520 if g['options'] & dsdb.GPLINK_OPT_DISABLE:
524 sd_flags = (security.SECINFO_OWNER |
525 security.SECINFO_GROUP |
526 security.SECINFO_DACL)
527 gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
528 attrs=['name', 'displayName', 'flags',
529 'nTSecurityDescriptor'],
530 controls=['sd_flags:1:%d' % sd_flags])
531 secdesc_ndr = gmsg[0]['nTSecurityDescriptor'][0]
532 secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
534 self.outf.write("Failed to fetch gpo object with nTSecurityDescriptor %s\n" %
539 samba.security.access_check(secdesc, token,
540 security.SEC_STD_READ_CONTROL |
541 security.SEC_ADS_LIST |
542 security.SEC_ADS_READ_PROP)
544 self.outf.write("Failed access check on %s\n" % msg.dn)
547 # check the flags on the GPO
548 flags = int(attr_default(gmsg[0], 'flags', 0))
549 if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
551 if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
553 gpos.append((gmsg[0]['displayName'][0], gmsg[0]['name'][0]))
555 # check if this blocks inheritance
556 gpoptions = int(attr_default(msg, 'gPOptions', 0))
557 if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
560 if dn == self.samdb.get_default_basedn():
569 self.outf.write("GPOs for %s %s\n" % (msg_str, username))
571 self.outf.write(" %s %s\n" % (g[0], g[1]))
574 class cmd_show(GPOCommand):
575 """Show information for a GPO."""
577 synopsis = "%prog <gpo> [options]"
579 takes_optiongroups = {
580 "sambaopts": options.SambaOptions,
581 "versionopts": options.VersionOptions,
582 "credopts": options.CredentialsOptions,
588 Option("-H", help="LDB URL for database or target server", type=str)
591 def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
593 self.lp = sambaopts.get_loadparm()
594 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
596 self.url = dc_url(self.lp, self.creds, H)
601 msg = get_gpo_info(self.samdb, gpo)[0]
603 raise CommandError("GPO '%s' does not exist" % gpo)
606 secdesc_ndr = msg['nTSecurityDescriptor'][0]
607 secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
608 secdesc_sddl = secdesc.as_sddl()
610 secdesc_sddl = "<hidden>"
612 self.outf.write("GPO : %s\n" % msg['name'][0])
613 self.outf.write("display name : %s\n" % msg['displayName'][0])
614 self.outf.write("path : %s\n" % msg['gPCFileSysPath'][0])
615 self.outf.write("dn : %s\n" % msg.dn)
616 self.outf.write("version : %s\n" % attr_default(msg, 'versionNumber', '0'))
617 self.outf.write("flags : %s\n" % gpo_flags_string(int(attr_default(msg, 'flags', 0))))
618 self.outf.write("ACL : %s\n" % secdesc_sddl)
619 self.outf.write("\n")
622 class cmd_getlink(GPOCommand):
623 """List GPO Links for a container."""
625 synopsis = "%prog <container_dn> [options]"
627 takes_optiongroups = {
628 "sambaopts": options.SambaOptions,
629 "versionopts": options.VersionOptions,
630 "credopts": options.CredentialsOptions,
633 takes_args = ['container_dn']
636 Option("-H", help="LDB URL for database or target server", type=str)
639 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
642 self.lp = sambaopts.get_loadparm()
643 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
645 self.url = dc_url(self.lp, self.creds, H)
650 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
651 expression="(objectClass=*)",
654 raise CommandError("Container '%s' does not exist" % container_dn)
657 self.outf.write("GPO(s) linked to DN %s\n" % container_dn)
658 gplist = parse_gplink(str(msg['gPLink'][0]))
660 msg = get_gpo_info(self.samdb, dn=g['dn'])
661 self.outf.write(" GPO : %s\n" % msg[0]['name'][0])
662 self.outf.write(" Name : %s\n" % msg[0]['displayName'][0])
663 self.outf.write(" Options : %s\n" % gplink_options_string(g['options']))
664 self.outf.write("\n")
666 self.outf.write("No GPO(s) linked to DN=%s\n" % container_dn)
669 class cmd_setlink(GPOCommand):
670 """Add or update a GPO link to a container."""
672 synopsis = "%prog <container_dn> <gpo> [options]"
674 takes_optiongroups = {
675 "sambaopts": options.SambaOptions,
676 "versionopts": options.VersionOptions,
677 "credopts": options.CredentialsOptions,
680 takes_args = ['container_dn', 'gpo']
683 Option("-H", help="LDB URL for database or target server", type=str),
684 Option("--disable", dest="disabled", default=False, action='store_true',
685 help="Disable policy"),
686 Option("--enforce", dest="enforced", default=False, action='store_true',
687 help="Enforce policy")
690 def run(self, container_dn, gpo, H=None, disabled=False, enforced=False,
691 sambaopts=None, credopts=None, versionopts=None):
693 self.lp = sambaopts.get_loadparm()
694 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
696 self.url = dc_url(self.lp, self.creds, H)
702 gplink_options |= dsdb.GPLINK_OPT_DISABLE
704 gplink_options |= dsdb.GPLINK_OPT_ENFORCE
706 # Check if valid GPO DN
708 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
710 raise CommandError("GPO '%s' does not exist" % gpo)
711 gpo_dn = str(get_gpo_dn(self.samdb, gpo))
713 # Check if valid Container DN
715 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
716 expression="(objectClass=*)",
719 raise CommandError("Container '%s' does not exist" % container_dn)
721 # Update existing GPlinks or Add new one
722 existing_gplink = False
724 gplist = parse_gplink(str(msg['gPLink'][0]))
725 existing_gplink = True
728 if g['dn'].lower() == gpo_dn.lower():
729 g['options'] = gplink_options
733 raise CommandError("GPO '%s' already linked to this container" % gpo)
735 gplist.insert(0, {'dn': gpo_dn, 'options': gplink_options})
738 gplist.append({'dn': gpo_dn, 'options': gplink_options})
740 gplink_str = encode_gplink(gplist)
743 m.dn = ldb.Dn(self.samdb, container_dn)
746 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
748 m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_ADD, 'gPLink')
752 except Exception as e:
753 raise CommandError("Error adding GPO Link", e)
755 self.outf.write("Added/Updated GPO link\n")
756 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
759 class cmd_dellink(GPOCommand):
760 """Delete GPO link from a container."""
762 synopsis = "%prog <container_dn> <gpo> [options]"
764 takes_optiongroups = {
765 "sambaopts": options.SambaOptions,
766 "versionopts": options.VersionOptions,
767 "credopts": options.CredentialsOptions,
770 takes_args = ['container', 'gpo']
773 Option("-H", help="LDB URL for database or target server", type=str),
776 def run(self, container, gpo, H=None, sambaopts=None, credopts=None,
779 self.lp = sambaopts.get_loadparm()
780 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
782 self.url = dc_url(self.lp, self.creds, H)
788 get_gpo_info(self.samdb, gpo=gpo)[0]
790 raise CommandError("GPO '%s' does not exist" % gpo)
792 container_dn = ldb.Dn(self.samdb, container)
793 del_gpo_link(self.samdb, container_dn, gpo)
794 self.outf.write("Deleted GPO link.\n")
795 cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
798 class cmd_listcontainers(GPOCommand):
799 """List all linked containers for a GPO."""
801 synopsis = "%prog <gpo> [options]"
803 takes_optiongroups = {
804 "sambaopts": options.SambaOptions,
805 "versionopts": options.VersionOptions,
806 "credopts": options.CredentialsOptions,
812 Option("-H", help="LDB URL for database or target server", type=str)
815 def run(self, gpo, H=None, sambaopts=None, credopts=None,
818 self.lp = sambaopts.get_loadparm()
819 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
821 self.url = dc_url(self.lp, self.creds, H)
825 msg = get_gpo_containers(self.samdb, gpo)
827 self.outf.write("Container(s) using GPO %s\n" % gpo)
829 self.outf.write(" DN: %s\n" % m['dn'])
831 self.outf.write("No Containers using GPO %s\n" % gpo)
834 class cmd_getinheritance(GPOCommand):
835 """Get inheritance flag for a container."""
837 synopsis = "%prog <container_dn> [options]"
839 takes_optiongroups = {
840 "sambaopts": options.SambaOptions,
841 "versionopts": options.VersionOptions,
842 "credopts": options.CredentialsOptions,
845 takes_args = ['container_dn']
848 Option("-H", help="LDB URL for database or target server", type=str)
851 def run(self, container_dn, H=None, sambaopts=None, credopts=None,
854 self.lp = sambaopts.get_loadparm()
855 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
857 self.url = dc_url(self.lp, self.creds, H)
862 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
863 expression="(objectClass=*)",
864 attrs=['gPOptions'])[0]
866 raise CommandError("Container '%s' does not exist" % container_dn)
869 if 'gPOptions' in msg:
870 inheritance = int(msg['gPOptions'][0])
872 if inheritance == dsdb.GPO_BLOCK_INHERITANCE:
873 self.outf.write("Container has GPO_BLOCK_INHERITANCE\n")
875 self.outf.write("Container has GPO_INHERIT\n")
878 class cmd_setinheritance(GPOCommand):
879 """Set inheritance flag on a container."""
881 synopsis = "%prog <container_dn> <block|inherit> [options]"
883 takes_optiongroups = {
884 "sambaopts": options.SambaOptions,
885 "versionopts": options.VersionOptions,
886 "credopts": options.CredentialsOptions,
889 takes_args = ['container_dn', 'inherit_state']
892 Option("-H", help="LDB URL for database or target server", type=str)
895 def run(self, container_dn, inherit_state, H=None, sambaopts=None, credopts=None,
898 if inherit_state.lower() == 'block':
899 inheritance = dsdb.GPO_BLOCK_INHERITANCE
900 elif inherit_state.lower() == 'inherit':
901 inheritance = dsdb.GPO_INHERIT
903 raise CommandError("Unknown inheritance state (%s)" % inherit_state)
905 self.lp = sambaopts.get_loadparm()
906 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
908 self.url = dc_url(self.lp, self.creds, H)
912 msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
913 expression="(objectClass=*)",
914 attrs=['gPOptions'])[0]
916 raise CommandError("Container '%s' does not exist" % container_dn)
919 m.dn = ldb.Dn(self.samdb, container_dn)
921 if 'gPOptions' in msg:
922 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_REPLACE, 'gPOptions')
924 m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_ADD, 'gPOptions')
928 except Exception as e:
929 raise CommandError("Error setting inheritance state %s" % inherit_state, e)
932 class cmd_fetch(GPOCommand):
933 """Download a GPO."""
935 synopsis = "%prog <gpo> [options]"
937 takes_optiongroups = {
938 "sambaopts": options.SambaOptions,
939 "versionopts": options.VersionOptions,
940 "credopts": options.CredentialsOptions,
946 Option("-H", help="LDB URL for database or target server", type=str),
947 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
950 def run(self, gpo, H=None, tmpdir=None, sambaopts=None, credopts=None, versionopts=None):
952 self.lp = sambaopts.get_loadparm()
953 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
955 # We need to know writable DC to setup SMB connection
956 if H and H.startswith('ldap://'):
960 dc_hostname = netcmd_finddc(self.lp, self.creds)
961 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
965 msg = get_gpo_info(self.samdb, gpo)[0]
967 raise CommandError("GPO '%s' does not exist" % gpo)
970 unc = str(msg['gPCFileSysPath'][0])
972 [dom_name, service, sharepath] = parse_unc(unc)
974 raise CommandError("Invalid GPO path (%s)" % unc)
977 conn = smb_connection(dc_hostname, service, lp=self.lp,
978 creds=self.creds, sign=True)
981 tmpdir, gpodir = self.construct_tmpdir(tmpdir, gpo)
983 copy_directory_remote_to_local(conn, sharepath, gpodir)
984 except Exception as e:
985 # FIXME: Catch more specific exception
986 raise CommandError("Error copying GPO from DC", e)
987 self.outf.write('GPO copied to %s\n' % gpodir)
990 class cmd_backup(GPOCommand):
993 synopsis = "%prog <gpo> [options]"
995 takes_optiongroups = {
996 "sambaopts": options.SambaOptions,
997 "versionopts": options.VersionOptions,
998 "credopts": options.CredentialsOptions,
1001 takes_args = ['gpo']
1004 Option("-H", help="LDB URL for database or target server", type=str),
1005 Option("--tmpdir", help="Temporary directory for copying policy files", type=str),
1006 Option("--generalize", help="Generalize XML entities to restore",
1007 default=False, action='store_true'),
1008 Option("--entities", help="File to export defining XML entities for the restore",
1009 dest='ent_file', type=str)
1012 def run(self, gpo, H=None, tmpdir=None, generalize=False, sambaopts=None,
1013 credopts=None, versionopts=None, ent_file=None):
1015 self.lp = sambaopts.get_loadparm()
1016 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1018 # We need to know writable DC to setup SMB connection
1019 if H and H.startswith('ldap://'):
1023 dc_hostname = netcmd_finddc(self.lp, self.creds)
1024 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1026 self.samdb_connect()
1028 msg = get_gpo_info(self.samdb, gpo)[0]
1030 raise CommandError("GPO '%s' does not exist" % gpo)
1033 unc = str(msg['gPCFileSysPath'][0])
1035 [dom_name, service, sharepath] = parse_unc(unc)
1037 raise CommandError("Invalid GPO path (%s)" % unc)
1040 conn = smb_connection(dc_hostname, service, lp=self.lp,
1044 tmpdir, gpodir = self.construct_tmpdir(tmpdir, gpo)
1047 backup_directory_remote_to_local(conn, sharepath, gpodir)
1048 except Exception as e:
1049 # FIXME: Catch more specific exception
1050 raise CommandError("Error copying GPO from DC", e)
1052 self.outf.write('GPO copied to %s\n' % gpodir)
1055 self.outf.write('\nAttempting to generalize XML entities:\n')
1056 entities = cmd_backup.generalize_xml_entities(self.outf, gpodir,
1060 for ent in sorted(entities.items(), key=operator.itemgetter(1)):
1061 ents += '<!ENTITY {} "{}">\n'.format(ent[1].strip('&;'), ent[0])
1064 with open(ent_file, 'w') as f:
1066 self.outf.write('Entities successfully written to %s\n' %
1069 self.outf.write('\nEntities:\n')
1070 self.outf.write(ents)
1073 def generalize_xml_entities(outf, sourcedir, targetdir):
1076 if not os.path.exists(targetdir):
1079 l_dirs = [ sourcedir ]
1080 r_dirs = [ targetdir ]
1082 l_dir = l_dirs.pop()
1083 r_dir = r_dirs.pop()
1085 dirlist = os.listdir(l_dir)
1088 l_name = os.path.join(l_dir, e)
1089 r_name = os.path.join(r_dir, e)
1091 if os.path.isdir(l_name):
1092 l_dirs.append(l_name)
1093 r_dirs.append(r_name)
1094 if not os.path.exists(r_name):
1097 if l_name.endswith('.xml'):
1098 # Restore the xml file if possible
1100 # Get the filename to find the parser
1101 to_parse = os.path.basename(l_name)[:-4]
1103 parser = find_parser(to_parse)
1105 with open(l_name, 'r') as ltemp:
1108 concrete_xml = ET.fromstring(data)
1109 found_entities = parser.generalize_xml(concrete_xml, r_name, entities)
1110 except GPGeneralizeException:
1111 outf.write('SKIPPING: Generalizing failed for %s\n' % to_parse)
1114 # No need to generalize non-xml files.
1116 # TODO This could be improved with xml files stored in
1117 # the renamed backup file (with custom extension) by
1118 # inlining them into the exported backups.
1119 if not os.path.samefile(l_name, r_name):
1120 shutil.copy2(l_name, r_name)
1125 class cmd_create(GPOCommand):
1126 """Create an empty GPO."""
1128 synopsis = "%prog <displayname> [options]"
1130 takes_optiongroups = {
1131 "sambaopts": options.SambaOptions,
1132 "versionopts": options.VersionOptions,
1133 "credopts": options.CredentialsOptions,
1136 takes_args = ['displayname']
1139 Option("-H", help="LDB URL for database or target server", type=str),
1140 Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
1143 def run(self, displayname, H=None, tmpdir=None, sambaopts=None, credopts=None,
1146 self.lp = sambaopts.get_loadparm()
1147 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1149 net = Net(creds=self.creds, lp=self.lp)
1151 # We need to know writable DC to setup SMB connection
1152 if H and H.startswith('ldap://'):
1155 flags = (nbt.NBT_SERVER_LDAP |
1157 nbt.NBT_SERVER_WRITABLE)
1158 cldap_ret = net.finddc(address=dc_hostname, flags=flags)
1160 flags = (nbt.NBT_SERVER_LDAP |
1162 nbt.NBT_SERVER_WRITABLE)
1163 cldap_ret = net.finddc(domain=self.lp.get('realm'), flags=flags)
1164 dc_hostname = cldap_ret.pdc_dns_name
1165 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1167 self.samdb_connect()
1169 msg = get_gpo_info(self.samdb, displayname=displayname)
1171 raise CommandError("A GPO already existing with name '%s'" % displayname)
1174 guid = str(uuid.uuid4())
1175 gpo = "{%s}" % guid.upper()
1179 realm = cldap_ret.dns_domain
1180 unc_path = "\\\\%s\\sysvol\\%s\\Policies\\%s" % (realm, realm, gpo)
1183 self.tmpdir, gpodir = self.construct_tmpdir(tmpdir, gpo)
1184 self.gpodir = 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
1197 conn = smb_connection(dc_hostname, service, lp=self.lp,
1202 self.samdb.transaction_start()
1205 gpo_dn = get_gpo_dn(self.samdb, gpo)
1209 m['a01'] = ldb.MessageElement("groupPolicyContainer", ldb.FLAG_MOD_ADD, "objectClass")
1212 # Add cn=User,cn=<guid>
1214 m.dn = ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn))
1215 m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
1218 # Add cn=Machine,cn=<guid>
1220 m.dn = ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn))
1221 m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
1224 # Get new security descriptor
1225 ds_sd_flags = (security.SECINFO_OWNER |
1226 security.SECINFO_GROUP |
1227 security.SECINFO_DACL)
1228 msg = get_gpo_info(self.samdb, gpo=gpo, sd_flags=ds_sd_flags)[0]
1229 ds_sd_ndr = msg['nTSecurityDescriptor'][0]
1230 ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
1232 # Create a file system security descriptor
1233 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
1234 sddl = dsacl2fsacl(ds_sd, domain_sid)
1235 fs_sd = security.descriptor.from_sddl(sddl, domain_sid)
1237 # Copy GPO directory
1238 create_directory_hier(conn, sharepath)
1241 sio = (security.SECINFO_OWNER |
1242 security.SECINFO_GROUP |
1243 security.SECINFO_DACL |
1244 security.SECINFO_PROTECTED_DACL)
1245 conn.set_acl(sharepath, fs_sd, sio)
1247 # Copy GPO files over SMB
1248 copy_directory_local_to_remote(conn, gpodir, sharepath)
1252 m['a02'] = ldb.MessageElement(displayname, ldb.FLAG_MOD_REPLACE, "displayName")
1253 m['a03'] = ldb.MessageElement(unc_path, ldb.FLAG_MOD_REPLACE, "gPCFileSysPath")
1254 m['a05'] = ldb.MessageElement("0", ldb.FLAG_MOD_REPLACE, "versionNumber")
1255 m['a07'] = ldb.MessageElement("2", ldb.FLAG_MOD_REPLACE, "gpcFunctionalityVersion")
1256 m['a04'] = ldb.MessageElement("0", ldb.FLAG_MOD_REPLACE, "flags")
1257 controls = ["permissive_modify:0"]
1258 self.samdb.modify(m, controls=controls)
1260 self.samdb.transaction_cancel()
1263 self.samdb.transaction_commit()
1265 self.outf.write("GPO '%s' created as %s\n" % (displayname, gpo))
1268 class cmd_restore(cmd_create):
1269 """Restore a GPO to a new container."""
1271 synopsis = "%prog <displayname> <backup location> [options]"
1273 takes_optiongroups = {
1274 "sambaopts": options.SambaOptions,
1275 "versionopts": options.VersionOptions,
1276 "credopts": options.CredentialsOptions,
1279 takes_args = ['displayname', 'backup']
1282 Option("-H", help="LDB URL for database or target server", type=str),
1283 Option("--tmpdir", help="Temporary directory for copying policy files", type=str),
1284 Option("--entities", help="File defining XML entities to insert into DOCTYPE header", type=str)
1287 def restore_from_backup_to_local_dir(self, sourcedir, targetdir, dtd_header=''):
1288 SUFFIX = '.SAMBABACKUP'
1290 if not os.path.exists(targetdir):
1293 l_dirs = [ sourcedir ]
1294 r_dirs = [ targetdir ]
1296 l_dir = l_dirs.pop()
1297 r_dir = r_dirs.pop()
1299 dirlist = os.listdir(l_dir)
1302 l_name = os.path.join(l_dir, e)
1303 r_name = os.path.join(r_dir, e)
1305 if os.path.isdir(l_name):
1306 l_dirs.append(l_name)
1307 r_dirs.append(r_name)
1308 if not os.path.exists(r_name):
1311 if l_name.endswith('.xml'):
1312 # Restore the xml file if possible
1314 # Get the filename to find the parser
1315 to_parse = os.path.basename(l_name)[:-4]
1317 parser = find_parser(to_parse)
1319 with open(l_name, 'r') as ltemp:
1321 xml_head = '<?xml version="1.0" encoding="utf-8"?>'
1323 if data.startswith(xml_head):
1324 # It appears that sometimes the DTD rejects
1325 # the xml header being after it.
1326 data = data[len(xml_head):]
1328 # Load the XML file with the DTD (entity) header
1329 parser.load_xml(ET.fromstring(xml_head + dtd_header + data))
1331 parser.load_xml(ET.fromstring(dtd_header + data))
1333 # Write out the substituted files in the output
1334 # location, ready to copy over.
1335 parser.write_binary(r_name[:-4])
1337 except GPNoParserException:
1338 # In the failure case, we fallback
1339 original_file = l_name[:-4] + SUFFIX
1340 shutil.copy2(original_file, r_name[:-4])
1342 self.outf.write('WARNING: No such parser for %s\n' % to_parse)
1343 self.outf.write('WARNING: Falling back to simple copy-restore.\n')
1346 traceback.print_exc()
1348 # In the failure case, we fallback
1349 original_file = l_name[:-4] + SUFFIX
1350 shutil.copy2(original_file, r_name[:-4])
1352 self.outf.write('WARNING: Error during parsing for %s\n' % l_name)
1353 self.outf.write('WARNING: Falling back to simple copy-restore.\n')
1355 def run(self, displayname, backup, H=None, tmpdir=None, entities=None, sambaopts=None, credopts=None,
1360 if not os.path.exists(backup):
1361 raise CommandError("Backup directory does not exist %s" % backup)
1363 if entities is not None:
1364 # DOCTYPE name is meant to match root element, but ElementTree does
1365 # not seem to care, so this seems to be enough.
1367 dtd_header = '<!DOCTYPE foobar [\n'
1369 if not os.path.exists(entities):
1370 raise CommandError("Entities file does not exist %s" %
1372 with open(entities, 'r') as entities_file:
1373 entities_content = entities_file.read()
1375 # Do a basic regex test of the entities file format
1376 if re.match('(\s*<!ENTITY\s*[a-zA-Z0-9_]+\s*.*?>)+\s*\Z',
1377 entities_content, flags=re.MULTILINE) is None:
1378 raise CommandError("Entities file does not appear to "
1379 "conform to format\n"
1380 'e.g. <!ENTITY entity "value">')
1381 dtd_header += entities_content.strip()
1383 dtd_header += '\n]>\n'
1385 super(cmd_restore, self).run(displayname, H, tmpdir, sambaopts,
1386 credopts, versionopts)
1389 # Iterate over backup files and restore with DTD
1390 self.restore_from_backup_to_local_dir(backup, self.gpodir,
1393 # Copy GPO files over SMB
1394 copy_directory_local_to_remote(self.conn, self.gpodir,
1396 ignore_existing=True)
1398 except Exception as e:
1400 traceback.print_exc()
1401 self.outf.write(str(e) + '\n')
1403 self.outf.write("Failed to restore GPO -- deleting...\n")
1405 cmd.run(self.gpo_name, H, sambaopts, credopts, versionopts)
1407 raise CommandError("Failed to restore: %s" % e)
1410 class cmd_del(GPOCommand):
1413 synopsis = "%prog <gpo> [options]"
1415 takes_optiongroups = {
1416 "sambaopts": options.SambaOptions,
1417 "versionopts": options.VersionOptions,
1418 "credopts": options.CredentialsOptions,
1421 takes_args = ['gpo']
1424 Option("-H", help="LDB URL for database or target server", type=str),
1427 def run(self, gpo, H=None, sambaopts=None, credopts=None,
1430 self.lp = sambaopts.get_loadparm()
1431 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1433 # We need to know writable DC to setup SMB connection
1434 if H and H.startswith('ldap://'):
1438 dc_hostname = netcmd_finddc(self.lp, self.creds)
1439 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1441 self.samdb_connect()
1443 # Check if valid GPO
1445 msg = get_gpo_info(self.samdb, gpo=gpo)[0]
1446 unc_path = str(msg['gPCFileSysPath'][0])
1448 raise CommandError("GPO '%s' does not exist" % gpo)
1450 # Connect to DC over SMB
1451 [dom_name, service, sharepath] = parse_unc(unc_path)
1452 conn = smb_connection(dc_hostname, service, lp=self.lp,
1455 self.samdb.transaction_start()
1457 # Check for existing links
1458 msg = get_gpo_containers(self.samdb, gpo)
1461 self.outf.write("GPO %s is linked to containers\n" % gpo)
1463 del_gpo_link(self.samdb, m['dn'], gpo)
1464 self.outf.write(" Removed link from %s.\n" % m['dn'])
1466 # Remove LDAP entries
1467 gpo_dn = get_gpo_dn(self.samdb, gpo)
1468 self.samdb.delete(ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn)))
1469 self.samdb.delete(ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn)))
1470 self.samdb.delete(gpo_dn)
1473 conn.deltree(sharepath)
1476 self.samdb.transaction_cancel()
1479 self.samdb.transaction_commit()
1481 self.outf.write("GPO %s deleted.\n" % gpo)
1484 class cmd_aclcheck(GPOCommand):
1485 """Check all GPOs have matching LDAP and DS ACLs."""
1487 synopsis = "%prog [options]"
1489 takes_optiongroups = {
1490 "sambaopts": options.SambaOptions,
1491 "versionopts": options.VersionOptions,
1492 "credopts": options.CredentialsOptions,
1496 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
1497 metavar="URL", dest="H")
1500 def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
1502 self.lp = sambaopts.get_loadparm()
1503 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1505 self.url = dc_url(self.lp, self.creds, H)
1507 # We need to know writable DC to setup SMB connection
1508 if H and H.startswith('ldap://'):
1512 dc_hostname = netcmd_finddc(self.lp, self.creds)
1513 self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1515 self.samdb_connect()
1517 msg = get_gpo_info(self.samdb, None)
1521 unc = str(m['gPCFileSysPath'][0])
1523 [dom_name, service, sharepath] = parse_unc(unc)
1525 raise CommandError("Invalid GPO path (%s)" % unc)
1528 conn = smb_connection(dc_hostname, service, lp=self.lp,
1531 fs_sd = conn.get_acl(sharepath, security.SECINFO_OWNER | security.SECINFO_GROUP | security.SECINFO_DACL, security.SEC_FLAG_MAXIMUM_ALLOWED)
1533 ds_sd_ndr = m['nTSecurityDescriptor'][0]
1534 ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
1536 # Create a file system security descriptor
1537 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
1538 expected_fs_sddl = dsacl2fsacl(ds_sd, domain_sid)
1540 if (fs_sd.as_sddl(domain_sid) != expected_fs_sddl):
1541 raise CommandError("Invalid GPO ACL %s on path (%s), should be %s" % (fs_sd.as_sddl(domain_sid), sharepath, expected_fs_sddl))
1544 class cmd_gpo(SuperCommand):
1545 """Group Policy Object (GPO) management."""
1548 subcommands["listall"] = cmd_listall()
1549 subcommands["list"] = cmd_list()
1550 subcommands["show"] = cmd_show()
1551 subcommands["getlink"] = cmd_getlink()
1552 subcommands["setlink"] = cmd_setlink()
1553 subcommands["dellink"] = cmd_dellink()
1554 subcommands["listcontainers"] = cmd_listcontainers()
1555 subcommands["getinheritance"] = cmd_getinheritance()
1556 subcommands["setinheritance"] = cmd_setinheritance()
1557 subcommands["fetch"] = cmd_fetch()
1558 subcommands["create"] = cmd_create()
1559 subcommands["del"] = cmd_del()
1560 subcommands["aclcheck"] = cmd_aclcheck()
1561 subcommands["backup"] = cmd_backup()
1562 subcommands["restore"] = cmd_restore()