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