python: Remove talloc_stackframe() held in an object
[nivanova/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         TALLOC_CTX *frame = NULL;
103
104         static const char *kwlist[] = {"cache_dir", NULL};
105         if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s", discard_const_p(char *, kwlist), &cache_dir)) {
106                 PyErr_SetString(PyExc_SystemError, "Failed to parse arguments to gpo_get_unix_path()");
107                 goto out;
108         }
109
110         if (!cache_dir) {
111                 cache_dir = cache_path(GPO_CACHE_DIR);
112                 if (!cache_dir) {
113                         PyErr_SetString(PyExc_MemoryError, "Failed to determine gpo cache dir");
114                         goto out;
115                 }
116         }
117
118         frame = talloc_stackframe();
119
120         status = gpo_get_unix_path(self->frame, cache_dir, self->gpo_ptr, &unix_path);
121
122         TALLOC_FREE(frame);
123
124         if (!NT_STATUS_IS_OK(status)) {
125                 PyErr_SetString(PyExc_SystemError, "Failed to determine gpo unix path");
126                 goto out;
127         }
128
129         ret = PyString_FromString(unix_path);
130
131 out:
132         return ret;
133 }
134
135 static PyMethodDef GPO_methods[] = {
136         {"get_unix_path", (PyCFunction)py_gpo_get_unix_path, METH_KEYWORDS, NULL },
137         {NULL}
138 };
139
140 static PyTypeObject GPOType;
141 static PyObject* py_gpo_iternext(GPO *self)
142 {
143         if (self->gpo_ptr && self->gpo_ptr->next) {
144                 self->gpo_ptr = self->gpo_ptr->next;
145                 return (PyObject *)self;
146         } else {
147                 self->gpo_ptr = self->head;
148                 PyErr_SetNone(PyExc_StopIteration);
149                 return NULL;
150         }
151 }
152
153 static PyObject* py_gpo_iter(PyObject *self)
154 {
155         Py_INCREF(self);
156         return self;
157 }
158
159 static PyTypeObject GPOType = {
160         .tp_name = "gpo.GROUP_POLICY_OBJECT",
161         .tp_basicsize = sizeof(GPO),
162         .tp_new = py_gpo_new,
163         .tp_free = PyObject_Del,
164         .tp_init = (initproc)py_gpo_init,
165         .tp_alloc = PyType_GenericAlloc,
166         .tp_dealloc = (destructor)py_gpo_dealloc,
167         .tp_doc = "GROUP_POLICY_OBJECT",
168         .tp_getset = GPO_setters,
169         .tp_methods = GPO_methods,
170         .tp_iter = py_gpo_iter,
171         .tp_iternext = (iternextfunc)py_gpo_iternext,
172         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER,
173 };
174
175 typedef struct {
176         PyObject_HEAD
177         ADS_STRUCT *ads_ptr;
178         struct cli_credentials *cli_creds;
179 } ADS;
180
181 static void py_ads_dealloc(ADS* self)
182 {
183         ads_destroy(&(self->ads_ptr));
184         Py_TYPE(self)->tp_free((PyObject*)self);
185 }
186
187 static PyObject* py_ads_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
188 {
189         ADS *self;
190         self = (ADS*)type->tp_alloc(type, 0);
191         return (PyObject*)self;
192 }
193
194 static PyObject* py_ads_connect(ADS *self);
195 static int py_ads_init(ADS *self, PyObject *args, PyObject *kwds)
196 {
197         const char *realm = NULL;
198         const char *workgroup = NULL;
199         const char *ldap_server = NULL;
200         PyObject *py_creds = NULL;
201         PyObject *lp_obj = NULL;
202         struct loadparm_context *lp_ctx = NULL;
203
204         static const char *kwlist[] = {"ldap_server", "loadparm_context", "credentials", NULL};
205         if (!PyArg_ParseTupleAndKeywords(args, kwds, "sO|O", discard_const_p(char *, kwlist), &ldap_server, &lp_obj, &py_creds))
206                 return -1;
207
208         if (py_creds) {
209                 if (!py_check_dcerpc_type(py_creds, "samba.credentials",
210                                           "Credentials")) {
211                         PyErr_Format(PyExc_TypeError,
212                                      "Expected samba.credentaials "
213                                      "for credentials argument");
214                         return -1;
215                 }
216                 self->cli_creds
217                         = PyCredentials_AsCliCredentials(py_creds);
218         }
219
220         if (lp_obj) {
221                 lp_ctx = pytalloc_get_type(lp_obj, struct loadparm_context);
222                 if (lp_ctx == NULL) {
223                         return -1;
224                 }
225         }
226         if (!lp_load_initial_only(lp_ctx->szConfigFile)) return -1;
227
228         if (self->cli_creds) {
229                 realm = cli_credentials_get_realm(self->cli_creds);
230                 workgroup = cli_credentials_get_domain(self->cli_creds);
231         } else {
232                 realm = lp_realm();
233                 workgroup = lp_workgroup();
234                 if (!ldap_server) return -1;
235         }
236
237         if ( !(self->ads_ptr = ads_init(realm, workgroup, ldap_server)) )
238                 return -1;
239
240         return 0;
241 }
242
243 static PyObject* py_ads_connect(ADS *self)
244 {
245         ADS_STATUS status;
246         TALLOC_CTX *frame = talloc_stackframe();
247         if (self->cli_creds) {
248                 self->ads_ptr->auth.user_name = SMB_STRDUP(cli_credentials_get_username(self->cli_creds));
249 self->ads_ptr->auth.flags |= ADS_AUTH_USER_CREDS;
250                 self->ads_ptr->auth.password = SMB_STRDUP(cli_credentials_get_password(self->cli_creds));
251                 self->ads_ptr->auth.realm = SMB_STRDUP(cli_credentials_get_realm(self->cli_creds));
252
253                 status = ads_connect_user_creds(self->ads_ptr);
254                 if (!ADS_ERR_OK(status)) {
255                         PyErr_SetString(PyExc_SystemError, "ads_connect() failed");
256                         TALLOC_FREE(frame);
257                         Py_RETURN_FALSE;
258                 }
259         } else {
260                 char *passwd;
261
262                 if (asprintf(&(self->ads_ptr->auth.user_name), "%s$", lp_netbios_name()) == -1) {
263                         PyErr_SetString(PyExc_SystemError, "Failed to asprintf");
264                         TALLOC_FREE(frame);
265                         Py_RETURN_FALSE;
266                 } else
267                         self->ads_ptr->auth.flags |= ADS_AUTH_USER_CREDS;
268                 if (!secrets_init()) {
269                         PyErr_SetString(PyExc_SystemError, "secrets_init() failed");
270                         TALLOC_FREE(frame);
271                         Py_RETURN_FALSE;
272                 }
273
274                 if (!(passwd = secrets_fetch_machine_password(self->ads_ptr->server.workgroup, NULL, NULL))) {
275                         PyErr_SetString(PyExc_SystemError, "Failed to fetch the machine account password");
276                         TALLOC_FREE(frame);
277                         Py_RETURN_FALSE;
278                 }
279                 self->ads_ptr->auth.password = smb_xstrdup(passwd);
280                 self->ads_ptr->auth.realm = smb_xstrdup(self->ads_ptr->server.realm);
281                 if (!strupper_m(self->ads_ptr->auth.realm)) {
282                         PyErr_SetString(PyExc_SystemError, "Failed to strdup");
283                         TALLOC_FREE(frame);
284                         Py_RETURN_FALSE;
285                 }
286
287                 status = ads_connect(self->ads_ptr);
288                 if (!ADS_ERR_OK(status)) {
289                         PyErr_SetString(PyExc_SystemError, "ads_connect() failed");
290                         TALLOC_FREE(frame);
291                         Py_RETURN_FALSE;
292                 }
293         }
294
295         TALLOC_FREE(frame);
296         Py_RETURN_TRUE;
297 }
298
299 /* Parameter mapping and functions for the GP_EXT struct */
300 void initgpo(void);
301
302 /* Global methods aka do not need a special pyobject type */
303 static PyObject *py_gpo_get_sysvol_gpt_version(PyObject * self, PyObject * args)
304 {
305         TALLOC_CTX *tmp_ctx = NULL;
306         char *unix_path;
307         char *display_name = NULL;
308         uint32_t sysvol_version = 0;
309         PyObject *result;
310         NTSTATUS status;
311
312         tmp_ctx = talloc_new(NULL);
313
314         if (!PyArg_ParseTuple(args, "s", &unix_path)) {
315                 return NULL;
316         }
317         status = gpo_get_sysvol_gpt_version(tmp_ctx, unix_path,
318                                             &sysvol_version,
319                                             &display_name);
320         if (!NT_STATUS_IS_OK(status)) {
321                 PyErr_SetNTSTATUS(status);
322                 TALLOC_FREE(tmp_ctx);
323                 return NULL;
324         }
325
326         talloc_free(tmp_ctx);
327         result = Py_BuildValue("[s,i]", display_name, sysvol_version);
328         return result;
329 }
330
331 static ADS_STATUS find_samaccount(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const char *samaccountname, uint32_t *uac_ret, const char **dn_ret)
332 {
333         ADS_STATUS status;
334         const char *attrs[] = { "userAccountControl", NULL };
335         const char *filter;
336         LDAPMessage *res = NULL;
337         char *dn = NULL;
338         uint32_t uac = 0;
339
340         filter = talloc_asprintf(mem_ctx, "(sAMAccountName=%s)", samaccountname);
341         if (filter == NULL) {
342                 status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
343                 goto out;
344         }
345
346         status = ads_do_search_all(ads, ads->config.bind_path, LDAP_SCOPE_SUBTREE, filter, attrs, &res);
347
348         if (!ADS_ERR_OK(status)) {
349                 goto out;
350         }
351
352         if (ads_count_replies(ads, res) != 1) {
353                 status = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
354                 goto out;
355         }
356
357         dn = ads_get_dn(ads, talloc_tos(), res);
358         if (dn == NULL) {
359                 status = ADS_ERROR(LDAP_NO_MEMORY);
360                 goto out;
361         }
362
363         if (!ads_pull_uint32(ads, res, "userAccountControl", &uac)) {
364                 status = ADS_ERROR(LDAP_NO_SUCH_ATTRIBUTE);
365                 goto out;
366         }
367
368         if (uac_ret) {
369                 *uac_ret = uac;
370         }
371
372         if (dn_ret) {
373                 *dn_ret = talloc_strdup(mem_ctx, dn);
374                 if (!*dn_ret) {
375                         status = ADS_ERROR(LDAP_NO_MEMORY);
376                         goto out;
377                 }
378         }
379 out:
380         TALLOC_FREE(dn);
381         ads_msgfree(ads, res);
382
383         return status;
384 }
385
386 static PyObject *py_ads_get_gpo_list(ADS *self, PyObject *args, PyObject *kwds)
387 {
388         TALLOC_CTX *frame = NULL;
389         struct GROUP_POLICY_OBJECT *gpo_list = NULL;
390         ADS_STATUS status;
391         const char *samaccountname = NULL;
392         const char *dn = NULL;
393         uint32_t uac = 0;
394         uint32_t flags = 0;
395         struct security_token *token = NULL;
396         PyObject *ret = Py_None;
397         TALLOC_CTX *gpo_ctx;
398
399         static const char *kwlist[] = {"samaccountname", NULL};
400         if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", discard_const_p(char *, kwlist), &samaccountname)) {
401                 PyErr_SetString(PyExc_SystemError, "Failed to parse arguments to py_ads_get_gpo_list()");
402                 goto out;
403         }
404
405         frame = talloc_stackframe();
406
407         status = find_samaccount(self->ads_ptr, frame, samaccountname, &uac, &dn);
408         if (!ADS_ERR_OK(status)) {
409                 TALLOC_FREE(frame);
410                 PyErr_SetString(PyExc_SystemError, "Failed to find samAccountName");
411                 goto out;
412         }
413
414         if (uac & UF_WORKSTATION_TRUST_ACCOUNT || uac & UF_SERVER_TRUST_ACCOUNT) {
415                 flags |= GPO_LIST_FLAG_MACHINE;
416                 status = gp_get_machine_token(self->ads_ptr, frame, dn, &token);
417         } else {
418                 status = ads_get_sid_token(self->ads_ptr, frame, dn, &token);
419         }
420         if (!ADS_ERR_OK(status)) {
421                 TALLOC_FREE(frame);
422                 PyErr_SetString(PyExc_SystemError, "Failed to get token");
423                 goto out;
424         }
425
426         gpo_ctx = talloc_new(NULL);
427         status = ads_get_gpo_list(self->ads_ptr, gpo_ctx, dn, flags, token, &gpo_list);
428         if (!ADS_ERR_OK(status)) {
429                 TALLOC_FREE(frame);
430                 PyErr_SetString(PyExc_SystemError, "Failed to fetch GPO list");
431                 goto out;
432         }
433
434         t_args = PyTuple_New(2);
435         PyTuple_SetItem(t_args, 0, PyCapsule_New(gpo_list, NULL, NULL));
436         PyTuple_SetItem(t_args, 1, PyCapsule_New(gpo_ctx, NULL, NULL));
437         ret = PyObject_CallObject((PyObject *)&GPOType, t_args);
438
439 out:
440         TALLOC_FREE(frame);
441         if (!ret) {
442                 PyErr_Print();
443                 return Py_None;
444         }
445         return ret;
446 }
447
448 static PyMethodDef ADS_methods[] = {
449         { "connect", (PyCFunction)py_ads_connect, METH_NOARGS, "Connect to the LDAP server" },
450         { "get_gpo_list", (PyCFunction)py_ads_get_gpo_list, METH_KEYWORDS, NULL },
451         { NULL }
452 };
453
454 static PyTypeObject ads_ADSType = {
455         .tp_name = "gpo.ADS_STRUCT",
456         .tp_basicsize = sizeof(ADS),
457         .tp_dealloc = (destructor)py_ads_dealloc,
458         .tp_flags = Py_TPFLAGS_DEFAULT,
459         .tp_doc = "ADS struct",
460         .tp_methods = ADS_methods,
461         .tp_init = (initproc)py_ads_init,
462         .tp_new = py_ads_new,
463 };
464
465 static PyMethodDef py_gpo_methods[] = {
466         {"gpo_get_sysvol_gpt_version", (PyCFunction) py_gpo_get_sysvol_gpt_version, METH_VARARGS, NULL},
467         {NULL}
468 };
469
470 /* Will be called by python when loading this module */
471 void initgpo(void)
472 {
473         PyObject *m;
474
475         debug_setup_talloc_log();
476         /* Instantiate the types */
477         m = Py_InitModule3("gpo", py_gpo_methods, "libgpo python bindings");
478         if (m == NULL) return;
479         PyModule_AddObject(m, "version", PyString_FromString(SAMBA_VERSION_STRING));
480         if (PyType_Ready(&ads_ADSType) < 0)
481                 return;
482         PyModule_AddObject(m, "ADS_STRUCT", (PyObject *)&ads_ADSType);
483         if (PyType_Ready(&GPOType) < 0)
484                 return;
485         PyModule_AddObject(m, "GROUP_POLICY_OBJECT", (PyObject *)&GPOType);
486 }