78e60f6d6a6d2d1bc50892b9cc96bb00991aba4c
[sfrench/samba-autobuild/.git] / source4 / libnet / py_net.c
1 /*
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4
5    Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008-2010
6    Copyright (C) Kamen Mazdrashki <kamen.mazdrashki@postpath.com> 2009
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include <Python.h>
23 #include "python/py3compat.h"
24 #include "includes.h"
25 #include <pyldb.h>
26 #include <pytalloc.h>
27 #include "libnet.h"
28 #include "auth/credentials/pycredentials.h"
29 #include "libcli/security/security.h"
30 #include "lib/events/events.h"
31 #include "param/pyparam.h"
32 #include "auth/gensec/gensec.h"
33 #include "librpc/rpc/pyrpc_util.h"
34 #include "libcli/resolve/resolve.h"
35 #include "libcli/finddc.h"
36 #include "dsdb/samdb/samdb.h"
37 #include "py_net.h"
38 #include "librpc/rpc/pyrpc_util.h"
39 #include "libcli/drsuapi/drsuapi.h"
40
41 static void PyErr_SetDsExtendedError(enum drsuapi_DsExtendedError ext_err, const char *error_description)
42 {
43         PyObject *error = PyObject_GetAttrString(PyImport_ImportModule("samba"),
44                                                  "DsExtendedError");
45         if (error_description == NULL) {
46                 switch (ext_err) {
47                         /* Copied out of ndr_drsuapi.c:ndr_print_drsuapi_DsExtendedError() */
48                         case DRSUAPI_EXOP_ERR_NONE:
49                                 error_description = "DRSUAPI_EXOP_ERR_NONE";
50                                 break;
51                         case DRSUAPI_EXOP_ERR_SUCCESS:
52                                 error_description = "DRSUAPI_EXOP_ERR_SUCCESS";
53                                 break;
54                         case DRSUAPI_EXOP_ERR_UNKNOWN_OP:
55                                 error_description = "DRSUAPI_EXOP_ERR_UNKNOWN_OP";
56                                 break;
57                         case DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER:
58                                 error_description = "DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER";
59                                 break;
60                         case DRSUAPI_EXOP_ERR_UPDATE_ERR:
61                                 error_description = "DRSUAPI_EXOP_ERR_UPDATE_ERR";
62                                 break;
63                         case DRSUAPI_EXOP_ERR_EXCEPTION:
64                                 error_description = "DRSUAPI_EXOP_ERR_EXCEPTION";
65                                 break;
66                         case DRSUAPI_EXOP_ERR_UNKNOWN_CALLER:
67                                 error_description = "DRSUAPI_EXOP_ERR_UNKNOWN_CALLER";
68                                 break;
69                         case DRSUAPI_EXOP_ERR_RID_ALLOC:
70                                 error_description = "DRSUAPI_EXOP_ERR_RID_ALLOC";
71                                 break;
72                         case DRSUAPI_EXOP_ERR_FSMO_OWNER_DELETED:
73                                 error_description = "DRSUAPI_EXOP_ERR_FSMO_OWNER_DELETED";
74                                 break;
75                         case DRSUAPI_EXOP_ERR_FMSO_PENDING_OP:
76                                 error_description = "DRSUAPI_EXOP_ERR_FMSO_PENDING_OP";
77                                 break;
78                         case DRSUAPI_EXOP_ERR_MISMATCH:
79                                 error_description = "DRSUAPI_EXOP_ERR_MISMATCH";
80                                 break;
81                         case DRSUAPI_EXOP_ERR_COULDNT_CONTACT:
82                                 error_description = "DRSUAPI_EXOP_ERR_COULDNT_CONTACT";
83                                 break;
84                         case DRSUAPI_EXOP_ERR_FSMO_REFUSING_ROLES:
85                                 error_description = "DRSUAPI_EXOP_ERR_FSMO_REFUSING_ROLES";
86                                 break;
87                         case DRSUAPI_EXOP_ERR_DIR_ERROR:
88                                 error_description = "DRSUAPI_EXOP_ERR_DIR_ERROR";
89                                 break;
90                         case DRSUAPI_EXOP_ERR_FSMO_MISSING_SETTINGS:
91                                 error_description = "DRSUAPI_EXOP_ERR_FSMO_MISSING_SETTINGS";
92                                 break;
93                         case DRSUAPI_EXOP_ERR_ACCESS_DENIED:
94                                 error_description = "DRSUAPI_EXOP_ERR_ACCESS_DENIED";
95                                 break;
96                         case DRSUAPI_EXOP_ERR_PARAM_ERROR:
97                                 error_description = "DRSUAPI_EXOP_ERR_PARAM_ERROR";
98                                 break;
99                 }
100         }
101         PyErr_SetObject(error,
102                         Py_BuildValue(discard_const_p(char, "(i,s)"),
103                                       ext_err,
104                                       error_description));
105 }
106
107 static PyObject *py_net_join_member(py_net_Object *self, PyObject *args, PyObject *kwargs)
108 {
109         struct libnet_Join_member r;
110         int _level = 0;
111         NTSTATUS status;
112         PyObject *result;
113         TALLOC_CTX *mem_ctx;
114         const char *kwnames[] = { "domain_name", "netbios_name", "level", "machinepass", NULL };
115
116         ZERO_STRUCT(r);
117
118         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ssi|z:Join", discard_const_p(char *, kwnames),
119                                          &r.in.domain_name, &r.in.netbios_name, 
120                                          &_level,
121                                          &r.in.account_pass)) {
122                 return NULL;
123         }
124         r.in.level = _level;
125
126         mem_ctx = talloc_new(self->mem_ctx);
127         if (mem_ctx == NULL) {
128                 PyErr_NoMemory();
129                 return NULL;
130         }
131
132         status = libnet_Join_member(self->libnet_ctx, mem_ctx, &r);
133         if (NT_STATUS_IS_ERR(status)) {
134                 PyErr_SetNTSTATUS_and_string(status,
135                                              r.out.error_string
136                                              ? r.out.error_string
137                                              : nt_errstr(status));
138                 talloc_free(mem_ctx);
139                 return NULL;
140         }
141
142         result = Py_BuildValue("sss", r.out.join_password,
143                                dom_sid_string(mem_ctx, r.out.domain_sid),
144                                r.out.domain_name);
145
146         talloc_free(mem_ctx);
147
148         return result;
149 }
150
151 static const char py_net_join_member_doc[] = "join_member(domain_name, netbios_name, level) -> (join_password, domain_sid, domain_name)\n\n" \
152 "Join the domain with the specified name.";
153
154 static PyObject *py_net_change_password(py_net_Object *self, PyObject *args, PyObject *kwargs)
155 {
156         union libnet_ChangePassword r;
157         NTSTATUS status;
158         TALLOC_CTX *mem_ctx;
159         struct tevent_context *ev;
160         const char *kwnames[] = { "newpassword", "oldpassword", "domain", "username", NULL };
161
162         ZERO_STRUCT(r);
163
164         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|sss:change_password",
165                                          discard_const_p(char *, kwnames),
166                                          &r.generic.in.newpassword,
167                                          &r.generic.in.oldpassword,
168                                          &r.generic.in.domain_name,
169                                          &r.generic.in.account_name)) {
170                 return NULL;
171         }
172
173         r.generic.level = LIBNET_CHANGE_PASSWORD_GENERIC;
174         if (r.generic.in.account_name == NULL) {
175                 r.generic.in.account_name
176                         = cli_credentials_get_username(self->libnet_ctx->cred);
177         }
178         if (r.generic.in.domain_name == NULL) {
179                 r.generic.in.domain_name
180                         = cli_credentials_get_domain(self->libnet_ctx->cred);
181         }
182         if (r.generic.in.oldpassword == NULL) {
183                 r.generic.in.oldpassword
184                         = cli_credentials_get_password(self->libnet_ctx->cred);
185         }
186
187         /* FIXME: we really need to get a context from the caller or we may end
188          * up with 2 event contexts */
189         ev = s4_event_context_init(NULL);
190
191         mem_ctx = talloc_new(ev);
192         if (mem_ctx == NULL) {
193                 PyErr_NoMemory();
194                 return NULL;
195         }
196
197         status = libnet_ChangePassword(self->libnet_ctx, mem_ctx, &r);
198         if (NT_STATUS_IS_ERR(status)) {
199                 PyErr_SetNTSTATUS_and_string(status,
200                                              r.generic.out.error_string
201                                              ? r.generic.out.error_string
202                                              : nt_errstr(status));
203                 talloc_free(mem_ctx);
204                 return NULL;
205         }
206
207         talloc_free(mem_ctx);
208
209         Py_RETURN_NONE;
210 }
211
212 static const char py_net_change_password_doc[] = "change_password(newpassword) -> True\n\n" \
213 "Change password for a user. You must supply credential with enough rights to do this.\n\n" \
214 "Sample usage is:\n" \
215 "net.change_password(newpassword=<new_password>)\n";
216
217
218 static PyObject *py_net_set_password(py_net_Object *self, PyObject *args, PyObject *kwargs)
219 {
220         union libnet_SetPassword r;
221         NTSTATUS status;
222         TALLOC_CTX *mem_ctx;
223         struct tevent_context *ev;
224         const char *kwnames[] = { "account_name", "domain_name", "newpassword", NULL };
225
226         ZERO_STRUCT(r);
227
228         r.generic.level = LIBNET_SET_PASSWORD_GENERIC;
229
230         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sss:set_password",
231                                         discard_const_p(char *, kwnames),
232                                          &r.generic.in.account_name,
233                                          &r.generic.in.domain_name,
234                                          &r.generic.in.newpassword)) {
235                 return NULL;
236         }
237
238         /* FIXME: we really need to get a context from the caller or we may end
239          * up with 2 event contexts */
240         ev = s4_event_context_init(NULL);
241
242         mem_ctx = talloc_new(ev);
243         if (mem_ctx == NULL) {
244                 PyErr_NoMemory();
245                 return NULL;
246         }
247
248         status = libnet_SetPassword(self->libnet_ctx, mem_ctx, &r);
249         if (NT_STATUS_IS_ERR(status)) {
250                 PyErr_SetNTSTATUS_and_string(status,
251                                              r.generic.out.error_string
252                                              ? r.generic.out.error_string
253                                              : nt_errstr(status));
254                 talloc_free(mem_ctx);
255                 return NULL;
256         }
257
258         talloc_free(mem_ctx);
259
260         Py_RETURN_NONE;
261 }
262
263 static const char py_net_set_password_doc[] = "set_password(account_name, domain_name, newpassword) -> True\n\n" \
264 "Set password for a user. You must supply credential with enough rights to do this.\n\n" \
265 "Sample usage is:\n" \
266 "net.set_password(account_name=account_name, domain_name=domain_name, newpassword=new_pass)\n";
267
268
269 static PyObject *py_net_time(py_net_Object *self, PyObject *args, PyObject *kwargs)
270 {
271         const char *kwnames[] = { "server_name", NULL };
272         union libnet_RemoteTOD r;
273         NTSTATUS status;
274         TALLOC_CTX *mem_ctx;
275         char timestr[64];
276         PyObject *ret;
277         struct tm *tm;
278
279         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s",
280                 discard_const_p(char *, kwnames), &r.generic.in.server_name))
281                 return NULL;
282
283         r.generic.level                 = LIBNET_REMOTE_TOD_GENERIC;
284
285         mem_ctx = talloc_new(NULL);
286         if (mem_ctx == NULL) {
287                 PyErr_NoMemory();
288                 return NULL;
289         }
290
291         status = libnet_RemoteTOD(self->libnet_ctx, mem_ctx, &r);
292         if (!NT_STATUS_IS_OK(status)) {
293                 PyErr_SetNTSTATUS_and_string(status,
294                                              r.generic.out.error_string
295                                              ? r.generic.out.error_string
296                                              : nt_errstr(status));
297                 talloc_free(mem_ctx);
298                 return NULL;
299         }
300
301         ZERO_STRUCT(timestr);
302         tm = localtime(&r.generic.out.time);
303         strftime(timestr, sizeof(timestr)-1, "%c %Z",tm);
304         
305         ret = PyStr_FromString(timestr);
306
307         talloc_free(mem_ctx);
308
309         return ret;
310 }
311
312 static const char py_net_time_doc[] = "time(server_name) -> timestr\n"
313 "Retrieve the remote time on a server";
314
315 static PyObject *py_net_user_create(py_net_Object *self, PyObject *args, PyObject *kwargs)
316 {
317         const char *kwnames[] = { "username", NULL };
318         NTSTATUS status;
319         TALLOC_CTX *mem_ctx;
320         struct libnet_CreateUser r;
321
322         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", discard_const_p(char *, kwnames), 
323                                                                          &r.in.user_name))
324                 return NULL;
325
326         r.in.domain_name = cli_credentials_get_domain(self->libnet_ctx->cred);
327
328         mem_ctx = talloc_new(NULL);
329         if (mem_ctx == NULL) {
330                 PyErr_NoMemory();
331                 return NULL;
332         }
333
334         status = libnet_CreateUser(self->libnet_ctx, mem_ctx, &r);
335         if (!NT_STATUS_IS_OK(status)) {
336                 PyErr_SetNTSTATUS_and_string(status,
337                                              r.out.error_string
338                                              ? r.out.error_string
339                                              : nt_errstr(status));
340                 talloc_free(mem_ctx);
341                 return NULL;
342         }
343
344         talloc_free(mem_ctx);
345         
346         Py_RETURN_NONE;
347 }
348
349 static const char py_net_create_user_doc[] = "create_user(username)\n"
350 "Create a new user.";
351
352 static PyObject *py_net_user_delete(py_net_Object *self, PyObject *args, PyObject *kwargs)
353 {
354         const char *kwnames[] = { "username", NULL };
355         NTSTATUS status;
356         TALLOC_CTX *mem_ctx;
357         struct libnet_DeleteUser r;
358
359         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", discard_const_p(char *, kwnames), 
360                                                                          &r.in.user_name))
361                 return NULL;
362
363         r.in.domain_name = cli_credentials_get_domain(self->libnet_ctx->cred);
364
365         mem_ctx = talloc_new(NULL);
366         if (mem_ctx == NULL) {
367                 PyErr_NoMemory();
368                 return NULL;
369         }
370
371         status = libnet_DeleteUser(self->libnet_ctx, mem_ctx, &r);
372         if (!NT_STATUS_IS_OK(status)) {
373                 PyErr_SetNTSTATUS_and_string(status,
374                                            r.out.error_string
375                                           ? r.out.error_string
376                                           : nt_errstr(status));
377                 talloc_free(mem_ctx);
378                 return NULL;
379         }
380
381         talloc_free(mem_ctx);
382         
383         Py_RETURN_NONE;
384 }
385
386 static const char py_net_delete_user_doc[] = "delete_user(username)\n"
387 "Delete a user.";
388
389 struct replicate_state {
390         void *vampire_state;
391         dcerpc_InterfaceObject *drs_pipe;
392         struct libnet_BecomeDC_StoreChunk chunk;
393         DATA_BLOB gensec_skey;
394         struct libnet_BecomeDC_Partition partition;
395         struct libnet_BecomeDC_Forest forest;
396         struct libnet_BecomeDC_DestDSA dest_dsa;
397 };
398
399 /*
400   setup for replicate_chunk() calls
401  */
402 static PyObject *py_net_replicate_init(py_net_Object *self, PyObject *args, PyObject *kwargs)
403 {
404         const char *kwnames[] = { "samdb", "lp", "drspipe", "invocation_id", NULL };
405         PyObject *py_ldb, *py_lp, *py_drspipe, *py_invocation_id;
406         struct ldb_context *samdb;
407         struct loadparm_context *lp;
408         struct replicate_state *s;
409         NTSTATUS status;
410
411         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOOO",
412                                          discard_const_p(char *, kwnames),
413                                          &py_ldb, &py_lp, &py_drspipe,
414                                          &py_invocation_id)) {
415                 return NULL;
416         }
417
418         s = talloc_zero(NULL, struct replicate_state);
419         if (!s) return NULL;
420
421         lp = lpcfg_from_py_object(s, py_lp);
422         if (lp == NULL) {
423                 PyErr_SetString(PyExc_TypeError, "Expected lp object");
424                 talloc_free(s);
425                 return NULL;
426         }
427
428         samdb = pyldb_Ldb_AsLdbContext(py_ldb);
429         if (samdb == NULL) {
430                 PyErr_SetString(PyExc_TypeError, "Expected ldb object");
431                 talloc_free(s);
432                 return NULL;
433         }
434         if (!py_check_dcerpc_type(py_invocation_id, "samba.dcerpc.misc", "GUID")) {
435                 
436                 talloc_free(s);
437                 return NULL;
438         }
439         s->dest_dsa.invocation_id = *pytalloc_get_type(py_invocation_id, struct GUID);
440
441         s->drs_pipe = (dcerpc_InterfaceObject *)(py_drspipe);
442
443         s->vampire_state = libnet_vampire_replicate_init(s, samdb, lp);
444         if (s->vampire_state == NULL) {
445                 PyErr_SetString(PyExc_TypeError, "Failed to initialise vampire_state");
446                 talloc_free(s);
447                 return NULL;
448         }
449
450         status = gensec_session_key(s->drs_pipe->pipe->conn->security_state.generic_state,
451                                     s,
452                                     &s->gensec_skey);
453         if (!NT_STATUS_IS_OK(status)) {
454                 char *error_string = talloc_asprintf(s,
455                                                      "Unable to get session key from drspipe: %s",
456                                                      nt_errstr(status));
457                 PyErr_SetNTSTATUS_and_string(status, error_string);
458                 talloc_free(s);
459                 return NULL;
460         }
461
462         s->forest.dns_name = samdb_dn_to_dns_domain(s, ldb_get_root_basedn(samdb));
463         s->forest.root_dn_str = ldb_dn_get_linearized(ldb_get_root_basedn(samdb));
464         s->forest.config_dn_str = ldb_dn_get_linearized(ldb_get_config_basedn(samdb));
465         s->forest.schema_dn_str = ldb_dn_get_linearized(ldb_get_schema_basedn(samdb));
466
467         s->chunk.gensec_skey = &s->gensec_skey;
468         s->chunk.partition = &s->partition;
469         s->chunk.forest = &s->forest;
470         s->chunk.dest_dsa = &s->dest_dsa;
471
472         return pytalloc_GenericObject_steal(s);
473 }
474
475
476 /*
477   process one replication chunk
478  */
479 static PyObject *py_net_replicate_chunk(py_net_Object *self, PyObject *args, PyObject *kwargs)
480 {
481         const char *kwnames[] = { "state", "level", "ctr",
482                                   "schema", "req_level", "req",
483                                   NULL };
484         PyObject *py_state, *py_ctr, *py_schema = Py_None, *py_req = Py_None;
485         struct replicate_state *s;
486         unsigned level;
487         unsigned req_level = 0;
488         WERROR (*chunk_handler)(void *private_data, const struct libnet_BecomeDC_StoreChunk *c);
489         WERROR werr;
490         enum drsuapi_DsExtendedError extended_ret = DRSUAPI_EXOP_ERR_NONE;
491         enum drsuapi_DsExtendedOperation exop = DRSUAPI_EXOP_NONE;
492
493         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OIO|OIO",
494                                          discard_const_p(char *, kwnames),
495                                          &py_state, &level, &py_ctr,
496                                          &py_schema, &req_level, &py_req)) {
497                 return NULL;
498         }
499
500         s = pytalloc_get_type(py_state, struct replicate_state);
501         if (!s) {
502                 return NULL;
503         }
504
505         switch (level) {
506         case 1:
507                 if (!py_check_dcerpc_type(py_ctr, "samba.dcerpc.drsuapi", "DsGetNCChangesCtr1")) {
508                         return NULL;
509                 }
510                 s->chunk.ctr1                         = pytalloc_get_ptr(py_ctr);
511                 if (s->chunk.ctr1->naming_context != NULL) {
512                         s->partition.nc = *s->chunk.ctr1->naming_context;
513                 }
514                 extended_ret = s->chunk.ctr1->extended_ret;
515                 s->partition.more_data                = s->chunk.ctr1->more_data;
516                 s->partition.source_dsa_guid          = s->chunk.ctr1->source_dsa_guid;
517                 s->partition.source_dsa_invocation_id = s->chunk.ctr1->source_dsa_invocation_id;
518                 s->partition.highwatermark            = s->chunk.ctr1->new_highwatermark;
519                 break;
520         case 6:
521                 if (!py_check_dcerpc_type(py_ctr, "samba.dcerpc.drsuapi", "DsGetNCChangesCtr6")) {
522                         return NULL;
523                 }
524                 s->chunk.ctr6                         = pytalloc_get_ptr(py_ctr);
525                 if (s->chunk.ctr6->naming_context != NULL) {
526                         s->partition.nc = *s->chunk.ctr6->naming_context;
527                 }
528                 extended_ret = s->chunk.ctr6->extended_ret;
529                 s->partition.more_data                = s->chunk.ctr6->more_data;
530                 s->partition.source_dsa_guid          = s->chunk.ctr6->source_dsa_guid;
531                 s->partition.source_dsa_invocation_id = s->chunk.ctr6->source_dsa_invocation_id;
532                 s->partition.highwatermark            = s->chunk.ctr6->new_highwatermark;
533                 break;
534         default:
535                 PyErr_Format(PyExc_TypeError, "Bad level %u in replicate_chunk", level);
536                 return NULL;
537         }
538
539         s->chunk.req5 = NULL;
540         s->chunk.req8 = NULL;
541         s->chunk.req10 = NULL;
542         if (py_req) {
543                 switch (req_level) {
544                 case 0:
545                         break;
546                 case 5:
547                         if (!py_check_dcerpc_type(py_req, "samba.dcerpc.drsuapi", "DsGetNCChangesRequest5")) {
548                                 return NULL;
549                         }
550
551                         s->chunk.req5 = pytalloc_get_ptr(py_req);
552                         exop = s->chunk.req5->extended_op;
553                         break;
554                 case 8:
555                         if (!py_check_dcerpc_type(py_req, "samba.dcerpc.drsuapi", "DsGetNCChangesRequest8")) {
556                                 return NULL;
557                         }
558
559                         s->chunk.req8 = pytalloc_get_ptr(py_req);
560                         exop = s->chunk.req8->extended_op;
561                         break;
562                 case 10:
563                         if (!py_check_dcerpc_type(py_req, "samba.dcerpc.drsuapi", "DsGetNCChangesRequest10")) {
564                                 return NULL;
565                         }
566
567                         s->chunk.req10 = pytalloc_get_ptr(py_req);
568                         exop = s->chunk.req10->extended_op;
569                         break;
570                 default:
571                         PyErr_Format(PyExc_TypeError, "Bad req_level %u in replicate_chunk", req_level);
572                         return NULL;
573                 }
574         }
575
576         if (exop != DRSUAPI_EXOP_NONE && extended_ret != DRSUAPI_EXOP_ERR_SUCCESS) {
577                 PyErr_SetDsExtendedError(extended_ret, NULL);
578                 return NULL;
579         }
580
581         s->chunk.req_level = req_level;
582
583         chunk_handler = libnet_vampire_cb_store_chunk;
584         if (py_schema) {
585                 if (!PyBool_Check(py_schema)) {
586                         PyErr_SetString(PyExc_TypeError, "Expected boolean schema");
587                         return NULL;
588                 }
589                 if (py_schema == Py_True) {
590                         chunk_handler = libnet_vampire_cb_schema_chunk;
591                 }
592         }
593
594         s->chunk.ctr_level = level;
595
596         werr = chunk_handler(s->vampire_state, &s->chunk);
597         if (!W_ERROR_IS_OK(werr)) {
598                 char *error_string
599                         = talloc_asprintf(NULL,
600                                           "Failed to process 'chunk' of DRS replicated objects: %s",
601                                           win_errstr(werr));
602                 PyErr_SetWERROR_and_string(werr, error_string);
603                 TALLOC_FREE(error_string);
604                 return NULL;
605         }
606
607         Py_RETURN_NONE;
608 }
609
610
611 /*
612   just do the decryption of a DRS replicated attribute
613  */
614 static PyObject *py_net_replicate_decrypt(py_net_Object *self, PyObject *args, PyObject *kwargs)
615 {
616         const char *kwnames[] = { "drspipe", "attribute", "rid", NULL };
617         PyObject *py_drspipe, *py_attribute;
618         NTSTATUS status;
619         dcerpc_InterfaceObject *drs_pipe;
620         TALLOC_CTX *frame;
621         TALLOC_CTX *context;
622         DATA_BLOB gensec_skey;
623         unsigned int rid;
624         struct drsuapi_DsReplicaAttribute *attribute;
625         WERROR werr;
626
627         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOI",
628                                          discard_const_p(char *, kwnames),
629                                          &py_drspipe,
630                                          &py_attribute, &rid)) {
631                 return NULL;
632         }
633
634         frame = talloc_stackframe();
635
636         if (!py_check_dcerpc_type(py_drspipe,
637                                   "samba.dcerpc.base",
638                                   "ClientConnection")) {
639                 return NULL;
640         }
641         drs_pipe = (dcerpc_InterfaceObject *)(py_drspipe);
642
643         status = gensec_session_key(drs_pipe->pipe->conn->security_state.generic_state,
644                                     frame,
645                                     &gensec_skey);
646         if (!NT_STATUS_IS_OK(status)) {
647                 char *error_string
648                         = talloc_asprintf(frame,
649                                           "Unable to get session key from drspipe: %s",
650                                           nt_errstr(status));
651                 PyErr_SetNTSTATUS_and_string(status, error_string);
652                 talloc_free(frame);
653                 return NULL;
654         }
655
656         if (!py_check_dcerpc_type(py_attribute, "samba.dcerpc.drsuapi",
657                                   "DsReplicaAttribute")) {
658                 return NULL;
659         }
660
661         attribute = pytalloc_get_ptr(py_attribute);
662         context   = pytalloc_get_mem_ctx(py_attribute);
663         werr = drsuapi_decrypt_attribute(context, &gensec_skey,
664                                          rid, 0, attribute);
665         if (!W_ERROR_IS_OK(werr)) {
666                 char *error_string = talloc_asprintf(frame,
667                                                      "Unable to get decrypt attribute: %s",
668                                                      win_errstr(werr));
669                 PyErr_SetWERROR_and_string(werr, error_string);
670                 talloc_free(frame);
671                 return NULL;
672         }
673
674         talloc_free(frame);
675
676         Py_RETURN_NONE;
677
678 }
679
680 /*
681   find a DC given a domain name and server type
682  */
683 static PyObject *py_net_finddc(py_net_Object *self, PyObject *args, PyObject *kwargs)
684 {
685         const char *domain = NULL, *address = NULL;
686         unsigned server_type;
687         NTSTATUS status;
688         struct finddcs *io;
689         TALLOC_CTX *mem_ctx;
690         PyObject *ret;
691         const char * const kwnames[] = { "flags", "domain", "address", NULL };
692
693         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "I|zz",
694                                          discard_const_p(char *, kwnames),
695                                          &server_type, &domain, &address)) {
696                 return NULL;
697         }
698
699         mem_ctx = talloc_new(self->mem_ctx);
700
701         io = talloc_zero(mem_ctx, struct finddcs);
702         if (domain != NULL) {
703                 io->in.domain_name = domain;
704         }
705         if (address != NULL) {
706                 io->in.server_address = address;
707         }
708         io->in.minimum_dc_flags = server_type;
709
710         status = finddcs_cldap(io, io,
711                                lpcfg_resolve_context(self->libnet_ctx->lp_ctx), self->ev);
712         if (NT_STATUS_IS_ERR(status)) {
713                 PyErr_SetNTSTATUS(status);
714                 talloc_free(mem_ctx);
715                 return NULL;
716         }
717
718         ret = py_return_ndr_struct("samba.dcerpc.nbt", "NETLOGON_SAM_LOGON_RESPONSE_EX",
719                                    io, &io->out.netlogon.data.nt5_ex);
720         talloc_free(mem_ctx);
721
722         return ret;
723 }
724
725
726 static const char py_net_replicate_init_doc[] = "replicate_init(samdb, lp, drspipe)\n"
727                                          "Setup for replicate_chunk calls.";
728
729 static const char py_net_replicate_chunk_doc[] = "replicate_chunk(state, level, ctr, schema)\n"
730                                          "Process replication for one chunk";
731
732 static const char py_net_replicate_decrypt_doc[] = "replicate_decrypt(drs, attribute, rid)\n"
733                                          "Decrypt (in place) a DsReplicaAttribute replicated with drs.GetNCChanges()";
734
735 static const char py_net_finddc_doc[] = "finddc(flags=server_type, domain=None, address=None)\n"
736                                          "Find a DC with the specified 'server_type' bits. The 'domain' and/or 'address' have to be used as additional search criteria. Returns the whole netlogon struct";
737
738 static PyMethodDef net_obj_methods[] = {
739         {"join_member", (PyCFunction)py_net_join_member, METH_VARARGS|METH_KEYWORDS, py_net_join_member_doc},
740         {"change_password", (PyCFunction)py_net_change_password, METH_VARARGS|METH_KEYWORDS, py_net_change_password_doc},
741         {"set_password", (PyCFunction)py_net_set_password, METH_VARARGS|METH_KEYWORDS, py_net_set_password_doc},
742         {"time", (PyCFunction)py_net_time, METH_VARARGS|METH_KEYWORDS, py_net_time_doc},
743         {"create_user", (PyCFunction)py_net_user_create, METH_VARARGS|METH_KEYWORDS, py_net_create_user_doc},
744         {"delete_user", (PyCFunction)py_net_user_delete, METH_VARARGS|METH_KEYWORDS, py_net_delete_user_doc},
745         {"replicate_init", (PyCFunction)py_net_replicate_init, METH_VARARGS|METH_KEYWORDS, py_net_replicate_init_doc},
746         {"replicate_chunk", (PyCFunction)py_net_replicate_chunk, METH_VARARGS|METH_KEYWORDS, py_net_replicate_chunk_doc},
747         {"replicate_decrypt", (PyCFunction)py_net_replicate_decrypt, METH_VARARGS|METH_KEYWORDS, py_net_replicate_decrypt_doc},
748         {"finddc", (PyCFunction)py_net_finddc, METH_KEYWORDS, py_net_finddc_doc},
749         { NULL }
750 };
751
752 static void py_net_dealloc(py_net_Object *self)
753 {
754         talloc_free(self->mem_ctx);
755         PyObject_Del(self);
756 }
757
758 static PyObject *net_obj_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
759 {
760         PyObject *py_creds, *py_lp = Py_None;
761         const char *kwnames[] = { "creds", "lp", "server", NULL };
762         py_net_Object *ret;
763         struct loadparm_context *lp;
764         const char *server_address = NULL;
765
766         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|Oz",
767                                          discard_const_p(char *, kwnames), &py_creds, &py_lp,
768                                          &server_address))
769                 return NULL;
770
771         ret = PyObject_New(py_net_Object, type);
772         if (ret == NULL) {
773                 return NULL;
774         }
775
776         /* FIXME: we really need to get a context from the caller or we may end
777          * up with 2 event contexts */
778         ret->ev = s4_event_context_init(NULL);
779         ret->mem_ctx = talloc_new(ret->ev);
780
781         lp = lpcfg_from_py_object(ret->mem_ctx, py_lp);
782         if (lp == NULL) {
783                 Py_DECREF(ret);
784                 return NULL;
785         }
786
787         ret->libnet_ctx = libnet_context_init(ret->ev, lp);
788         if (ret->libnet_ctx == NULL) {
789                 PyErr_SetString(PyExc_RuntimeError, "Unable to initialize net");
790                 Py_DECREF(ret);
791                 return NULL;
792         }
793
794         ret->libnet_ctx->server_address = server_address;
795
796         ret->libnet_ctx->cred = cli_credentials_from_py_object(py_creds);
797         if (ret->libnet_ctx->cred == NULL) {
798                 PyErr_SetString(PyExc_TypeError, "Expected credentials object");
799                 Py_DECREF(ret);
800                 return NULL;
801         }
802
803         return (PyObject *)ret;
804 }
805
806
807 PyTypeObject py_net_Type = {
808         PyVarObject_HEAD_INIT(NULL, 0)
809         .tp_name = "net.Net",
810         .tp_basicsize = sizeof(py_net_Object),
811         .tp_dealloc = (destructor)py_net_dealloc,
812         .tp_methods = net_obj_methods,
813         .tp_new = net_obj_new,
814 };
815
816 static struct PyModuleDef moduledef = {
817         PyModuleDef_HEAD_INIT,
818         .m_name = "net",
819         .m_size = -1,
820 };
821
822 MODULE_INIT_FUNC(net)
823 {
824         PyObject *m;
825
826         if (PyType_Ready(&py_net_Type) < 0)
827                 return NULL;
828
829         m = PyModule_Create(&moduledef);
830         if (m == NULL)
831                 return NULL;
832
833         Py_INCREF(&py_net_Type);
834         PyModule_AddObject(m, "Net", (PyObject *)&py_net_Type);
835         PyModule_AddIntConstant(m, "LIBNET_JOINDOMAIN_AUTOMATIC", LIBNET_JOINDOMAIN_AUTOMATIC);
836         PyModule_AddIntConstant(m, "LIBNET_JOINDOMAIN_SPECIFIED", LIBNET_JOINDOMAIN_SPECIFIED);
837         PyModule_AddIntConstant(m, "LIBNET_JOIN_AUTOMATIC", LIBNET_JOIN_AUTOMATIC);
838         PyModule_AddIntConstant(m, "LIBNET_JOIN_SPECIFIED", LIBNET_JOIN_SPECIFIED);
839
840         return m;
841 }