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