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