s4-dsdb: change samdb_replace() to dsdb_replace() and allow for dsdb_flags
[ira/wip.git] / source4 / libnet / libnet_join.c
1 /* 
2    Unix SMB/CIFS implementation.
3    
4    Copyright (C) Stefan Metzmacher      2004
5    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
6    Copyright (C) Brad Henry 2005
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 "includes.h"
23 #include "libnet/libnet.h"
24 #include "librpc/gen_ndr/ndr_drsuapi_c.h"
25 #include "lib/ldb/include/ldb.h"
26 #include "lib/ldb/include/ldb_errors.h"
27 #include "param/secrets.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "ldb_wrap.h"
30 #include "../lib/util/util_ldb.h"
31 #include "libcli/security/security.h"
32 #include "auth/credentials/credentials.h"
33 #include "auth/credentials/credentials_krb5.h"
34 #include "librpc/gen_ndr/ndr_samr_c.h"
35 #include "param/param.h"
36 #include "param/provision.h"
37
38 /*
39  * complete a domain join, when joining to a AD domain:
40  * 1.) connect and bind to the DRSUAPI pipe
41  * 2.) do a DsCrackNames() to find the machine account dn
42  * 3.) connect to LDAP
43  * 4.) do an ldap search to find the "msDS-KeyVersionNumber" of the machine account
44  * 5.) set the servicePrincipalName's of the machine account via LDAP, (maybe we should use DsWriteAccountSpn()...)
45  * 6.) do a DsCrackNames() to find the domain dn
46  * 7.) find out Site specific stuff, look at libnet_JoinSite() for details
47  */
48 static NTSTATUS libnet_JoinADSDomain(struct libnet_context *ctx, struct libnet_JoinDomain *r)
49 {
50         NTSTATUS status;
51
52         TALLOC_CTX *tmp_ctx;
53
54         const char *realm = r->out.realm;
55
56         struct dcerpc_binding *samr_binding = r->out.samr_binding;
57
58         struct dcerpc_pipe *drsuapi_pipe;
59         struct dcerpc_binding *drsuapi_binding;
60         struct drsuapi_DsBind r_drsuapi_bind;
61         struct drsuapi_DsCrackNames r_crack_names;
62         struct drsuapi_DsNameString names[1];
63         struct policy_handle drsuapi_bind_handle;
64         struct GUID drsuapi_bind_guid;
65
66         struct ldb_context *remote_ldb;
67         struct ldb_dn *account_dn;
68         const char *account_dn_str;
69         const char *remote_ldb_url;
70         struct ldb_result *res;
71         struct ldb_message *msg;
72
73         int ret, rtn;
74
75         const char * const attrs[] = {
76                 "msDS-KeyVersionNumber",
77                 "servicePrincipalName",
78                 "dNSHostName",
79                 "objectGUID",
80                 NULL,
81         };
82
83         r->out.error_string = NULL;
84         
85         /* We need to convert between a samAccountName and domain to a
86          * DN in the directory.  The correct way to do this is with
87          * DRSUAPI CrackNames */
88
89         /* Fiddle with the bindings, so get to DRSUAPI on
90          * NCACN_IP_TCP, sealed */
91         tmp_ctx = talloc_named(r, 0, "libnet_JoinADSDomain temp context");  
92         if (!tmp_ctx) {
93                 r->out.error_string = NULL;
94                 return NT_STATUS_NO_MEMORY;
95         }
96                                                    
97         drsuapi_binding = talloc(tmp_ctx, struct dcerpc_binding);
98         if (!drsuapi_binding) {
99                 r->out.error_string = NULL;
100                 talloc_free(tmp_ctx);
101                 return NT_STATUS_NO_MEMORY;
102         }
103         
104         *drsuapi_binding = *samr_binding;
105
106         /* DRSUAPI is only available on IP_TCP, and locally on NCALRPC */
107         if (drsuapi_binding->transport != NCALRPC) {
108                 drsuapi_binding->transport = NCACN_IP_TCP;
109         }
110         drsuapi_binding->endpoint = NULL;
111         drsuapi_binding->flags |= DCERPC_SEAL;
112
113         status = dcerpc_pipe_connect_b(tmp_ctx, 
114                                        &drsuapi_pipe,
115                                        drsuapi_binding,
116                                        &ndr_table_drsuapi,
117                                        ctx->cred, 
118                                        ctx->event_ctx,
119                                        ctx->lp_ctx);
120         if (!NT_STATUS_IS_OK(status)) {
121                 r->out.error_string = talloc_asprintf(r,
122                                         "Connection to DRSUAPI pipe of PDC of domain '%s' failed: %s",
123                                         r->out.domain_name,
124                                         nt_errstr(status));
125                 talloc_free(tmp_ctx);
126                 return status;
127         }
128
129         /* get a DRSUAPI pipe handle */
130         GUID_from_string(DRSUAPI_DS_BIND_GUID, &drsuapi_bind_guid);
131
132         r_drsuapi_bind.in.bind_guid = &drsuapi_bind_guid;
133         r_drsuapi_bind.in.bind_info = NULL;
134         r_drsuapi_bind.out.bind_handle = &drsuapi_bind_handle;
135
136         status = dcerpc_drsuapi_DsBind(drsuapi_pipe, tmp_ctx, &r_drsuapi_bind);
137         if (!NT_STATUS_IS_OK(status)) {
138                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
139                         r->out.error_string
140                                 = talloc_asprintf(r,
141                                                   "dcerpc_drsuapi_DsBind failed - %s", 
142                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
143                         talloc_free(tmp_ctx);
144                         return status;
145                 } else {
146                         r->out.error_string
147                                 = talloc_asprintf(r,
148                                                   "dcerpc_drsuapi_DsBind failed - %s", 
149                                                   nt_errstr(status));
150                         talloc_free(tmp_ctx);
151                         return status;
152                 }
153         } else if (!W_ERROR_IS_OK(r_drsuapi_bind.out.result)) {
154                 r->out.error_string
155                                 = talloc_asprintf(r,
156                                                   "DsBind failed - %s", 
157                                                   win_errstr(r_drsuapi_bind.out.result));
158                         talloc_free(tmp_ctx);
159                 return NT_STATUS_UNSUCCESSFUL;
160         }
161
162         /* Actually 'crack' the names */
163         ZERO_STRUCT(r_crack_names);
164         r_crack_names.in.bind_handle            = &drsuapi_bind_handle;
165         r_crack_names.in.level                  = 1;
166         r_crack_names.in.req                    = talloc(r, union drsuapi_DsNameRequest);
167         if (!r_crack_names.in.req) {
168                 r->out.error_string = NULL;
169                 talloc_free(tmp_ctx);
170                 return NT_STATUS_NO_MEMORY;
171         }
172         r_crack_names.in.req->req1.codepage     = 1252; /* western european */
173         r_crack_names.in.req->req1.language     = 0x00000407; /* german */
174         r_crack_names.in.req->req1.count        = 1;
175         r_crack_names.in.req->req1.names        = names;
176         r_crack_names.in.req->req1.format_flags = DRSUAPI_DS_NAME_FLAG_NO_FLAGS;
177         r_crack_names.in.req->req1.format_offered = DRSUAPI_DS_NAME_FORMAT_SID_OR_SID_HISTORY;
178         r_crack_names.in.req->req1.format_desired = DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
179         names[0].str = dom_sid_string(tmp_ctx, r->out.account_sid);
180         if (!names[0].str) {
181                 r->out.error_string = NULL;
182                 talloc_free(tmp_ctx);
183                 return NT_STATUS_NO_MEMORY;
184         }
185
186         r_crack_names.out.ctr                   = talloc(r, union drsuapi_DsNameCtr);
187         r_crack_names.out.level_out             = talloc(r, int32_t);
188         if (!r_crack_names.out.ctr || !r_crack_names.out.level_out) {
189                 r->out.error_string = NULL;
190                 talloc_free(tmp_ctx);
191                 return NT_STATUS_NO_MEMORY;
192         }
193
194         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
195         if (!NT_STATUS_IS_OK(status)) {
196                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
197                         r->out.error_string
198                                 = talloc_asprintf(r,
199                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s", 
200                                                   names[0].str,
201                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
202                         talloc_free(tmp_ctx);
203                         return status;
204                 } else {
205                         r->out.error_string
206                                 = talloc_asprintf(r,
207                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s", 
208                                                   names[0].str,
209                                                   nt_errstr(status));
210                         talloc_free(tmp_ctx);
211                         return status;
212                 }
213         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
214                 r->out.error_string
215                                 = talloc_asprintf(r,
216                                                   "DsCrackNames failed - %s", win_errstr(r_crack_names.out.result));
217                 talloc_free(tmp_ctx);
218                 return NT_STATUS_UNSUCCESSFUL;
219         } else if (*r_crack_names.out.level_out != 1
220                    || !r_crack_names.out.ctr->ctr1
221                    || r_crack_names.out.ctr->ctr1->count != 1) {
222                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed");
223                 talloc_free(tmp_ctx);
224                 return NT_STATUS_INVALID_PARAMETER;
225         } else if (r_crack_names.out.ctr->ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
226                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed: %d", r_crack_names.out.ctr->ctr1->array[0].status);
227                 talloc_free(tmp_ctx);
228                 return NT_STATUS_UNSUCCESSFUL;
229         } else if (r_crack_names.out.ctr->ctr1->array[0].result_name == NULL) {
230                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed: no result name");
231                 talloc_free(tmp_ctx);
232                 return NT_STATUS_INVALID_PARAMETER;
233         }
234
235         /* Store the DN of our machine account. */
236         account_dn_str = r_crack_names.out.ctr->ctr1->array[0].result_name;
237
238         /* Now we know the user's DN, open with LDAP, read and modify a few things */
239
240         remote_ldb_url = talloc_asprintf(tmp_ctx, "ldap://%s", 
241                                          drsuapi_binding->target_hostname);
242         if (!remote_ldb_url) {
243                 r->out.error_string = NULL;
244                 talloc_free(tmp_ctx);
245                 return NT_STATUS_NO_MEMORY;
246         }
247
248         remote_ldb = ldb_wrap_connect(tmp_ctx, ctx->event_ctx, ctx->lp_ctx, 
249                                       remote_ldb_url, 
250                                       NULL, ctx->cred, 0);
251         if (!remote_ldb) {
252                 r->out.error_string = NULL;
253                 talloc_free(tmp_ctx);
254                 return NT_STATUS_UNSUCCESSFUL;
255         }
256
257         account_dn = ldb_dn_new(tmp_ctx, remote_ldb, account_dn_str);
258         if (! ldb_dn_validate(account_dn)) {
259                 r->out.error_string = talloc_asprintf(r, "Invalid account dn: %s",
260                                                       account_dn_str);
261                 talloc_free(tmp_ctx);
262                 return NT_STATUS_UNSUCCESSFUL;
263         }
264
265         /* search for the user's record */
266         ret = ldb_search(remote_ldb, tmp_ctx, &res,
267                          account_dn, LDB_SCOPE_BASE, attrs, NULL);
268         if (ret != LDB_SUCCESS) {
269                 r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - %s",
270                                                       account_dn_str, ldb_errstring(remote_ldb));
271                 talloc_free(tmp_ctx);
272                 return NT_STATUS_UNSUCCESSFUL;
273         }
274
275         if (res->count != 1) {
276                 r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - found %d entries",
277                                                       account_dn_str, res->count);
278                 talloc_free(tmp_ctx);
279                 return NT_STATUS_UNSUCCESSFUL;
280         }
281
282         /* Prepare a new message, for the modify */
283         msg = ldb_msg_new(tmp_ctx);
284         if (!msg) {
285                 r->out.error_string = NULL;
286                 talloc_free(tmp_ctx);
287                 return NT_STATUS_NO_MEMORY;
288         }
289         msg->dn = res->msgs[0]->dn;
290
291         {
292                 int i;
293                 const char *service_principal_name[6];
294                 const char *dns_host_name = strlower_talloc(tmp_ctx, 
295                                                             talloc_asprintf(tmp_ctx, 
296                                                                             "%s.%s", 
297                                                                             r->in.netbios_name, 
298                                                                             realm));
299
300                 if (!dns_host_name) {
301                         r->out.error_string = NULL;
302                         talloc_free(tmp_ctx);
303                         return NT_STATUS_NO_MEMORY;
304                 }
305
306                 service_principal_name[0] = talloc_asprintf(tmp_ctx, "host/%s", dns_host_name);
307                 service_principal_name[1] = talloc_asprintf(tmp_ctx, "host/%s", strlower_talloc(tmp_ctx, r->in.netbios_name));
308                 service_principal_name[2] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, realm);
309                 service_principal_name[3] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), realm);
310                 service_principal_name[4] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, r->out.domain_name);
311                 service_principal_name[5] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), r->out.domain_name);
312                 
313                 for (i=0; i < ARRAY_SIZE(service_principal_name); i++) {
314                         if (!service_principal_name[i]) {
315                                 r->out.error_string = NULL;
316                                 talloc_free(tmp_ctx);
317                                 return NT_STATUS_NO_MEMORY;
318                         }
319                         rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "servicePrincipalName", service_principal_name[i]);
320                         if (rtn == -1) {
321                                 r->out.error_string = NULL;
322                                 talloc_free(tmp_ctx);
323                                 return NT_STATUS_NO_MEMORY;
324                         }
325                 }
326
327                 rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "dNSHostName", dns_host_name);
328                 if (rtn == -1) {
329                         r->out.error_string = NULL;
330                         talloc_free(tmp_ctx);
331                         return NT_STATUS_NO_MEMORY;
332                 }
333
334                 rtn = dsdb_replace(remote_ldb, msg, 0);
335                 if (rtn != 0) {
336                         r->out.error_string
337                                 = talloc_asprintf(r, 
338                                                   "Failed to replace entries on %s", 
339                                                   ldb_dn_get_linearized(msg->dn));
340                         talloc_free(tmp_ctx);
341                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
342                 }
343         }
344                                 
345         /* DsCrackNames to find out the DN of the domain. */
346         r_crack_names.in.req->req1.format_offered = DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT;
347         r_crack_names.in.req->req1.format_desired = DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
348         names[0].str = talloc_asprintf(tmp_ctx, "%s\\", r->out.domain_name);
349         if (!names[0].str) {
350                 r->out.error_string = NULL;
351                 talloc_free(tmp_ctx);
352                 return NT_STATUS_NO_MEMORY;
353         }
354
355         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
356         if (!NT_STATUS_IS_OK(status)) {
357                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
358                         r->out.error_string
359                                 = talloc_asprintf(r,
360                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s", 
361                                                   r->in.domain_name, 
362                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
363                         talloc_free(tmp_ctx);
364                         return status;
365                 } else {
366                         r->out.error_string
367                                 = talloc_asprintf(r,
368                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s", 
369                                                   r->in.domain_name, 
370                                                   nt_errstr(status));
371                         talloc_free(tmp_ctx);
372                         return status;
373                 }
374         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
375                 r->out.error_string
376                         = talloc_asprintf(r,
377                                           "DsCrackNames failed - %s", win_errstr(r_crack_names.out.result));
378                 talloc_free(tmp_ctx);
379                 return NT_STATUS_UNSUCCESSFUL;
380         } else if (*r_crack_names.out.level_out != 1
381                    || !r_crack_names.out.ctr->ctr1
382                    || r_crack_names.out.ctr->ctr1->count != 1
383                    || !r_crack_names.out.ctr->ctr1->array[0].result_name
384                    || r_crack_names.out.ctr->ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
385                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed");
386                 talloc_free(tmp_ctx);
387                 return NT_STATUS_UNSUCCESSFUL;
388         }
389
390         /* Store the account DN. */
391         r->out.account_dn_str = account_dn_str;
392         talloc_steal(r, account_dn_str);
393
394         /* Store the domain DN. */
395         r->out.domain_dn_str = r_crack_names.out.ctr->ctr1->array[0].result_name;
396         talloc_steal(r, r_crack_names.out.ctr->ctr1->array[0].result_name);
397
398         /* Store the KVNO of the account, critical for some kerberos
399          * operations */
400         r->out.kvno = ldb_msg_find_attr_as_uint(res->msgs[0], "msDS-KeyVersionNumber", 0);
401
402         /* Store the account GUID. */
403         r->out.account_guid = samdb_result_guid(res->msgs[0], "objectGUID");
404
405         if (r->in.acct_type == ACB_SVRTRUST) {
406                 status = libnet_JoinSite(ctx, remote_ldb, r);
407         }
408         talloc_free(tmp_ctx);
409
410         return status;
411 }
412
413 /*
414  * do a domain join using DCERPC/SAMR calls
415  * - connect to the LSA pipe, to try and find out information about the domain
416  * - create a secondary connection to SAMR pipe
417  * - do a samr_Connect to get a policy handle
418  * - do a samr_LookupDomain to get the domain sid
419  * - do a samr_OpenDomain to get a domain handle
420  * - do a samr_CreateAccount to try and get a new account 
421  * 
422  * If that fails, do:
423  * - do a samr_LookupNames to get the users rid
424  * - do a samr_OpenUser to get a user handle
425  * - potentially delete and recreate the user
426  * - assert the account is of the right type with samrQueryUserInfo
427  * 
428  * - call libnet_SetPassword_samr_handle to set the password,
429  *   and pass a samr_UserInfo21 struct to set full_name and the account flags
430  *
431  * - do some ADS specific things when we join as Domain Controller,
432  *    look at libnet_joinADSDomain() for the details
433  */
434 NTSTATUS libnet_JoinDomain(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_JoinDomain *r)
435 {
436         TALLOC_CTX *tmp_ctx;
437
438         NTSTATUS status, cu_status;
439
440         struct libnet_RpcConnect *connect_with_info;
441         struct dcerpc_pipe *samr_pipe;
442
443         struct samr_Connect sc;
444         struct policy_handle p_handle;
445         struct samr_OpenDomain od;
446         struct policy_handle d_handle;
447         struct samr_LookupNames ln;
448         struct samr_Ids rids, types;
449         struct samr_OpenUser ou;
450         struct samr_CreateUser2 cu;
451         struct policy_handle *u_handle = NULL;
452         struct samr_QueryUserInfo qui;
453         union samr_UserInfo *uinfo;
454         struct samr_UserInfo21 u_info21;
455         union libnet_SetPassword r2;
456         struct samr_GetUserPwInfo pwp;
457         struct samr_PwInfo info;
458         struct lsa_String samr_account_name;
459         
460         uint32_t acct_flags, old_acct_flags;
461         uint32_t rid, access_granted;
462         int policy_min_pw_len = 0;
463
464         struct dom_sid *account_sid = NULL;
465         const char *password_str = NULL;
466         
467         r->out.error_string = NULL;
468         r2.samr_handle.out.error_string = NULL;
469         
470         tmp_ctx = talloc_named(mem_ctx, 0, "libnet_Join temp context");
471         if (!tmp_ctx) {
472                 r->out.error_string = NULL;
473                 return NT_STATUS_NO_MEMORY;
474         }
475         
476         u_handle = talloc(tmp_ctx, struct policy_handle);
477         if (!u_handle) {
478                 r->out.error_string = NULL;
479                 talloc_free(tmp_ctx);
480                 return NT_STATUS_NO_MEMORY;
481         }
482         
483         connect_with_info = talloc_zero(tmp_ctx, struct libnet_RpcConnect);
484         if (!connect_with_info) {
485                 r->out.error_string = NULL;
486                 talloc_free(tmp_ctx);
487                 return NT_STATUS_NO_MEMORY;
488         }
489
490         /* prepare connect to the SAMR pipe of PDC */
491         if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
492                 connect_with_info->in.binding = NULL;
493                 connect_with_info->in.name    = r->in.domain_name;
494         } else {
495                 connect_with_info->in.binding = r->in.binding;
496                 connect_with_info->in.name    = NULL;
497         }
498
499         /* This level makes a connection to the LSA pipe on the way,
500          * to get some useful bits of information about the domain */
501         connect_with_info->level              = LIBNET_RPC_CONNECT_DC_INFO;
502         connect_with_info->in.dcerpc_iface    = &ndr_table_samr;
503
504         /*
505           establish the SAMR connection
506         */
507         status = libnet_RpcConnect(ctx, tmp_ctx, connect_with_info);
508         if (!NT_STATUS_IS_OK(status)) {
509                 if (r->in.binding) {
510                         r->out.error_string = talloc_asprintf(mem_ctx,
511                                                               "Connection to SAMR pipe of DC %s failed: %s",
512                                                               r->in.binding, connect_with_info->out.error_string);
513                 } else {
514                         r->out.error_string = talloc_asprintf(mem_ctx,
515                                                               "Connection to SAMR pipe of PDC for %s failed: %s",
516                                                               r->in.domain_name, connect_with_info->out.error_string);
517                 }
518                 talloc_free(tmp_ctx);
519                 return status;
520         }
521
522         samr_pipe = connect_with_info->out.dcerpc_pipe;
523
524         status = dcerpc_pipe_auth(tmp_ctx, &samr_pipe,
525                                   connect_with_info->out.dcerpc_pipe->binding, 
526                                   &ndr_table_samr, ctx->cred, ctx->lp_ctx);
527         if (!NT_STATUS_IS_OK(status)) {
528                 r->out.error_string = talloc_asprintf(mem_ctx,
529                                                 "SAMR bind failed: %s",
530                                                 nt_errstr(status));
531                 talloc_free(tmp_ctx);
532                 return status;
533         }
534
535         /* prepare samr_Connect */
536         ZERO_STRUCT(p_handle);
537         sc.in.system_name = NULL;
538         sc.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
539         sc.out.connect_handle = &p_handle;
540
541         /* 2. do a samr_Connect to get a policy handle */
542         status = dcerpc_samr_Connect(samr_pipe, tmp_ctx, &sc);
543         if (!NT_STATUS_IS_OK(status)) {
544                 r->out.error_string = talloc_asprintf(mem_ctx,
545                                                 "samr_Connect failed: %s",
546                                                 nt_errstr(status));
547                 talloc_free(tmp_ctx);
548                 return status;
549         }
550
551         /* If this is a connection on ncacn_ip_tcp to Win2k3 SP1, we don't get back this useful info */
552         if (!connect_with_info->out.domain_name) {
553                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
554                         connect_with_info->out.domain_name = talloc_strdup(tmp_ctx, r->in.domain_name);
555                 } else {
556                         /* Bugger, we just lost our way to automaticly find the domain name */
557                         connect_with_info->out.domain_name = talloc_strdup(tmp_ctx, lp_workgroup(ctx->lp_ctx));
558                         connect_with_info->out.realm = talloc_strdup(tmp_ctx, lp_realm(ctx->lp_ctx));
559                 }
560         }
561
562         /* Perhaps we didn't get a SID above, because we are against ncacn_ip_tcp */
563         if (!connect_with_info->out.domain_sid) {
564                 struct lsa_String name;
565                 struct samr_LookupDomain l;
566                 struct dom_sid2 *sid = NULL;
567                 name.string = connect_with_info->out.domain_name;
568                 l.in.connect_handle = &p_handle;
569                 l.in.domain_name = &name;
570                 l.out.sid = &sid;
571                 
572                 status = dcerpc_samr_LookupDomain(samr_pipe, tmp_ctx, &l);
573                 if (!NT_STATUS_IS_OK(status)) {
574                         r->out.error_string = talloc_asprintf(mem_ctx,
575                                                               "SAMR LookupDomain failed: %s",
576                                                               nt_errstr(status));
577                         talloc_free(tmp_ctx);
578                         return status;
579                 }
580                 connect_with_info->out.domain_sid = *l.out.sid;
581         }
582
583         /* prepare samr_OpenDomain */
584         ZERO_STRUCT(d_handle);
585         od.in.connect_handle = &p_handle;
586         od.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
587         od.in.sid = connect_with_info->out.domain_sid;
588         od.out.domain_handle = &d_handle;
589
590         /* do a samr_OpenDomain to get a domain handle */
591         status = dcerpc_samr_OpenDomain(samr_pipe, tmp_ctx, &od);                       
592         if (!NT_STATUS_IS_OK(status)) {
593                 r->out.error_string = talloc_asprintf(mem_ctx,
594                                                       "samr_OpenDomain for [%s] failed: %s",
595                                                       dom_sid_string(tmp_ctx, connect_with_info->out.domain_sid),
596                                                       nt_errstr(status));
597                 talloc_free(tmp_ctx);
598                 return status;
599         }
600         
601         /* prepare samr_CreateUser2 */
602         ZERO_STRUCTP(u_handle);
603         cu.in.domain_handle  = &d_handle;
604         cu.in.access_mask     = SEC_FLAG_MAXIMUM_ALLOWED;
605         samr_account_name.string = r->in.account_name;
606         cu.in.account_name    = &samr_account_name;
607         cu.in.acct_flags      = r->in.acct_type;
608         cu.out.user_handle    = u_handle;
609         cu.out.rid            = &rid;
610         cu.out.access_granted = &access_granted;
611
612         /* do a samr_CreateUser2 to get an account handle, or an error */
613         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
614         status = cu_status;
615         if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
616                 /* prepare samr_LookupNames */
617                 ln.in.domain_handle = &d_handle;
618                 ln.in.num_names = 1;
619                 ln.in.names = talloc_array(tmp_ctx, struct lsa_String, 1);
620                 ln.out.rids = &rids;
621                 ln.out.types = &types;
622                 if (!ln.in.names) {
623                         r->out.error_string = NULL;
624                         talloc_free(tmp_ctx);
625                         return NT_STATUS_NO_MEMORY;
626                 }
627                 ln.in.names[0].string = r->in.account_name;
628                 
629                 /* 5. do a samr_LookupNames to get the users rid */
630                 status = dcerpc_samr_LookupNames(samr_pipe, tmp_ctx, &ln);
631                 if (!NT_STATUS_IS_OK(status)) {
632                         r->out.error_string = talloc_asprintf(mem_ctx,
633                                                 "samr_LookupNames for [%s] failed: %s",
634                                                 r->in.account_name,
635                                                 nt_errstr(status));
636                         talloc_free(tmp_ctx);
637                         return status;
638                 }
639                 
640                 /* check if we got one RID for the user */
641                 if (ln.out.rids->count != 1) {
642                         r->out.error_string = talloc_asprintf(mem_ctx,
643                                                               "samr_LookupNames for [%s] returns %d RIDs",
644                                                               r->in.account_name, ln.out.rids->count);
645                         talloc_free(tmp_ctx);
646                         return NT_STATUS_INVALID_PARAMETER;
647                 }
648                 
649                 /* prepare samr_OpenUser */
650                 ZERO_STRUCTP(u_handle);
651                 ou.in.domain_handle = &d_handle;
652                 ou.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
653                 ou.in.rid = ln.out.rids->ids[0];
654                 rid = ou.in.rid;
655                 ou.out.user_handle = u_handle;
656                 
657                 /* 6. do a samr_OpenUser to get a user handle */
658                 status = dcerpc_samr_OpenUser(samr_pipe, tmp_ctx, &ou); 
659                 if (!NT_STATUS_IS_OK(status)) {
660                         r->out.error_string = talloc_asprintf(mem_ctx,
661                                                         "samr_OpenUser for [%s] failed: %s",
662                                                         r->in.account_name,
663                                                         nt_errstr(status));
664                         talloc_free(tmp_ctx);
665                         return status;
666                 }
667
668                 if (r->in.recreate_account) {
669                         struct samr_DeleteUser d;
670                         d.in.user_handle = u_handle;
671                         d.out.user_handle = u_handle;
672                         status = dcerpc_samr_DeleteUser(samr_pipe, mem_ctx, &d);
673                         if (!NT_STATUS_IS_OK(status)) {
674                                 r->out.error_string = talloc_asprintf(mem_ctx,
675                                                                       "samr_DeleteUser (for recreate) of [%s] failed: %s",
676                                                                       r->in.account_name,
677                                                                       nt_errstr(status));
678                                 talloc_free(tmp_ctx);
679                                 return status;
680                         }
681
682                         /* We want to recreate, so delete and another samr_CreateUser2 */
683                         
684                         /* &cu filled in above */
685                         status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                      
686                         if (!NT_STATUS_IS_OK(status)) {
687                                 r->out.error_string = talloc_asprintf(mem_ctx,
688                                                                       "samr_CreateUser2 (recreate) for [%s] failed: %s",
689                                                                       r->in.account_name, nt_errstr(status));
690                                 talloc_free(tmp_ctx);
691                                 return status;
692                         }
693                 }
694         } else if (!NT_STATUS_IS_OK(status)) {
695                 r->out.error_string = talloc_asprintf(mem_ctx,
696                                                       "samr_CreateUser2 for [%s] failed: %s",
697                                                       r->in.account_name, nt_errstr(status));
698                 talloc_free(tmp_ctx);
699                 return status;
700         }
701
702         /* prepare samr_QueryUserInfo (get flags) */
703         qui.in.user_handle = u_handle;
704         qui.in.level = 16;
705         qui.out.info = &uinfo;
706         
707         status = dcerpc_samr_QueryUserInfo(samr_pipe, tmp_ctx, &qui);
708         if (!NT_STATUS_IS_OK(status)) {
709                 r->out.error_string = talloc_asprintf(mem_ctx,
710                                                 "samr_QueryUserInfo for [%s] failed: %s",
711                                                 r->in.account_name,
712                                                 nt_errstr(status));
713                 talloc_free(tmp_ctx);
714                 return status;
715         }
716         
717         if (!uinfo) {
718                 status = NT_STATUS_INVALID_PARAMETER;
719                 r->out.error_string
720                         = talloc_asprintf(mem_ctx,
721                                           "samr_QueryUserInfo failed to return qui.out.info for [%s]: %s",
722                                           r->in.account_name, nt_errstr(status));
723                 talloc_free(tmp_ctx);
724                 return status;
725         }
726
727         old_acct_flags = (uinfo->info16.acct_flags & (ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST));
728         /* Possibly bail if the account is of the wrong type */
729         if (old_acct_flags
730             != r->in.acct_type) {
731                 const char *old_account_type, *new_account_type;
732                 switch (old_acct_flags) {
733                 case ACB_WSTRUST:
734                         old_account_type = "domain member (member)";
735                         break;
736                 case ACB_SVRTRUST:
737                         old_account_type = "domain controller (bdc)";
738                         break;
739                 case ACB_DOMTRUST:
740                         old_account_type = "trusted domain";
741                         break;
742                 default:
743                         return NT_STATUS_INVALID_PARAMETER;
744                 }
745                 switch (r->in.acct_type) {
746                 case ACB_WSTRUST:
747                         new_account_type = "domain member (member)";
748                         break;
749                 case ACB_SVRTRUST:
750                         new_account_type = "domain controller (bdc)";
751                         break;
752                 case ACB_DOMTRUST:
753                         new_account_type = "trusted domain";
754                         break;
755                 default:
756                         return NT_STATUS_INVALID_PARAMETER;
757                 }
758
759                 if (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS)) {
760                         /* We created a new user, but they didn't come out the right type?!? */
761                         r->out.error_string
762                                 = talloc_asprintf(mem_ctx,
763                                                   "We asked to create a new machine account (%s) of type %s, "
764                                                   "but we got an account of type %s.  This is unexpected.  "
765                                                   "Perhaps delete the account and try again.",
766                                                   r->in.account_name, new_account_type, old_account_type);
767                         talloc_free(tmp_ctx);
768                         return NT_STATUS_INVALID_PARAMETER;
769                 } else {
770                         /* The account is of the wrong type, so bail */
771
772                         /* TODO: We should allow a --force option to override, and redo this from the top setting r.in.recreate_account */
773                         r->out.error_string
774                                 = talloc_asprintf(mem_ctx,
775                                                   "The machine account (%s) already exists in the domain %s, "
776                                                   "but is a %s.  You asked to join as a %s.  Please delete "
777                                                   "the account and try again.",
778                                                   r->in.account_name, connect_with_info->out.domain_name, old_account_type, new_account_type);
779                         talloc_free(tmp_ctx);
780                         return NT_STATUS_USER_EXISTS;
781                 }
782         } else {
783                 acct_flags = uinfo->info16.acct_flags;
784         }
785         
786         acct_flags = (acct_flags & ~(ACB_DISABLED|ACB_PWNOTREQ));
787
788         /* Find out what password policy this user has */
789         pwp.in.user_handle = u_handle;
790         pwp.out.info = &info;
791
792         status = dcerpc_samr_GetUserPwInfo(samr_pipe, tmp_ctx, &pwp);                           
793         if (NT_STATUS_IS_OK(status)) {
794                 policy_min_pw_len = pwp.out.info->min_password_length;
795         }
796         
797         /* Grab a password of that minimum length */
798         
799         password_str = generate_random_str(tmp_ctx, MAX(8, policy_min_pw_len)); 
800
801         /* set full_name and reset flags */
802         ZERO_STRUCT(u_info21);
803         u_info21.full_name.string       = r->in.account_name;
804         u_info21.acct_flags             = acct_flags;
805         u_info21.fields_present         = SAMR_FIELD_FULL_NAME | SAMR_FIELD_ACCT_FLAGS;
806
807         r2.samr_handle.level            = LIBNET_SET_PASSWORD_SAMR_HANDLE;
808         r2.samr_handle.in.account_name  = r->in.account_name;
809         r2.samr_handle.in.newpassword   = password_str;
810         r2.samr_handle.in.user_handle   = u_handle;
811         r2.samr_handle.in.dcerpc_pipe   = samr_pipe;
812         r2.samr_handle.in.info21        = &u_info21;
813
814         status = libnet_SetPassword(ctx, tmp_ctx, &r2); 
815         if (!NT_STATUS_IS_OK(status)) {
816                 r->out.error_string = talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
817                 talloc_free(tmp_ctx);
818                 return status;
819         }
820
821         account_sid = dom_sid_add_rid(mem_ctx, connect_with_info->out.domain_sid, rid);
822         if (!account_sid) {
823                 r->out.error_string = NULL;
824                 talloc_free(tmp_ctx);
825                 return NT_STATUS_NO_MEMORY;
826         }
827
828         /* Finish out by pushing various bits of status data out for the caller to use */
829         r->out.join_password = password_str;
830         talloc_steal(mem_ctx, r->out.join_password);
831
832         r->out.domain_sid = connect_with_info->out.domain_sid;
833         talloc_steal(mem_ctx, r->out.domain_sid);
834
835         r->out.account_sid = account_sid;
836         talloc_steal(mem_ctx, r->out.account_sid);
837
838         r->out.domain_name = connect_with_info->out.domain_name;
839         talloc_steal(mem_ctx, r->out.domain_name);
840         r->out.realm = connect_with_info->out.realm;
841         talloc_steal(mem_ctx, r->out.realm);
842         r->out.samr_pipe = samr_pipe;
843         talloc_reparent(tmp_ctx, mem_ctx, samr_pipe);
844         r->out.samr_binding = samr_pipe->binding;
845         talloc_steal(mem_ctx, r->out.samr_binding);
846         r->out.user_handle = u_handle;
847         talloc_steal(mem_ctx, u_handle);
848         r->out.error_string = r2.samr_handle.out.error_string;
849         talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
850         r->out.kvno = 0;
851         r->out.server_dn_str = NULL;
852         talloc_free(tmp_ctx); 
853
854         /* Now, if it was AD, then we want to start looking changing a
855          * few more things.  Otherwise, we are done. */
856         if (r->out.realm) {
857                 status = libnet_JoinADSDomain(ctx, r);
858                 return status;
859         }
860
861         return status;
862 }
863
864 static NTSTATUS libnet_Join_primary_domain(struct libnet_context *ctx, 
865                                            TALLOC_CTX *mem_ctx, 
866                                            struct libnet_Join *r)
867 {
868         NTSTATUS status;
869         TALLOC_CTX *tmp_mem;
870         struct libnet_JoinDomain *r2;
871         struct provision_store_self_join_settings *set_secrets;
872         uint32_t acct_type = 0;
873         const char *account_name;
874         const char *netbios_name;
875         const char *error_string;
876
877         r->out.error_string = NULL;
878
879         tmp_mem = talloc_new(mem_ctx);
880         if (!tmp_mem) {
881                 return NT_STATUS_NO_MEMORY;
882         }
883
884         r2 = talloc(tmp_mem, struct libnet_JoinDomain);
885         if (!r2) {
886                 r->out.error_string = NULL;
887                 talloc_free(tmp_mem);
888                 return NT_STATUS_NO_MEMORY;
889         }
890         
891         if (r->in.join_type == SEC_CHAN_BDC) {
892                 acct_type = ACB_SVRTRUST;
893         } else if (r->in.join_type == SEC_CHAN_WKSTA) {
894                 acct_type = ACB_WSTRUST;
895         } else {
896                 r->out.error_string = NULL;
897                 talloc_free(tmp_mem);   
898                 return NT_STATUS_INVALID_PARAMETER;
899         }
900
901         if (r->in.netbios_name != NULL) {
902                 netbios_name = r->in.netbios_name;
903         } else {
904                 netbios_name = talloc_strdup(tmp_mem, lp_netbios_name(ctx->lp_ctx));
905                 if (!netbios_name) {
906                         r->out.error_string = NULL;
907                         talloc_free(tmp_mem);
908                         return NT_STATUS_NO_MEMORY;
909                 }
910         }
911
912         account_name = talloc_asprintf(tmp_mem, "%s$", netbios_name);
913         if (!account_name) {
914                 r->out.error_string = NULL;
915                 talloc_free(tmp_mem);
916                 return NT_STATUS_NO_MEMORY;
917         }
918         
919         /*
920          * join the domain
921          */
922         ZERO_STRUCTP(r2);
923         r2->in.domain_name      = r->in.domain_name;
924         r2->in.account_name     = account_name;
925         r2->in.netbios_name     = netbios_name;
926         r2->in.level            = LIBNET_JOINDOMAIN_AUTOMATIC;
927         r2->in.acct_type        = acct_type;
928         r2->in.recreate_account = false;
929         status = libnet_JoinDomain(ctx, r2, r2);
930         if (!NT_STATUS_IS_OK(status)) {
931                 r->out.error_string = talloc_steal(mem_ctx, r2->out.error_string);
932                 talloc_free(tmp_mem);
933                 return status;
934         }
935
936         set_secrets = talloc(tmp_mem, struct provision_store_self_join_settings);
937         if (!set_secrets) {
938                 r->out.error_string = NULL;
939                 talloc_free(tmp_mem);
940                 return NT_STATUS_NO_MEMORY;
941         }
942         
943         ZERO_STRUCTP(set_secrets);
944         set_secrets->domain_name = r2->out.domain_name;
945         set_secrets->realm = r2->out.realm;
946         set_secrets->account_name = account_name;
947         set_secrets->netbios_name = netbios_name;
948         set_secrets->secure_channel_type = r->in.join_type;
949         set_secrets->machine_password = r2->out.join_password;
950         set_secrets->key_version_number = r2->out.kvno;
951         set_secrets->domain_sid = r2->out.domain_sid;
952         
953         status = provision_store_self_join(ctx, ctx->lp_ctx, ctx->event_ctx, set_secrets, &error_string);
954         if (!NT_STATUS_IS_OK(status)) {
955                 r->out.error_string = talloc_steal(mem_ctx, error_string);
956                 talloc_free(tmp_mem);
957                 return status;
958         }
959
960         /* move all out parameter to the callers TALLOC_CTX */
961         r->out.error_string     = NULL;
962         r->out.join_password    = r2->out.join_password;
963         talloc_reparent(r2, mem_ctx, r2->out.join_password);
964         r->out.domain_sid       = r2->out.domain_sid;
965         talloc_reparent(r2, mem_ctx, r2->out.domain_sid);
966         r->out.domain_name      = r2->out.domain_name;
967         talloc_reparent(r2, mem_ctx, r2->out.domain_name);
968         talloc_free(tmp_mem);
969         return NT_STATUS_OK;
970 }
971
972 NTSTATUS libnet_Join(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_Join *r)
973 {
974         switch (r->in.join_type) {
975                 case SEC_CHAN_WKSTA:
976                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
977                 case SEC_CHAN_BDC:
978                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
979                 case SEC_CHAN_DOMAIN:
980                 case SEC_CHAN_DNS_DOMAIN:
981                 case SEC_CHAN_NULL:
982                         break;
983         }
984
985         r->out.error_string = talloc_asprintf(mem_ctx,
986                                               "Invalid join type specified (%08X) attempting to join domain %s",
987                                               r->in.join_type, r->in.domain_name);
988         return NT_STATUS_INVALID_PARAMETER;
989 }