WHATSNEW: Up to Samba 4.16.0rc1.
[Samba.git] / libgpo / pygpo.c
blobb5ec85a48d41258a0c400f0c8b6578ffc46fd4f3
1 /*
2 Unix SMB/CIFS implementation.
3 Copyright (C) Luke Morrison <luc785@hotmail.com> 2013
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.
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.
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/>.
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"
33 /* A Python C API module to use LIBGPO */
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); \
41 if (gpo_ptr->ATTR) \
42 return PyUnicode_FromString(gpo_ptr->ATTR); \
43 else \
44 Py_RETURN_NONE; \
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)
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 {0}
73 static PyObject *py_gpo_get_unix_path(PyObject *self, PyObject *args,
74 PyObject *kwds)
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);
85 frame = talloc_stackframe();
87 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s",
88 discard_const_p(char *, kwlist),
89 &cache_dir)) {
90 goto out;
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;
102 status = gpo_get_unix_path(frame, cache_dir, gpo_ptr, &unix_path);
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;
111 ret = PyUnicode_FromString(unix_path);
113 out:
114 TALLOC_FREE(frame);
115 return ret;
118 static PyMethodDef GPO_methods[] = {
119 {"get_unix_path", PY_DISCARD_FUNC_SIG(PyCFunction,
120 py_gpo_get_unix_path),
121 METH_VARARGS | METH_KEYWORDS,
122 NULL },
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,
135 typedef struct {
136 PyObject_HEAD
137 ADS_STRUCT *ads_ptr;
138 PyObject *py_creds;
139 struct cli_credentials *cli_creds;
140 } ADS;
142 static void py_ads_dealloc(ADS* self)
144 ads_destroy(&(self->ads_ptr));
145 Py_CLEAR(self->py_creds);
146 Py_TYPE(self)->tp_free((PyObject*)self);
149 static PyObject* py_ads_connect(ADS *self, PyObject *Py_UNUSED(ignored));
150 static int py_ads_init(ADS *self, PyObject *args, PyObject *kwds)
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;
160 static const char *kwlist[] = {
161 "ldap_server", "loadparm_context", "credentials", NULL
163 if (!PyArg_ParseTupleAndKeywords(args, kwds, "sO|O",
164 discard_const_p(char *, kwlist),
165 &ldap_server, &lp_obj, &py_creds)) {
166 return -1;
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);
174 if (self->py_creds) {
175 ok = py_check_dcerpc_type(self->py_creds, "samba.credentials",
176 "Credentials");
177 if (!ok) {
178 return -1;
180 self->cli_creds
181 = PyCredentials_AsCliCredentials(self->py_creds);
184 ok = py_check_dcerpc_type(lp_obj, "samba.param", "LoadParm");
185 if (!ok) {
186 return -1;
188 lp_ctx = pytalloc_get_type(lp_obj, struct loadparm_context);
189 if (lp_ctx == NULL) {
190 return -1;
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;
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();
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;
212 /* always succeeds or crashes */
213 self->ads_ptr = ads_init(realm, workgroup, ldap_server, ADS_SASL_PLAIN);
215 return 0;
218 /* connect. Failure to connect results in an Exception */
219 static PyObject* py_ads_connect(ADS *self,
220 PyObject *Py_UNUSED(ignored))
222 ADS_STATUS status;
223 TALLOC_CTX *frame = talloc_stackframe();
224 if (!self->ads_ptr) {
225 PyErr_SetString(PyExc_RuntimeError, "Uninitialized");
226 return NULL;
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;
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;
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;
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;
271 self->ads_ptr->auth.flags |= ADS_AUTH_USER_CREDS;
272 status = ads_connect(self->ads_ptr);
274 if (!ADS_ERR_OK(status)) {
275 PyErr_Format(PyExc_RuntimeError,
276 "ads_connect() failed: %s",
277 ads_errstr(status));
278 goto err;
281 TALLOC_FREE(frame);
282 Py_RETURN_TRUE;
284 err:
285 TALLOC_FREE(frame);
286 return NULL;
289 /* Parameter mapping and functions for the GP_EXT struct */
290 void initgpo(void);
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)
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;
303 if (!PyArg_ParseTuple(args, "s", &unix_path)) {
304 return NULL;
306 tmp_ctx = talloc_new(NULL);
307 if (!tmp_ctx) {
308 return PyErr_NoMemory();
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;
319 result = Py_BuildValue("[s,i]", display_name, sysvol_version);
320 talloc_free(tmp_ctx);
321 return result;
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)
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;
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;
343 status = ads_do_search_all(ads, ads->config.bind_path,
344 LDAP_SCOPE_SUBTREE, filter, attrs, &res);
346 if (!ADS_ERR_OK(status)) {
347 goto out;
350 if (ads_count_replies(ads, res) != 1) {
351 status = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
352 goto out;
355 dn = ads_get_dn(ads, talloc_tos(), res);
356 if (dn == NULL) {
357 status = ADS_ERROR(LDAP_NO_MEMORY);
358 goto out;
361 if (!ads_pull_uint32(ads, res, "userAccountControl", &uac)) {
362 status = ADS_ERROR(LDAP_NO_SUCH_ATTRIBUTE);
363 goto out;
366 if (uac_ret) {
367 *uac_ret = uac;
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;
377 out:
378 TALLOC_FREE(dn);
379 ads_msgfree(ads, res);
381 return status;
384 static PyObject *py_ads_get_gpo_list(ADS *self, PyObject *args, PyObject *kwds)
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;
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;
405 if (!self->ads_ptr) {
406 PyErr_SetString(PyExc_RuntimeError, "Uninitialized");
407 return NULL;
410 frame = talloc_stackframe();
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;
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;
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;
442 gpo_ctx = talloc_new(frame);
443 if (!gpo_ctx) {
444 PyErr_NoMemory();
445 goto out;
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;
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++;
462 i = 0;
463 ret = PyList_New(list_size);
464 if (ret == NULL) {
465 goto out;
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;
476 PyList_SetItem(ret, i, obj);
477 i++;
480 out:
481 TALLOC_FREE(frame);
482 return ret;
485 #endif
487 static PyMethodDef ADS_methods[] = {
488 { "connect", (PyCFunction)py_ads_connect, METH_NOARGS,
489 "Connect to the LDAP server" },
490 #ifdef HAVE_ADS
491 { "get_gpo_list", PY_DISCARD_FUNC_SIG(PyCFunction, py_ads_get_gpo_list),
492 METH_VARARGS | METH_KEYWORDS,
493 NULL },
494 #endif
498 static PyTypeObject ads_ADSType = {
499 .tp_name = "gpo.ADS_STRUCT",
500 .tp_basicsize = sizeof(ADS),
501 .tp_dealloc = (destructor)py_ads_dealloc,
502 .tp_flags = Py_TPFLAGS_DEFAULT,
503 .tp_doc = "ADS struct",
504 .tp_methods = ADS_methods,
505 .tp_init = (initproc)py_ads_init,
508 static PyMethodDef py_gpo_methods[] = {
509 {"gpo_get_sysvol_gpt_version",
510 (PyCFunction)py_gpo_get_sysvol_gpt_version,
511 METH_VARARGS, NULL},
515 static struct PyModuleDef moduledef = {
516 PyModuleDef_HEAD_INIT,
517 .m_name = "gpo",
518 .m_doc = "libgpo python bindings",
519 .m_size = -1,
520 .m_methods = py_gpo_methods,
523 /* Will be called by python when loading this module */
524 void initgpo(void);
526 MODULE_INIT_FUNC(gpo)
528 PyObject *m;
530 debug_setup_talloc_log();
532 /* Instantiate the types */
533 m = PyModule_Create(&moduledef);
534 if (m == NULL) {
535 goto err;
538 if (PyModule_AddObject(m, "version",
539 PyUnicode_FromString(SAMBA_VERSION_STRING)) ) {
540 goto err;
543 ads_ADSType.tp_new = PyType_GenericNew;
544 if (PyType_Ready(&ads_ADSType) < 0) {
545 goto err;
548 Py_INCREF(&ads_ADSType);
549 if (PyModule_AddObject(m, "ADS_STRUCT", (PyObject *)&ads_ADSType)) {
550 goto err;
553 if (pytalloc_BaseObject_PyType_Ready(&GPOType) < 0) {
554 goto err;
557 Py_INCREF((PyObject *)(void *)&GPOType);
558 if (PyModule_AddObject(m, "GROUP_POLICY_OBJECT",
559 (PyObject *)&GPOType)) {
560 goto err;
562 return m;
564 err:
565 Py_CLEAR(m);
566 return NULL;