59850bb20e6d0bc1dc554c1bba9f372efbc742d2
[samba.git] / source3 / auth / auth_util.c
1 /*
2    Unix SMB/CIFS implementation.
3    Authentication utility functions
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Andrew Bartlett 2001-2011
6    Copyright (C) Jeremy Allison 2000-2001
7    Copyright (C) Rafal Szczesniak 2002
8    Copyright (C) Volker Lendecke 2006
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "auth.h"
26 #include "../libcli/auth/libcli_auth.h"
27 #include "../lib/crypto/arcfour.h"
28 #include "rpc_client/init_lsa.h"
29 #include "../libcli/security/security.h"
30 #include "../lib/util/util_pw.h"
31 #include "lib/winbind_util.h"
32 #include "passdb.h"
33
34 #undef DBGC_CLASS
35 #define DBGC_CLASS DBGC_AUTH
36
37 /****************************************************************************
38  Create a UNIX user on demand.
39 ****************************************************************************/
40
41 static int _smb_create_user(const char *domain, const char *unix_username, const char *homedir)
42 {
43         TALLOC_CTX *ctx = talloc_tos();
44         char *add_script;
45         int ret;
46
47         add_script = talloc_strdup(ctx, lp_adduser_script());
48         if (!add_script || !*add_script) {
49                 return -1;
50         }
51         add_script = talloc_all_string_sub(ctx,
52                                 add_script,
53                                 "%u",
54                                 unix_username);
55         if (!add_script) {
56                 return -1;
57         }
58         if (domain) {
59                 add_script = talloc_all_string_sub(ctx,
60                                         add_script,
61                                         "%D",
62                                         domain);
63                 if (!add_script) {
64                         return -1;
65                 }
66         }
67         if (homedir) {
68                 add_script = talloc_all_string_sub(ctx,
69                                 add_script,
70                                 "%H",
71                                 homedir);
72                 if (!add_script) {
73                         return -1;
74                 }
75         }
76         ret = smbrun(add_script,NULL);
77         flush_pwnam_cache();
78         DEBUG(ret ? 0 : 3,
79                 ("smb_create_user: Running the command `%s' gave %d\n",
80                  add_script,ret));
81         return ret;
82 }
83
84 /****************************************************************************
85  Create an auth_usersupplied_data structure after appropriate mapping.
86 ****************************************************************************/
87
88 NTSTATUS make_user_info_map(struct auth_usersupplied_info **user_info,
89                             const char *smb_name,
90                             const char *client_domain,
91                             const char *workstation_name,
92                             const struct tsocket_address *remote_address,
93                             DATA_BLOB *lm_pwd,
94                             DATA_BLOB *nt_pwd,
95                             const struct samr_Password *lm_interactive_pwd,
96                             const struct samr_Password *nt_interactive_pwd,
97                             const char *plaintext,
98                             enum auth_password_state password_state)
99 {
100         const char *domain;
101         NTSTATUS result;
102         bool was_mapped;
103         char *internal_username = NULL;
104
105         was_mapped = map_username(talloc_tos(), smb_name, &internal_username);
106         if (!internal_username) {
107                 return NT_STATUS_NO_MEMORY;
108         }
109
110         DEBUG(5, ("Mapping user [%s]\\[%s] from workstation [%s]\n",
111                  client_domain, smb_name, workstation_name));
112
113         domain = client_domain;
114
115         /* If you connect to a Windows domain member using a bogus domain name,
116          * the Windows box will map the BOGUS\user to SAMNAME\user.  Thus, if
117          * the Windows box is a DC the name will become DOMAIN\user and be
118          * authenticated against AD, if the Windows box is a member server but
119          * not a DC the name will become WORKSTATION\user.  A standalone
120          * non-domain member box will also map to WORKSTATION\user.
121          * This also deals with the client passing in a "" domain */
122
123         if (!is_trusted_domain(domain) &&
124             !strequal(domain, my_sam_name()))
125         {
126                 if (lp_map_untrusted_to_domain())
127                         domain = my_sam_name();
128                 else
129                         domain = get_global_sam_name();
130                 DEBUG(5, ("Mapped domain from [%s] to [%s] for user [%s] from "
131                           "workstation [%s]\n",
132                           client_domain, domain, smb_name, workstation_name));
133         }
134
135         /* We know that the given domain is trusted (and we are allowing them),
136          * it is our global SAM name, or for legacy behavior it is our
137          * primary domain name */
138
139         result = make_user_info(user_info, smb_name, internal_username,
140                               client_domain, domain, workstation_name,
141                               remote_address, lm_pwd, nt_pwd,
142                               lm_interactive_pwd, nt_interactive_pwd,
143                               plaintext, password_state);
144         if (NT_STATUS_IS_OK(result)) {
145                 /* We have tried mapping */
146                 (*user_info)->mapped_state = True;
147                 /* did we actually map the user to a different name? */
148                 (*user_info)->was_mapped = was_mapped;
149         }
150         return result;
151 }
152
153 /****************************************************************************
154  Create an auth_usersupplied_data, making the DATA_BLOBs here. 
155  Decrypt and encrypt the passwords.
156 ****************************************************************************/
157
158 bool make_user_info_netlogon_network(struct auth_usersupplied_info **user_info,
159                                      const char *smb_name, 
160                                      const char *client_domain, 
161                                      const char *workstation_name,
162                                      const struct tsocket_address *remote_address,
163                                      uint32 logon_parameters,
164                                      const uchar *lm_network_pwd,
165                                      int lm_pwd_len,
166                                      const uchar *nt_network_pwd,
167                                      int nt_pwd_len)
168 {
169         bool ret;
170         NTSTATUS status;
171         DATA_BLOB lm_blob = data_blob(lm_network_pwd, lm_pwd_len);
172         DATA_BLOB nt_blob = data_blob(nt_network_pwd, nt_pwd_len);
173
174         status = make_user_info_map(user_info,
175                                     smb_name, client_domain, 
176                                     workstation_name,
177                                     remote_address,
178                                     lm_pwd_len ? &lm_blob : NULL, 
179                                     nt_pwd_len ? &nt_blob : NULL,
180                                     NULL, NULL, NULL,
181                                     AUTH_PASSWORD_RESPONSE);
182
183         if (NT_STATUS_IS_OK(status)) {
184                 (*user_info)->logon_parameters = logon_parameters;
185         }
186         ret = NT_STATUS_IS_OK(status) ? True : False;
187
188         data_blob_free(&lm_blob);
189         data_blob_free(&nt_blob);
190         return ret;
191 }
192
193 /****************************************************************************
194  Create an auth_usersupplied_data, making the DATA_BLOBs here. 
195  Decrypt and encrypt the passwords.
196 ****************************************************************************/
197
198 bool make_user_info_netlogon_interactive(struct auth_usersupplied_info **user_info,
199                                          const char *smb_name, 
200                                          const char *client_domain, 
201                                          const char *workstation_name,
202                                          const struct tsocket_address *remote_address,
203                                          uint32 logon_parameters,
204                                          const uchar chal[8], 
205                                          const uchar lm_interactive_pwd[16], 
206                                          const uchar nt_interactive_pwd[16], 
207                                          const uchar *dc_sess_key)
208 {
209         struct samr_Password lm_pwd;
210         struct samr_Password nt_pwd;
211         unsigned char local_lm_response[24];
212         unsigned char local_nt_response[24];
213         unsigned char key[16];
214
215         memcpy(key, dc_sess_key, 16);
216
217         if (lm_interactive_pwd)
218                 memcpy(lm_pwd.hash, lm_interactive_pwd, sizeof(lm_pwd.hash));
219
220         if (nt_interactive_pwd)
221                 memcpy(nt_pwd.hash, nt_interactive_pwd, sizeof(nt_pwd.hash));
222
223 #ifdef DEBUG_PASSWORD
224         DEBUG(100,("key:"));
225         dump_data(100, key, sizeof(key));
226
227         DEBUG(100,("lm owf password:"));
228         dump_data(100, lm_pwd.hash, sizeof(lm_pwd.hash));
229
230         DEBUG(100,("nt owf password:"));
231         dump_data(100, nt_pwd.hash, sizeof(nt_pwd.hash));
232 #endif
233
234         if (lm_interactive_pwd)
235                 arcfour_crypt(lm_pwd.hash, key, sizeof(lm_pwd.hash));
236
237         if (nt_interactive_pwd)
238                 arcfour_crypt(nt_pwd.hash, key, sizeof(nt_pwd.hash));
239
240 #ifdef DEBUG_PASSWORD
241         DEBUG(100,("decrypt of lm owf password:"));
242         dump_data(100, lm_pwd.hash, sizeof(lm_pwd));
243
244         DEBUG(100,("decrypt of nt owf password:"));
245         dump_data(100, nt_pwd.hash, sizeof(nt_pwd));
246 #endif
247
248         if (lm_interactive_pwd)
249                 SMBOWFencrypt(lm_pwd.hash, chal,
250                               local_lm_response);
251
252         if (nt_interactive_pwd)
253                 SMBOWFencrypt(nt_pwd.hash, chal,
254                               local_nt_response);
255
256         /* Password info paranoia */
257         ZERO_STRUCT(key);
258
259         {
260                 bool ret;
261                 NTSTATUS nt_status;
262                 DATA_BLOB local_lm_blob;
263                 DATA_BLOB local_nt_blob;
264
265                 if (lm_interactive_pwd) {
266                         local_lm_blob = data_blob(local_lm_response,
267                                                   sizeof(local_lm_response));
268                 }
269
270                 if (nt_interactive_pwd) {
271                         local_nt_blob = data_blob(local_nt_response,
272                                                   sizeof(local_nt_response));
273                 }
274
275                 nt_status = make_user_info_map(
276                         user_info, 
277                         smb_name, client_domain, workstation_name,
278                         remote_address,
279                         lm_interactive_pwd ? &local_lm_blob : NULL,
280                         nt_interactive_pwd ? &local_nt_blob : NULL,
281                         lm_interactive_pwd ? &lm_pwd : NULL,
282                         nt_interactive_pwd ? &nt_pwd : NULL,
283                         NULL, AUTH_PASSWORD_HASH);
284
285                 if (NT_STATUS_IS_OK(nt_status)) {
286                         (*user_info)->logon_parameters = logon_parameters;
287                 }
288
289                 ret = NT_STATUS_IS_OK(nt_status) ? True : False;
290                 data_blob_free(&local_lm_blob);
291                 data_blob_free(&local_nt_blob);
292                 return ret;
293         }
294 }
295
296
297 /****************************************************************************
298  Create an auth_usersupplied_data structure
299 ****************************************************************************/
300
301 bool make_user_info_for_reply(struct auth_usersupplied_info **user_info,
302                               const char *smb_name, 
303                               const char *client_domain,
304                               const struct tsocket_address *remote_address,
305                               const uint8 chal[8],
306                               DATA_BLOB plaintext_password)
307 {
308
309         DATA_BLOB local_lm_blob;
310         DATA_BLOB local_nt_blob;
311         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
312         char *plaintext_password_string;
313         /*
314          * Not encrypted - do so.
315          */
316
317         DEBUG(5,("make_user_info_for_reply: User passwords not in encrypted "
318                  "format.\n"));
319         if (plaintext_password.data && plaintext_password.length) {
320                 unsigned char local_lm_response[24];
321
322 #ifdef DEBUG_PASSWORD
323                 DEBUG(10,("Unencrypted password (len %d):\n",
324                           (int)plaintext_password.length));
325                 dump_data(100, plaintext_password.data,
326                           plaintext_password.length);
327 #endif
328
329                 SMBencrypt( (const char *)plaintext_password.data,
330                             (const uchar*)chal, local_lm_response);
331                 local_lm_blob = data_blob(local_lm_response, 24);
332
333                 /* We can't do an NT hash here, as the password needs to be
334                    case insensitive */
335                 local_nt_blob = data_blob_null; 
336         } else {
337                 local_lm_blob = data_blob_null; 
338                 local_nt_blob = data_blob_null; 
339         }
340
341         plaintext_password_string = talloc_strndup(talloc_tos(),
342                                                    (const char *)plaintext_password.data,
343                                                    plaintext_password.length);
344         if (!plaintext_password_string) {
345                 return False;
346         }
347
348         ret = make_user_info_map(
349                 user_info, smb_name, client_domain, 
350                 get_remote_machine_name(),
351                 remote_address,
352                 local_lm_blob.data ? &local_lm_blob : NULL,
353                 local_nt_blob.data ? &local_nt_blob : NULL,
354                 NULL, NULL,
355                 plaintext_password_string,
356                 AUTH_PASSWORD_PLAIN);
357
358         if (plaintext_password_string) {
359                 memset(plaintext_password_string, '\0', strlen(plaintext_password_string));
360                 talloc_free(plaintext_password_string);
361         }
362
363         data_blob_free(&local_lm_blob);
364         return NT_STATUS_IS_OK(ret) ? True : False;
365 }
366
367 /****************************************************************************
368  Create an auth_usersupplied_data structure
369 ****************************************************************************/
370
371 NTSTATUS make_user_info_for_reply_enc(struct auth_usersupplied_info **user_info,
372                                       const char *smb_name,
373                                       const char *client_domain,
374                                       const struct tsocket_address *remote_address,
375                                       DATA_BLOB lm_resp, DATA_BLOB nt_resp)
376 {
377         return make_user_info_map(user_info, smb_name, 
378                                   client_domain, 
379                                   get_remote_machine_name(),
380                                   remote_address,
381                                   lm_resp.data && (lm_resp.length > 0) ? &lm_resp : NULL,
382                                   nt_resp.data && (nt_resp.length > 0) ? &nt_resp : NULL,
383                                   NULL, NULL, NULL,
384                                   AUTH_PASSWORD_RESPONSE);
385 }
386
387 /****************************************************************************
388  Create a guest user_info blob, for anonymous authenticaion.
389 ****************************************************************************/
390
391 bool make_user_info_guest(const struct tsocket_address *remote_address,
392                           struct auth_usersupplied_info **user_info)
393 {
394         NTSTATUS nt_status;
395
396         nt_status = make_user_info(user_info, 
397                                    "","", 
398                                    "","", 
399                                    "", 
400                                    remote_address,
401                                    NULL, NULL, 
402                                    NULL, NULL, 
403                                    NULL,
404                                    AUTH_PASSWORD_RESPONSE);
405
406         return NT_STATUS_IS_OK(nt_status) ? True : False;
407 }
408
409 static NTSTATUS log_nt_token(struct security_token *token)
410 {
411         TALLOC_CTX *frame = talloc_stackframe();
412         char *command;
413         char *group_sidstr;
414         size_t i;
415
416         if ((lp_log_nt_token_command() == NULL) ||
417             (strlen(lp_log_nt_token_command()) == 0)) {
418                 TALLOC_FREE(frame);
419                 return NT_STATUS_OK;
420         }
421
422         group_sidstr = talloc_strdup(frame, "");
423         for (i=1; i<token->num_sids; i++) {
424                 group_sidstr = talloc_asprintf(
425                         frame, "%s %s", group_sidstr,
426                         sid_string_talloc(frame, &token->sids[i]));
427         }
428
429         command = talloc_string_sub(
430                 frame, lp_log_nt_token_command(),
431                 "%s", sid_string_talloc(frame, &token->sids[0]));
432         command = talloc_string_sub(frame, command, "%t", group_sidstr);
433
434         if (command == NULL) {
435                 TALLOC_FREE(frame);
436                 return NT_STATUS_NO_MEMORY;
437         }
438
439         DEBUG(8, ("running command: [%s]\n", command));
440         if (smbrun(command, NULL) != 0) {
441                 DEBUG(0, ("Could not log NT token\n"));
442                 TALLOC_FREE(frame);
443                 return NT_STATUS_ACCESS_DENIED;
444         }
445
446         TALLOC_FREE(frame);
447         return NT_STATUS_OK;
448 }
449
450 /*
451  * Create the token to use from server_info->info3 and
452  * server_info->sids (the info3/sam groups). Find the unix gids.
453  */
454
455 NTSTATUS create_local_token(TALLOC_CTX *mem_ctx,
456                             const struct auth_serversupplied_info *server_info,
457                             DATA_BLOB *session_key,
458                             struct auth_serversupplied_info **session_info_out)
459 {
460         struct security_token *t;
461         NTSTATUS status;
462         size_t i;
463         struct dom_sid tmp_sid;
464         struct auth_serversupplied_info *session_info;
465         struct wbcUnixId *ids;
466
467         /* Ensure we can't possible take a code path leading to a
468          * null defref. */
469         if (!server_info) {
470                 return NT_STATUS_LOGON_FAILURE;
471         }
472
473         session_info = copy_serverinfo(mem_ctx, server_info);
474
475         if (!session_info) {
476                 return NT_STATUS_NO_MEMORY;
477         }
478
479         if (session_key) {
480                 data_blob_free(&session_info->session_key);
481                 session_info->session_key = data_blob_talloc(session_info,
482                                                                   session_key->data,
483                                                                   session_key->length);
484                 if (!session_info->session_key.data && session_key->length) {
485                         return NT_STATUS_NO_MEMORY;
486                 }
487         }
488
489         if (session_info->security_token) {
490                 /* Just copy the token, it has already been finalised
491                  * (nasty hack to support a cached guest session_info,
492                  * and a possible strategy for auth_samba4 to pass in
493                  * a finalised session) */
494                 *session_info_out = session_info;
495                 return NT_STATUS_OK;
496         }
497
498         /*
499          * If winbind is not around, we can not make much use of the SIDs the
500          * domain controller provided us with. Likewise if the user name was
501          * mapped to some local unix user.
502          */
503
504         if (((lp_server_role() == ROLE_DOMAIN_MEMBER) && !winbind_ping()) ||
505             (server_info->nss_token)) {
506                 status = create_token_from_username(session_info,
507                                                     session_info->unix_name,
508                                                     session_info->guest,
509                                                     &session_info->utok.uid,
510                                                     &session_info->utok.gid,
511                                                     &session_info->unix_name,
512                                                     &session_info->security_token);
513
514         } else {
515                 status = create_local_nt_token_from_info3(session_info,
516                                                           session_info->guest,
517                                                           session_info->info3,
518                                                           &session_info->extra,
519                                                           &session_info->security_token);
520         }
521
522         if (!NT_STATUS_IS_OK(status)) {
523                 return status;
524         }
525
526         /* Convert the SIDs to gids. */
527
528         session_info->utok.ngroups = 0;
529         session_info->utok.groups = NULL;
530
531         t = session_info->security_token;
532
533         ids = talloc_array(talloc_tos(), struct wbcUnixId,
534                            t->num_sids);
535         if (ids == NULL) {
536                 return NT_STATUS_NO_MEMORY;
537         }
538
539         if (!sids_to_unix_ids(t->sids, t->num_sids, ids)) {
540                 TALLOC_FREE(ids);
541                 return NT_STATUS_NO_MEMORY;
542         }
543
544         /* Start at index 1, where the groups start. */
545
546         for (i=1; i<t->num_sids; i++) {
547
548                 if (ids[i].type != WBC_ID_TYPE_GID) {
549                         DEBUG(10, ("Could not convert SID %s to gid, "
550                                    "ignoring it\n",
551                                    sid_string_dbg(&t->sids[i])));
552                         continue;
553                 }
554                 if (!add_gid_to_array_unique(session_info, ids[i].id.gid,
555                                              &session_info->utok.groups,
556                                              &session_info->utok.ngroups)) {
557                         return NT_STATUS_NO_MEMORY;
558                 }
559         }
560
561         /*
562          * Add the "Unix Group" SID for each gid to catch mapped groups
563          * and their Unix equivalent.  This is to solve the backwards
564          * compatibility problem of 'valid users = +ntadmin' where
565          * ntadmin has been paired with "Domain Admins" in the group
566          * mapping table.  Otherwise smb.conf would need to be changed
567          * to 'valid user = "Domain Admins"'.  --jerry
568          *
569          * For consistency we also add the "Unix User" SID,
570          * so that the complete unix token is represented within
571          * the nt token.
572          */
573
574         uid_to_unix_users_sid(session_info->utok.uid, &tmp_sid);
575
576         add_sid_to_array_unique(session_info->security_token, &tmp_sid,
577                                 &session_info->security_token->sids,
578                                 &session_info->security_token->num_sids);
579
580         for ( i=0; i<session_info->utok.ngroups; i++ ) {
581                 gid_to_unix_groups_sid(session_info->utok.groups[i], &tmp_sid);
582                 add_sid_to_array_unique(session_info->security_token, &tmp_sid,
583                                         &session_info->security_token->sids,
584                                         &session_info->security_token->num_sids);
585         }
586
587         security_token_debug(DBGC_AUTH, 10, session_info->security_token);
588         debug_unix_user_token(DBGC_AUTH, 10,
589                               session_info->utok.uid,
590                               session_info->utok.gid,
591                               session_info->utok.ngroups,
592                               session_info->utok.groups);
593
594         status = log_nt_token(session_info->security_token);
595         if (!NT_STATUS_IS_OK(status)) {
596                 return status;
597         }
598
599         *session_info_out = session_info;
600         return NT_STATUS_OK;
601 }
602
603 /***************************************************************************
604  Make (and fill) a server_info struct from a 'struct passwd' by conversion
605  to a struct samu
606 ***************************************************************************/
607
608 NTSTATUS make_server_info_pw(struct auth_serversupplied_info **server_info,
609                              char *unix_username,
610                              struct passwd *pwd)
611 {
612         NTSTATUS status;
613         struct samu *sampass = NULL;
614         char *qualified_name = NULL;
615         TALLOC_CTX *mem_ctx = NULL;
616         struct dom_sid u_sid;
617         enum lsa_SidType type;
618         struct auth_serversupplied_info *result;
619
620         /*
621          * The SID returned in server_info->sam_account is based
622          * on our SAM sid even though for a pure UNIX account this should
623          * not be the case as it doesn't really exist in the SAM db.
624          * This causes lookups on "[in]valid users" to fail as they
625          * will lookup this name as a "Unix User" SID to check against
626          * the user token. Fix this by adding the "Unix User"\unix_username
627          * SID to the sid array. The correct fix should probably be
628          * changing the server_info->sam_account user SID to be a
629          * S-1-22 Unix SID, but this might break old configs where
630          * plaintext passwords were used with no SAM backend.
631          */
632
633         mem_ctx = talloc_init("make_server_info_pw_tmp");
634         if (!mem_ctx) {
635                 return NT_STATUS_NO_MEMORY;
636         }
637
638         qualified_name = talloc_asprintf(mem_ctx, "%s\\%s",
639                                         unix_users_domain_name(),
640                                         unix_username );
641         if (!qualified_name) {
642                 TALLOC_FREE(mem_ctx);
643                 return NT_STATUS_NO_MEMORY;
644         }
645
646         if (!lookup_name(mem_ctx, qualified_name, LOOKUP_NAME_ALL,
647                                                 NULL, NULL,
648                                                 &u_sid, &type)) {
649                 TALLOC_FREE(mem_ctx);
650                 return NT_STATUS_NO_SUCH_USER;
651         }
652
653         TALLOC_FREE(mem_ctx);
654
655         if (type != SID_NAME_USER) {
656                 return NT_STATUS_NO_SUCH_USER;
657         }
658
659         if ( !(sampass = samu_new( NULL )) ) {
660                 return NT_STATUS_NO_MEMORY;
661         }
662
663         status = samu_set_unix( sampass, pwd );
664         if (!NT_STATUS_IS_OK(status)) {
665                 return status;
666         }
667
668         /* In pathological cases the above call can set the account
669          * name to the DOMAIN\username form. Reset the account name
670          * using unix_username */
671         pdb_set_username(sampass, unix_username, PDB_SET);
672
673         /* set the user sid to be the calculated u_sid */
674         pdb_set_user_sid(sampass, &u_sid, PDB_SET);
675
676         result = make_server_info(NULL);
677         if (result == NULL) {
678                 TALLOC_FREE(sampass);
679                 return NT_STATUS_NO_MEMORY;
680         }
681
682         status = samu_to_SamInfo3(result, sampass, lp_netbios_name(),
683                                   &result->info3, &result->extra);
684         TALLOC_FREE(sampass);
685         if (!NT_STATUS_IS_OK(status)) {
686                 DEBUG(10, ("Failed to convert samu to info3: %s\n",
687                            nt_errstr(status)));
688                 TALLOC_FREE(result);
689                 return status;
690         }
691
692         result->unix_name = talloc_strdup(result, unix_username);
693         result->sanitized_username = sanitize_username(result, unix_username);
694
695         if ((result->unix_name == NULL)
696             || (result->sanitized_username == NULL)) {
697                 TALLOC_FREE(result);
698                 return NT_STATUS_NO_MEMORY;
699         }
700
701         result->utok.uid = pwd->pw_uid;
702         result->utok.gid = pwd->pw_gid;
703
704         *server_info = result;
705
706         return NT_STATUS_OK;
707 }
708
709 static NTSTATUS get_guest_info3(TALLOC_CTX *mem_ctx,
710                                 struct netr_SamInfo3 *info3)
711 {
712         const char *guest_account = lp_guestaccount();
713         struct dom_sid domain_sid;
714         struct passwd *pwd;
715         const char *tmp;
716
717         pwd = Get_Pwnam_alloc(mem_ctx, guest_account);
718         if (pwd == NULL) {
719                 DEBUG(0,("SamInfo3_for_guest: Unable to locate guest "
720                          "account [%s]!\n", guest_account));
721                 return NT_STATUS_NO_SUCH_USER;
722         }
723
724         /* Set acount name */
725         tmp = talloc_strdup(mem_ctx, pwd->pw_name);
726         if (tmp == NULL) {
727                 return NT_STATUS_NO_MEMORY;
728         }
729         init_lsa_String(&info3->base.account_name, tmp);
730
731         /* Set domain name */
732         tmp = talloc_strdup(mem_ctx, get_global_sam_name());
733         if (tmp == NULL) {
734                 return NT_STATUS_NO_MEMORY;
735         }
736         init_lsa_StringLarge(&info3->base.domain, tmp);
737
738         /* Domain sid */
739         sid_copy(&domain_sid, get_global_sam_sid());
740
741         info3->base.domain_sid = dom_sid_dup(mem_ctx, &domain_sid);
742         if (info3->base.domain_sid == NULL) {
743                 return NT_STATUS_NO_MEMORY;
744         }
745
746         /* Guest rid */
747         info3->base.rid = DOMAIN_RID_GUEST;
748
749         /* Primary gid */
750         info3->base.primary_gid = BUILTIN_RID_GUESTS;
751
752         TALLOC_FREE(pwd);
753         return NT_STATUS_OK;
754 }
755
756 /***************************************************************************
757  Make (and fill) a user_info struct for a guest login.
758  This *must* succeed for smbd to start. If there is no mapping entry for
759  the guest gid, then create one.
760
761  The resulting structure is a 'session_info' because
762  create_local_token() has already been called on it.  This is quite
763  nasty, as the auth subsystem isn't expect this, but the behaviour is
764  left as-is for now.
765 ***************************************************************************/
766
767 static NTSTATUS make_new_server_info_guest(struct auth_serversupplied_info **session_info)
768 {
769         struct auth_serversupplied_info *server_info;
770         static const char zeros[16] = {0};
771         const char *guest_account = lp_guestaccount();
772         const char *domain = lp_netbios_name();
773         struct netr_SamInfo3 info3;
774         TALLOC_CTX *tmp_ctx;
775         NTSTATUS status;
776         fstring tmp;
777
778         tmp_ctx = talloc_stackframe();
779         if (tmp_ctx == NULL) {
780                 return NT_STATUS_NO_MEMORY;
781         }
782
783         ZERO_STRUCT(info3);
784
785         status = get_guest_info3(tmp_ctx, &info3);
786         if (!NT_STATUS_IS_OK(status)) {
787                 DEBUG(0, ("get_guest_info3 failed with %s\n",
788                           nt_errstr(status)));
789                 goto done;
790         }
791
792         status = make_server_info_info3(tmp_ctx,
793                                         guest_account,
794                                         domain,
795                                         &server_info,
796                                         &info3);
797         if (!NT_STATUS_IS_OK(status)) {
798                 DEBUG(0, ("make_server_info_info3 failed with %s\n",
799                           nt_errstr(status)));
800                 goto done;
801         }
802
803         server_info->guest = True;
804
805         /* This should not be done here (we should produce a server
806          * info, and later construct a session info from it), but for
807          * now this does not change the previous behaviours */
808         status = create_local_token(tmp_ctx, server_info, NULL, session_info);
809         TALLOC_FREE(server_info);
810         if (!NT_STATUS_IS_OK(status)) {
811                 DEBUG(0, ("create_local_token failed: %s\n",
812                           nt_errstr(status)));
813                 goto done;
814         }
815         talloc_steal(NULL, *session_info);
816
817         /* annoying, but the Guest really does have a session key, and it is
818            all zeros! */
819         (*session_info)->session_key = data_blob(zeros, sizeof(zeros));
820         (*session_info)->lm_session_key = data_blob(zeros, sizeof(zeros));
821
822         alpha_strcpy(tmp, (*session_info)->info3->base.account_name.string,
823                      ". _-$", sizeof(tmp));
824         (*session_info)->sanitized_username = talloc_strdup(*session_info, tmp);
825
826         status = NT_STATUS_OK;
827 done:
828         TALLOC_FREE(tmp_ctx);
829         return status;
830 }
831
832 /***************************************************************************
833  Make (and fill) a auth_session_info struct for a system user login.
834  This *must* succeed for smbd to start.
835 ***************************************************************************/
836
837 static NTSTATUS make_new_session_info_system(TALLOC_CTX *mem_ctx,
838                                             struct auth_serversupplied_info **session_info)
839 {
840         struct passwd *pwd;
841         NTSTATUS status;
842
843         pwd = getpwuid_alloc(mem_ctx, sec_initial_uid());
844         if (pwd == NULL) {
845                 return NT_STATUS_NO_SUCH_USER;
846         }
847
848         status = make_session_info_from_username(mem_ctx,
849                                                  pwd->pw_name,
850                                                  false,
851                                                  session_info);
852         TALLOC_FREE(pwd);
853         if (!NT_STATUS_IS_OK(status)) {
854                 return status;
855         }
856
857         (*session_info)->system = true;
858
859         status = add_sid_to_array_unique((*session_info)->security_token->sids,
860                                          &global_sid_System,
861                                          &(*session_info)->security_token->sids,
862                                          &(*session_info)->security_token->num_sids);
863         if (!NT_STATUS_IS_OK(status)) {
864                 TALLOC_FREE((*session_info));
865                 return status;
866         }
867
868         return NT_STATUS_OK;
869 }
870
871 /****************************************************************************
872   Fake a auth_serversupplied_info just from a username (as a
873   session_info structure, with create_local_token() already called on
874   it.
875 ****************************************************************************/
876
877 NTSTATUS make_session_info_from_username(TALLOC_CTX *mem_ctx,
878                                          const char *username,
879                                          bool is_guest,
880                                          struct auth_serversupplied_info **session_info)
881 {
882         struct auth_serversupplied_info *result;
883         struct passwd *pwd;
884         NTSTATUS status;
885
886         pwd = Get_Pwnam_alloc(talloc_tos(), username);
887         if (pwd == NULL) {
888                 return NT_STATUS_NO_SUCH_USER;
889         }
890
891         status = make_server_info_pw(&result, pwd->pw_name, pwd);
892
893         TALLOC_FREE(pwd);
894
895         if (!NT_STATUS_IS_OK(status)) {
896                 return status;
897         }
898
899         result->nss_token = true;
900         result->guest = is_guest;
901
902         /* Now turn the server_info into a session_info with the full token etc */
903         status = create_local_token(mem_ctx, result, NULL, session_info);
904         talloc_free(result);
905         return status;
906 }
907
908
909 struct auth_serversupplied_info *copy_serverinfo(TALLOC_CTX *mem_ctx,
910                                                  const struct auth_serversupplied_info *src)
911 {
912         struct auth_serversupplied_info *dst;
913
914         dst = make_server_info(mem_ctx);
915         if (dst == NULL) {
916                 return NULL;
917         }
918
919         dst->guest = src->guest;
920         dst->system = src->system;
921         dst->utok.uid = src->utok.uid;
922         dst->utok.gid = src->utok.gid;
923         dst->utok.ngroups = src->utok.ngroups;
924         if (src->utok.ngroups != 0) {
925                 dst->utok.groups = (gid_t *)talloc_memdup(
926                         dst, src->utok.groups,
927                         sizeof(gid_t)*dst->utok.ngroups);
928         } else {
929                 dst->utok.groups = NULL;
930         }
931
932         if (src->security_token) {
933                 dst->security_token = dup_nt_token(dst, src->security_token);
934                 if (!dst->security_token) {
935                         TALLOC_FREE(dst);
936                         return NULL;
937                 }
938         }
939
940         dst->session_key = data_blob_talloc( dst, src->session_key.data,
941                                                 src->session_key.length);
942
943         dst->lm_session_key = data_blob_talloc(dst, src->lm_session_key.data,
944                                                 src->lm_session_key.length);
945
946         dst->info3 = copy_netr_SamInfo3(dst, src->info3);
947         if (!dst->info3) {
948                 TALLOC_FREE(dst);
949                 return NULL;
950         }
951         dst->extra = src->extra;
952
953         dst->unix_name = talloc_strdup(dst, src->unix_name);
954         if (!dst->unix_name) {
955                 TALLOC_FREE(dst);
956                 return NULL;
957         }
958
959         dst->sanitized_username = talloc_strdup(dst, src->sanitized_username);
960         if (!dst->sanitized_username) {
961                 TALLOC_FREE(dst);
962                 return NULL;
963         }
964
965         return dst;
966 }
967
968 /*
969  * Set a new session key. Used in the rpc server where we have to override the
970  * SMB level session key with SystemLibraryDTC
971  */
972
973 bool session_info_set_session_key(struct auth_serversupplied_info *info,
974                                  DATA_BLOB session_key)
975 {
976         TALLOC_FREE(info->session_key.data);
977
978         info->session_key = data_blob_talloc(
979                 info, session_key.data, session_key.length);
980
981         return (info->session_key.data != NULL);
982 }
983
984 static struct auth_serversupplied_info *guest_info = NULL;
985
986 bool init_guest_info(void)
987 {
988         if (guest_info != NULL)
989                 return True;
990
991         return NT_STATUS_IS_OK(make_new_server_info_guest(&guest_info));
992 }
993
994 NTSTATUS make_server_info_guest(TALLOC_CTX *mem_ctx,
995                                 struct auth_serversupplied_info **server_info)
996 {
997         *server_info = copy_serverinfo(mem_ctx, guest_info);
998         return (*server_info != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
999 }
1000
1001 static struct auth_serversupplied_info *system_info = NULL;
1002
1003 NTSTATUS init_system_info(void)
1004 {
1005         if (system_info != NULL)
1006                 return NT_STATUS_OK;
1007
1008         return make_new_session_info_system(NULL, &system_info);
1009 }
1010
1011 NTSTATUS make_session_info_system(TALLOC_CTX *mem_ctx,
1012                                 struct auth_serversupplied_info **session_info)
1013 {
1014         if (system_info == NULL) return NT_STATUS_UNSUCCESSFUL;
1015         *session_info = copy_serverinfo(mem_ctx, system_info);
1016         return (*session_info != NULL) ? NT_STATUS_OK : NT_STATUS_NO_MEMORY;
1017 }
1018
1019 const struct auth_serversupplied_info *get_session_info_system(void)
1020 {
1021     return system_info;
1022 }
1023
1024 bool copy_current_user(struct current_user *dst, struct current_user *src)
1025 {
1026         gid_t *groups;
1027         struct security_token *nt_token;
1028
1029         groups = (gid_t *)memdup(src->ut.groups,
1030                                  sizeof(gid_t) * src->ut.ngroups);
1031         if ((src->ut.ngroups != 0) && (groups == NULL)) {
1032                 return False;
1033         }
1034
1035         nt_token = dup_nt_token(NULL, src->nt_user_token);
1036         if (nt_token == NULL) {
1037                 SAFE_FREE(groups);
1038                 return False;
1039         }
1040
1041         dst->conn = src->conn;
1042         dst->vuid = src->vuid;
1043         dst->ut.uid = src->ut.uid;
1044         dst->ut.gid = src->ut.gid;
1045         dst->ut.ngroups = src->ut.ngroups;
1046         dst->ut.groups = groups;
1047         dst->nt_user_token = nt_token;
1048         return True;
1049 }
1050
1051 /***************************************************************************
1052  Purely internal function for make_server_info_info3
1053 ***************************************************************************/
1054
1055 static NTSTATUS check_account(TALLOC_CTX *mem_ctx, const char *domain,
1056                               const char *username, char **found_username,
1057                               struct passwd **pwd,
1058                               bool *username_was_mapped)
1059 {
1060         char *orig_dom_user = NULL;
1061         char *dom_user = NULL;
1062         char *lower_username = NULL;
1063         char *real_username = NULL;
1064         struct passwd *passwd;
1065
1066         lower_username = talloc_strdup(mem_ctx, username);
1067         if (!lower_username) {
1068                 return NT_STATUS_NO_MEMORY;
1069         }
1070         strlower_m( lower_username );
1071
1072         orig_dom_user = talloc_asprintf(mem_ctx,
1073                                 "%s%c%s",
1074                                 domain,
1075                                 *lp_winbind_separator(),
1076                                 lower_username);
1077         if (!orig_dom_user) {
1078                 return NT_STATUS_NO_MEMORY;
1079         }
1080
1081         /* Get the passwd struct.  Try to create the account if necessary. */
1082
1083         *username_was_mapped = map_username(mem_ctx, orig_dom_user, &dom_user);
1084         if (!dom_user) {
1085                 return NT_STATUS_NO_MEMORY;
1086         }
1087
1088         passwd = smb_getpwnam(mem_ctx, dom_user, &real_username, True );
1089         if (!passwd) {
1090                 DEBUG(3, ("Failed to find authenticated user %s via "
1091                           "getpwnam(), denying access.\n", dom_user));
1092                 return NT_STATUS_NO_SUCH_USER;
1093         }
1094
1095         if (!real_username) {
1096                 return NT_STATUS_NO_MEMORY;
1097         }
1098
1099         *pwd = passwd;
1100
1101         /* This is pointless -- there is no suport for differing 
1102            unix and windows names.  Make sure to always store the 
1103            one we actually looked up and succeeded. Have I mentioned
1104            why I hate the 'winbind use default domain' parameter?   
1105                                          --jerry              */
1106
1107         *found_username = talloc_strdup( mem_ctx, real_username );
1108
1109         return NT_STATUS_OK;
1110 }
1111
1112 /****************************************************************************
1113  Wrapper to allow the getpwnam() call to strip the domain name and 
1114  try again in case a local UNIX user is already there.  Also run through 
1115  the username if we fallback to the username only.
1116  ****************************************************************************/
1117
1118 struct passwd *smb_getpwnam( TALLOC_CTX *mem_ctx, const char *domuser,
1119                              char **p_save_username, bool create )
1120 {
1121         struct passwd *pw = NULL;
1122         char *p = NULL;
1123         char *username = NULL;
1124
1125         /* we only save a copy of the username it has been mangled 
1126            by winbindd use default domain */
1127         *p_save_username = NULL;
1128
1129         /* don't call map_username() here since it has to be done higher 
1130            up the stack so we don't call it multiple times */
1131
1132         username = talloc_strdup(mem_ctx, domuser);
1133         if (!username) {
1134                 return NULL;
1135         }
1136
1137         p = strchr_m( username, *lp_winbind_separator() );
1138
1139         /* code for a DOMAIN\user string */
1140
1141         if ( p ) {
1142                 pw = Get_Pwnam_alloc( mem_ctx, domuser );
1143                 if ( pw ) {
1144                         /* make sure we get the case of the username correct */
1145                         /* work around 'winbind use default domain = yes' */
1146
1147                         if ( !strchr_m( pw->pw_name, *lp_winbind_separator() ) ) {
1148                                 char *domain;
1149
1150                                 /* split the domain and username into 2 strings */
1151                                 *p = '\0';
1152                                 domain = username;
1153
1154                                 *p_save_username = talloc_asprintf(mem_ctx,
1155                                                                 "%s%c%s",
1156                                                                 domain,
1157                                                                 *lp_winbind_separator(),
1158                                                                 pw->pw_name);
1159                                 if (!*p_save_username) {
1160                                         TALLOC_FREE(pw);
1161                                         return NULL;
1162                                 }
1163                         } else {
1164                                 *p_save_username = talloc_strdup(mem_ctx, pw->pw_name);
1165                         }
1166
1167                         /* whew -- done! */
1168                         return pw;
1169                 }
1170
1171                 /* setup for lookup of just the username */
1172                 /* remember that p and username are overlapping memory */
1173
1174                 p++;
1175                 username = talloc_strdup(mem_ctx, p);
1176                 if (!username) {
1177                         return NULL;
1178                 }
1179         }
1180
1181         /* just lookup a plain username */
1182
1183         pw = Get_Pwnam_alloc(mem_ctx, username);
1184
1185         /* Create local user if requested but only if winbindd
1186            is not running.  We need to protect against cases
1187            where winbindd is failing and then prematurely
1188            creating users in /etc/passwd */
1189
1190         if ( !pw && create && !winbind_ping() ) {
1191                 /* Don't add a machine account. */
1192                 if (username[strlen(username)-1] == '$')
1193                         return NULL;
1194
1195                 _smb_create_user(NULL, username, NULL);
1196                 pw = Get_Pwnam_alloc(mem_ctx, username);
1197         }
1198
1199         /* one last check for a valid passwd struct */
1200
1201         if (pw) {
1202                 *p_save_username = talloc_strdup(mem_ctx, pw->pw_name);
1203         }
1204         return pw;
1205 }
1206
1207 /***************************************************************************
1208  Make a server_info struct from the info3 returned by a domain logon 
1209 ***************************************************************************/
1210
1211 NTSTATUS make_server_info_info3(TALLOC_CTX *mem_ctx, 
1212                                 const char *sent_nt_username,
1213                                 const char *domain,
1214                                 struct auth_serversupplied_info **server_info,
1215                                 struct netr_SamInfo3 *info3)
1216 {
1217         static const char zeros[16] = {0, };
1218
1219         NTSTATUS nt_status = NT_STATUS_OK;
1220         char *found_username = NULL;
1221         const char *nt_domain;
1222         const char *nt_username;
1223         bool username_was_mapped;
1224         struct passwd *pwd;
1225         struct auth_serversupplied_info *result;
1226         struct dom_sid *group_sid;
1227         struct netr_SamInfo3 *i3;
1228
1229         /* 
1230            Here is where we should check the list of
1231            trusted domains, and verify that the SID 
1232            matches.
1233         */
1234
1235         nt_username = talloc_strdup(mem_ctx, info3->base.account_name.string);
1236         if (!nt_username) {
1237                 /* If the server didn't give us one, just use the one we sent
1238                  * them */
1239                 nt_username = sent_nt_username;
1240         }
1241
1242         nt_domain = talloc_strdup(mem_ctx, info3->base.domain.string);
1243         if (!nt_domain) {
1244                 /* If the server didn't give us one, just use the one we sent
1245                  * them */
1246                 nt_domain = domain;
1247         }
1248
1249         /* If getpwnam() fails try the add user script (2.2.x behavior).
1250
1251            We use the _unmapped_ username here in an attempt to provide
1252            consistent username mapping behavior between kerberos and NTLM[SSP]
1253            authentication in domain mode security.  I.E. Username mapping
1254            should be applied to the fully qualified username
1255            (e.g. DOMAIN\user) and not just the login name.  Yes this means we
1256            called map_username() unnecessarily in make_user_info_map() but
1257            that is how the current code is designed.  Making the change here
1258            is the least disruptive place.  -- jerry */
1259
1260         /* this call will try to create the user if necessary */
1261
1262         nt_status = check_account(mem_ctx, nt_domain, sent_nt_username,
1263                                      &found_username, &pwd,
1264                                      &username_was_mapped);
1265
1266         if (!NT_STATUS_IS_OK(nt_status)) {
1267                 return nt_status;
1268         }
1269
1270         result = make_server_info(NULL);
1271         if (result == NULL) {
1272                 DEBUG(4, ("make_server_info failed!\n"));
1273                 return NT_STATUS_NO_MEMORY;
1274         }
1275
1276         result->unix_name = talloc_strdup(result, found_username);
1277
1278         result->sanitized_username = sanitize_username(result,
1279                                                        result->unix_name);
1280         if (result->sanitized_username == NULL) {
1281                 TALLOC_FREE(result);
1282                 return NT_STATUS_NO_MEMORY;
1283         }
1284
1285         /* copy in the info3 */
1286         result->info3 = i3 = copy_netr_SamInfo3(result, info3);
1287         if (result->info3 == NULL) {
1288                 TALLOC_FREE(result);
1289                 return NT_STATUS_NO_MEMORY;
1290         }
1291
1292         /* Fill in the unix info we found on the way */
1293         result->utok.uid = pwd->pw_uid;
1294         result->utok.gid = pwd->pw_gid;
1295
1296         /* We can't just trust that the primary group sid sent us is something
1297          * we can really use. Obtain the useable sid, and store the original
1298          * one as an additional group if it had to be replaced */
1299         nt_status = get_primary_group_sid(mem_ctx, found_username,
1300                                           &pwd, &group_sid);
1301         if (!NT_STATUS_IS_OK(nt_status)) {
1302                 TALLOC_FREE(result);
1303                 return nt_status;
1304         }
1305
1306         /* store and check if it is the same we got originally */
1307         sid_peek_rid(group_sid, &i3->base.primary_gid);
1308         if (i3->base.primary_gid != info3->base.primary_gid) {
1309                 uint32_t n = i3->base.groups.count;
1310                 /* not the same, store the original as an additional group */
1311                 i3->base.groups.rids =
1312                         talloc_realloc(i3, i3->base.groups.rids,
1313                                         struct samr_RidWithAttribute, n + 1);
1314                 if (i3->base.groups.rids == NULL) {
1315                         TALLOC_FREE(result);
1316                         return NT_STATUS_NO_MEMORY;
1317                 }
1318                 i3->base.groups.rids[n].rid = info3->base.primary_gid;
1319                 i3->base.groups.rids[n].attributes = SE_GROUP_ENABLED;
1320                 i3->base.groups.count = n + 1;
1321         }
1322
1323         /* ensure we are never given NULL session keys */
1324
1325         if (memcmp(info3->base.key.key, zeros, sizeof(zeros)) == 0) {
1326                 result->session_key = data_blob_null;
1327         } else {
1328                 result->session_key = data_blob_talloc(
1329                         result, info3->base.key.key,
1330                         sizeof(info3->base.key.key));
1331         }
1332
1333         if (memcmp(info3->base.LMSessKey.key, zeros, 8) == 0) {
1334                 result->lm_session_key = data_blob_null;
1335         } else {
1336                 result->lm_session_key = data_blob_talloc(
1337                         result, info3->base.LMSessKey.key,
1338                         sizeof(info3->base.LMSessKey.key));
1339         }
1340
1341         result->nss_token |= username_was_mapped;
1342
1343         *server_info = result;
1344
1345         return NT_STATUS_OK;
1346 }
1347
1348 /*****************************************************************************
1349  Make a server_info struct from the wbcAuthUserInfo returned by a domain logon
1350 ******************************************************************************/
1351
1352 NTSTATUS make_server_info_wbcAuthUserInfo(TALLOC_CTX *mem_ctx,
1353                                           const char *sent_nt_username,
1354                                           const char *domain,
1355                                           const struct wbcAuthUserInfo *info,
1356                                           struct auth_serversupplied_info **server_info)
1357 {
1358         struct netr_SamInfo3 *info3;
1359
1360         info3 = wbcAuthUserInfo_to_netr_SamInfo3(mem_ctx, info);
1361         if (!info3) {
1362                 return NT_STATUS_NO_MEMORY;
1363         }
1364
1365         return make_server_info_info3(mem_ctx,
1366                                       sent_nt_username, domain,
1367                                       server_info, info3);
1368 }
1369
1370 /**
1371  * Verify whether or not given domain is trusted.
1372  *
1373  * @param domain_name name of the domain to be verified
1374  * @return true if domain is one of the trusted ones or
1375  *         false if otherwise
1376  **/
1377
1378 bool is_trusted_domain(const char* dom_name)
1379 {
1380         struct dom_sid trustdom_sid;
1381         bool ret;
1382
1383         /* no trusted domains for a standalone server */
1384
1385         if ( lp_server_role() == ROLE_STANDALONE )
1386                 return False;
1387
1388         if (dom_name == NULL || dom_name[0] == '\0') {
1389                 return false;
1390         }
1391
1392         if (strequal(dom_name, get_global_sam_name())) {
1393                 return false;
1394         }
1395
1396         /* if we are a DC, then check for a direct trust relationships */
1397
1398         if ( IS_DC ) {
1399                 become_root();
1400                 DEBUG (5,("is_trusted_domain: Checking for domain trust with "
1401                           "[%s]\n", dom_name ));
1402                 ret = pdb_get_trusteddom_pw(dom_name, NULL, NULL, NULL);
1403                 unbecome_root();
1404                 if (ret)
1405                         return True;
1406         }
1407         else {
1408                 wbcErr result;
1409
1410                 /* If winbind is around, ask it */
1411
1412                 result = wb_is_trusted_domain(dom_name);
1413
1414                 if (result == WBC_ERR_SUCCESS) {
1415                         return True;
1416                 }
1417
1418                 if (result == WBC_ERR_DOMAIN_NOT_FOUND) {
1419                         /* winbind could not find the domain */
1420                         return False;
1421                 }
1422
1423                 /* The only other possible result is that winbind is not up
1424                    and running. We need to update the trustdom_cache
1425                    ourselves */
1426
1427                 update_trustdom_cache();
1428         }
1429
1430         /* now the trustdom cache should be available a DC could still
1431          * have a transitive trust so fall back to the cache of trusted
1432          * domains (like a domain member would use  */
1433
1434         if ( trustdom_cache_fetch(dom_name, &trustdom_sid) ) {
1435                 return True;
1436         }
1437
1438         return False;
1439 }
1440