s4:netcmd/gpo.py: let get_gpo_info explicitly ask for the full ntSecurityDescriptor
[metze/samba/wip.git] / source4 / scripting / python / samba / netcmd / gpo.py
1 # implement samba_tool gpo commands
2 #
3 # Copyright Andrew Tridgell 2010
4 # Copyright Amitay Isaacs 2011-2012 <amitay@gmail.com>
5 #
6 # based on C implementation by Guenther Deschner and Wilco Baan Hofman
7 #
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.
12 #
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.
17 #
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/>.
20 #
21
22 import os
23 import samba.getopt as options
24 import ldb
25
26 from samba.auth import system_session
27 from samba.netcmd import (
28     Command,
29     CommandError,
30     Option,
31     SuperCommand,
32     )
33 from samba.samdb import SamDB
34 from samba import dsdb
35 from samba.dcerpc import security
36 from samba.ndr import ndr_unpack
37 import samba.security
38 import samba.auth
39 from samba.auth import AUTH_SESSION_INFO_DEFAULT_GROUPS, AUTH_SESSION_INFO_AUTHENTICATED, AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
40 from samba.netcmd.common import netcmd_finddc
41 from samba import policy
42 from samba import smb
43 import uuid
44 from samba.ntacls import dsacl2fsacl
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 gpo_flags_string(value):
65     '''return gpo flags string'''
66     flags = policy.get_gpo_flags(value)
67     if not flags:
68         ret = 'NONE'
69     else:
70         ret = ' '.join(flags)
71     return ret
72
73
74 def gplink_options_string(value):
75     '''return gplink options string'''
76     options = policy.get_gplink_options(value)
77     if not options:
78         ret = 'NONE'
79     else:
80         ret = ' '.join(options)
81     return ret
82
83
84 def parse_gplink(gplink):
85     '''parse a gPLink into an array of dn and options'''
86     ret = []
87     a = gplink.split(']')
88     for g in a:
89         if not g:
90             continue
91         d = g.split(';')
92         if len(d) != 2 or not d[0].startswith("[LDAP://"):
93             raise RuntimeError("Badly formed gPLink '%s'" % g)
94         ret.append({ 'dn' : d[0][8:], 'options' : int(d[1])})
95     return ret
96
97
98 def encode_gplink(gplist):
99     '''Encode an array of dn and options into gPLink string'''
100     ret = ''
101     for g in gplist:
102         ret += "[LDAP://%s;%d]" % (g['dn'], g['options'])
103     return ret
104
105
106 def dc_url(lp, creds, url=None, dc=None):
107     '''If URL is not specified, return URL for writable DC.
108     If dc is provided, use that to construct ldap URL'''
109
110     if url is None:
111         if dc is None:
112             try:
113                 dc = netcmd_finddc(lp, creds)
114             except Exception, e:
115                 raise RuntimeError("Could not find a DC for domain", e)
116         url = 'ldap://' + dc
117     return url
118
119
120 def get_gpo_dn(samdb, gpo):
121     '''Construct the DN for gpo'''
122
123     dn = samdb.get_default_basedn()
124     dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
125     dn.add_child(ldb.Dn(samdb, "CN=%s" % gpo))
126     return dn
127
128
129 def get_gpo_info(samdb, gpo=None, displayname=None, dn=None,
130                  sd_flags=security.SECINFO_OWNER|security.SECINFO_GROUP|security.SECINFO_DACL|security.SECINFO_SACL):
131     '''Get GPO information using gpo, displayname or dn'''
132
133     policies_dn = samdb.get_default_basedn()
134     policies_dn.add_child(ldb.Dn(samdb, "CN=Policies,CN=System"))
135
136     base_dn = policies_dn
137     search_expr = "(objectClass=groupPolicyContainer)"
138     search_scope = ldb.SCOPE_ONELEVEL
139
140     if gpo is not None:
141         search_expr = "(&(objectClass=groupPolicyContainer)(name=%s))" % ldb.binary_encode(gpo)
142
143     if displayname is not None:
144         search_expr = "(&(objectClass=groupPolicyContainer)(displayname=%s))" % ldb.binary_encode(displayname)
145
146     if dn is not None:
147         base_dn = dn
148         search_scope = ldb.SCOPE_BASE
149
150     try:
151         msg = samdb.search(base=base_dn, scope=search_scope,
152                             expression=search_expr,
153                             attrs=['nTSecurityDescriptor',
154                                     'versionNumber',
155                                     'flags',
156                                     'name',
157                                     'displayName',
158                                     'gPCFileSysPath'],
159                             controls=['sd_flags:1:%d' % sd_flags])
160     except Exception, e:
161         if gpo is not None:
162             mesg = "Cannot get information for GPO %s" % gpo
163         else:
164             mesg = "Cannot get information for GPOs"
165         raise CommandError(mesg, e)
166
167     return msg
168
169
170 def get_gpo_containers(samdb, gpo):
171     '''lists dn of containers for a GPO'''
172
173     search_expr = "(&(objectClass=*)(gPLink=*%s*))" % gpo
174     try:
175         msg = samdb.search(expression=search_expr, attrs=['gPLink'])
176     except Exception, e:
177         raise CommandError("Could not find container(s) with GPO %s" % gpo, e)
178
179     return msg
180
181
182 def del_gpo_link(samdb, container_dn, gpo):
183     '''delete GPO link for the container'''
184     # Check if valid Container DN and get existing GPlinks
185     try:
186         msg = samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
187                             expression="(objectClass=*)",
188                             attrs=['gPLink'])[0]
189     except Exception, e:
190         raise CommandError("Container '%s' does not exist" % container_dn, e)
191
192     found = False
193     gpo_dn = str(get_gpo_dn(samdb, gpo))
194     if 'gPLink' in msg:
195         gplist = parse_gplink(msg['gPLink'][0])
196         for g in gplist:
197             if g['dn'].lower() == gpo_dn.lower():
198                 gplist.remove(g)
199                 found = True
200                 break
201     else:
202         raise CommandError("No GPO(s) linked to this container")
203
204     if not found:
205         raise CommandError("GPO '%s' not linked to this container" % gpo)
206
207     m = ldb.Message()
208     m.dn = container_dn
209     if gplist:
210         gplink_str = encode_gplink(gplist)
211         m['r0'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
212     else:
213         m['d0'] = ldb.MessageElement(msg['gPLink'][0], ldb.FLAG_MOD_DELETE, 'gPLink')
214     try:
215         samdb.modify(m)
216     except Exception, e:
217         raise CommandError("Error removing GPO from container", e)
218
219
220 def parse_unc(unc):
221     '''Parse UNC string into a hostname, a service, and a filepath'''
222     if unc.startswith('\\\\') and unc.startswith('//'):
223         raise ValueError("UNC doesn't start with \\\\ or //")
224     tmp = unc[2:].split('/', 2)
225     if len(tmp) == 3:
226         return tmp
227     tmp = unc[2:].split('\\', 2)
228     if len(tmp) == 3:
229         return tmp
230     raise ValueError("Invalid UNC string: %s" % unc)
231
232
233 def copy_directory_remote_to_local(conn, remotedir, localdir):
234     if not os.path.isdir(localdir):
235         os.mkdir(localdir)
236     r_dirs = [ remotedir ]
237     l_dirs = [ localdir ]
238     while r_dirs:
239         r_dir = r_dirs.pop()
240         l_dir = l_dirs.pop()
241
242         dirlist = conn.list(r_dir)
243         for e in dirlist:
244             r_name = r_dir + '\\' + e['name']
245             l_name = os.path.join(l_dir, e['name'])
246
247             if e['attrib'] & smb.FILE_ATTRIBUTE_DIRECTORY:
248                 r_dirs.append(r_name)
249                 l_dirs.append(l_name)
250                 os.mkdir(l_name)
251             else:
252                 data = conn.loadfile(r_name)
253                 file(l_name, 'w').write(data)
254
255
256 def copy_directory_local_to_remote(conn, localdir, remotedir):
257     if not conn.chkpath(remotedir):
258         conn.mkdir(remotedir)
259     l_dirs = [ localdir ]
260     r_dirs = [ remotedir ]
261     while l_dirs:
262         l_dir = l_dirs.pop()
263         r_dir = r_dirs.pop()
264
265         dirlist = os.listdir(l_dir)
266         for e in dirlist:
267             l_name = os.path.join(l_dir, e)
268             r_name = r_dir + '\\' + e
269
270             if os.path.isdir(l_name):
271                 l_dirs.append(l_name)
272                 r_dirs.append(r_name)
273                 conn.mkdir(r_name)
274             else:
275                 data = file(l_name, 'r').read()
276                 conn.savefile(r_name, data)
277
278
279 def create_directory_hier(conn, remotedir):
280     elems = remotedir.replace('/', '\\').split('\\')
281     path = ""
282     for e in elems:
283         path = path + '\\' + e
284         if not conn.chkpath(path):
285             conn.mkdir(path)
286
287
288 class cmd_listall(Command):
289     """List all GPOs."""
290
291     synopsis = "%prog [options]"
292
293     takes_optiongroups = {
294         "sambaopts": options.SambaOptions,
295         "versionopts": options.VersionOptions,
296         "credopts": options.CredentialsOptions,
297     }
298
299     takes_options = [
300         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
301                metavar="URL", dest="H")
302         ]
303
304     def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
305
306         self.lp = sambaopts.get_loadparm()
307         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
308
309         self.url = dc_url(self.lp, self.creds, H)
310
311         samdb_connect(self)
312
313         msg = get_gpo_info(self.samdb, None)
314
315         for m in msg:
316             self.outf.write("GPO          : %s\n" % m['name'][0])
317             self.outf.write("display name : %s\n" % m['displayName'][0])
318             self.outf.write("path         : %s\n" % m['gPCFileSysPath'][0])
319             self.outf.write("dn           : %s\n" % m.dn)
320             self.outf.write("version      : %s\n" % attr_default(m, 'versionNumber', '0'))
321             self.outf.write("flags        : %s\n" % gpo_flags_string(int(attr_default(m, 'flags', 0))))
322             self.outf.write("\n")
323
324
325 class cmd_list(Command):
326     """List GPOs for an account."""
327
328     synopsis = "%prog <username> [options]"
329
330     takes_args = ['username']
331     takes_optiongroups = {
332         "sambaopts": options.SambaOptions,
333         "versionopts": options.VersionOptions,
334         "credopts": options.CredentialsOptions,
335     }
336
337     takes_options = [
338         Option("-H", "--URL", help="LDB URL for database or target server",
339             type=str, metavar="URL", dest="H")
340         ]
341
342     def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None):
343
344         self.lp = sambaopts.get_loadparm()
345         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
346
347         self.url = dc_url(self.lp, self.creds, H)
348
349         samdb_connect(self)
350
351         try:
352             msg = self.samdb.search(expression='(&(|(samAccountName=%s)(samAccountName=%s$))(objectClass=User))' %
353                                                 (ldb.binary_encode(username),ldb.binary_encode(username)))
354             user_dn = msg[0].dn
355         except Exception:
356             raise CommandError("Failed to find account %s" % username)
357
358         # check if its a computer account
359         try:
360             msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
361             is_computer = 'computer' in msg['objectClass']
362         except Exception:
363             raise CommandError("Failed to find objectClass for user %s" % username)
364
365         session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS |
366                                AUTH_SESSION_INFO_AUTHENTICATED )
367
368         # When connecting to a remote server, don't look up the local privilege DB
369         if self.url is not None and self.url.startswith('ldap'):
370             session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
371
372         session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
373                                           session_info_flags=session_info_flags)
374
375         token = session.security_token
376
377         gpos = []
378
379         inherit = True
380         dn = ldb.Dn(self.samdb, str(user_dn)).parent()
381         while True:
382             msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
383             if 'gPLink' in msg:
384                 glist = parse_gplink(msg['gPLink'][0])
385                 for g in glist:
386                     if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
387                         continue
388                     if g['options'] & dsdb.GPLINK_OPT_DISABLE:
389                         continue
390
391                     try:
392                         sd_flags=security.SECINFO_OWNER|security.SECINFO_GROUP|security.SECINFO_DACL
393                         gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
394                                                  attrs=['name', 'displayName', 'flags',
395                                                         'nTSecurityDescriptor'],
396                                                  controls=['sd_flags:1:%d' % sd_flags])
397                         secdesc_ndr = gmsg[0]['nTSecurityDescriptor'][0]
398                         secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
399                     except Exception:
400                         self.outf.write("Failed to fetch gpo object with nTSecurityDescriptor %s\n" %
401                             g['dn'])
402                         continue
403
404                     try:
405                         samba.security.access_check(secdesc, token,
406                                                     security.SEC_STD_READ_CONTROL |
407                                                     security.SEC_ADS_LIST |
408                                                     security.SEC_ADS_READ_PROP)
409                     except RuntimeError:
410                         self.outf.write("Failed access check on %s\n" % msg.dn)
411                         continue
412
413                     # check the flags on the GPO
414                     flags = int(attr_default(gmsg[0], 'flags', 0))
415                     if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
416                         continue
417                     if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
418                         continue
419                     gpos.append((gmsg[0]['displayName'][0], gmsg[0]['name'][0]))
420
421             # check if this blocks inheritance
422             gpoptions = int(attr_default(msg, 'gPOptions', 0))
423             if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
424                 inherit = False
425
426             if dn == self.samdb.get_default_basedn():
427                 break
428             dn = dn.parent()
429
430         if is_computer:
431             msg_str = 'computer'
432         else:
433             msg_str = 'user'
434
435         self.outf.write("GPOs for %s %s\n" % (msg_str, username))
436         for g in gpos:
437             self.outf.write("    %s %s\n" % (g[0], g[1]))
438
439
440 class cmd_show(Command):
441     """Show information for a GPO."""
442
443     synopsis = "%prog <gpo> [options]"
444
445     takes_optiongroups = {
446         "sambaopts": options.SambaOptions,
447         "versionopts": options.VersionOptions,
448         "credopts": options.CredentialsOptions,
449     }
450
451     takes_args = ['gpo']
452
453     takes_options = [
454         Option("-H", help="LDB URL for database or target server", type=str)
455         ]
456
457     def run(self, gpo, H=None, sambaopts=None, credopts=None, versionopts=None):
458
459         self.lp = sambaopts.get_loadparm()
460         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
461
462         self.url = dc_url(self.lp, self.creds, H)
463
464         samdb_connect(self)
465
466         try:
467             msg = get_gpo_info(self.samdb, gpo)[0]
468         except Exception:
469             raise CommandError("GPO '%s' does not exist" % gpo)
470
471         try:
472             secdesc_ndr = msg['nTSecurityDescriptor'][0]
473             secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
474             secdesc_sddl = secdesc.as_sddl()
475         except Exception:
476             secdesc_sddl = "<hidden>"
477
478         self.outf.write("GPO          : %s\n" % msg['name'][0])
479         self.outf.write("display name : %s\n" % msg['displayName'][0])
480         self.outf.write("path         : %s\n" % msg['gPCFileSysPath'][0])
481         self.outf.write("dn           : %s\n" % msg.dn)
482         self.outf.write("version      : %s\n" % attr_default(msg, 'versionNumber', '0'))
483         self.outf.write("flags        : %s\n" % gpo_flags_string(int(attr_default(msg, 'flags', 0))))
484         self.outf.write("ACL          : %s\n" % secdesc_sddl)
485         self.outf.write("\n")
486
487
488 class cmd_getlink(Command):
489     """List GPO Links for a container."""
490
491     synopsis = "%prog <container_dn> [options]"
492
493     takes_optiongroups = {
494         "sambaopts": options.SambaOptions,
495         "versionopts": options.VersionOptions,
496         "credopts": options.CredentialsOptions,
497     }
498
499     takes_args = ['container_dn']
500
501     takes_options = [
502         Option("-H", help="LDB URL for database or target server", type=str)
503         ]
504
505     def run(self, container_dn, H=None, sambaopts=None, credopts=None,
506                 versionopts=None):
507
508         self.lp = sambaopts.get_loadparm()
509         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
510
511         self.url = dc_url(self.lp, self.creds, H)
512
513         samdb_connect(self)
514
515         try:
516             msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
517                                     expression="(objectClass=*)",
518                                     attrs=['gPLink'])[0]
519         except Exception:
520             raise CommandError("Container '%s' does not exist" % container_dn)
521
522         if msg['gPLink']:
523             self.outf.write("GPO(s) linked to DN %s\n" % container_dn)
524             gplist = parse_gplink(msg['gPLink'][0])
525             for g in gplist:
526                 msg = get_gpo_info(self.samdb, dn=g['dn'])
527                 self.outf.write("    GPO     : %s\n" % msg[0]['name'][0])
528                 self.outf.write("    Name    : %s\n" % msg[0]['displayName'][0])
529                 self.outf.write("    Options : %s\n" % gplink_options_string(g['options']))
530                 self.outf.write("\n")
531         else:
532             self.outf.write("No GPO(s) linked to DN=%s\n" % container_dn)
533
534
535 class cmd_setlink(Command):
536     """Add or update a GPO link to a container."""
537
538     synopsis = "%prog <container_dn> <gpo> [options]"
539
540     takes_optiongroups = {
541         "sambaopts": options.SambaOptions,
542         "versionopts": options.VersionOptions,
543         "credopts": options.CredentialsOptions,
544     }
545
546     takes_args = ['container_dn', 'gpo']
547
548     takes_options = [
549         Option("-H", help="LDB URL for database or target server", type=str),
550         Option("--disable", dest="disabled", default=False, action='store_true',
551             help="Disable policy"),
552         Option("--enforce", dest="enforced", default=False, action='store_true',
553             help="Enforce policy")
554         ]
555
556     def run(self, container_dn, gpo, H=None, disabled=False, enforced=False,
557                 sambaopts=None, credopts=None, versionopts=None):
558
559         self.lp = sambaopts.get_loadparm()
560         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
561
562         self.url = dc_url(self.lp, self.creds, H)
563
564         samdb_connect(self)
565
566         gplink_options = 0
567         if disabled:
568             gplink_options |= dsdb.GPLINK_OPT_DISABLE
569         if enforced:
570             gplink_options |= dsdb.GPLINK_OPT_ENFORCE
571
572         # Check if valid GPO DN
573         try:
574             msg = get_gpo_info(self.samdb, gpo=gpo)[0]
575         except Exception:
576             raise CommandError("GPO '%s' does not exist" % gpo)
577         gpo_dn = str(get_gpo_dn(self.samdb, gpo))
578
579         # Check if valid Container DN
580         try:
581             msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
582                                     expression="(objectClass=*)",
583                                     attrs=['gPLink'])[0]
584         except Exception:
585             raise CommandError("Container '%s' does not exist" % container_dn)
586
587         # Update existing GPlinks or Add new one
588         existing_gplink = False
589         if 'gPLink' in msg:
590             gplist = parse_gplink(msg['gPLink'][0])
591             existing_gplink = True
592             found = False
593             for g in gplist:
594                 if g['dn'].lower() == gpo_dn.lower():
595                     g['options'] = gplink_options
596                     found = True
597                     break
598             if found:
599                 raise CommandError("GPO '%s' already linked to this container" % gpo)
600             else:
601                 gplist.insert(0, { 'dn' : gpo_dn, 'options' : gplink_options })
602         else:
603             gplist = []
604             gplist.append({ 'dn' : gpo_dn, 'options' : gplink_options })
605
606         gplink_str = encode_gplink(gplist)
607
608         m = ldb.Message()
609         m.dn = ldb.Dn(self.samdb, container_dn)
610
611         if existing_gplink:
612             m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_REPLACE, 'gPLink')
613         else:
614             m['new_value'] = ldb.MessageElement(gplink_str, ldb.FLAG_MOD_ADD, 'gPLink')
615
616         try:
617             self.samdb.modify(m)
618         except Exception, e:
619             raise CommandError("Error adding GPO Link", e)
620
621         self.outf.write("Added/Updated GPO link\n")
622         cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
623
624
625 class cmd_dellink(Command):
626     """Delete GPO link from a container."""
627
628     synopsis = "%prog <container_dn> <gpo> [options]"
629
630     takes_optiongroups = {
631         "sambaopts": options.SambaOptions,
632         "versionopts": options.VersionOptions,
633         "credopts": options.CredentialsOptions,
634     }
635
636     takes_args = ['container', 'gpo']
637
638     takes_options = [
639         Option("-H", help="LDB URL for database or target server", type=str),
640         ]
641
642     def run(self, container, gpo, H=None, sambaopts=None, credopts=None,
643                 versionopts=None):
644
645         self.lp = sambaopts.get_loadparm()
646         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
647
648         self.url = dc_url(self.lp, self.creds, H)
649
650         samdb_connect(self)
651
652         # Check if valid GPO
653         try:
654             get_gpo_info(self.samdb, gpo=gpo)[0]
655         except Exception:
656             raise CommandError("GPO '%s' does not exist" % gpo)
657
658         container_dn = ldb.Dn(self.samdb, container)
659         del_gpo_link(self.samdb, container_dn, gpo)
660         self.outf.write("Deleted GPO link.\n")
661         cmd_getlink().run(container_dn, H, sambaopts, credopts, versionopts)
662
663
664 class cmd_listcontainers(Command):
665     """List all linked containers for a GPO."""
666
667     synopsis = "%prog <gpo> [options]"
668
669     takes_optiongroups = {
670         "sambaopts": options.SambaOptions,
671         "versionopts": options.VersionOptions,
672         "credopts": options.CredentialsOptions,
673     }
674
675     takes_args = ['gpo']
676
677     takes_options = [
678         Option("-H", help="LDB URL for database or target server", type=str)
679         ]
680
681     def run(self, gpo, H=None, sambaopts=None, credopts=None,
682                 versionopts=None):
683
684         self.lp = sambaopts.get_loadparm()
685         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
686
687         self.url = dc_url(self.lp, self.creds, H)
688
689         samdb_connect(self)
690
691         msg = get_gpo_containers(self.samdb, gpo)
692         if len(msg):
693             self.outf.write("Container(s) using GPO %s\n" % gpo)
694             for m in msg:
695                 self.outf.write("    DN: %s\n" % m['dn'])
696         else:
697             self.outf.write("No Containers using GPO %s\n" % gpo)
698
699
700 class cmd_getinheritance(Command):
701     """Get inheritance flag for a container."""
702
703     synopsis = "%prog <container_dn> [options]"
704
705     takes_optiongroups = {
706         "sambaopts": options.SambaOptions,
707         "versionopts": options.VersionOptions,
708         "credopts": options.CredentialsOptions,
709     }
710
711     takes_args = ['container_dn']
712
713     takes_options = [
714         Option("-H", help="LDB URL for database or target server", type=str)
715         ]
716
717     def run(self, container_dn, H=None, sambaopts=None, credopts=None,
718                 versionopts=None):
719
720         self.lp = sambaopts.get_loadparm()
721         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
722
723         self.url = dc_url(self.lp, self.creds, H)
724
725         samdb_connect(self)
726
727         try:
728             msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
729                                     expression="(objectClass=*)",
730                                     attrs=['gPOptions'])[0]
731         except Exception:
732             raise CommandError("Container '%s' does not exist" % container_dn)
733
734         inheritance = 0
735         if 'gPOptions' in msg:
736             inheritance = int(msg['gPOptions'][0])
737
738         if inheritance == dsdb.GPO_BLOCK_INHERITANCE:
739             self.outf.write("Container has GPO_BLOCK_INHERITANCE\n")
740         else:
741             self.outf.write("Container has GPO_INHERIT\n")
742
743
744 class cmd_setinheritance(Command):
745     """Set inheritance flag on a container."""
746
747     synopsis = "%prog <container_dn> <block|inherit> [options]"
748
749     takes_optiongroups = {
750         "sambaopts": options.SambaOptions,
751         "versionopts": options.VersionOptions,
752         "credopts": options.CredentialsOptions,
753     }
754
755     takes_args = [ 'container_dn', 'inherit_state' ]
756
757     takes_options = [
758         Option("-H", help="LDB URL for database or target server", type=str)
759         ]
760
761     def run(self, container_dn, inherit_state, H=None, sambaopts=None, credopts=None,
762                 versionopts=None):
763
764         if inherit_state.lower() == 'block':
765             inheritance = dsdb.GPO_BLOCK_INHERITANCE
766         elif inherit_state.lower() == 'inherit':
767             inheritance = dsdb.GPO_INHERIT
768         else:
769             raise CommandError("Unknown inheritance state (%s)" % inherit_state)
770
771         self.lp = sambaopts.get_loadparm()
772         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
773
774         self.url = dc_url(self.lp, self.creds, H)
775
776         samdb_connect(self)
777         try:
778             msg = self.samdb.search(base=container_dn, scope=ldb.SCOPE_BASE,
779                                     expression="(objectClass=*)",
780                                     attrs=['gPOptions'])[0]
781         except Exception:
782             raise CommandError("Container '%s' does not exist" % container_dn)
783
784         m = ldb.Message()
785         m.dn = ldb.Dn(self.samdb, container_dn)
786
787         if 'gPOptions' in msg:
788             m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_REPLACE, 'gPOptions')
789         else:
790             m['new_value'] = ldb.MessageElement(str(inheritance), ldb.FLAG_MOD_ADD, 'gPOptions')
791
792         try:
793             self.samdb.modify(m)
794         except Exception, e:
795             raise CommandError("Error setting inheritance state %s" % inherit_state, e)
796
797
798 class cmd_fetch(Command):
799     """Download a GPO."""
800
801     synopsis = "%prog <gpo> [options]"
802
803     takes_optiongroups = {
804         "sambaopts": options.SambaOptions,
805         "versionopts": options.VersionOptions,
806         "credopts": options.CredentialsOptions,
807     }
808
809     takes_args = ['gpo']
810
811     takes_options = [
812         Option("-H", help="LDB URL for database or target server", type=str),
813         Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
814         ]
815
816     def run(self, gpo, H=None, tmpdir=None, sambaopts=None, credopts=None, versionopts=None):
817
818         self.lp = sambaopts.get_loadparm()
819         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
820
821         # We need to know writable DC to setup SMB connection
822         if H and H.startswith('ldap://'):
823             dc_hostname = H[7:]
824             self.url = H
825         else:
826             dc_hostname = netcmd_finddc(self.lp, self.creds)
827             self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
828
829         samdb_connect(self)
830         try:
831             msg = get_gpo_info(self.samdb, gpo)[0]
832         except Exception:
833             raise CommandError("GPO '%s' does not exist" % gpo)
834
835         # verify UNC path
836         unc = msg['gPCFileSysPath'][0]
837         try:
838             [dom_name, service, sharepath] = parse_unc(unc)
839         except ValueError:
840             raise CommandError("Invalid GPO path (%s)" % unc)
841
842         # SMB connect to DC
843         try:
844             conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
845         except Exception:
846             raise CommandError("Error connecting to '%s' using SMB" % dc_hostname)
847
848         # Copy GPT
849         if tmpdir is None:
850             tmpdir = "/tmp"
851         if not os.path.isdir(tmpdir):
852             raise CommandError("Temoprary directory '%s' does not exist" % tmpdir)
853
854         localdir = os.path.join(tmpdir, "policy")
855         if not os.path.isdir(localdir):
856             os.mkdir(localdir)
857
858         gpodir = os.path.join(localdir, gpo)
859         if os.path.isdir(gpodir):
860             raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
861
862         try:
863             os.mkdir(gpodir)
864             copy_directory_remote_to_local(conn, sharepath, gpodir)
865         except Exception, e:
866             # FIXME: Catch more specific exception
867             raise CommandError("Error copying GPO from DC", e)
868         self.outf.write('GPO copied to %s\n' % gpodir)
869
870
871 class cmd_create(Command):
872     """Create an empty GPO."""
873
874     synopsis = "%prog <displayname> [options]"
875
876     takes_optiongroups = {
877         "sambaopts": options.SambaOptions,
878         "versionopts": options.VersionOptions,
879         "credopts": options.CredentialsOptions,
880     }
881
882     takes_args = ['displayname']
883
884     takes_options = [
885         Option("-H", help="LDB URL for database or target server", type=str),
886         Option("--tmpdir", help="Temporary directory for copying policy files", type=str)
887         ]
888
889     def run(self, displayname, H=None, tmpdir=None, sambaopts=None, credopts=None,
890             versionopts=None):
891
892         self.lp = sambaopts.get_loadparm()
893         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
894
895         # We need to know writable DC to setup SMB connection
896         if H and H.startswith('ldap://'):
897             dc_hostname = H[7:]
898             self.url = H
899         else:
900             dc_hostname = netcmd_finddc(self.lp, self.creds)
901             self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
902
903         samdb_connect(self)
904
905         msg = get_gpo_info(self.samdb, displayname=displayname)
906         if msg.count > 0:
907             raise CommandError("A GPO already existing with name '%s'" % displayname)
908
909         # Create new GUID
910         guid  = str(uuid.uuid4())
911         gpo = "{%s}" % guid.upper()
912         realm = self.lp.get('realm')
913         unc_path = "\\\\%s\\sysvol\\%s\\Policies\\%s" % (realm, realm, gpo)
914
915         # Create GPT
916         if tmpdir is None:
917             tmpdir = "/tmp"
918         if not os.path.isdir(tmpdir):
919             raise CommandError("Temporary directory '%s' does not exist" % tmpdir)
920
921         localdir = os.path.join(tmpdir, "policy")
922         if not os.path.isdir(localdir):
923             os.mkdir(localdir)
924
925         gpodir = os.path.join(localdir, gpo)
926         if os.path.isdir(gpodir):
927             raise CommandError("GPO directory '%s' already exists, refusing to overwrite" % gpodir)
928
929         try:
930             os.mkdir(gpodir)
931             os.mkdir(os.path.join(gpodir, "Machine"))
932             os.mkdir(os.path.join(gpodir, "User"))
933             gpt_contents = "[General]\r\nVersion=0\r\n"
934             file(os.path.join(gpodir, "GPT.INI"), "w").write(gpt_contents)
935         except Exception, e:
936             raise CommandError("Error Creating GPO files", e)
937
938         # Connect to DC over SMB
939         [dom_name, service, sharepath] = parse_unc(unc_path)
940         try:
941             conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
942         except Exception, e:
943             raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
944
945         self.samdb.transaction_start()
946         try:
947             # Add cn=<guid>
948             gpo_dn = get_gpo_dn(self.samdb, gpo)
949
950             m = ldb.Message()
951             m.dn = gpo_dn
952             m['a01'] = ldb.MessageElement("groupPolicyContainer", ldb.FLAG_MOD_ADD, "objectClass")
953             m['a02'] = ldb.MessageElement(displayname, ldb.FLAG_MOD_ADD, "displayName")
954             m['a03'] = ldb.MessageElement(unc_path, ldb.FLAG_MOD_ADD, "gPCFileSysPath")
955             m['a04'] = ldb.MessageElement("0", ldb.FLAG_MOD_ADD, "flags")
956             m['a05'] = ldb.MessageElement("0", ldb.FLAG_MOD_ADD, "versionNumber")
957             m['a06'] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_ADD, "showInAdvancedViewOnly")
958             m['a07'] = ldb.MessageElement("2", ldb.FLAG_MOD_ADD, "gpcFunctionalityVersion")
959             self.samdb.add(m)
960
961             # Add cn=User,cn=<guid>
962             m = ldb.Message()
963             m.dn = ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn))
964             m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
965             m['a02'] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_ADD, "showInAdvancedViewOnly")
966             self.samdb.add(m)
967
968             # Add cn=Machine,cn=<guid>
969             m = ldb.Message()
970             m.dn = ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn))
971             m['a01'] = ldb.MessageElement("container", ldb.FLAG_MOD_ADD, "objectClass")
972             m['a02'] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_ADD, "showInAdvancedViewOnly")
973             self.samdb.add(m)
974
975             # Copy GPO files over SMB
976             create_directory_hier(conn, sharepath)
977             copy_directory_local_to_remote(conn, gpodir, sharepath)
978
979             # Get new security descriptor
980             msg = get_gpo_info(self.samdb, gpo=gpo)[0]
981             ds_sd_ndr = msg['nTSecurityDescriptor'][0]
982             ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
983
984             # Create a file system security descriptor
985             domain_sid = security.dom_sid(self.samdb.get_domain_sid())
986             sddl = dsacl2fsacl(ds_sd, domain_sid)
987             fs_sd = security.descriptor.from_sddl(sddl, domain_sid)
988
989             # Set ACL
990             sio = ( security.SECINFO_OWNER |
991                     security.SECINFO_GROUP |
992                     security.SECINFO_DACL |
993                     security.SECINFO_PROTECTED_DACL )
994             conn.set_acl(sharepath, fs_sd, sio)
995         except Exception:
996             self.samdb.transaction_cancel()
997             raise
998         else:
999             self.samdb.transaction_commit()
1000
1001         self.outf.write("GPO '%s' created as %s\n" % (displayname, gpo))
1002
1003
1004 class cmd_del(Command):
1005     """Delete a GPO."""
1006
1007     synopsis = "%prog <gpo> [options]"
1008
1009     takes_optiongroups = {
1010         "sambaopts": options.SambaOptions,
1011         "versionopts": options.VersionOptions,
1012         "credopts": options.CredentialsOptions,
1013     }
1014
1015     takes_args = ['gpo']
1016
1017     takes_options = [
1018         Option("-H", help="LDB URL for database or target server", type=str),
1019         ]
1020
1021     def run(self, gpo, H=None, sambaopts=None, credopts=None,
1022                 versionopts=None):
1023
1024         self.lp = sambaopts.get_loadparm()
1025         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1026
1027         # We need to know writable DC to setup SMB connection
1028         if H and H.startswith('ldap://'):
1029             dc_hostname = H[7:]
1030             self.url = H
1031         else:
1032             dc_hostname = netcmd_finddc(self.lp, self.creds)
1033             self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1034
1035         samdb_connect(self)
1036
1037         # Check if valid GPO
1038         try:
1039             get_gpo_info(self.samdb, gpo=gpo)[0]
1040         except Exception:
1041             raise CommandError("GPO '%s' does not exist" % gpo)
1042
1043         realm = self.lp.get('realm')
1044         unc_path = "\\\\%s\\sysvol\\%s\\Policies\\%s" % (realm, realm, gpo)
1045
1046         # Connect to DC over SMB
1047         [dom_name, service, sharepath] = parse_unc(unc_path)
1048         try:
1049             conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
1050         except Exception, e:
1051             raise CommandError("Error connecting to '%s' using SMB" % dc_hostname, e)
1052
1053         self.samdb.transaction_start()
1054         try:
1055             # Check for existing links
1056             msg = get_gpo_containers(self.samdb, gpo)
1057
1058             if len(msg):
1059                 self.outf.write("GPO %s is linked to containers\n" % gpo)
1060                 for m in msg:
1061                     del_gpo_link(self.samdb, m['dn'], gpo)
1062                     self.outf.write("    Removed link from %s.\n" % m['dn'])
1063
1064             # Remove LDAP entries
1065             gpo_dn = get_gpo_dn(self.samdb, gpo)
1066             self.samdb.delete(ldb.Dn(self.samdb, "CN=User,%s" % str(gpo_dn)))
1067             self.samdb.delete(ldb.Dn(self.samdb, "CN=Machine,%s" % str(gpo_dn)))
1068             self.samdb.delete(gpo_dn)
1069
1070             # Remove GPO files
1071             conn.deltree(sharepath)
1072
1073         except Exception:
1074             self.samdb.transaction_cancel()
1075             raise
1076         else:
1077             self.samdb.transaction_commit()
1078
1079         self.outf.write("GPO %s deleted.\n" % gpo)
1080
1081
1082 class cmd_aclcheck(Command):
1083     """Check all GPOs have matching LDAP and DS ACLs."""
1084
1085     synopsis = "%prog [options]"
1086
1087     takes_optiongroups = {
1088         "sambaopts": options.SambaOptions,
1089         "versionopts": options.VersionOptions,
1090         "credopts": options.CredentialsOptions,
1091     }
1092
1093     takes_options = [
1094         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
1095                metavar="URL", dest="H")
1096         ]
1097
1098     def run(self, H=None, sambaopts=None, credopts=None, versionopts=None):
1099
1100         self.lp = sambaopts.get_loadparm()
1101         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
1102
1103         self.url = dc_url(self.lp, self.creds, H)
1104
1105         # We need to know writable DC to setup SMB connection
1106         if H and H.startswith('ldap://'):
1107             dc_hostname = H[7:]
1108             self.url = H
1109         else:
1110             dc_hostname = netcmd_finddc(self.lp, self.creds)
1111             self.url = dc_url(self.lp, self.creds, dc=dc_hostname)
1112
1113         samdb_connect(self)
1114
1115         msg = get_gpo_info(self.samdb, None)
1116
1117         for m in msg:
1118             # verify UNC path
1119             unc = m['gPCFileSysPath'][0]
1120             try:
1121                 [dom_name, service, sharepath] = parse_unc(unc)
1122             except ValueError:
1123                 raise CommandError("Invalid GPO path (%s)" % unc)
1124
1125             # SMB connect to DC
1126             try:
1127                 conn = smb.SMB(dc_hostname, service, lp=self.lp, creds=self.creds)
1128             except Exception:
1129                 raise CommandError("Error connecting to '%s' using SMB" % dc_hostname)
1130
1131             fs_sd = conn.get_acl(sharepath, security.SECINFO_OWNER | security.SECINFO_GROUP | security.SECINFO_DACL, security.SEC_FLAG_MAXIMUM_ALLOWED)
1132
1133             ds_sd_ndr = m['nTSecurityDescriptor'][0]
1134             ds_sd = ndr_unpack(security.descriptor, ds_sd_ndr).as_sddl()
1135
1136             # Create a file system security descriptor
1137             domain_sid = security.dom_sid(self.samdb.get_domain_sid())
1138             expected_fs_sddl = dsacl2fsacl(ds_sd, domain_sid)
1139
1140             if (fs_sd.as_sddl(domain_sid) != expected_fs_sddl):
1141                 raise CommandError("Invalid GPO ACL %s on path (%s), should be %s" % (fs_sd.as_sddl(domain_sid), sharepath, expected_fs_sddl))
1142
1143
1144 class cmd_gpo(SuperCommand):
1145     """Group Policy Object (GPO) management."""
1146
1147     subcommands = {}
1148     subcommands["listall"] = cmd_listall()
1149     subcommands["list"] = cmd_list()
1150     subcommands["show"] = cmd_show()
1151     subcommands["getlink"] = cmd_getlink()
1152     subcommands["setlink"] = cmd_setlink()
1153     subcommands["dellink"] = cmd_dellink()
1154     subcommands["listcontainers"] = cmd_listcontainers()
1155     subcommands["getinheritance"] = cmd_getinheritance()
1156     subcommands["setinheritance"] = cmd_setinheritance()
1157     subcommands["fetch"] = cmd_fetch()
1158     subcommands["create"] = cmd_create()
1159     subcommands["del"] = cmd_del()
1160     subcommands["aclcheck"] = cmd_aclcheck()