3 # implement samba_tool gpo commands
5 # Copyright Andrew Tridgell 2010
6 # Copyright Giampaolo Lauria 2011 <lauria2@yahoo.com>
8 # based on C implementation by Guenther Deschner and Wilco Baan Hofman
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.
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.
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/>.
24 import samba.getopt as options
27 from samba.auth import system_session
28 from samba.netcmd import (
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
40 from samba.auth import AUTH_SESSION_INFO_DEFAULT_GROUPS, AUTH_SESSION_INFO_AUTHENTICATED, AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
42 def samdb_connect(ctx):
43 '''make a ldap connection to the server'''
45 ctx.samdb = SamDB(url=ctx.url,
46 session_info=system_session(),
47 credentials=ctx.creds, lp=ctx.lp)
49 raise CommandError("LDAP connection to %s failed " % ctx.url, e)
52 def attr_default(msg, attrname, default):
53 '''get an attribute from a ldap msg with a default'''
55 return msg[attrname][0]
59 def flags_string(flags, value):
60 '''return a set of flags as a string'''
64 for (str, val) in flags:
69 ret += '0x%08x' % value
73 def parse_gplink(gplink):
74 '''parse a gPLink into an array of dn and options'''
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])})
87 class cmd_listall(Command):
90 synopsis = "%prog gpo listall"
93 Option("-H", help="LDB URL for database or target server", type=str)
96 def run(self, H=None, sambaopts=None,
97 credopts=None, versionopts=None, server=None):
100 self.lp = sambaopts.get_loadparm()
102 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
106 policies_dn = self.samdb.get_default_basedn()
107 policies_dn.add_child(ldb.Dn(self.samdb, "CN=Policies,CN=System"))
110 ("GPO_FLAG_USER_DISABLE", dsdb.GPO_FLAG_USER_DISABLE ),
111 ( "GPO_FLAG_MACHINE_DISABLE", dsdb.GPO_FLAG_MACHINE_DISABLE ) ]
114 msg = self.samdb.search(base=policies_dn, scope=ldb.SCOPE_ONELEVEL,
115 expression="(objectClass=groupPolicyContainer)",
116 attrs=['nTSecurityDescriptor', 'versionNumber', 'flags', 'name', 'displayName', 'gPCFileSysPath'])
118 raise CommandError("Failed to list policies in %s" % policies_dn, e)
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))))
129 class cmd_list(Command):
130 """list GPOs for a user"""
132 synopsis = "%prog gpo list <username>"
134 takes_args = [ 'username' ]
137 Option("-H", help="LDB URL for database or target server", type=str)
140 def run(self, username, H=None, sambaopts=None,
141 credopts=None, versionopts=None, server=None):
144 self.lp = sambaopts.get_loadparm()
146 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
151 user_dn = self.samdb.search(expression='(&(samAccountName=%s)(objectclass=User))' % username)[0].dn
153 raise CommandError("Failed to find user %s" % username, e)
155 # check if its a computer account
157 msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
158 is_computer = 'computer' in msg['objectClass']
160 raise CommandError("Failed to find objectClass for user %s" % username, e)
162 session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS |
163 AUTH_SESSION_INFO_AUTHENTICATED )
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
169 session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
170 session_info_flags=session_info_flags)
172 token = session.security_token
177 dn = ldb.Dn(self.samdb, str(user_dn)).parent()
179 msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
181 glist = parse_gplink(msg['gPLink'][0])
183 if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
185 if g['options'] & dsdb.GPLINK_OPT_DISABLE:
189 gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
190 attrs=['flags', 'ntSecurityDescriptor'])
192 print "Failed to fetch gpo object %s" % g['dn']
195 secdesc_ndr = gmsg[0]['ntSecurityDescriptor'][0]
196 secdesc = ndr_unpack(dcerpc.security.descriptor, secdesc_ndr)
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)
204 print "Failed access check on %s" % msg.dn
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):
211 if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
215 # check if this blocks inheritance
216 gpoptions = int(attr_default(msg, 'gPOptions', 0))
217 if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
220 if dn == self.samdb.get_default_basedn():
224 print("GPO's for user %s" % username)
226 print("\t%s" % g['dn'])
229 class cmd_gpo(SuperCommand):
233 subcommands["listall"] = cmd_listall()
234 subcommands["list"] = cmd_list()