samba-tool: add -H or --URL where necessary
[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", "--URL", help="LDB URL for database or target server", type=str,
94                metavar="URL", dest="H")
95         ]
96
97     def run(self, H=None, sambaopts=None,
98             credopts=None, versionopts=None, server=None):
99
100         self.url = H
101         self.lp = sambaopts.get_loadparm()
102
103         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
104
105         samdb_connect(self)
106
107         policies_dn = self.samdb.get_default_basedn()
108         policies_dn.add_child(ldb.Dn(self.samdb, "CN=Policies,CN=System"))
109
110         gpo_flags = [
111             ("GPO_FLAG_USER_DISABLE", dsdb.GPO_FLAG_USER_DISABLE ),
112             ( "GPO_FLAG_MACHINE_DISABLE", dsdb.GPO_FLAG_MACHINE_DISABLE ) ]
113
114         try:
115             msg = self.samdb.search(base=policies_dn, scope=ldb.SCOPE_ONELEVEL,
116                                     expression="(objectClass=groupPolicyContainer)",
117                                     attrs=['nTSecurityDescriptor', 'versionNumber', 'flags', 'name', 'displayName', 'gPCFileSysPath'])
118         except Exception, e:
119             raise CommandError("Failed to list policies in %s" % policies_dn, e)
120         for m in msg:
121             print("GPO          : %s" % m['name'][0])
122             print("display name : %s" % m['displayName'][0])
123             print("path         : %s" % m['gPCFileSysPath'][0])
124             print("dn           : %s" % m.dn)
125             print("version      : %s" % attr_default(m, 'versionNumber', '0'))
126             print("flags        : %s" % flags_string(gpo_flags, int(attr_default(m, 'flags', 0))))
127             print("")
128
129
130 class cmd_list(Command):
131     """list GPOs for a user"""
132
133     synopsis = "%prog gpo list <username>"
134
135     takes_args = [ 'username' ]
136
137     takes_options = [
138         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
139                metavar="URL", dest="H")
140         ]
141
142     def run(self, username, H=None, sambaopts=None,
143             credopts=None, versionopts=None, server=None):
144
145         self.url = H
146         self.lp = sambaopts.get_loadparm()
147
148         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
149
150         samdb_connect(self)
151
152         try:
153             user_dn = self.samdb.search(expression='(&(samAccountName=%s)(objectclass=User))' % username)[0].dn
154         except Exception, e:
155             raise CommandError("Failed to find user %s" % username, e)
156
157         # check if its a computer account
158         try:
159             msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
160             is_computer = 'computer' in msg['objectClass']
161         except Exception, e:
162             raise CommandError("Failed to find objectClass for user %s" % username, e)
163
164         session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS |
165                                AUTH_SESSION_INFO_AUTHENTICATED )
166
167         # When connecting to a remote server, don't look up the local privilege DB
168         if self.url is not None and self.url.startswith('ldap'):
169             session_info_flags |= AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
170
171         session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
172                                           session_info_flags=session_info_flags)
173
174         token = session.security_token
175
176         gpos = []
177
178         inherit = True
179         dn = ldb.Dn(self.samdb, str(user_dn)).parent()
180         while True:
181             msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
182             if 'gPLink' in msg:
183                 glist = parse_gplink(msg['gPLink'][0])
184                 for g in glist:
185                     if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
186                         continue
187                     if g['options'] & dsdb.GPLINK_OPT_DISABLE:
188                         continue
189
190                     try:
191                         gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
192                                                  attrs=['flags', 'ntSecurityDescriptor'])
193                     except Exception:
194                         print "Failed to fetch gpo object %s" % g['dn']
195                         continue
196
197                     secdesc_ndr = gmsg[0]['ntSecurityDescriptor'][0]
198                     secdesc = ndr_unpack(dcerpc.security.descriptor, secdesc_ndr)
199
200                     try:
201                         samba.security.access_check(secdesc, token,
202                                                     dcerpc.security.SEC_STD_READ_CONTROL |
203                                                     dcerpc.security.SEC_ADS_LIST |
204                                                     dcerpc.security.SEC_ADS_READ_PROP)
205                     except RuntimeError:
206                         print "Failed access check on %s" % msg.dn
207                         continue
208
209                     # check the flags on the GPO
210                     flags = int(attr_default(gmsg[0], 'flags', 0))
211                     if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
212                         continue
213                     if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
214                         continue
215                     gpos.append(g)
216
217             # check if this blocks inheritance
218             gpoptions = int(attr_default(msg, 'gPOptions', 0))
219             if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
220                 inherit = False
221
222             if dn == self.samdb.get_default_basedn():
223                 break
224             dn = dn.parent()
225
226         print("GPO's for user %s" % username)
227         for g in gpos:
228             print("\t%s" % g['dn'])
229
230
231 class cmd_gpo(SuperCommand):
232     """GPO commands"""
233
234     subcommands = {}
235     subcommands["listall"] = cmd_listall()
236     subcommands["list"] = cmd_list()