samba-tool: Added gpo fetch command implementation using python smb module.
[metze/samba/wip.git] / source4 / scripting / python / samba / netcmd / gpo.py
1 #!/usr/bin/env python
2 #
3 # implement samba_tool gpo commands
4 #
5 # Copyright Andrew Tridgell 2010
6 # Copyright Giampaolo Lauria 2011 <lauria2@yahoo.com>
7 # Copyright Amitay Isaacs 2011 <amitay@gmail.com>
8 #
9 # based on C implementation by Guenther Deschner and Wilco Baan Hofman
10 #
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 #
24
25 import os
26 import samba.getopt as options
27 import ldb
28
29 from samba.auth import system_session
30 from samba.netcmd import (
31     Command,
32     CommandError,
33     Option,
34     SuperCommand,
35     )
36 from samba.samdb import SamDB
37 from samba import drs_utils, nttime2string, dsdb, dcerpc
38 from samba.dcerpc import misc
39 from samba.ndr import ndr_unpack
40 import samba.security
41 import samba.auth
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 smb
45
46
47 def samdb_connect(ctx):
48     '''make a ldap connection to the server'''
49     try:
50         ctx.samdb = SamDB(url=ctx.url,
51                           session_info=system_session(),
52                           credentials=ctx.creds, lp=ctx.lp)
53     except Exception, e:
54         raise CommandError("LDAP connection to %s failed " % ctx.url, e)
55
56
57 def attr_default(msg, attrname, default):
58     '''get an attribute from a ldap msg with a default'''
59     if attrname in msg:
60         return msg[attrname][0]
61     return default
62
63
64 def flags_string(flags, value):
65     '''return a set of flags as a string'''
66     if value == 0:
67         return 'NONE'
68     ret = ''
69     for (str, val) in flags:
70         if val & value:
71             ret += str + ' '
72             value &= ~val
73     if value != 0:
74         ret += '0x%08x' % value
75     return ret.rstrip()
76
77
78 def parse_gplink(gplink):
79     '''parse a gPLink into an array of dn and options'''
80     ret = []
81     a = gplink.split(']')
82     for g in a:
83         if not g:
84             continue
85         d = g.split(';')
86         if len(d) != 2 or not d[0].startswith("[LDAP://"):
87             raise RuntimeError("Badly formed gPLink '%s'" % g)
88         ret.append({ 'dn' : d[0][8:], 'options' : int(d[1])})
89     return ret
90
91
92 def encode_gplink(gplist):
93     '''Encode an array of dn and options into gPLink string'''
94     ret = ''
95     for g in gplist:
96         ret += "[LDAP://%s;%d]" % (g['dn'], g['options'])
97     return ret
98
99
100 def dc_url(lp, creds, url=None, dc=None):
101     '''If URL is not specified, return URL for writable DC.
102     If dc is provided, use that to construct ldap URL'''
103
104     if url is None:
105         if dc is None:
106             try:
107                 dc = netcmd_finddc(lp, creds)
108             except Exception, e:
109                 raise RunTimeError("Could not find a DC for domain", e)
110         url = 'ldap://' + dc
111     return url
112
113
114 def get_gpo_dn(samdb, gpo):
115     '''Construct the DN for gpo'''
116
117     dn = samdb.get_default_basedn()
118     dn.add_child(ldb.Dn(samdb, "CN=Policies,DC=System"))
119     dn.add_child(ldb.Dn(samdb, "CN=%s" % gpo))
120     return dn
121
122
123 def get_gpo_info(samdb, gpo=None, displayname=None, dn=None):
124     '''Get GPO information using gpo, displayname or dn'''
125
126     policies_dn = samdb.get_default_basedn()
127     policies_dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
128
129     base_dn = policies_dn
130     search_expr = "(objectClass=groupPolicyContainer)"
131     search_scope = ldb.SCOPE_ONELEVEL
132
133     if gpo is not None:
134         search_expr = "(&(objectClass=groupPolicyContainer)(name=%s))" % gpo
135
136     if displayname is not None:
137         search_expr = "(&(objectClass=groupPolicyContainer)(displayname=%s))" % displayname
138
139     if dn is not None:
140         base_dn = dn
141         search_scope = ldb.SCOPE_BASE
142
143     try:
144         msg = samdb.search(base=base_dn, scope=search_scope,
145                             expression=search_expr,
146                             attrs=['nTSecurityDescriptor',
147                                     'versionNumber',
148                                     'flags',
149                                     'name',
150                                     'displayName',
151                                     'gPCFileSysPath'])
152     except Exception, e:
153         if gpo is not None:
154             mesg = "Cannot get information for GPO %s" % gpo
155         else:
156             mesg = "Cannot get information for GPOs"
157         raise CommandError(mesg, e)
158
159     return msg
160
161
162 def parse_unc(unc):
163     '''Parse UNC string into a hostname, a service, and a filepath'''
164     if unc.startswith('\\\\') and unc.startswith('//'):
165         return []
166     tmp = unc[2:].split('/', 2)
167     if len(tmp) == 3:
168         return tmp
169     tmp = unc[2:].split('\\', 2)
170     if len(tmp) == 3:
171         return tmp;
172     return []
173
174
175 def copy_directory_recurse(conn, remotedir, localdir):
176     if not os.path.isdir(localdir):
177         os.mkdir(localdir)
178     r_dirs = [ remotedir ]
179     l_dirs = [ localdir ]
180     while r_dirs:
181         r_dir = r_dirs.pop()
182         l_dir = l_dirs.pop()
183
184         dirlist = conn.list(r_dir)
185         for e in dirlist:
186             r_name = r_dir + '\\' + e['name']
187             l_name = l_dir + os.path.sep + e['name']
188
189             if e['attrib'] & smb.FILE_ATTRIBUTE_DIRECTORY:
190                 r_dirs.append(r_name)
191                 l_dirs.append(l_name)
192                 os.mkdir(l_name)
193             elif e['attrib'] & smb.FILE_ATTRIBUTE_ARCHIVE:
194                 data = conn.loadfile(r_name)
195                 file(l_name, 'w').write(data)
196
197
198 class cmd_listall(Command):
199     """list all GPOs"""
200
201     synopsis = "%prog gpo listall [options]"
202
203     takes_options = [
204         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
205                metavar="URL", dest="H")
206         ]
207
208     def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
209
210         self.lp = sambaopts.get_loadparm()
211         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
212
213         self.url = dc_url(self.lp, self.creds, H)
214
215         samdb_connect(self)
216
217         gpo_flags = [
218             ("GPO_FLAG_USER_DISABLE", dsdb.GPO_FLAG_USER_DISABLE ),
219             ( "GPO_FLAG_MACHINE_DISABLE", dsdb.GPO_FLAG_MACHINE_DISABLE ) ]
220
221         msg = get_gpo_info(self.samdb, None)
222
223         for m in msg:
224             print("GPO          : %s" % m['name'][0])
225             print("display name : %s" % m['displayName'][0])
226             print("path         : %s" % m['gPCFileSysPath'][0])
227             print("dn           : %s" % m.dn)
228             print("version      : %s" % attr_default(m, 'versionNumber', '0'))
229             print("flags        : %s" % flags_string(gpo_flags, int(attr_default(m, 'flags', 0))))
230             print("")
231
232
233 class cmd_list(Command):
234     """list GPOs for an account"""
235
236     synopsis = "%prog gpo list <username> [options]"
237
238     takes_args = [ 'username' ]
239
240     takes_options = [
241         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
242                metavar="URL", dest="H")
243         ]
244
245     def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None):
246
247         self.lp = sambaopts.get_loadparm()
248         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
249
250         self.url = dc_url(self.lp, self.creds, H)
251
252         samdb_connect(self)
253
254         try:
255             msg = self.samdb.search(expression='(&(|(samAccountName=%s)(samAccountName=%s$))(objectClass=User))' %
256                                                 (username,username))
257             user_dn = msg[0].dn
258         except Exception, e:
259             raise CommandError("Failed to find account %s" % username, e)
260
261         # check if its a computer account
262         try:
263             msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
264             is_computer = 'computer' in msg['objectClass']
265         except Exception, e:
266             raise CommandError("Failed to find objectClass for user %s" % username, e)
267
268         session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS |
269                                AUTH_SESSION_INFO_AUTHENTICATED )
270
271         # When connecting to a remote server, don't look up the local privilege DB
272         if self.url is not None and self.url.startswith('ldap'):
273             session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
274
275         session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
276                                           session_info_flags=session_info_flags)
277
278         token = session.security_token
279
280         gpos = []
281
282         inherit = True
283         dn = ldb.Dn(self.samdb, str(user_dn)).parent()
284         while True:
285             msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
286             if 'gPLink' in msg:
287                 glist = parse_gplink(msg['gPLink'][0])
288                 for g in glist:
289                     if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
290                         continue
291                     if g['options'] & dsdb.GPLINK_OPT_DISABLE:
292                         continue
293
294                     try:
295                         gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
296                                                  attrs=['name', 'displayName', 'flags',
297                                                         'ntSecurityDescriptor'])
298                     except Exception:
299                         print("Failed to fetch gpo object %s" % g['dn'])
300                         continue
301
302                     secdesc_ndr = gmsg[0]['ntSecurityDescriptor'][0]
303                     secdesc = ndr_unpack(dcerpc.security.descriptor, secdesc_ndr)
304
305                     try:
306                         samba.security.access_check(secdesc, token,
307                                                     dcerpc.security.SEC_STD_READ_CONTROL |
308                                                     dcerpc.security.SEC_ADS_LIST |
309                                                     dcerpc.security.SEC_ADS_READ_PROP)
310                     except RuntimeError:
311                         print("Failed access check on %s" % msg.dn)
312                         continue
313
314                     # check the flags on the GPO
315                     flags = int(attr_default(gmsg[0], 'flags', 0))
316                     if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
317                         continue
318                     if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
319                         continue
320                     gpos.append((gmsg[0]['displayName'][0], gmsg[0]['name'][0]))
321
322             # check if this blocks inheritance
323             gpoptions = int(attr_default(msg, 'gPOptions', 0))
324             if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
325                 inherit = False
326
327             if dn == self.samdb.get_default_basedn():
328                 break
329             dn = dn.parent()
330
331         if is_computer:
332             msg_str = 'computer'
333         else:
334             msg_str = 'user'
335
336         print("GPOs for %s %s" % (msg_str, username))
337         for g in gpos:
338             print("    %s %s" % (g[0], g[1]))
339
340
341 class cmd_show(Command):
342     """Show information for a GPO"""
343
344     synopsis = "%prog gpo show <gpo> [options]"
345
346     takes_optiongroups = {
347         "sambaopts": options.SambaOptions,
348         "versionopts": options.VersionOptions,
349         "credopts": options.CredentialsOptions,
350     }
351
352     takes_args = [ 'gpo' ]
353
354     takes_options = [
355         Option("-H", help="LDB URL for database or target server", type=str)
356         ]
357
358     def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
359
360         self.lp = sambaopts.get_loadparm()
361         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
362
363         self.url = dc_url(self.lp, self.creds, H)
364
365         samdb_connect(self)
366
367         gpo_flags = [
368             ("GPO_FLAG_USER_DISABLE", dsdb.GPO_FLAG_USER_DISABLE ),
369             ( "GPO_FLAG_MACHINE_DISABLE", dsdb.GPO_FLAG_MACHINE_DISABLE ) ]
370
371         try:
372             msg = get_gpo_info(self.samdb, gpo)[0]
373         except Exception, e:
374             raise CommandError("GPO %s does not exist" % gpo, e)
375
376         secdesc_ndr = msg['ntSecurityDescriptor'][0]
377         secdesc = ndr_unpack(dcerpc.security.descriptor, secdesc_ndr)
378
379         print("GPO          : %s" % msg['name'][0])
380         print("display name : %s" % msg['displayName'][0])
381         print("path         : %s" % msg['gPCFileSysPath'][0])
382         print("dn           : %s" % msg.dn)
383         print("version      : %s" % attr_default(msg, 'versionNumber', '0'))
384         print("flags        : %s" % flags_string(gpo_flags, int(attr_default(msg, 'flags', 0))))
385         print("ACL          : %s" % secdesc.as_sddl())
386         print("")
387
388
389 class cmd_getlink(Command):
390     """List GPO Links for a container"""
391
392     synopsis = "%prog gpo getlink <container_dn> [options]"
393
394     takes_optiongroups = {
395         "sambaopts": options.SambaOptions,
396         "versionopts": options.VersionOptions,
397         "credopts": options.CredentialsOptions,
398     }
399
400     takes_args = [ 'container_dn' ]
401
402     takes_options = [
403         Option("-H", help="LDB URL for database or target server", type=str)
404         ]
405
406     def run(self, container_dn, H=None, sambaopts=None, credopts=None,
407                 versionopts=None):
408
409         self.lp = sambaopts.get_loadparm()
410         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
411
412         self.url = dc_url(self.lp, self.creds, H)
413
414         samdb_connect(self)
415
416         gplink_options = [
417                 ("GPLINK_OPT_DISABLE", dsdb.GPLINK_OPT_DISABLE),
418                 ("GPLINK_OPT_ENFORCE", dsdb.GPLINK_OPT_ENFORCE),
419             ]
420
421         try:
422             msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
423                                     expression="(objectClass=*)",
424                                     attrs=['gPlink'])[0]
425         except Exception, e:
426             raise CommandError("Could not find Container DN %s (%s)" % container_dn, e)
427
428         if 'gPLink' in msg:
429             print("GPO(s) linked to DN %s" % container_dn)
430             gplist = parse_gplink(msg['gPLink'][0])
431             for g in gplist:
432                 msg = get_gpo_info(self.samdb, dn=g['dn'])
433                 print("    GPO     : %s" % msg[0]['name'][0])
434                 print("    Name    : %s" % msg[0]['displayName'][0])
435                 print("    Options : %s" % flags_string(gplink_options, g['options']))
436                 print("")
437         else:
438             print("No GPO(s) linked to DN=%s" % container_dn)
439
440
441 class cmd_setlink(Command):
442     """Add or Update a GPO link to a container"""
443
444     synopsis = "%prog gpo setlink <container_dn> <gpo> [options]"
445
446     takes_optiongroups = {
447         "sambaopts": options.SambaOptions,
448         "versionopts": options.VersionOptions,
449         "credopts": options.CredentialsOptions,
450     }
451
452     takes_args = [ 'container_dn', 'gpo' ]
453
454     takes_options = [
455         Option("-H", help="LDB URL for database or target server", type=str),
456         Option("--disable", dest="disabled", default=False, action='store_true',
457             help="Disable policy"),
458         Option("--enforce", dest="enforced", default=False, action='store_true',
459             help="Enforce policy")
460         ]
461
462     def run(self, container_dn, gpo, H=None, disabled=False, enforced=False,
463                 sambaopts=None, credopts=None, versionopts=None):
464
465         self.lp = sambaopts.get_loadparm()
466         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
467
468         self.url = dc_url(self.lp, self.creds, H)
469
470         samdb_connect(self)
471
472         gplink_options = 0
473         if disabled:
474             gplink_options |= dsdb.GPLINK_OPT_DISABLE
475         if enforced:
476             gplink_options |= dsdb.GPLINK_OPT_ENFORCE
477
478         # Check if valid GPO DN
479         try:
480             msg = get_gpo_info(self.samdb, gpo=gpo)[0]
481         except Exception, e:
482             raise CommandError("GPO %s does not exist" % gpo_dn, e)
483         gpo_dn = get_gpo_dn(self.samdb, gpo)
484
485         # Check if valid Container DN
486         try:
487             msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
488                                     expression="(objectClass=*)",
489                                     attrs=['gPlink'])[0]
490         except Exception, e:
491             raise CommandError("Could not find container DN %s" % container_dn, e)
492
493         # Update existing GPlinks or Add new one
494         existing_gplink = False
495         if 'gPLink' in msg:
496             gplist = parse_gplink(msg['gPLink'][0])
497             existing_gplink = True
498             found = False
499             for g in gplist:
500                 if g['dn'].lower() == gpo_dn.lower():
501                     g['options'] = gplink_options
502                     found = True
503                     break
504             if not found:
505                 gplist.insert(0, { 'dn' : gpo_dn, 'options' : gplink_options })
506         else:
507             gplist = []
508             gplist.append({ 'dn' : gpo_dn, 'options' : gplink_options })
509
510         gplink_str = encode_gplink(gplist)
511
512         m = ldb.Message()
513         m.dn = ldb.Dn(self.samdb, container_dn)
514
515         if existing_gplink:
516             m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
517         else:
518             m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_ADD, 'gPLink')
519
520         try:
521             self.samdb.modify(m)
522         except Exception, e:
523             raise CommandError("Error adding GPO Link", e)
524
525         print("Added/Updated GPO link")
526         cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
527
528
529 class cmd_dellink(Command):
530     """Delete GPO link from a container"""
531
532     synopsis = "%prog gpo dellink <container_dn> <gpo> [options]"
533
534     takes_optiongroups = {
535         "sambaopts": options.SambaOptions,
536         "versionopts": options.VersionOptions,
537         "credopts": options.CredentialsOptions,
538     }
539
540     takes_args = [ 'container_dn', 'gpo' ]
541
542     takes_options = [
543         Option("-H", help="LDB URL for database or target server", type=str),
544         ]
545
546     def run(self, container_dn, gpo_dn, H=None, sambaopts=None, credopts=None,
547                 versionopts=None):
548
549         self.lp = sambaopts.get_loadparm()
550         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
551
552         self.url = dc_url(self.lp, self.creds, H)
553
554         samdb_connect(self)
555
556         # Check if valid GPO
557         try:
558             msg = get_gpo_info(self.sambdb, gpo=gpo)[0]
559         except Exception, e:
560                 raise CommandError("GPO %s does not exist" % gpo, e)
561         gpo_dn = get_gpo_dn(self.samdb, gpo)
562
563         # Check if valid Container DN and get existing GPlinks
564         try:
565             msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
566                                     expression="(objectClass=*)",
567                                     attrs=['gPlink'])[0]
568         except Exception, e:
569             raise CommandError("Could not find container DN %s" % dn, e)
570
571         if 'gPLink' in msg:
572             gplist = parse_gplink(msg['gPLink'][0])
573             for g in gplist:
574                 if g['dn'].lower() == gpo_dn.lower():
575                     gplist.remove(g)
576                     break
577         else:
578             raise CommandError("Specified GPO is not linked to this container");
579
580         m = ldb.Message()
581         m.dn = ldb.Dn(self.samdb, container_dn)
582
583         if gplist:
584             gplink_str = encode_gplink(gplist)
585             m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
586         else:
587             m['new_value'] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, 'gPLink')
588
589         try:
590             self.samdb.modify(m)
591         except Exception, e:
592             raise CommandError("Error Removing GPO Link (%s)" % e)
593
594         print("Deleted GPO link.")
595         cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
596
597
598 class cmd_getinheritance(Command):
599     """Get inheritance flag for a container"""
600
601     synopsis = "%prog gpo getinheritance <container_dn> [options]"
602
603     takes_optiongroups = {
604         "sambaopts": options.SambaOptions,
605         "versionopts": options.VersionOptions,
606         "credopts": options.CredentialsOptions,
607     }
608
609     takes_args = [ 'container_dn' ]
610
611     takes_options = [
612         Option("-H", help="LDB URL for database or target server", type=str)
613         ]
614
615     def run(self, container_dn, H=None, sambaopts=None, credopts=None,
616                 versionopts=None):
617
618         self.url = H
619         self.lp = sambaopts.get_loadparm()
620
621         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
622
623         samdb_connect(self)
624
625         try:
626             msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
627                                     expression="(objectClass=*)",
628                                     attrs=['gPOptions'])[0]
629         except Exception, e:
630             raise CommandError("Could not find Container DN %s" % container_dn, e)
631
632         inheritance = 0
633         if 'gPOptions' in msg:
634             inheritance = int(msg['gPOptions'][0]);
635
636         if inheritance == dsdb.GPO_BLOCK_INHERITANCE:
637             print("Container has GPO_BLOCK_INHERITANCE")
638         else:
639             print("Container has GPO_INHERIT")
640
641
642 class cmd_setinheritance(Command):
643     """Set inheritance flag on a container"""
644
645     synopsis = "%prog gpo setinheritance <container_dn> <block|inherit> [options]"
646
647     takes_optiongroups = {
648         "sambaopts": options.SambaOptions,
649         "versionopts": options.VersionOptions,
650         "credopts": options.CredentialsOptions,
651     }
652
653     takes_args = [ 'container_dn', 'inherit_state' ]
654
655     takes_options = [
656         Option("-H", help="LDB URL for database or target server", type=str)
657         ]
658
659     def run(self, container_dn, inherit_state, H=None, sambaopts=None, credopts=None,
660                 versionopts=None):
661
662         if inherit_state.lower() == 'block':
663             inheritance = dsdb.GPO_BLOCK_INHERITANCE
664         elif inherit_state.lower() == 'inherit':
665             inheritance = dsdb.GPO_INHERIT
666         else:
667             raise CommandError("Unknown inheritance state (%s)" % inherit_state)
668
669         self.url = H
670         self.lp = sambaopts.get_loadparm()
671
672         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
673
674         samdb_connect(self)
675
676         try:
677             msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
678                                     expression="(objectClass=*)",
679                                     attrs=['gPOptions'])[0]
680         except Exception, e:
681             raise CommandError("Could not find Container DN %s" % container_dn, e)
682
683         m = ldb.Message()
684         m.dn = ldb.Dn(self.samdb, container_dn)
685
686         if 'gPOptions' in msg:
687             m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_REPLACE, 'gPOptions')
688         else:
689             m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_ADD, 'gPOptions');
690
691         try:
692             self.samdb.modify(m)
693         except Exception, e:
694             raise CommandError("Error setting inheritance state %s" % inherit_state, e)
695
696
697 class cmd_fetch(Command):
698     """Download a GPO"""
699
700     synopsis = "%prog gpo fetch <gpo> [options]"
701
702     takes_optiongroups = {
703         "sambaopts": options.SambaOptions,
704         "versionopts": options.VersionOptions,
705         "credopts": options.CredentialsOptions,
706     }
707
708     takes_args = [ 'gpo' ]
709
710     takes_options = [
711         Option("-H", help="LDB URL for database or target server", type=str),
712         Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
713         ]
714
715     def run(self, gpo, H=None, tmpdir=None, sambaopts=None, credopts=None, versionopts=None):
716
717         self.lp = sambaopts.get_loadparm()
718         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
719
720         dc_hostname = netcmd_finddc(self.lp, self.creds)
721         self.url = dc_url(self.lp, self.creds, H, dc=dc_hostname)
722
723         samdb_connect(self)
724         try:
725             msg = get_gpo_info(self.samdb, gpo)[0]
726         except Exception, e:
727             raise CommandError("GPO %s does not exist" % gpo)
728
729         unc = msg['gPCFileSysPath'][0]
730         try:
731             [dom_name, service, sharepath] = parse_unc(unc)
732         except:
733             raise CommandError("Invalid GPO path (%s)" % unc)
734
735         try:
736             conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
737         except Exception, e:
738             raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
739
740         if tmpdir is None:
741             tmpdir = "/tmp"
742
743         try:
744             localdir = tmpdir + os.path.sep + "policy"
745             if not os.path.isdir(localdir):
746                 os.mkdir(localdir)
747             gpodir = localdir + os.path.sep + gpo
748             if not os.path.isdir(gpodir):
749                 os.mkdir(gpodir)
750             copy_directory_recurse(conn, sharepath, gpodir)
751         except Exception, e:
752             raise CommandError("Error copying GPO", e)
753         print('GPO copied to %s' % gpodir)
754
755
756 class cmd_create(Command):
757     """Create a GPO"""
758
759 class cmd_setacl(Command):
760     """Set ACL on a GPO"""
761
762
763 class cmd_gpo(SuperCommand):
764     """Group Policy Object (GPO) commands"""
765
766     subcommands = {}
767     subcommands["listall"] = cmd_listall()
768     subcommands["list"] = cmd_list()
769     subcommands["show"] = cmd_show()
770     subcommands["getlink"] = cmd_getlink()
771     subcommands["setlink"] = cmd_setlink()
772     subcommands["dellink"] = cmd_dellink()
773     subcommands["getinheritance"] = cmd_getinheritance()
774     subcommands["setinheritance"] = cmd_setinheritance()
775     subcommands["fetch"] = cmd_fetch()
776     subcommands["create"] = cmd_create()
777     subcommands["setacl"] = cmd_setacl()