3 # implement samba_tool gpo commands
5 # Copyright Andrew Tridgell 2010
7 # based on C implementation by Guenther Deschner and Wilco Baan Hofman
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.
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.
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/>.
23 import samba.getopt as options
26 from samba.auth import system_session
27 from samba.netcmd import (
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
39 from samba.auth import AUTH_SESSION_INFO_DEFAULT_GROUPS, AUTH_SESSION_INFO_AUTHENTICATED, AUTH_SESSION_INFO_SIMPLE_PRIVILEGES
41 def samdb_connect(ctx):
42 '''make a ldap connection to the server'''
44 ctx.samdb = SamDB(url=ctx.url,
45 session_info=system_session(),
46 credentials=ctx.creds, lp=ctx.lp)
48 raise CommandError("LDAP connection to %s failed " % ctx.url, e)
51 def attr_default(msg, attrname, default):
52 '''get an attribute from a ldap msg with a default'''
54 return msg[attrname][0]
58 def flags_string(flags, value):
59 '''return a set of flags as a string'''
63 for (str, val) in flags:
68 ret += '0x%08x' % value
72 def parse_gplink(gplink):
73 '''parse a gPLink into an array of dn and options'''
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])})
86 class cmd_listall(Command):
89 synopsis = "%prog gpo listall"
91 takes_optiongroups = {
92 "sambaopts": options.SambaOptions,
93 "versionopts": options.VersionOptions,
94 "credopts": options.CredentialsOptions,
98 Option("-H", help="LDB URL for database or target server", type=str)
101 def run(self, H=None, sambaopts=None,
102 credopts=None, versionopts=None, server=None):
105 self.lp = sambaopts.get_loadparm()
107 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
111 policies_dn = self.samdb.get_default_basedn()
112 policies_dn.add_child(ldb.Dn(self.samdb, "CN=Policies,CN=System"))
115 ("GPO_FLAG_USER_DISABLE", dsdb.GPO_FLAG_USER_DISABLE ),
116 ( "GPO_FLAG_MACHINE_DISABLE", dsdb.GPO_FLAG_MACHINE_DISABLE ) ]
119 msg = self.samdb.search(base=policies_dn, scope=ldb.SCOPE_ONELEVEL,
120 expression="(objectClass=groupPolicyContainer)",
121 attrs=['nTSecurityDescriptor', 'versionNumber', 'flags', 'name', 'displayName', 'gPCFileSysPath'])
123 raise CommandError("Failed to list policies in %s" % policies_dn, e)
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, 'versionNumber', '0'))
130 print("flags : %s" % flags_string(gpo_flags, int(attr_default(m, 'flags', 0))))
134 class cmd_list(Command):
135 """list GPOs for a user"""
137 synopsis = "%prog gpo list <username>"
139 takes_optiongroups = {
140 "sambaopts": options.SambaOptions,
141 "versionopts": options.VersionOptions,
142 "credopts": options.CredentialsOptions,
145 takes_args = [ 'username' ]
148 Option("-H", help="LDB URL for database or target server", type=str)
151 def run(self, username, H=None, sambaopts=None,
152 credopts=None, versionopts=None, server=None):
155 self.lp = sambaopts.get_loadparm()
157 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
162 user_dn = self.samdb.search(expression='(&(samAccountName=%s)(objectclass=User))' % username)[0].dn
164 raise CommandError("Failed to find user %s" % username, e)
166 # check if its a computer account
168 msg = self.samdb.search(base=user_dn, scope=ldb.SCOPE_BASE, attrs=['objectClass'])[0]
169 is_computer = 'computer' in msg['objectClass']
171 raise CommandError("Failed to find objectClass for user %s" % username, e)
173 session_info_flags = ( AUTH_SESSION_INFO_DEFAULT_GROUPS |
174 AUTH_SESSION_INFO_AUTHENTICATED )
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
180 session = samba.auth.user_session(self.samdb, lp_ctx=self.lp, dn=user_dn,
181 session_info_flags=session_info_flags)
183 token = session.security_token
188 dn = ldb.Dn(self.samdb, str(user_dn)).parent()
190 msg = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=['gPLink', 'gPOptions'])[0]
192 glist = parse_gplink(msg['gPLink'][0])
194 if not inherit and not (g['options'] & dsdb.GPLINK_OPT_ENFORCE):
196 if g['options'] & dsdb.GPLINK_OPT_DISABLE:
200 gmsg = self.samdb.search(base=g['dn'], scope=ldb.SCOPE_BASE,
201 attrs=['flags', 'ntSecurityDescriptor'])
203 print "Failed to fetch gpo object %s" % g['dn']
206 secdesc_ndr = gmsg[0]['ntSecurityDescriptor'][0]
207 secdesc = ndr_unpack(dcerpc.security.descriptor, secdesc_ndr)
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)
215 print "Failed access check on %s" % msg.dn
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):
222 if not is_computer and (flags & dsdb.GPO_FLAG_USER_DISABLE):
226 # check if this blocks inheritance
227 gpoptions = int(attr_default(msg, 'gPOptions', 0))
228 if gpoptions & dsdb.GPO_BLOCK_INHERITANCE:
231 if dn == self.samdb.get_default_basedn():
235 print("GPO's for user %s" % username)
237 print("\t%s" % g['dn'])
240 class cmd_gpo(SuperCommand):
244 subcommands["listall"] = cmd_listall()
245 subcommands["list"] = cmd_list()