s4-pynet: some systems don't have Py_TYPE()
[metze/samba/wip.git] / source4 / libnet / py_net.c
1 /*
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008-2010
5    Copyright (C) Kamen Mazdrashki <kamen.mazdrashki@postpath.com> 2009
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <Python.h>
22 #include "includes.h"
23 #include "libnet.h"
24 #include "auth/credentials/pycredentials.h"
25 #include "libcli/security/security.h"
26 #include "lib/events/events.h"
27 #include "param/param.h"
28 #include "param/pyparam.h"
29 #include "lib/ldb/pyldb.h"
30 #include "auth/gensec/gensec.h"
31 #include "librpc/rpc/pyrpc.h"
32
33 typedef struct {
34         PyObject_HEAD
35         TALLOC_CTX *mem_ctx;
36         struct libnet_context *libnet_ctx;
37         struct tevent_context *ev;
38 } py_net_Object;
39
40 static PyObject *py_net_join(py_net_Object *self, PyObject *args, PyObject *kwargs)
41 {
42         struct libnet_Join r;
43         NTSTATUS status;
44         PyObject *result;
45         TALLOC_CTX *mem_ctx;
46         const char *kwnames[] = { "domain_name", "netbios_name", "join_type", "level", NULL };
47
48         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ssii:Join", discard_const_p(char *, kwnames), 
49                                          &r.in.domain_name, &r.in.netbios_name, 
50                                          &r.in.join_type, &r.in.level))
51                 return NULL;
52
53         mem_ctx = talloc_new(self->mem_ctx);
54
55         status = libnet_Join(self->libnet_ctx, mem_ctx, &r);
56         if (NT_STATUS_IS_ERR(status)) {
57                 PyErr_SetString(PyExc_RuntimeError, r.out.error_string?r.out.error_string:nt_errstr(status));
58                 talloc_free(mem_ctx);
59                 return NULL;
60         }
61
62         result = Py_BuildValue("sss", r.out.join_password,
63                                dom_sid_string(mem_ctx, r.out.domain_sid),
64                                r.out.domain_name);
65
66         talloc_free(mem_ctx);
67
68         return result;
69 }
70
71 static const char py_net_join_doc[] = "join(domain_name, netbios_name, join_type, level) -> (join_password, domain_sid, domain_name)\n\n" \
72 "Join the domain with the specified name.";
73
74 static PyObject *py_net_set_password(py_net_Object *self, PyObject *args, PyObject *kwargs)
75 {
76         union libnet_SetPassword r;
77         NTSTATUS status;
78         PyObject *py_creds;
79         TALLOC_CTX *mem_ctx;
80         struct tevent_context *ev;
81         const char *kwnames[] = { "account_name", "domain_name", "newpassword", "credentials", NULL };
82
83         r.generic.level = LIBNET_SET_PASSWORD_GENERIC;
84
85         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sssO:set_password", discard_const_p(char *, kwnames),
86                                          &r.generic.in.account_name, &r.generic.in.domain_name,
87                                          &r.generic.in.newpassword, &py_creds)) {
88                 return NULL;
89         }
90
91         /* FIXME: we really need to get a context from the caller or we may end
92          * up with 2 event contexts */
93         ev = s4_event_context_init(NULL);
94         mem_ctx = talloc_new(ev);
95
96         status = libnet_SetPassword(self->libnet_ctx, mem_ctx, &r);
97         if (NT_STATUS_IS_ERR(status)) {
98                 PyErr_SetString(PyExc_RuntimeError,
99                                 r.generic.out.error_string?r.generic.out.error_string:nt_errstr(status));
100                 talloc_free(mem_ctx);
101                 return NULL;
102         }
103
104         talloc_free(mem_ctx);
105
106         Py_RETURN_NONE;
107 }
108
109 static const char py_net_set_password_doc[] = "set_password(account_name, domain_name, newpassword) -> True\n\n" \
110 "Set password for a user. You must supply credential with enough rights to do this.\n\n" \
111 "Sample usage is:\n" \
112 "net.set_password(account_name=<account_name>,\n" \
113 "                domain_name=domain_name,\n" \
114 "                newpassword=new_pass)\n";
115
116
117 static PyObject *py_net_export_keytab(py_net_Object *self, PyObject *args, PyObject *kwargs)
118 {
119         struct libnet_export_keytab r;
120         TALLOC_CTX *mem_ctx;
121         const char *kwnames[] = { "keytab", NULL };
122         NTSTATUS status;
123
124         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s:export_keytab", discard_const_p(char *, kwnames),
125                                          &r.in.keytab_name)) {
126                 return NULL;
127         }
128
129         mem_ctx = talloc_new(self->mem_ctx);
130
131         status = libnet_export_keytab(self->libnet_ctx, mem_ctx, &r);
132         if (NT_STATUS_IS_ERR(status)) {
133                 PyErr_SetString(PyExc_RuntimeError,
134                                 r.out.error_string?r.out.error_string:nt_errstr(status));
135                 talloc_free(mem_ctx);
136                 return NULL;
137         }
138
139         talloc_free(mem_ctx);
140
141         Py_RETURN_NONE;
142 }
143
144 static const char py_net_export_keytab_doc[] = "export_keytab(keytab, name)\n\n"
145 "Export the DC keytab to a keytab file.";
146
147 static PyObject *py_net_time(py_net_Object *self, PyObject *args, PyObject *kwargs)
148 {
149         const char *kwnames[] = { "server_name", NULL };
150         union libnet_RemoteTOD r;
151         NTSTATUS status;
152         TALLOC_CTX *mem_ctx;
153         char timestr[64];
154         PyObject *ret;
155         struct tm *tm;
156
157         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s",
158                 discard_const_p(char *, kwnames), &r.generic.in.server_name))
159                 return NULL;
160
161         r.generic.level                 = LIBNET_REMOTE_TOD_GENERIC;
162
163         mem_ctx = talloc_new(NULL);
164         if (mem_ctx == NULL) {
165                 PyErr_NoMemory();
166                 return NULL;
167         }
168
169         status = libnet_RemoteTOD(self->libnet_ctx, mem_ctx, &r);
170         if (!NT_STATUS_IS_OK(status)) {
171                 PyErr_SetString(PyExc_RuntimeError,
172                                 r.generic.out.error_string?r.generic.out.error_string:nt_errstr(status));
173                 talloc_free(mem_ctx);
174                 return NULL;
175         }
176
177         ZERO_STRUCT(timestr);
178         tm = localtime(&r.generic.out.time);
179         strftime(timestr, sizeof(timestr)-1, "%c %Z",tm);
180         
181         ret = PyString_FromString(timestr);
182
183         talloc_free(mem_ctx);
184
185         return ret;
186 }
187
188 static const char py_net_time_doc[] = "time(server_name) -> timestr\n"
189 "Retrieve the remote time on a server";
190
191 static PyObject *py_net_user_create(py_net_Object *self, PyObject *args, PyObject *kwargs)
192 {
193         const char *kwnames[] = { "username", NULL };
194         NTSTATUS status;
195         TALLOC_CTX *mem_ctx;
196         struct libnet_CreateUser r;
197
198         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", discard_const_p(char *, kwnames), 
199                                                                          &r.in.user_name))
200                 return NULL;
201
202         r.in.domain_name = cli_credentials_get_domain(self->libnet_ctx->cred);
203
204         mem_ctx = talloc_new(NULL);
205         if (mem_ctx == NULL) {
206                 PyErr_NoMemory();
207                 return NULL;
208         }
209
210         status = libnet_CreateUser(self->libnet_ctx, mem_ctx, &r);
211         if (!NT_STATUS_IS_OK(status)) {
212                 PyErr_SetString(PyExc_RuntimeError, r.out.error_string?r.out.error_string:nt_errstr(status));
213                 talloc_free(mem_ctx);
214                 return NULL;
215         }
216
217         talloc_free(mem_ctx);
218         
219         Py_RETURN_NONE;
220 }
221
222 static const char py_net_create_user_doc[] = "create_user(username)\n"
223 "Create a new user.";
224
225 static PyObject *py_net_user_delete(py_net_Object *self, PyObject *args, PyObject *kwargs)
226 {
227         const char *kwnames[] = { "username", NULL };
228         NTSTATUS status;
229         TALLOC_CTX *mem_ctx;
230         struct libnet_DeleteUser r;
231
232         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", discard_const_p(char *, kwnames), 
233                                                                          &r.in.user_name))
234                 return NULL;
235
236         r.in.domain_name = cli_credentials_get_domain(self->libnet_ctx->cred);
237
238         mem_ctx = talloc_new(NULL);
239         if (mem_ctx == NULL) {
240                 PyErr_NoMemory();
241                 return NULL;
242         }
243
244         status = libnet_DeleteUser(self->libnet_ctx, mem_ctx, &r);
245         if (!NT_STATUS_IS_OK(status)) {
246                 PyErr_SetString(PyExc_RuntimeError, r.out.error_string?r.out.error_string:nt_errstr(status));
247                 talloc_free(mem_ctx);
248                 return NULL;
249         }
250
251         talloc_free(mem_ctx);
252         
253         Py_RETURN_NONE;
254 }
255
256 static const char py_net_delete_user_doc[] = "delete_user(username)\n"
257 "Delete a user.";
258
259 static PyObject *py_dom_sid_FromSid(struct dom_sid *sid)
260 {
261         PyObject *mod_security, *dom_sid_Type;
262
263         mod_security = PyImport_ImportModule("samba.dcerpc.security");
264         if (mod_security == NULL)
265                 return NULL;
266
267         dom_sid_Type = PyObject_GetAttrString(mod_security, "dom_sid");
268         if (dom_sid_Type == NULL)
269                 return NULL;
270
271         return py_talloc_reference((PyTypeObject *)dom_sid_Type, sid);
272 }
273
274 static PyObject *py_net_vampire(py_net_Object *self, PyObject *args, PyObject *kwargs)
275 {
276         const char *kwnames[] = { "domain", "target_dir", NULL };
277         NTSTATUS status;
278         TALLOC_CTX *mem_ctx;
279         PyObject *ret;
280         struct libnet_Vampire r;
281
282         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|z", discard_const_p(char *, kwnames),
283                                          &r.in.domain_name, &r.in.targetdir)) {
284                 return NULL;
285         }
286
287         r.in.netbios_name  = lpcfg_netbios_name(self->libnet_ctx->lp_ctx);
288         r.out.error_string = NULL;
289
290         mem_ctx = talloc_new(NULL);
291         if (mem_ctx == NULL) {
292                 PyErr_NoMemory();
293                 return NULL;
294         }
295
296         status = libnet_Vampire(self->libnet_ctx, mem_ctx, &r);
297
298         if (!NT_STATUS_IS_OK(status)) {
299                 PyErr_SetString(PyExc_RuntimeError,
300                                 r.out.error_string ? r.out.error_string : nt_errstr(status));
301                 talloc_free(mem_ctx);
302                 return NULL;
303         }
304
305         ret = Py_BuildValue("(sO)", r.out.domain_name, py_dom_sid_FromSid(r.out.domain_sid));
306
307         talloc_free(mem_ctx);
308
309         return ret;
310 }
311
312 struct replicate_state {
313         void *vampire_state;
314         dcerpc_InterfaceObject *drs_pipe;
315         struct libnet_BecomeDC_StoreChunk chunk;
316         DATA_BLOB gensec_skey;
317         struct libnet_BecomeDC_Partition partition;
318         struct libnet_BecomeDC_Forest forest;
319         struct libnet_BecomeDC_DestDSA dest_dsa;
320 };
321
322 /*
323   setup for replicate_chunk() calls
324  */
325 static PyObject *py_net_replicate_init(py_net_Object *self, PyObject *args, PyObject *kwargs)
326 {
327         const char *kwnames[] = { "samdb", "lp", "drspipe", NULL };
328         PyObject *py_ldb, *py_lp, *py_drspipe;
329         struct ldb_context *samdb;
330         struct loadparm_context *lp;
331         struct replicate_state *s;
332         NTSTATUS status;
333
334         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOO",
335                                          discard_const_p(char *, kwnames),
336                                          &py_ldb, &py_lp, &py_drspipe)) {
337                 return NULL;
338         }
339
340         s = talloc_zero(NULL, struct replicate_state);
341         if (!s) return NULL;
342
343         lp = lpcfg_from_py_object(s, py_lp);
344         if (lp == NULL) {
345                 PyErr_SetString(PyExc_TypeError, "Expected lp object");
346                 talloc_free(s);
347                 return NULL;
348         }
349
350         samdb = PyLdb_AsLdbContext(py_ldb);
351         if (samdb == NULL) {
352                 PyErr_SetString(PyExc_TypeError, "Expected ldb object");
353                 talloc_free(s);
354                 return NULL;
355         }
356
357         s->drs_pipe = (dcerpc_InterfaceObject *)(py_drspipe);
358
359         s->vampire_state = libnet_vampire_replicate_init(s, samdb, lp);
360         if (s->vampire_state == NULL) {
361                 PyErr_SetString(PyExc_TypeError, "Failed to initialise vampire_state");
362                 talloc_free(s);
363                 return NULL;
364         }
365
366         status = gensec_session_key(s->drs_pipe->pipe->conn->security_state.generic_state,
367                                     &s->gensec_skey);
368         if (!NT_STATUS_IS_OK(status)) {
369                 PyErr_Format(PyExc_RuntimeError, "Unable to get session key from drspipe: %s",
370                              nt_errstr(status));
371                 talloc_free(s);
372                 return NULL;
373         }
374
375         s->chunk.gensec_skey = &s->gensec_skey;
376         s->chunk.partition = &s->partition;
377         s->chunk.forest = &s->forest;
378         s->chunk.dest_dsa = &s->dest_dsa;
379
380         return PyCObject_FromTallocPtr(s);
381 }
382
383
384 /*
385   process one replication chunk
386  */
387 static PyObject *py_net_replicate_chunk(py_net_Object *self, PyObject *args, PyObject *kwargs)
388 {
389         const char *kwnames[] = { "state", "level", "ctr", "schema", NULL };
390         PyObject *py_state, *py_ctr, *py_schema;
391         struct replicate_state *s;
392         unsigned level;
393         NTSTATUS (*chunk_handler)(void *private_data, const struct libnet_BecomeDC_StoreChunk *c);
394         NTSTATUS status;
395
396         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OIO|O",
397                                          discard_const_p(char *, kwnames),
398                                          &py_state, &level, &py_ctr, &py_schema)) {
399                 return NULL;
400         }
401
402         s = talloc_get_type(PyCObject_AsVoidPtr(py_state), struct replicate_state);
403         if (!s) {
404                 PyErr_SetString(PyExc_TypeError, "Expected replication_state");
405                 return NULL;
406         }
407
408         switch (level) {
409         case 1:
410 #ifdef Py_TYPE
411                 if (strcmp("drsuapi.DsGetNCChangesCtr1", Py_TYPE(py_ctr)->tp_name) != 0) {
412                         PyErr_SetString(PyExc_TypeError, "Expected DsGetNCChangesCtr1 type for ctr");
413                         return NULL;
414                 }
415 #endif
416                 s->chunk.ctr1                         = py_talloc_get_ptr(py_ctr);
417                 s->partition.nc                       = *s->chunk.ctr1->naming_context;
418                 s->partition.more_data                = s->chunk.ctr1->more_data;
419                 s->partition.source_dsa_guid          = s->chunk.ctr1->source_dsa_guid;
420                 s->partition.source_dsa_invocation_id = s->chunk.ctr1->source_dsa_invocation_id;
421                 s->partition.highwatermark            = s->chunk.ctr1->new_highwatermark;
422                 break;
423         case 6:
424 #ifdef Py_TYPE
425                 if (strcmp("drsuapi.DsGetNCChangesCtr6", Py_TYPE(py_ctr)->tp_name) != 0) {
426                         PyErr_SetString(PyExc_TypeError, "Expected DsGetNCChangesCtr6 type for ctr");
427                         return NULL;
428                 }
429 #endif
430                 s->chunk.ctr6                         = py_talloc_get_ptr(py_ctr);
431                 s->partition.nc                       = *s->chunk.ctr6->naming_context;
432                 s->partition.more_data                = s->chunk.ctr6->more_data;
433                 s->partition.source_dsa_guid          = s->chunk.ctr6->source_dsa_guid;
434                 s->partition.source_dsa_invocation_id = s->chunk.ctr6->source_dsa_invocation_id;
435                 s->partition.highwatermark            = s->chunk.ctr6->new_highwatermark;
436                 break;
437         default:
438                 PyErr_Format(PyExc_TypeError, "Bad level %u in replicate_chunk", level);
439                 return NULL;
440         }
441
442         chunk_handler = libnet_vampire_cb_store_chunk;
443         if (py_schema) {
444                 if (!PyBool_Check(py_schema)) {
445                         PyErr_SetString(PyExc_TypeError, "Expected boolean schema");
446                         return NULL;
447                 }
448                 if (py_schema == Py_True) {
449                         chunk_handler = libnet_vampire_cb_schema_chunk;
450                 }
451         }
452
453         s->chunk.ctr_level = level;
454
455         status = chunk_handler(s->vampire_state, &s->chunk);
456         if (!NT_STATUS_IS_OK(status)) {
457                 PyErr_Format(PyExc_TypeError, "Failed to process chunk: %s", nt_errstr(status));
458                 return NULL;
459         }
460
461         return Py_None;
462 }
463
464 static const char py_net_vampire_doc[] = "vampire(domain, target_dir=None)\n"
465                                          "Vampire a domain.";
466
467 static const char py_net_replicate_init_doc[] = "replicate_init(samdb, lp, drspipe)\n"
468                                          "Setup for replicate_chunk calls.";
469
470 static const char py_net_replicate_chunk_doc[] = "replicate_chunk(state, level, ctr, schema)\n"
471                                          "Process replication for one chunk";
472
473 static PyMethodDef net_obj_methods[] = {
474         {"join", (PyCFunction)py_net_join, METH_VARARGS|METH_KEYWORDS, py_net_join_doc},
475         {"set_password", (PyCFunction)py_net_set_password, METH_VARARGS|METH_KEYWORDS, py_net_set_password_doc},
476         {"export_keytab", (PyCFunction)py_net_export_keytab, METH_VARARGS|METH_KEYWORDS, py_net_export_keytab_doc},
477         {"time", (PyCFunction)py_net_time, METH_VARARGS|METH_KEYWORDS, py_net_time_doc},
478         {"create_user", (PyCFunction)py_net_user_create, METH_VARARGS|METH_KEYWORDS, py_net_create_user_doc},
479         {"delete_user", (PyCFunction)py_net_user_delete, METH_VARARGS|METH_KEYWORDS, py_net_delete_user_doc},
480         {"vampire", (PyCFunction)py_net_vampire, METH_VARARGS|METH_KEYWORDS, py_net_vampire_doc},
481         {"replicate_init", (PyCFunction)py_net_replicate_init, METH_VARARGS|METH_KEYWORDS, py_net_replicate_init_doc},
482         {"replicate_chunk", (PyCFunction)py_net_replicate_chunk, METH_VARARGS|METH_KEYWORDS, py_net_replicate_chunk_doc},
483         { NULL }
484 };
485
486 static void py_net_dealloc(py_net_Object *self)
487 {
488         talloc_free(self->mem_ctx);
489 }
490
491 static PyObject *net_obj_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
492 {
493         PyObject *py_creds, *py_lp = Py_None;
494         const char *kwnames[] = { "creds", "lp", NULL };
495         py_net_Object *ret;
496         struct loadparm_context *lp;
497
498         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", 
499                         discard_const_p(char *, kwnames), &py_creds, &py_lp))
500                 return NULL;
501
502         ret = PyObject_New(py_net_Object, type);
503         if (ret == NULL) {
504                 return NULL;
505         }
506
507         /* FIXME: we really need to get a context from the caller or we may end
508          * up with 2 event contexts */
509         ret->ev = s4_event_context_init(NULL);
510         ret->mem_ctx = talloc_new(ret->ev);
511
512         lp = lpcfg_from_py_object(ret->mem_ctx, py_lp);
513         if (lp == NULL) {
514                 Py_DECREF(ret);
515                 return NULL;
516         }
517
518         ret->libnet_ctx = libnet_context_init(ret->ev, lp);
519         if (ret->libnet_ctx == NULL) {
520                 PyErr_SetString(PyExc_RuntimeError, "Unable to initialize net");
521                 Py_DECREF(ret);
522                 return NULL;
523         }
524
525         ret->libnet_ctx->cred = cli_credentials_from_py_object(py_creds);
526         if (ret->libnet_ctx->cred == NULL) {
527                 PyErr_SetString(PyExc_TypeError, "Expected credentials object");
528                 Py_DECREF(ret);
529                 return NULL;
530         }
531
532         return (PyObject *)ret;
533 }
534
535
536 PyTypeObject py_net_Type = {
537         PyObject_HEAD_INIT(NULL) 0,
538         .tp_name = "net.Net",
539         .tp_basicsize = sizeof(py_net_Object),
540         .tp_dealloc = (destructor)py_net_dealloc,
541         .tp_methods = net_obj_methods,
542         .tp_new = net_obj_new,
543 };
544
545 void initnet(void)
546 {
547         PyObject *m;
548
549         if (PyType_Ready(&py_net_Type) < 0)
550                 return;
551
552         m = Py_InitModule3("net", NULL, NULL);
553         if (m == NULL)
554                 return;
555
556         Py_INCREF(&py_net_Type);
557         PyModule_AddObject(m, "Net", (PyObject *)&py_net_Type);
558         PyModule_AddObject(m, "LIBNET_JOINDOMAIN_AUTOMATIC", PyInt_FromLong(LIBNET_JOINDOMAIN_AUTOMATIC));
559         PyModule_AddObject(m, "LIBNET_JOINDOMAIN_SPECIFIED", PyInt_FromLong(LIBNET_JOINDOMAIN_SPECIFIED));
560         PyModule_AddObject(m, "LIBNET_JOIN_AUTOMATIC", PyInt_FromLong(LIBNET_JOIN_AUTOMATIC));
561         PyModule_AddObject(m, "LIBNET_JOIN_SPECIFIED", PyInt_FromLong(LIBNET_JOIN_SPECIFIED));
562 }