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