s4-samba-tool: fixed the gpo command to use the right DN for access checks
[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 #
7 # based on C implementation by Guenther Deschner and Wilco Baan Hofman
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22
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 drs_utils, nttime2string, dsdb, dcerpc
35 from samba.dcerpc import misc
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
41 def samdb_connect(ctx):
42     '''make a ldap connection to the server'''
43     try:
44         ctx.samdb = SamDB(url=ctx.url,
45                           session_info=system_session(),
46                           credentials=ctx.creds, lp=ctx.lp)
47     except Exception, e:
48         raise CommandError("LDAP connection to %s failed " % ctx.url, e)
49
50
51 def attr_default(msg, attrname, default):
52     '''get an attribute from a ldap msg with a default'''
53     if attrname in msg:
54         return msg[attrname][0]
55     return default
56
57
58 def flags_string(flags, value):
59     '''return a set of flags as a string'''
60     if value == 0:
61         return 'NONE'
62     ret = ''
63     for (str, val) in flags:
64         if val & value:
65             ret += str + ' '
66             value &= ~val
67     if value != 0:
68         ret += '0x%08x' % value
69     return ret.rstrip()
70
71
72 def parse_gplink(gplink):
73     '''parse a gPLink into an array of dn and options'''
74     ret = []
75     a = gplink.split(']')
76     for g in a:
77         if not g:
78             continue
79         d = g.split(';')
80         if len(d) != 2 or not d[0].startswith("[LDAP://"):
81             raise RuntimeError("Badly formed gPLink '%s'" % g)
82         ret.append({ 'dn' : d[0][8:], 'options' : int(d[1])})
83     return ret
84
85
86 class cmd_listall(Command):
87     """list all GPOs"""
88
89     synopsis = "%prog gpo listall"
90
91     takes_optiongroups = {
92         "sambaopts": options.SambaOptions,
93         "versionopts": options.VersionOptions,
94         "credopts": options.CredentialsOptions,
95     }
96
97     takes_options = [
98         Option("-H", help="LDB URL for database or target server", type=str)
99         ]
100
101     def run(self, H=None, sambaopts=None,
102             credopts=None, versionopts=None, server=None):
103
104         self.url = H
105         self.lp = sambaopts.get_loadparm()
106
107         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
108
109         samdb_connect(self)
110
111         policies_dn = self.samdb.get_default_basedn()
112         policies_dn.add_child(ldb.Dn(self.samdb, "CN=Policies,CN=System"))
113
114         gpo_flags = [
115             ("GPO_FLAG_USER_DISABLE", dsdb.GPO_FLAG_USER_DISABLE ),
116             ( "GPO_FLAG_MACHINE_DISABLE", dsdb.GPO_FLAG_MACHINE_DISABLE ) ]
117
118         try:
119             msg = self.samdb.search(base=policies_dn, scope=ldb.SCOPE_ONELEVEL,
120                                     expression="(objectClass=groupPolicyContainer)",
121                                     attrs=['nTSecurityDescriptor', 'versionNumber', 'flags', 'name', 'displayName', 'gPCFileSysPath'])
122         except Exception, e:
123             raise CommandError("Failed to list policies in %s" % policies_dn, e)
124         for m in msg:
125             print("GPO          : %s" % m['name'][0])
126             print("display name : %s" % m['displayName'][0])
127             print("path         : %s" % m['gPCFileSysPath'][0])
128             print("dn           : %s" % m.dn)
129             print("version      : %s" % attr_default(m, 'version', '0'))
130             print("flags        : %s" % flags_string(gpo_flags, int(attr_default(m, 'flags', 0))))
131             print("")
132
133
134 class cmd_list(Command):
135     """list GPOs for a user"""
136
137     synopsis = "%prog gpo list <username>"
138
139     takes_optiongroups = {
140         "sambaopts": options.SambaOptions,
141         "versionopts": options.VersionOptions,
142         "credopts": options.CredentialsOptions,
143     }
144
145     takes_args = [ 'username' ]
146
147     takes_options = [
148         Option("-H", help="LDB URL for database or target server", type=str)
149         ]
150
151     def run(self, username, H=None, sambaopts=None,
152             credopts=None, versionopts=None, server=None):
153
154         self.url = H
155         self.lp = sambaopts.get_loadparm()
156
157         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
158
159         samdb_connect(self)
160
161         try:
162             user_dn = self.samdb.search(expression='(&(samAccountName=%s)(objectclass=User))' % username)[0].dn
163         except Exception, e:
164             raise CommandError("Failed to find user %s" % username, e)
165
166         # check if its a computer account
167         try:
168             msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
169             is_computer = 'computer' in msg['objectClass']
170         except Exception, e:
171             raise CommandError("Failed to find objectClass for user %s" % username, e)
172
173         session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS |
174                                AUTH_SESSION_INFO_AUTHENTICATED )
175
176         # When connecting to a remote server, don't look up the local privilege DB
177         if self.url is not None and self.url.startswith('ldap'):
178             session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
179
180         session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
181                                           session_info_flags=session_info_flags)
182
183         token = session.security_token
184
185         gpos = []
186
187         inherit = True
188         dn = ldb.Dn(self.samdb, str(user_dn)).parent()
189         while True:
190             msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
191             if 'gPLink' in msg:
192                 glist = parse_gplink(msg['gPLink'][0])
193                 for g in glist:
194                     if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
195                         continue
196                     if g['options'] & dsdb.GPLINK_OPT_DISABLE:
197                         continue
198
199                     try:
200                         gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
201                                                  attrs=['flags', 'ntSecurityDescriptor'])
202                     except Exception:
203                         print "Failed to fetch gpo object %s" % g['dn']
204                         continue
205
206                     secdesc_ndr = gmsg[0]['ntSecurityDescriptor'][0]
207                     secdesc = ndr_unpack(dcerpc.security.descriptor, secdesc_ndr)
208
209                     try:
210                         samba.security.access_check(secdesc, token,
211                                                     dcerpc.security.SEC_STD_READ_CONTROL |
212                                                     dcerpc.security.SEC_ADS_LIST |
213                                                     dcerpc.security.SEC_ADS_READ_PROP)
214                     except RuntimeError:
215                         print "Failed access check on %s" % msg.dn
216                         continue
217
218                     # check the flags on the GPO
219                     flags = int(attr_default(gmsg[0], 'flags', 0))
220                     if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
221                         continue
222                     if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
223                         continue
224                     gpos.append(g)
225
226             # check if this blocks inheritance
227             gpoptions = int(attr_default(msg, 'gPOptions', 0))
228             if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
229                 inherit = False
230
231             if dn == self.samdb.get_default_basedn():
232                 break
233             dn = dn.parent()
234
235         print("GPO's for user %s" % username)
236         for g in gpos:
237             print("\t%s" % g['dn'])
238
239
240 class cmd_gpo(SuperCommand):
241     """GPO commands"""
242
243     subcommands = {}
244     subcommands["listall"] = cmd_listall()
245     subcommands["list"] = cmd_list()