port latest changes from SAMBA_3_0 tree
[Samba.git] / source3 / nsswitch / winbindd_util.c
bloba810e503a00adbafc0181114e292d76d03c6cbf6
1 /*
2 Unix SMB/CIFS implementation.
4 Winbind daemon for ntdom nss module
6 Copyright (C) Tim Potter 2000-2001
7 Copyright (C) 2001 by Martin Pool <mbp@samba.org>
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #include "winbindd.h"
26 #undef DBGC_CLASS
27 #define DBGC_CLASS DBGC_WINBIND
29 /**
30 * @file winbindd_util.c
32 * Winbind daemon for NT domain authentication nss module.
33 **/
36 /**
37 * Used to clobber name fields that have an undefined value.
39 * Correct code should never look at a field that has this value.
40 **/
42 static const fstring name_deadbeef = "<deadbeef>";
44 /* The list of trusted domains. Note that the list can be deleted and
45 recreated using the init_domain_list() function so pointers to
46 individual winbindd_domain structures cannot be made. Keep a copy of
47 the domain name instead. */
49 static struct winbindd_domain *_domain_list;
51 struct winbindd_domain *domain_list(void)
53 /* Initialise list */
55 if (!_domain_list)
56 init_domain_list();
58 return _domain_list;
61 /* Free all entries in the trusted domain list */
63 void free_domain_list(void)
65 struct winbindd_domain *domain = _domain_list;
67 while(domain) {
68 struct winbindd_domain *next = domain->next;
70 DLIST_REMOVE(_domain_list, domain);
71 SAFE_FREE(domain);
72 domain = next;
77 /* Add a trusted domain to our list of domains */
78 static struct winbindd_domain *add_trusted_domain(const char *domain_name, const char *alt_name,
79 struct winbindd_methods *methods,
80 DOM_SID *sid)
82 struct winbindd_domain *domain;
84 /* We can't call domain_list() as this function is called from
85 init_domain_list() and we'll get stuck in a loop. */
86 for (domain = _domain_list; domain; domain = domain->next) {
87 if (strcasecmp(domain_name, domain->name) == 0 ||
88 strcasecmp(domain_name, domain->alt_name) == 0) {
89 return domain;
91 if (alt_name && *alt_name) {
92 if (strcasecmp(alt_name, domain->name) == 0 ||
93 strcasecmp(alt_name, domain->alt_name) == 0) {
94 return domain;
99 /* Create new domain entry */
101 if ((domain = (struct winbindd_domain *)
102 malloc(sizeof(*domain))) == NULL)
103 return NULL;
105 /* Fill in fields */
107 ZERO_STRUCTP(domain);
109 /* prioritise the short name */
110 if (strchr_m(domain_name, '.') && alt_name && *alt_name) {
111 fstrcpy(domain->name, alt_name);
112 fstrcpy(domain->alt_name, domain_name);
113 } else {
114 fstrcpy(domain->name, domain_name);
115 if (alt_name) {
116 fstrcpy(domain->alt_name, alt_name);
120 domain->methods = methods;
121 domain->backend = NULL;
122 domain->sequence_number = DOM_SEQUENCE_NONE;
123 domain->last_seq_check = 0;
124 if (sid) {
125 sid_copy(&domain->sid, sid);
128 /* see if this is a native mode win2k domain */
130 domain->native_mode = cm_check_for_native_mode_win2k( domain_name );
131 DEBUG(3,("add_trusted_domain: %s is a %s mode domain\n", domain_name,
132 domain->native_mode ? "native" : "mixed (or NT4)" ));
134 /* Link to domain list */
135 DLIST_ADD(_domain_list, domain);
137 DEBUG(1,("Added domain %s %s %s\n",
138 domain->name, domain->alt_name,
139 sid?sid_string_static(&domain->sid):""));
141 return domain;
146 rescan our domains looking for new trusted domains
148 void rescan_trusted_domains(BOOL force)
150 struct winbindd_domain *domain;
151 TALLOC_CTX *mem_ctx;
152 static time_t last_scan;
153 time_t t = time(NULL);
155 /* trusted domains might be disabled */
156 if (!lp_allow_trusted_domains()) {
157 return;
160 /* Only rescan every few minutes but force if necessary */
162 if (((unsigned)(t - last_scan) < WINBINDD_RESCAN_FREQ) && !force)
163 return;
165 last_scan = t;
167 DEBUG(1, ("scanning trusted domain list\n"));
169 if (!(mem_ctx = talloc_init("init_domain_list")))
170 return;
172 for (domain = _domain_list; domain; domain = domain->next) {
173 NTSTATUS result;
174 char **names;
175 char **alt_names;
176 int num_domains = 0;
177 DOM_SID *dom_sids, null_sid;
178 int i;
179 struct winbindd_domain *new_domain;
181 ZERO_STRUCTP(&null_sid);
183 result = domain->methods->trusted_domains(domain, mem_ctx, &num_domains,
184 &names, &alt_names, &dom_sids);
185 if (!NT_STATUS_IS_OK(result)) {
186 continue;
189 /* Add each domain to the trusted domain list */
191 for(i = 0; i < num_domains; i++) {
192 DEBUG(10,("Found domain %s\n", names[i]));
193 add_trusted_domain(names[i], alt_names?alt_names[i]:NULL,
194 domain->methods, &dom_sids[i]);
196 /* if the SID was empty, we better set it now */
198 if ( sid_equal(&dom_sids[i], &null_sid) ) {
200 new_domain = find_domain_from_name(names[i]);
202 /* this should never happen */
203 if ( !new_domain ) {
204 DEBUG(0,("rescan_trust_domains: can't find the domain I just added! [%s]\n",
205 names[i]));
206 break;
209 /* call the cache method; which will operate on the winbindd_domain \
210 passed in and choose either rpc or ads as appropriate */
212 result = domain->methods->domain_sid( new_domain, &new_domain->sid );
214 if ( NT_STATUS_IS_OK(result) )
215 sid_copy( &dom_sids[i], &domain->sid );
218 /* store trusted domain in the cache */
219 trustdom_cache_store(names[i], alt_names ? alt_names[i] : NULL,
220 &dom_sids[i], t + WINBINDD_RESCAN_FREQ);
224 talloc_destroy(mem_ctx);
227 /* Look up global info for the winbind daemon */
228 BOOL init_domain_list(void)
230 extern struct winbindd_methods cache_methods;
231 struct winbindd_domain *domain;
233 /* Free existing list */
234 free_domain_list();
236 /* Add ourselves as the first entry */
237 domain = add_trusted_domain( lp_workgroup(), NULL, &cache_methods, NULL);
238 if (!secrets_fetch_domain_sid(domain->name, &domain->sid)) {
239 DEBUG(1, ("Could not fetch sid for our domain %s\n",
240 domain->name));
241 return False;
244 /* get any alternate name for the primary domain */
245 cache_methods.alternate_name(domain);
247 /* do an initial scan for trusted domains */
248 rescan_trusted_domains(True);
250 return True;
253 /* Given a domain name, return the struct winbindd domain info for it
254 if it is actually working. */
256 struct winbindd_domain *find_domain_from_name(const char *domain_name)
258 struct winbindd_domain *domain;
260 /* Search through list */
262 for (domain = domain_list(); domain != NULL; domain = domain->next) {
263 if (strequal(domain_name, domain->name) ||
264 (domain->alt_name[0] && strequal(domain_name, domain->alt_name)))
265 return domain;
268 /* Not found */
270 return NULL;
273 /* Given a domain sid, return the struct winbindd domain info for it */
275 struct winbindd_domain *find_domain_from_sid(DOM_SID *sid)
277 struct winbindd_domain *domain;
279 /* Search through list */
281 for (domain = domain_list(); domain != NULL; domain = domain->next) {
282 if (sid_compare_domain(sid, &domain->sid) == 0)
283 return domain;
286 /* Not found */
288 return NULL;
291 /* Lookup a sid in a domain from a name */
293 BOOL winbindd_lookup_sid_by_name(struct winbindd_domain *domain,
294 const char *name, DOM_SID *sid,
295 enum SID_NAME_USE *type)
297 NTSTATUS result;
298 TALLOC_CTX *mem_ctx;
299 /* Don't bother with machine accounts */
301 if (name[strlen(name) - 1] == '$')
302 return False;
304 mem_ctx = talloc_init("lookup_sid_by_name for %s\n", name);
305 if (!mem_ctx)
306 return False;
308 /* Lookup name */
309 result = domain->methods->name_to_sid(domain, mem_ctx, name, sid, type);
311 talloc_destroy(mem_ctx);
313 /* Return rid and type if lookup successful */
314 if (!NT_STATUS_IS_OK(result)) {
315 *type = SID_NAME_UNKNOWN;
318 return NT_STATUS_IS_OK(result);
322 * @brief Lookup a name in a domain from a sid.
324 * @param sid Security ID you want to look up.
325 * @param name On success, set to the name corresponding to @p sid.
326 * @param dom_name On success, set to the 'domain name' corresponding to @p sid.
327 * @param type On success, contains the type of name: alias, group or
328 * user.
329 * @retval True if the name exists, in which case @p name and @p type
330 * are set, otherwise False.
332 BOOL winbindd_lookup_name_by_sid(DOM_SID *sid,
333 fstring dom_name,
334 fstring name,
335 enum SID_NAME_USE *type)
337 char *names;
338 NTSTATUS result;
339 TALLOC_CTX *mem_ctx;
340 BOOL rv = False;
341 struct winbindd_domain *domain;
343 domain = find_domain_from_sid(sid);
345 if (!domain) {
346 DEBUG(1,("Can't find domain from sid\n"));
347 return False;
350 /* Lookup name */
352 if (!(mem_ctx = talloc_init("winbindd_lookup_name_by_sid")))
353 return False;
355 result = domain->methods->sid_to_name(domain, mem_ctx, sid, &names, type);
357 /* Return name and type if successful */
359 if ((rv = NT_STATUS_IS_OK(result))) {
360 fstrcpy(dom_name, domain->name);
361 fstrcpy(name, names);
362 } else {
363 *type = SID_NAME_UNKNOWN;
364 fstrcpy(name, name_deadbeef);
367 talloc_destroy(mem_ctx);
369 return rv;
373 /* Free state information held for {set,get,end}{pw,gr}ent() functions */
375 void free_getent_state(struct getent_state *state)
377 struct getent_state *temp;
379 /* Iterate over state list */
381 temp = state;
383 while(temp != NULL) {
384 struct getent_state *next;
386 /* Free sam entries then list entry */
388 SAFE_FREE(state->sam_entries);
389 DLIST_REMOVE(state, state);
390 next = temp->next;
392 SAFE_FREE(temp);
393 temp = next;
397 /* Parse winbindd related parameters */
399 BOOL winbindd_param_init(void)
401 /* Parse winbind uid and winbind_gid parameters */
403 if (!lp_idmap_uid(&server_state.uid_low, &server_state.uid_high)) {
404 DEBUG(0, ("winbindd: idmap uid range missing or invalid\n"));
405 DEBUG(0, ("winbindd: cannot continue, exiting.\n"));
406 return False;
409 if (!lp_idmap_gid(&server_state.gid_low, &server_state.gid_high)) {
410 DEBUG(0, ("winbindd: idmap gid range missing or invalid\n"));
411 DEBUG(0, ("winbindd: cannot continue, exiting.\n"));
412 return False;
415 return True;
418 /* Check if a domain is present in a comma-separated list of domains */
420 BOOL check_domain_env(char *domain_env, char *domain)
422 fstring name;
423 const char *tmp = domain_env;
425 while(next_token(&tmp, name, ",", sizeof(fstring))) {
426 if (strequal(name, domain))
427 return True;
430 return False;
433 /* Parse a string of the form DOMAIN/user into a domain and a user */
435 BOOL parse_domain_user(const char *domuser, fstring domain, fstring user)
437 char *p = strchr(domuser,*lp_winbind_separator());
439 if ( !p ) {
440 fstrcpy(user, domuser);
442 if ( lp_winbind_use_default_domain() )
443 fstrcpy(domain, lp_workgroup());
444 else
445 fstrcpy( domain, "" );
447 else {
448 fstrcpy(user, p+1);
449 fstrcpy(domain, domuser);
450 domain[PTR_DIFF(p, domuser)] = 0;
453 strupper_m(domain);
455 return True;
459 Fill DOMAIN\\USERNAME entry accounting 'winbind use default domain' and
460 'winbind separator' options.
461 This means:
462 - omit DOMAIN when 'winbind use default domain = true' and DOMAIN is
463 lp_workgroup
466 void fill_domain_username(fstring name, const char *domain, const char *user)
468 if(lp_winbind_use_default_domain() &&
469 !strcmp(lp_workgroup(), domain)) {
470 strlcpy(name, user, sizeof(fstring));
471 } else {
472 slprintf(name, sizeof(fstring) - 1, "%s%s%s",
473 domain, lp_winbind_separator(),
474 user);
479 * Winbindd socket accessor functions
482 char *get_winbind_priv_pipe_dir(void)
484 return lock_path(WINBINDD_PRIV_SOCKET_SUBDIR);
487 /* Open the winbindd socket */
489 static int _winbindd_socket = -1;
490 static int _winbindd_priv_socket = -1;
492 int open_winbindd_socket(void)
494 if (_winbindd_socket == -1) {
495 _winbindd_socket = create_pipe_sock(
496 WINBINDD_SOCKET_DIR, WINBINDD_SOCKET_NAME, 0755);
497 DEBUG(10, ("open_winbindd_socket: opened socket fd %d\n",
498 _winbindd_socket));
501 return _winbindd_socket;
504 int open_winbindd_priv_socket(void)
506 if (_winbindd_priv_socket == -1) {
507 _winbindd_priv_socket = create_pipe_sock(
508 get_winbind_priv_pipe_dir(), WINBINDD_SOCKET_NAME, 0750);
509 DEBUG(10, ("open_winbindd_priv_socket: opened socket fd %d\n",
510 _winbindd_priv_socket));
513 return _winbindd_priv_socket;
516 /* Close the winbindd socket */
518 void close_winbindd_socket(void)
520 if (_winbindd_socket != -1) {
521 DEBUG(10, ("close_winbindd_socket: closing socket fd %d\n",
522 _winbindd_socket));
523 close(_winbindd_socket);
524 _winbindd_socket = -1;
526 if (_winbindd_priv_socket != -1) {
527 DEBUG(10, ("close_winbindd_socket: closing socket fd %d\n",
528 _winbindd_priv_socket));
529 close(_winbindd_priv_socket);
530 _winbindd_priv_socket = -1;
535 * Client list accessor functions
538 static struct winbindd_cli_state *_client_list;
539 static int _num_clients;
541 /* Return list of all connected clients */
543 struct winbindd_cli_state *winbindd_client_list(void)
545 return _client_list;
548 /* Add a connection to the list */
550 void winbindd_add_client(struct winbindd_cli_state *cli)
552 DLIST_ADD(_client_list, cli);
553 _num_clients++;
556 /* Remove a client from the list */
558 void winbindd_remove_client(struct winbindd_cli_state *cli)
560 DLIST_REMOVE(_client_list, cli);
561 _num_clients--;
564 /* Close all open clients */
566 void winbindd_kill_all_clients(void)
568 struct winbindd_cli_state *cl = winbindd_client_list();
570 DEBUG(10, ("winbindd_kill_all_clients: going postal\n"));
572 while (cl) {
573 struct winbindd_cli_state *next;
575 next = cl->next;
576 winbindd_remove_client(cl);
577 cl = next;
581 /* Return number of open clients */
583 int winbindd_num_clients(void)
585 return _num_clients;
588 /* Help with RID -> SID conversion */
590 DOM_SID *rid_to_talloced_sid(struct winbindd_domain *domain,
591 TALLOC_CTX *mem_ctx,
592 uint32 rid)
594 DOM_SID *sid;
595 sid = talloc(mem_ctx, sizeof(*sid));
596 if (!sid) {
597 smb_panic("rid_to_to_talloced_sid: talloc for DOM_SID failed!\n");
599 sid_copy(sid, &domain->sid);
600 sid_append_rid(sid, rid);
601 return sid;
604 /*****************************************************************************
605 For idmap conversion: convert one record to new format
606 Ancient versions (eg 2.2.3a) of winbindd_idmap.tdb mapped DOMAINNAME/rid
607 instead of the SID.
608 *****************************************************************************/
609 static int convert_fn(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA data, void *state)
611 struct winbindd_domain *domain;
612 char *p;
613 DOM_SID sid;
614 uint32 rid;
615 fstring keystr;
616 fstring dom_name;
617 TDB_DATA key2;
618 BOOL *failed = (BOOL *)state;
620 DEBUG(10,("Converting %s\n", key.dptr));
622 p = strchr(key.dptr, '/');
623 if (!p)
624 return 0;
626 *p = 0;
627 fstrcpy(dom_name, key.dptr);
628 *p++ = '/';
630 domain = find_domain_from_name(dom_name);
631 if (domain == NULL) {
632 /* We must delete the old record. */
633 DEBUG(0,("Unable to find domain %s\n", dom_name ));
634 DEBUG(0,("deleting record %s\n", key.dptr ));
636 if (tdb_delete(tdb, key) != 0) {
637 DEBUG(0, ("Unable to delete record %s\n", key.dptr));
638 *failed = True;
639 return -1;
642 return 0;
645 rid = atoi(p);
647 sid_copy(&sid, &domain->sid);
648 sid_append_rid(&sid, rid);
650 sid_to_string(keystr, &sid);
651 key2.dptr = keystr;
652 key2.dsize = strlen(keystr) + 1;
654 if (tdb_store(tdb, key2, data, TDB_INSERT) != 0) {
655 DEBUG(0,("Unable to add record %s\n", key2.dptr ));
656 *failed = True;
657 return -1;
660 if (tdb_store(tdb, data, key2, TDB_REPLACE) != 0) {
661 DEBUG(0,("Unable to update record %s\n", data.dptr ));
662 *failed = True;
663 return -1;
666 if (tdb_delete(tdb, key) != 0) {
667 DEBUG(0,("Unable to delete record %s\n", key.dptr ));
668 *failed = True;
669 return -1;
672 return 0;
675 /* These definitions are from sam/idmap_tdb.c. Replicated here just
676 out of laziness.... :-( */
678 /* High water mark keys */
679 #define HWM_GROUP "GROUP HWM"
680 #define HWM_USER "USER HWM"
682 /* idmap version determines auto-conversion */
683 #define IDMAP_VERSION 2
686 /*****************************************************************************
687 Convert the idmap database from an older version.
688 *****************************************************************************/
690 static BOOL idmap_convert(const char *idmap_name)
692 int32 vers;
693 BOOL bigendianheader;
694 BOOL failed = False;
695 TDB_CONTEXT *idmap_tdb;
697 if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
698 TDB_DEFAULT, O_RDWR,
699 0600))) {
700 DEBUG(0, ("idmap_convert: Unable to open idmap database\n"));
701 return False;
704 bigendianheader = (idmap_tdb->flags & TDB_BIGENDIAN) ? True : False;
706 vers = tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION");
708 if (((vers == -1) && bigendianheader) || (IREV(vers) == IDMAP_VERSION)) {
709 /* Arrggghh ! Bytereversed or old big-endian - make order independent ! */
711 * high and low records were created on a
712 * big endian machine and will need byte-reversing.
715 int32 wm;
717 wm = tdb_fetch_int32(idmap_tdb, HWM_USER);
719 if (wm != -1) {
720 wm = IREV(wm);
721 } else {
722 wm = server_state.uid_low;
725 if (tdb_store_int32(idmap_tdb, HWM_USER, wm) == -1) {
726 DEBUG(0, ("idmap_convert: Unable to byteswap user hwm in idmap database\n"));
727 tdb_close(idmap_tdb);
728 return False;
731 wm = tdb_fetch_int32(idmap_tdb, HWM_GROUP);
732 if (wm != -1) {
733 wm = IREV(wm);
734 } else {
735 wm = server_state.gid_low;
738 if (tdb_store_int32(idmap_tdb, HWM_GROUP, wm) == -1) {
739 DEBUG(0, ("idmap_convert: Unable to byteswap group hwm in idmap database\n"));
740 tdb_close(idmap_tdb);
741 return False;
745 /* the old format stored as DOMAIN/rid - now we store the SID direct */
746 tdb_traverse(idmap_tdb, convert_fn, &failed);
748 if (failed) {
749 DEBUG(0, ("Problem during conversion\n"));
750 tdb_close(idmap_tdb);
751 return False;
754 if (tdb_store_int32(idmap_tdb, "IDMAP_VERSION", IDMAP_VERSION) == -1) {
755 DEBUG(0, ("idmap_convert: Unable to dtore idmap version in databse\n"));
756 tdb_close(idmap_tdb);
757 return False;
760 tdb_close(idmap_tdb);
761 return True;
764 /*****************************************************************************
765 Convert the idmap database from an older version if necessary
766 *****************************************************************************/
768 BOOL winbindd_upgrade_idmap(void)
770 pstring idmap_name;
771 pstring backup_name;
772 SMB_STRUCT_STAT stbuf;
773 TDB_CONTEXT *idmap_tdb;
775 pstrcpy(idmap_name, lock_path("winbindd_idmap.tdb"));
777 if (!file_exist(idmap_name, &stbuf)) {
778 /* nothing to convert return */
779 return True;
782 if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
783 TDB_DEFAULT, O_RDWR,
784 0600))) {
785 DEBUG(0, ("idmap_convert: Unable to open idmap database\n"));
786 return False;
789 if (tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION") == IDMAP_VERSION) {
790 /* nothing to convert return */
791 tdb_close(idmap_tdb);
792 return True;
795 /* backup_tdb expects the tdb not to be open */
796 tdb_close(idmap_tdb);
798 DEBUG(0, ("Upgrading winbindd_idmap.tdb from an old version\n"));
800 pstrcpy(backup_name, idmap_name);
801 pstrcat(backup_name, ".bak");
803 if (backup_tdb(idmap_name, backup_name) != 0) {
804 DEBUG(0, ("Could not backup idmap database\n"));
805 return False;
808 return idmap_convert(idmap_name);
811 /*******************************************************************
812 wrapper around retrieving the trust account password
813 *******************************************************************/
815 BOOL get_trust_pw(const char *domain, uint8 ret_pwd[16],
816 time_t *pass_last_set_time, uint32 *channel)
818 DOM_SID sid;
819 char *pwd;
821 /* if we are a DC and this is not our domain, then lookup an account
822 for the domain trust */
824 if ( IS_DC && !strequal(domain, lp_workgroup()) && lp_allow_trusted_domains() )
826 if ( !secrets_fetch_trusted_domain_password(domain, &pwd, &sid,
827 pass_last_set_time) )
829 DEBUG(0, ("get_trust_pw: could not fetch trust account "
830 "password for trusted domain %s\n", domain));
831 return False;
834 *channel = SEC_CHAN_DOMAIN;
835 E_md4hash(pwd, ret_pwd);
836 SAFE_FREE(pwd);
838 return True;
840 else /* just get the account for our domain (covers
841 ROLE_DOMAIN_MEMBER as well */
843 /* get the machine trust account for our domain */
845 if ( !secrets_fetch_trust_account_password (lp_workgroup(), ret_pwd,
846 pass_last_set_time, channel) )
848 DEBUG(0, ("get_trust_pw: could not fetch trust account "
849 "password for my domain %s\n", domain));
850 return False;
853 return True;
856 /* Failure */
857 return False;