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