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