python: samba.dcerpc: Port RPC related stuff to Python 3
[sfrench/samba-autobuild/.git] / source4 / librpc / rpc / pyrpc.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <Python.h>
21 #include "python/py3compat.h"
22 #include "includes.h"
23 #include <structmember.h>
24 #include "librpc/rpc/pyrpc.h"
25 #include "lib/events/events.h"
26 #include "param/pyparam.h"
27 #include "librpc/rpc/dcerpc.h"
28 #include "librpc/rpc/pyrpc_util.h"
29 #include "auth/credentials/pycredentials.h"
30 #include "auth/gensec/gensec.h"
31
32 void initbase(void);
33
34 static PyTypeObject dcerpc_InterfaceType;
35
36 static PyTypeObject *ndr_syntax_id_Type;
37
38 static bool PyString_AsGUID(PyObject *object, struct GUID *uuid)
39 {
40         NTSTATUS status;
41         status = GUID_from_string(PyStr_AsString(object), uuid);
42         if (NT_STATUS_IS_ERR(status)) {
43                 PyErr_SetNTSTATUS(status);
44                 return false;
45         }
46         return true;
47 }
48
49 static bool ndr_syntax_from_py_object(PyObject *object, struct ndr_syntax_id *syntax_id)
50 {
51         ZERO_STRUCTP(syntax_id);
52
53         if (PyStr_Check(object)) {
54                 return PyString_AsGUID(object, &syntax_id->uuid);
55         } else if (PyTuple_Check(object)) {
56                 if (PyTuple_Size(object) < 1 || PyTuple_Size(object) > 2) {
57                         PyErr_SetString(PyExc_ValueError, "Syntax ID tuple has invalid size");
58                         return false;
59                 }
60
61                 if (!PyStr_Check(PyTuple_GetItem(object, 0))) {
62                         PyErr_SetString(PyExc_ValueError, "Expected GUID as first element in tuple");
63                         return false;
64                 }
65
66                 if (!PyString_AsGUID(PyTuple_GetItem(object, 0), &syntax_id->uuid)) 
67                         return false;
68
69                 if (!PyInt_Check(PyTuple_GetItem(object, 1))) {
70                         PyErr_SetString(PyExc_ValueError, "Expected version as second element in tuple");
71                         return false;
72                 }
73
74                 syntax_id->if_version = PyInt_AsLong(PyTuple_GetItem(object, 1));
75                 return true;
76         }
77
78         PyErr_SetString(PyExc_TypeError, "Expected UUID or syntax id tuple");
79         return false;
80 }
81
82 static PyObject *py_iface_server_name(PyObject *obj, void *closure)
83 {
84         const char *server_name;
85         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)obj;
86
87         server_name = dcerpc_server_name(iface->pipe);
88         if (server_name == NULL)
89                 Py_RETURN_NONE;
90
91         return PyStr_FromString(server_name);
92 }
93
94 static PyObject *py_ndr_syntax_id(struct ndr_syntax_id *syntax_id)
95 {
96         PyObject *ret;
97         char *uuid_str;
98
99         uuid_str = GUID_string(NULL, &syntax_id->uuid);
100         if (uuid_str == NULL)
101                 return NULL;
102
103         ret = Py_BuildValue("(s,i)", uuid_str, syntax_id->if_version);
104
105         talloc_free(uuid_str);
106
107         return ret;
108 }
109
110 static PyObject *py_iface_abstract_syntax(PyObject *obj, void *closure)
111 {
112         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)obj;
113
114         return py_ndr_syntax_id(&iface->pipe->syntax);
115 }
116
117 static PyObject *py_iface_transfer_syntax(PyObject *obj, void *closure)
118 {
119         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)obj;
120
121         return py_ndr_syntax_id(&iface->pipe->transfer_syntax);
122 }
123
124 static PyObject *py_iface_session_key(PyObject *obj, void *closure)
125 {
126         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)obj;
127         DATA_BLOB session_key;
128
129         NTSTATUS status = dcerpc_fetch_session_key(iface->pipe, &session_key);
130         PyErr_NTSTATUS_IS_ERR_RAISE(status);
131
132         return PyBytes_FromStringAndSize((const char *)session_key.data, session_key.length);
133 }
134
135 static PyObject *py_iface_user_session_key(PyObject *obj, void *closure)
136 {
137         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)obj;
138         TALLOC_CTX *mem_ctx;
139         NTSTATUS status;
140         struct gensec_security *security = NULL;
141         DATA_BLOB session_key = data_blob_null;
142         static PyObject *session_key_obj = NULL;
143
144         if (iface->pipe == NULL) {
145                 PyErr_SetNTSTATUS(NT_STATUS_NO_USER_SESSION_KEY);
146                 return NULL;
147         }
148
149         if (iface->pipe->conn == NULL) {
150                 PyErr_SetNTSTATUS(NT_STATUS_NO_USER_SESSION_KEY);
151                 return NULL;
152         }
153
154         if (iface->pipe->conn->security_state.generic_state == NULL) {
155                 PyErr_SetNTSTATUS(NT_STATUS_NO_USER_SESSION_KEY);
156                 return NULL;
157         }
158
159         security = iface->pipe->conn->security_state.generic_state;
160
161         mem_ctx = talloc_new(NULL);
162
163         status = gensec_session_key(security, mem_ctx, &session_key);
164         if (!NT_STATUS_IS_OK(status)) {
165                 talloc_free(mem_ctx);
166                 PyErr_SetNTSTATUS(status);
167                 return NULL;
168         }
169
170         session_key_obj = PyBytes_FromStringAndSize((const char *)session_key.data,
171                                                      session_key.length);
172         talloc_free(mem_ctx);
173         return session_key_obj;
174 }
175
176 static PyObject *py_iface_get_timeout(PyObject *obj, void *closure)
177 {
178         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)obj;
179         uint32_t timeout;
180
181         timeout = dcerpc_binding_handle_set_timeout(iface->binding_handle, 0);
182         dcerpc_binding_handle_set_timeout(iface->binding_handle, timeout);
183
184         return PyLong_FromUnsignedLong(timeout);
185 }
186
187 static int py_iface_set_timeout(PyObject *obj, PyObject *value, void *closure)
188 {
189         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)obj;
190         uint32_t timeout;
191
192         timeout = PyLong_AsUnsignedLong(value);
193         if (PyErr_Occurred() != NULL) {
194                 return -1;
195         }
196
197         dcerpc_binding_handle_set_timeout(iface->binding_handle, timeout);
198         return 0;
199 }
200
201 static PyGetSetDef dcerpc_interface_getsetters[] = {
202         { discard_const_p(char, "server_name"), py_iface_server_name, NULL,
203           discard_const_p(char, "name of the server, if connected over SMB") },
204         { discard_const_p(char, "abstract_syntax"), py_iface_abstract_syntax, NULL, 
205           discard_const_p(char, "syntax id of the abstract syntax") },
206         { discard_const_p(char, "transfer_syntax"), py_iface_transfer_syntax, NULL, 
207           discard_const_p(char, "syntax id of the transfersyntax") },
208         { discard_const_p(char, "session_key"), py_iface_session_key, NULL,
209           discard_const_p(char, "session key (as used for blob encryption on LSA and SAMR)") },
210         { discard_const_p(char, "user_session_key"), py_iface_user_session_key, NULL,
211           discard_const_p(char, "user_session key (as used for blob encryption on DRSUAPI)") },
212         { discard_const_p(char, "request_timeout"), py_iface_get_timeout, py_iface_set_timeout,
213           discard_const_p(char, "request timeout, in seconds") },
214         { NULL }
215 };
216
217 static PyObject *py_iface_request(PyObject *self, PyObject *args, PyObject *kwargs)
218 {
219         dcerpc_InterfaceObject *iface = (dcerpc_InterfaceObject *)self;
220         int opnum;
221         DATA_BLOB data_in, data_out;
222         NTSTATUS status;
223         char *in_data;
224         Py_ssize_t in_length;
225         PyObject *ret;
226         PyObject *object = NULL;
227         struct GUID object_guid;
228         TALLOC_CTX *mem_ctx = talloc_new(NULL);
229         uint32_t out_flags = 0;
230         const char *kwnames[] = { "opnum", "data", "object", NULL };
231
232         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "is#|O:request", 
233                 discard_const_p(char *, kwnames), &opnum, &in_data, &in_length, &object)) {
234                 talloc_free(mem_ctx);
235                 return NULL;
236         }
237
238         data_in.data = (uint8_t *)talloc_memdup(mem_ctx, in_data, in_length);
239         data_in.length = in_length;
240
241         ZERO_STRUCT(data_out);
242
243         if (object != NULL && !PyString_AsGUID(object, &object_guid)) {
244                 talloc_free(mem_ctx);
245                 return NULL;
246         }
247
248         status = dcerpc_binding_handle_raw_call(iface->binding_handle,
249                                                 object?&object_guid:NULL,
250                                                 opnum,
251                                                 0, /* in_flags */
252                                                 data_in.data,
253                                                 data_in.length,
254                                                 mem_ctx,
255                                                 &data_out.data,
256                                                 &data_out.length,
257                                                 &out_flags);
258         if (!NT_STATUS_IS_OK(status)) {
259                 PyErr_SetDCERPCStatus(iface->pipe, status);
260                 talloc_free(mem_ctx);
261                 return NULL;
262         }
263
264         ret = PyBytes_FromStringAndSize((char *)data_out.data, data_out.length);
265
266         talloc_free(mem_ctx);
267         return ret;
268 }
269
270 static PyMethodDef dcerpc_interface_methods[] = {
271         { "request", (PyCFunction)py_iface_request, METH_VARARGS|METH_KEYWORDS, "S.request(opnum, data, object=None) -> data\nMake a raw request" },
272         { NULL, NULL, 0, NULL },
273 };
274
275 static void dcerpc_interface_dealloc(PyObject* self)
276 {
277         dcerpc_InterfaceObject *interface = (dcerpc_InterfaceObject *)self;
278         interface->binding_handle = NULL;
279         interface->pipe = NULL;
280         TALLOC_FREE(interface->mem_ctx);
281         self->ob_type->tp_free(self);
282 }
283
284 static PyObject *dcerpc_interface_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
285 {
286         PyObject *ret;
287         const char *binding_string = NULL;
288         PyObject *py_lp_ctx = Py_None;
289         PyObject *py_credentials = Py_None;
290         PyObject *syntax = Py_None;
291         PyObject *py_basis = Py_None;
292         const char *kwnames[] = {
293                 "binding", "syntax", "lp_ctx", "credentials", "basis_connection", NULL
294         };
295         static struct ndr_interface_table dummy_table;
296         PyObject *args2 = Py_None;
297         PyObject *kwargs2 = Py_None;
298
299         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|OOO:connect", discard_const_p(char *, kwnames), &binding_string, &syntax, &py_lp_ctx, &py_credentials, &py_basis)) {
300                 return NULL;
301         }
302
303         if (strncmp(binding_string, "irpc:", 5) == 0) {
304                 PyErr_SetString(PyExc_ValueError, "irpc: transport not supported");
305                 return NULL;
306         }
307
308         /*
309          * Fill a dummy interface table struct. TODO: In the future, we should
310          * rather just allow connecting without requiring an interface table.
311          *
312          * We just fill the syntax during the connect, but keep the memory valid
313          * the whole time.
314          */
315         if (!ndr_syntax_from_py_object(syntax, &dummy_table.syntax_id)) {
316                 return NULL;
317         }
318
319         args2 = Py_BuildValue("(s)", binding_string);
320         if (args2 == NULL) {
321                 return NULL;
322         }
323
324         kwargs2 = Py_BuildValue("{s:O,s:O,s:O}",
325                                 "lp_ctx", py_lp_ctx,
326                                 "credentials", py_credentials,
327                                 "basis_connection", py_basis);
328         if (kwargs2 == NULL) {
329                 Py_DECREF(args2);
330                 return NULL;
331         }
332
333         ret = py_dcerpc_interface_init_helper(type, args2, kwargs2, &dummy_table);
334         ZERO_STRUCT(dummy_table.syntax_id);
335         Py_DECREF(args2);
336         Py_DECREF(kwargs2);
337         return ret;
338 }
339
340 static PyTypeObject dcerpc_InterfaceType = {
341         PyVarObject_HEAD_INIT(NULL, 0)
342         .tp_name = "dcerpc.ClientConnection",
343         .tp_basicsize = sizeof(dcerpc_InterfaceObject),
344         .tp_dealloc = dcerpc_interface_dealloc,
345         .tp_getset = dcerpc_interface_getsetters,
346         .tp_methods = dcerpc_interface_methods,
347         .tp_doc = "ClientConnection(binding, syntax, lp_ctx=None, credentials=None) -> connection\n"
348 "\n"
349 "binding should be a DCE/RPC binding string (for example: ncacn_ip_tcp:127.0.0.1)\n"
350 "syntax should be a tuple with a GUID and version number of an interface\n"
351 "lp_ctx should be a path to a smb.conf file or a param.LoadParm object\n"
352 "credentials should be a credentials.Credentials object.\n\n",
353         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
354         .tp_new = dcerpc_interface_new,
355 };
356
357 static PyObject *py_transfer_syntax_ndr_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
358 {
359         return py_dcerpc_syntax_init_helper(type, args, kwargs, &ndr_transfer_syntax_ndr);
360 }
361
362 static PyTypeObject py_transfer_syntax_ndr_SyntaxType = {
363         PyVarObject_HEAD_INIT(NULL, 0)
364         .tp_name = "base.transfer_syntax_ndr",
365         .tp_doc = "transfer_syntax_ndr()\n",
366         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
367         .tp_new = py_transfer_syntax_ndr_new,
368 };
369
370 static PyObject *py_transfer_syntax_ndr64_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
371 {
372         return py_dcerpc_syntax_init_helper(type, args, kwargs, &ndr_transfer_syntax_ndr64);
373 }
374
375 static PyTypeObject py_transfer_syntax_ndr64_SyntaxType = {
376         PyVarObject_HEAD_INIT(NULL, 0)
377         .tp_name = "base.transfer_syntax_ndr64",
378         .tp_doc = "transfer_syntax_ndr64()\n",
379         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
380         .tp_new = py_transfer_syntax_ndr64_new,
381 };
382
383 static PyObject *py_bind_time_features_syntax_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
384 {
385         const char *kwnames[] = {
386                 "features", NULL
387         };
388         unsigned long long features = 0;
389         struct ndr_syntax_id syntax;
390         PyObject *args2 = Py_None;
391         PyObject *kwargs2 = Py_None;
392
393         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "K:features", discard_const_p(char *, kwnames), &features)) {
394                 return NULL;
395         }
396
397         args2 = Py_BuildValue("()");
398         if (args2 == NULL) {
399                 return NULL;
400         }
401
402         kwargs2 = Py_BuildValue("{}");
403         if (kwargs2 == NULL) {
404                 Py_DECREF(args2);
405                 return NULL;
406         }
407
408         syntax = dcerpc_construct_bind_time_features(features);
409
410         return py_dcerpc_syntax_init_helper(type, args2, kwargs2, &syntax);
411 }
412
413 static PyTypeObject py_bind_time_features_syntax_SyntaxType = {
414         PyVarObject_HEAD_INIT(NULL, 0)
415         .tp_name = "base.bind_time_features_syntax",
416         .tp_doc = "bind_time_features_syntax(features)\n",
417         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
418         .tp_new = py_bind_time_features_syntax_new,
419 };
420
421 static struct PyModuleDef moduledef = {
422     PyModuleDef_HEAD_INIT,
423     .m_name = "base",
424     .m_doc = "DCE/RPC protocol implementation",
425     .m_size = -1,
426 };
427
428 MODULE_INIT_FUNC(base)
429 {
430         PyObject *m;
431         PyObject *dep_samba_dcerpc_misc;
432
433         dep_samba_dcerpc_misc = PyImport_ImportModule("samba.dcerpc.misc");
434         if (dep_samba_dcerpc_misc == NULL)
435                 return NULL;
436
437         ndr_syntax_id_Type = (PyTypeObject *)PyObject_GetAttrString(dep_samba_dcerpc_misc, "ndr_syntax_id");
438         if (ndr_syntax_id_Type == NULL)
439                 return NULL;
440
441         py_transfer_syntax_ndr_SyntaxType.tp_base = ndr_syntax_id_Type;
442         py_transfer_syntax_ndr_SyntaxType.tp_basicsize = pytalloc_BaseObject_size();
443         py_transfer_syntax_ndr64_SyntaxType.tp_base = ndr_syntax_id_Type;
444         py_transfer_syntax_ndr64_SyntaxType.tp_basicsize = pytalloc_BaseObject_size();
445         py_bind_time_features_syntax_SyntaxType.tp_base = ndr_syntax_id_Type;
446         py_bind_time_features_syntax_SyntaxType.tp_basicsize = pytalloc_BaseObject_size();
447
448         if (PyType_Ready(&dcerpc_InterfaceType) < 0)
449                 return NULL;
450
451         if (PyType_Ready(&py_transfer_syntax_ndr_SyntaxType) < 0)
452                 return NULL;
453         if (PyType_Ready(&py_transfer_syntax_ndr64_SyntaxType) < 0)
454                 return NULL;
455         if (PyType_Ready(&py_bind_time_features_syntax_SyntaxType) < 0)
456                 return NULL;
457
458         m = PyModule_Create(&moduledef);
459         if (m == NULL)
460                 return NULL;
461
462         Py_INCREF((PyObject *)&dcerpc_InterfaceType);
463         PyModule_AddObject(m, "ClientConnection", (PyObject *)&dcerpc_InterfaceType);
464
465         Py_INCREF((PyObject *)(void *)&py_transfer_syntax_ndr_SyntaxType);
466         PyModule_AddObject(m, "transfer_syntax_ndr", (PyObject *)(void *)&py_transfer_syntax_ndr_SyntaxType);
467         Py_INCREF((PyObject *)(void *)&py_transfer_syntax_ndr64_SyntaxType);
468         PyModule_AddObject(m, "transfer_syntax_ndr64", (PyObject *)(void *)&py_transfer_syntax_ndr64_SyntaxType);
469         Py_INCREF((PyObject *)(void *)&py_bind_time_features_syntax_SyntaxType);
470         PyModule_AddObject(m, "bind_time_features_syntax", (PyObject *)(void *)&py_bind_time_features_syntax_SyntaxType);
471         return m;
472 }