s4-gpo: started on samba-tool gpo list command
[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
35 from samba.dcerpc import misc
36
37
38 def samdb_connect(ctx):
39     '''make a ldap connection to the server'''
40     try:
41         ctx.samdb = SamDB(url=ctx.url,
42                           session_info=system_session(),
43                           credentials=ctx.creds, lp=ctx.lp)
44     except Exception, estr:
45         raise CommandError("LDAP connection to %s failed - %s" % (ctx.url, estr))
46
47
48 def attr_default(msg, attrname, default):
49     '''get an attribute from a ldap msg with a default'''
50     if attrname in msg:
51         return msg[attrname][0]
52     return default
53
54
55 def flags_string(flags, value):
56     '''return a set of flags as a string'''
57     if value == 0:
58         return 'NONE'
59     ret = ''
60     for (str, val) in flags:
61         if val & value:
62             ret += str + ' '
63             value &= ~val
64     if value != 0:
65         ret += '0x%08x' % value
66     return ret.rstrip()
67
68
69 def parse_gplink(gplink):
70     '''parse a gPLink into an array of dn and options'''
71     ret = []
72     a = gplink.split(']')
73     for g in a:
74         if not g:
75             continue
76         d = g.split(';')
77         if len(d) != 2 or not d[0].startswith("[LDAP://"):
78             raise RuntimeError("Badly formed gPLink '%s'" % g)
79         ret.append({ 'dn' : d[0][8:], 'options' : int(d[1])})
80     return ret
81
82
83 class cmd_listall(Command):
84     """list all GPOs"""
85
86     synopsis = "%prog gpo listall"
87
88     takes_optiongroups = {
89         "sambaopts": options.SambaOptions,
90         "versionopts": options.VersionOptions,
91         "credopts": options.CredentialsOptions,
92     }
93
94     takes_options = [
95         Option("-H", help="LDB URL for database or target server", type=str)
96         ]
97
98     def run(self, H=None, sambaopts=None,
99             credopts=None, versionopts=None, server=None):
100
101         self.url = H
102         self.lp = sambaopts.get_loadparm()
103
104         self.creds = credopts.get_credentials(self.lp)
105         if not self.creds.authentication_requested():
106             self.creds.set_machine_account(self.lp)
107
108         samdb_connect(self)
109
110         policies_dn = self.samdb.get_default_basedn()
111         policies_dn.add_child(ldb.Dn(self.samdb, "CN=Policies,CN=System"))
112
113         gpo_flags = [
114             ("GPO_FLAG_USER_DISABLE", dsdb.GPO_FLAG_USER_DISABLE ),
115             ( "GPO_FLAG_MACHINE_DISABLE", dsdb.GPO_FLAG_MACHINE_DISABLE ) ]
116
117         msg = self.samdb.search(base=policies_dn, scope=ldb.SCOPE_ONELEVEL,
118                                 expression="(objectClass=groupPolicyContainer)",
119                                 attrs=['nTSecurityDescriptor', 'versionNumber', 'flags', 'name', 'displayName', 'gPCFileSysPath'])
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, 'version', '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_optiongroups = {
136         "sambaopts": options.SambaOptions,
137         "versionopts": options.VersionOptions,
138         "credopts": options.CredentialsOptions,
139     }
140
141     takes_args = [ 'username' ]
142
143     takes_options = [
144         Option("-H", help="LDB URL for database or target server", type=str)
145         ]
146
147     def run(self, username, H=None, sambaopts=None,
148             credopts=None, versionopts=None, server=None):
149
150         self.url = H
151         self.lp = sambaopts.get_loadparm()
152
153         self.creds = credopts.get_credentials(self.lp)
154         if not self.creds.authentication_requested():
155             self.creds.set_machine_account(self.lp)
156
157         samdb_connect(self)
158
159         try:
160             user_dn = self.samdb.search(expression='(&(samAccountName=%s)(objectclass=User))' % username)[0].dn
161         except Exception, estr:
162             raise CommandError("Failed to find user %s - %s" % (username, estr))
163
164         # check if its a computer account
165         try:
166             msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
167             is_computer = 'computer' in msg['objectClass']
168         except Exception, estr:
169             raise CommandError("Failed to find objectClass for user %s - %s" % (username, estr))
170
171         print("TODO: get user token")
172         # token = self.samdb.get_user_token(username)
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                     print("TODO: access checking")
189                     #if not samdb.access_check(secdesc, token, security.SEC_RIGHTS_FILE_READ):
190                     #    continue
191
192                     # check the flags on the GPO
193                     flags = int(attr_default(self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE, attrs=['flags'])[0], 'flags', 0))
194                     if is_computer and (flags & dsdb.GPO_FLAG_MACHINE_DISABLE):
195                         continue
196                     if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
197                         continue
198                     gpos.append(g)
199
200             # check if this blocks inheritance
201             gpoptions = int(attr_default(msg, 'gPOptions', 0))
202             if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
203                 inherit = False
204
205             if dn == self.samdb.get_default_basedn():
206                 break
207             dn = dn.parent()
208
209         print("GPO's for user %s" % username)
210         for g in gpos:
211             print("\t%s" % g['dn'])
212
213
214 class cmd_gpo(SuperCommand):
215     """GPO commands"""
216
217     subcommands = {}
218     subcommands["listall"] = cmd_listall()
219     subcommands["list"] = cmd_list()