libgpo: Setup the stack frame in ads_connect
[vlendec/samba-autobuild/.git] / libgpo / pygpo.c
1 /*
2    Unix SMB/CIFS implementation.
3    Copyright (C) Luke Morrison <luc785@hotmail.com> 2013
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <Python.h>
20 #include "includes.h"
21 #include "version.h"
22 #include "param/pyparam.h"
23 #include "gpo.h"
24 #include "ads.h"
25 #include "secrets.h"
26 #include "../libds/common/flags.h"
27 #include "librpc/rpc/pyrpc_util.h"
28 #include "auth/credentials/pycredentials.h"
29 #include "libcli/util/pyerrors.h"
30
31 /* A Python C API module to use LIBGPO */
32
33 typedef struct {
34         PyObject_HEAD
35         TALLOC_CTX *frame;
36         struct GROUP_POLICY_OBJECT *gpo_ptr;
37         struct GROUP_POLICY_OBJECT *head;
38 } GPO;
39
40 static void py_gpo_dealloc(GPO* self)
41 {
42         talloc_free(self->frame);
43         Py_TYPE(self)->tp_free((PyObject*)self);
44 }
45
46 static PyObject* py_gpo_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
47 {
48         GPO *self;
49         PyObject *c_obj;
50         PyObject *talloc_obj;
51         static const char *kwlist[] = {"gpo_ptr", "talloc_ctx", NULL};
52         self = (GPO*)type->tp_alloc(type, 0);
53         if (PyArg_ParseTupleAndKeywords(args, kwds, "|OO", discard_const_p(char *, kwlist),
54                                         &c_obj, &talloc_obj)) {
55                 self->gpo_ptr = PyCapsule_GetPointer(c_obj, NULL);
56                 self->head = self->gpo_ptr;
57                 self->frame = PyCapsule_GetPointer(talloc_obj, NULL);
58         } else
59                 self->gpo_ptr = NULL;
60                 self->frame = NULL;
61         return (PyObject*)self;
62 }
63
64 static int py_gpo_init(GPO *self, PyObject *args, PyObject *kwds)
65 {
66         return 0;
67 }
68
69 #define GPO_getter(ATTR) \
70 static PyObject* GPO_get_##ATTR(GPO *self, void *closure) \
71 { \
72         if (self->gpo_ptr->ATTR) \
73                 return PyString_FromString(self->gpo_ptr->ATTR); \
74         else \
75                 return Py_None; \
76 }
77 GPO_getter(ds_path)
78 GPO_getter(file_sys_path)
79 GPO_getter(display_name)
80 GPO_getter(name)
81 GPO_getter(link)
82 GPO_getter(user_extensions)
83 GPO_getter(machine_extensions)
84
85 static PyGetSetDef GPO_setters[] = {
86         {discard_const_p(char, "ds_path"), (getter)GPO_get_ds_path, NULL, NULL, NULL},
87         {discard_const_p(char, "file_sys_path"), (getter)GPO_get_file_sys_path, NULL, NULL, NULL},
88         {discard_const_p(char, "display_name"), (getter)GPO_get_display_name, NULL, NULL, NULL},
89         {discard_const_p(char, "name"), (getter)GPO_get_name, NULL, NULL, NULL},
90         {discard_const_p(char, "link"), (getter)GPO_get_link, NULL, NULL, NULL},
91         {discard_const_p(char, "user_extensions"), (getter)GPO_get_user_extensions, NULL, NULL, NULL},
92         {discard_const_p(char, "machine_extensions"), (getter)GPO_get_machine_extensions, NULL, NULL, NULL},
93         {NULL}
94 };
95
96 static PyObject *py_gpo_get_unix_path(GPO *self, PyObject *args, PyObject *kwds)
97 {
98         NTSTATUS status;
99         const char *cache_dir = NULL;
100         PyObject *ret = Py_None;
101         char *unix_path = NULL;
102
103         static const char *kwlist[] = {"cache_dir", NULL};
104         if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s", discard_const_p(char *, kwlist), &cache_dir)) {
105                 PyErr_SetString(PyExc_SystemError, "Failed to parse arguments to gpo_get_unix_path()");
106                 goto out;
107         }
108
109         if (!cache_dir) {
110                 cache_dir = cache_path(GPO_CACHE_DIR);
111                 if (!cache_dir) {
112                         PyErr_SetString(PyExc_MemoryError, "Failed to determine gpo cache dir");
113                         goto out;
114                 }
115         }
116
117         status = gpo_get_unix_path(self->frame, cache_dir, self->gpo_ptr, &unix_path);
118         if (!NT_STATUS_IS_OK(status)) {
119                 PyErr_SetString(PyExc_SystemError, "Failed to determine gpo unix path");
120                 goto out;
121         }
122
123         ret = PyString_FromString(unix_path);
124
125 out:
126         return ret;
127 }
128
129 static PyMethodDef GPO_methods[] = {
130         {"get_unix_path", (PyCFunction)py_gpo_get_unix_path, METH_KEYWORDS, NULL },
131         {NULL}
132 };
133
134 static PyTypeObject GPOType;
135 static PyObject* py_gpo_iternext(GPO *self)
136 {
137         if (self->gpo_ptr && self->gpo_ptr->next) {
138                 self->gpo_ptr = self->gpo_ptr->next;
139                 return (PyObject *)self;
140         } else {
141                 self->gpo_ptr = self->head;
142                 PyErr_SetNone(PyExc_StopIteration);
143                 return NULL;
144         }
145 }
146
147 static PyObject* py_gpo_iter(PyObject *self)
148 {
149         Py_INCREF(self);
150         return self;
151 }
152
153 static PyTypeObject GPOType = {
154         .tp_name = "gpo.GROUP_POLICY_OBJECT",
155         .tp_basicsize = sizeof(GPO),
156         .tp_new = py_gpo_new,
157         .tp_free = PyObject_Del,
158         .tp_init = (initproc)py_gpo_init,
159         .tp_alloc = PyType_GenericAlloc,
160         .tp_dealloc = (destructor)py_gpo_dealloc,
161         .tp_doc = "GROUP_POLICY_OBJECT",
162         .tp_getset = GPO_setters,
163         .tp_methods = GPO_methods,
164         .tp_iter = py_gpo_iter,
165         .tp_iternext = (iternextfunc)py_gpo_iternext,
166         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER,
167 };
168
169 typedef struct {
170         PyObject_HEAD
171         TALLOC_CTX *frame;
172         ADS_STRUCT *ads_ptr;
173         struct cli_credentials *cli_creds;
174 } ADS;
175
176 static void py_ads_dealloc(ADS* self)
177 {
178         ads_destroy(&(self->ads_ptr));
179         talloc_free(self->frame);
180         Py_TYPE(self)->tp_free((PyObject*)self);
181 }
182
183 static PyObject* py_ads_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
184 {
185         ADS *self;
186         self = (ADS*)type->tp_alloc(type, 0);
187         return (PyObject*)self;
188 }
189
190 static PyObject* py_ads_connect(ADS *self);
191 static int py_ads_init(ADS *self, PyObject *args, PyObject *kwds)
192 {
193         const char *realm = NULL;
194         const char *workgroup = NULL;
195         const char *ldap_server = NULL;
196         PyObject *py_creds = NULL;
197         PyObject *lp_obj = NULL;
198         struct loadparm_context *lp_ctx = NULL;
199
200         static const char *kwlist[] = {"ldap_server", "loadparm_context", "credentials", NULL};
201         if (!PyArg_ParseTupleAndKeywords(args, kwds, "sO|O", discard_const_p(char *, kwlist), &ldap_server, &lp_obj, &py_creds))
202                 return -1;
203
204         self->frame = talloc_stackframe();
205
206         if (py_creds) {
207                 if (!py_check_dcerpc_type(py_creds, "samba.credentials",
208                                           "Credentials")) {
209                         PyErr_Format(PyExc_TypeError,
210                                      "Expected samba.credentaials "
211                                      "for credentials argument");
212                         return -1;
213                 }
214                 self->cli_creds
215                         = PyCredentials_AsCliCredentials(py_creds);
216         }
217
218         if (lp_obj) {
219                 lp_ctx = pytalloc_get_type(lp_obj, struct loadparm_context);
220                 if (lp_ctx == NULL) {
221                         return -1;
222                 }
223         }
224         if (!lp_load_initial_only(lp_ctx->szConfigFile)) return -1;
225
226         if (self->cli_creds) {
227                 realm = cli_credentials_get_realm(self->cli_creds);
228                 workgroup = cli_credentials_get_domain(self->cli_creds);
229         } else {
230                 realm = lp_realm();
231                 workgroup = lp_workgroup();
232                 if (!ldap_server) return -1;
233         }
234
235         if ( !(self->ads_ptr = ads_init(realm, workgroup, ldap_server)) )
236                 return -1;
237
238         return 0;
239 }
240
241 static PyObject* py_ads_connect(ADS *self)
242 {
243         ADS_STATUS status;
244         TALLOC_CTX *frame = talloc_stackframe();
245         if (self->cli_creds) {
246                 self->ads_ptr->auth.user_name = SMB_STRDUP(cli_credentials_get_username(self->cli_creds));
247 self->ads_ptr->auth.flags |= ADS_AUTH_USER_CREDS;
248                 self->ads_ptr->auth.password = SMB_STRDUP(cli_credentials_get_password(self->cli_creds));
249                 self->ads_ptr->auth.realm = SMB_STRDUP(cli_credentials_get_realm(self->cli_creds));
250
251                 status = ads_connect_user_creds(self->ads_ptr);
252                 if (!ADS_ERR_OK(status)) {
253                         PyErr_SetString(PyExc_SystemError, "ads_connect() failed");
254                         TALLOC_FREE(frame);
255                         Py_RETURN_FALSE;
256                 }
257         } else {
258                 char *passwd;
259
260                 if (asprintf(&(self->ads_ptr->auth.user_name), "%s$", lp_netbios_name()) == -1) {
261                         PyErr_SetString(PyExc_SystemError, "Failed to asprintf");
262                         TALLOC_FREE(frame);
263                         Py_RETURN_FALSE;
264                 } else
265                         self->ads_ptr->auth.flags |= ADS_AUTH_USER_CREDS;
266                 if (!secrets_init()) {
267                         PyErr_SetString(PyExc_SystemError, "secrets_init() failed");
268                         TALLOC_FREE(frame);
269                         Py_RETURN_FALSE;
270                 }
271
272                 if (!(passwd = secrets_fetch_machine_password(self->ads_ptr->server.workgroup, NULL, NULL))) {
273                         PyErr_SetString(PyExc_SystemError, "Failed to fetch the machine account password");
274                         TALLOC_FREE(frame);
275                         Py_RETURN_FALSE;
276                 }
277                 self->ads_ptr->auth.password = smb_xstrdup(passwd);
278                 self->ads_ptr->auth.realm = smb_xstrdup(self->ads_ptr->server.realm);
279                 if (!strupper_m(self->ads_ptr->auth.realm)) {
280                         PyErr_SetString(PyExc_SystemError, "Failed to strdup");
281                         TALLOC_FREE(frame);
282                         Py_RETURN_FALSE;
283                 }
284
285                 status = ads_connect(self->ads_ptr);
286                 if (!ADS_ERR_OK(status)) {
287                         PyErr_SetString(PyExc_SystemError, "ads_connect() failed");
288                         TALLOC_FREE(frame);
289                         Py_RETURN_FALSE;
290                 }
291         }
292
293         TALLOC_FREE(frame);
294         Py_RETURN_TRUE;
295 }
296
297 /* Parameter mapping and functions for the GP_EXT struct */
298 void initgpo(void);
299
300 /* Global methods aka do not need a special pyobject type */
301 static PyObject *py_gpo_get_sysvol_gpt_version(PyObject * self, PyObject * args)
302 {
303         TALLOC_CTX *tmp_ctx = NULL;
304         char *unix_path;
305         char *display_name = NULL;
306         uint32_t sysvol_version = 0;
307         PyObject *result;
308         NTSTATUS status;
309
310         tmp_ctx = talloc_new(NULL);
311
312         if (!PyArg_ParseTuple(args, "s", &unix_path)) {
313                 return NULL;
314         }
315         status = gpo_get_sysvol_gpt_version(tmp_ctx, unix_path,
316                                             &sysvol_version,
317                                             &display_name);
318         if (!NT_STATUS_IS_OK(status)) {
319                 PyErr_SetNTSTATUS(status);
320                 TALLOC_FREE(tmp_ctx);
321                 return NULL;
322         }
323
324         talloc_free(tmp_ctx);
325         result = Py_BuildValue("[s,i]", display_name, sysvol_version);
326         return result;
327 }
328
329 static ADS_STATUS find_samaccount(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const char *samaccountname, uint32_t *uac_ret, const char **dn_ret)
330 {
331         ADS_STATUS status;
332         const char *attrs[] = { "userAccountControl", NULL };
333         const char *filter;
334         LDAPMessage *res = NULL;
335         char *dn = NULL;
336         uint32_t uac = 0;
337
338         filter = talloc_asprintf(mem_ctx, "(sAMAccountName=%s)", samaccountname);
339         if (filter == NULL) {
340                 status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
341                 goto out;
342         }
343
344         status = ads_do_search_all(ads, ads->config.bind_path, LDAP_SCOPE_SUBTREE, filter, attrs, &res);
345
346         if (!ADS_ERR_OK(status)) {
347                 goto out;
348         }
349
350         if (ads_count_replies(ads, res) != 1) {
351                 status = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
352                 goto out;
353         }
354
355         dn = ads_get_dn(ads, talloc_tos(), res);
356         if (dn == NULL) {
357                 status = ADS_ERROR(LDAP_NO_MEMORY);
358                 goto out;
359         }
360
361         if (!ads_pull_uint32(ads, res, "userAccountControl", &uac)) {
362                 status = ADS_ERROR(LDAP_NO_SUCH_ATTRIBUTE);
363                 goto out;
364         }
365
366         if (uac_ret) {
367                 *uac_ret = uac;
368         }
369
370         if (dn_ret) {
371                 *dn_ret = talloc_strdup(mem_ctx, dn);
372                 if (!*dn_ret) {
373                         status = ADS_ERROR(LDAP_NO_MEMORY);
374                         goto out;
375                 }
376         }
377 out:
378         TALLOC_FREE(dn);
379         ads_msgfree(ads, res);
380
381         return status;
382 }
383
384 static PyObject *py_ads_get_gpo_list(ADS *self, PyObject *args, PyObject *kwds)
385 {
386         TALLOC_CTX *mem_ctx = NULL;
387         struct GROUP_POLICY_OBJECT *gpo_list = NULL;
388         ADS_STATUS status;
389         const char *samaccountname = NULL;
390         const char *dn = NULL;
391         uint32_t uac = 0;
392         uint32_t flags = 0;
393         struct security_token *token = NULL;
394         PyObject *ret = Py_None;
395         TALLOC_CTX *gpo_ctx;
396         PyObject * t_args;
397
398         static const char *kwlist[] = {"samaccountname", NULL};
399         if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", discard_const_p(char *, kwlist), &samaccountname)) {
400                 PyErr_SetString(PyExc_SystemError, "Failed to parse arguments to py_ads_get_gpo_list()");
401                 goto out;
402         }
403
404         mem_ctx = talloc_new(self->frame);
405
406         status = find_samaccount(self->ads_ptr, mem_ctx, samaccountname, &uac, &dn);
407         if (!ADS_ERR_OK(status)) {
408                 PyErr_SetString(PyExc_SystemError, "Failed to find samAccountName");
409                 goto out;
410         }
411
412         if (uac & UF_WORKSTATION_TRUST_ACCOUNT || uac & UF_SERVER_TRUST_ACCOUNT) {
413                 flags |= GPO_LIST_FLAG_MACHINE;
414                 status = gp_get_machine_token(self->ads_ptr, mem_ctx, dn, &token);
415         } else {
416                 status = ads_get_sid_token(self->ads_ptr, mem_ctx, dn, &token);
417         }
418         if (!ADS_ERR_OK(status)) {
419                 PyErr_SetString(PyExc_SystemError, "Failed to get token");
420                 goto out;
421         }
422
423         gpo_ctx = talloc_new(NULL);
424         status = ads_get_gpo_list(self->ads_ptr, gpo_ctx, dn, flags, token, &gpo_list);
425         if (!ADS_ERR_OK(status)) {
426                 PyErr_SetString(PyExc_SystemError, "Failed to fetch GPO list");
427                 goto out;
428         }
429
430         t_args = PyTuple_New(2);
431         PyTuple_SetItem(t_args, 0, PyCapsule_New(gpo_list, NULL, NULL));
432         PyTuple_SetItem(t_args, 1, PyCapsule_New(gpo_ctx, NULL, NULL));
433         ret = PyObject_CallObject((PyObject *)&GPOType, t_args);
434
435 out:
436         talloc_free(mem_ctx);
437         if (!ret) {
438                 PyErr_Print();
439                 return Py_None;
440         }
441         return ret;
442 }
443
444 static PyMethodDef ADS_methods[] = {
445         { "connect", (PyCFunction)py_ads_connect, METH_NOARGS, "Connect to the LDAP server" },
446         { "get_gpo_list", (PyCFunction)py_ads_get_gpo_list, METH_KEYWORDS, NULL },
447         { NULL }
448 };
449
450 static PyTypeObject ads_ADSType = {
451         .tp_name = "gpo.ADS_STRUCT",
452         .tp_basicsize = sizeof(ADS),
453         .tp_dealloc = (destructor)py_ads_dealloc,
454         .tp_flags = Py_TPFLAGS_DEFAULT,
455         .tp_doc = "ADS struct",
456         .tp_methods = ADS_methods,
457         .tp_init = (initproc)py_ads_init,
458         .tp_new = py_ads_new,
459 };
460
461 static PyMethodDef py_gpo_methods[] = {
462         {"gpo_get_sysvol_gpt_version", (PyCFunction) py_gpo_get_sysvol_gpt_version, METH_VARARGS, NULL},
463         {NULL}
464 };
465
466 /* Will be called by python when loading this module */
467 void initgpo(void)
468 {
469         PyObject *m;
470
471         debug_setup_talloc_log();
472         /* Instantiate the types */
473         m = Py_InitModule3("gpo", py_gpo_methods, "libgpo python bindings");
474         if (m == NULL) return;
475         PyModule_AddObject(m, "version", PyString_FromString(SAMBA_VERSION_STRING));
476         if (PyType_Ready(&ads_ADSType) < 0)
477                 return;
478         PyModule_AddObject(m, "ADS_STRUCT", (PyObject *)&ads_ADSType);
479         if (PyType_Ready(&GPOType) < 0)
480                 return;
481         PyModule_AddObject(m, "GROUP_POLICY_OBJECT", (PyObject *)&GPOType);
482 }