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