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