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