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