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