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