54f959173c7bf4b1440ab9b1fc82d8dea2b2625e
[samba.git] / source3 / libsmb / trustdom_cache.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Trusted domain names cache on top of gencache.
5
6    Copyright (C) Rafal Szczesniak       2002
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 "../libcli/security/security.h"
24 #include "../librpc/gen_ndr/ndr_lsa_c.h"
25 #include "libsmb/libsmb.h"
26 #include "rpc_client/cli_pipe.h"
27 #include "rpc_client/cli_lsarpc.h"
28
29 #undef DBGC_CLASS
30 #define DBGC_CLASS DBGC_ALL     /* there's no proper class yet */
31
32 #define TDOMKEY_FMT  "TDOM/%s"
33 #define TDOMTSKEY    "TDOMCACHE/TIMESTAMP"
34 #define TRUSTDOM_UPDATE_INTERVAL        600
35
36
37 /**
38  * @file trustdom_cache.c
39  *
40  * Implementation of trusted domain names cache useful when
41  * samba acts as domain member server. In such case, caching
42  * domain names currently trusted gives a performance gain
43  * because there's no need to query PDC each time we need
44  * list of trusted domains
45  **/
46
47 /**
48  * Form up trustdom name key. It is based only
49  * on domain name now.
50  *
51  * @param name trusted domain name
52  * @return cache key for use in gencache mechanism
53  **/
54
55 static char *trustdom_cache_key(TALLOC_CTX *mem_ctx, const char *name)
56 {
57         return talloc_asprintf_strupper_m(mem_ctx, TDOMKEY_FMT, name);
58 }
59
60
61 /**
62  * Store trusted domain in gencache as the domain name (key)
63  * and trusted domain's SID (value)
64  *
65  * @param name trusted domain name
66  * @param alt_name alternative trusted domain name (used in ADS domains)
67  * @param sid trusted domain's SID
68  * @param timeout cache entry expiration time
69  * @return true upon successful value storing or
70  *         false if store attempt failed
71  **/
72
73 bool trustdom_cache_store(const char *name, const struct dom_sid *sid)
74 {
75         char *key;
76         fstring sid_string;
77         bool ret;
78
79         DEBUG(5, ("trustdom_store: storing SID %s of domain %s\n",
80                   sid_string_dbg(sid), name));
81
82         key = trustdom_cache_key(talloc_tos(), name);
83
84         /* Generate string representation domain SID */
85         sid_to_fstring(sid_string, sid);
86
87         ret = gencache_set(key, sid_string,
88                            time(NULL) + TRUSTDOM_UPDATE_INTERVAL);
89         TALLOC_FREE(key);
90         return ret;
91 }
92
93
94 /**
95  * Fetch trusted domain's SID from the gencache.
96  * This routine can also be used to check whether given
97  * domain is currently trusted one.
98  *
99  * @param name trusted domain name
100  * @param sid trusted domain's SID to be returned
101  * @return true if entry is found or
102  *         false if has expired/doesn't exist
103  **/
104
105 bool trustdom_cache_fetch(const char* name, struct dom_sid* sid)
106 {
107         char *key = NULL, *value = NULL;
108         time_t timeout;
109         bool ok;
110
111         /* exit now if null pointers were passed as they're required further */
112         if (sid == NULL) {
113                 return false;
114         }
115
116         /* prepare a key and get the value */
117         key = trustdom_cache_key(talloc_tos(), name);
118         if (key == NULL) {
119                 return false;
120         }
121
122         ok = gencache_get(key, talloc_tos(), &value, &timeout);
123         TALLOC_FREE(key);
124         if (!ok) {
125                 DEBUG(5, ("no entry for trusted domain %s found.\n", name));
126                 return false;
127         }
128
129         DEBUG(5, ("trusted domain %s found (%s)\n", name, value));
130
131         /* convert sid string representation into struct dom_sid structure */
132         ok = string_to_sid(sid, value);
133         TALLOC_FREE(value);
134         return ok;
135 }
136
137 /*******************************************************************
138  fetch the timestamp from the last update
139 *******************************************************************/
140
141 static uint32_t trustdom_cache_fetch_timestamp(void)
142 {
143         char *value = NULL;
144         time_t timeout;
145         uint32_t timestamp;
146
147         if (!gencache_get(TDOMTSKEY, talloc_tos(), &value, &timeout)) {
148                 DEBUG(5, ("no timestamp for trusted domain cache located.\n"));
149                 SAFE_FREE(value);
150                 return 0;
151         }
152
153         timestamp = atoi(value);
154
155         TALLOC_FREE(value);
156         return timestamp;
157 }
158
159 /*******************************************************************
160  store the timestamp from the last update
161 *******************************************************************/
162
163 static bool trustdom_cache_store_timestamp(uint32_t t, time_t timeout)
164 {
165         fstring value;
166
167         fstr_sprintf(value, "%d", t );
168
169         if (!gencache_set(TDOMTSKEY, value, timeout)) {
170                 DEBUG(5, ("failed to set timestamp for trustdom_cache\n"));
171                 return False;
172         }
173
174         return True;
175 }
176
177
178 /**
179  * Delete single trustdom entry. Look at the
180  * gencache_iterate definition.
181  *
182  **/
183
184 static void flush_trustdom_name(const char* key, const char *value, time_t timeout, void* dptr)
185 {
186         gencache_del(key);
187         DEBUG(5, ("Deleting entry %s\n", key));
188 }
189
190
191 /**
192  * Flush all the trusted domains entries from the cache.
193  **/
194
195 void trustdom_cache_flush(void)
196 {
197         char *key = trustdom_cache_key(talloc_tos(), "*");
198         /*
199          * iterate through each TDOM cache's entry and flush it
200          * by flush_trustdom_name function
201          */
202         gencache_iterate(flush_trustdom_name, NULL, key);
203         TALLOC_FREE(key);
204         DEBUG(5, ("Trusted domains cache flushed\n"));
205 }
206
207 /*********************************************************************
208  Enumerate the list of trusted domains from a DC
209 *********************************************************************/
210
211 static bool enumerate_domain_trusts( TALLOC_CTX *mem_ctx, const char *domain,
212                                      char ***domain_names, uint32_t *num_domains,
213                                      struct dom_sid **sids )
214 {
215         struct policy_handle    pol;
216         NTSTATUS status, result;
217         fstring         dc_name;
218         struct sockaddr_storage dc_ss;
219         uint32_t                enum_ctx = 0;
220         struct cli_state *cli = NULL;
221         struct rpc_pipe_client *lsa_pipe = NULL;
222         struct lsa_DomainList dom_list;
223         int i;
224         struct dcerpc_binding_handle *b = NULL;
225
226         *domain_names = NULL;
227         *num_domains = 0;
228         *sids = NULL;
229
230         /* lookup a DC first */
231
232         if ( !get_dc_name(domain, NULL, dc_name, &dc_ss) ) {
233                 DEBUG(3,("enumerate_domain_trusts: can't locate a DC for domain %s\n",
234                         domain));
235                 return False;
236         }
237
238         /* setup the anonymous connection */
239
240         status = cli_full_connection( &cli, lp_netbios_name(), dc_name, &dc_ss, 0, "IPC$", "IPC",
241                 "", "", "", 0, Undefined);
242         if ( !NT_STATUS_IS_OK(status) )
243                 goto done;
244
245         /* open the LSARPC_PIPE */
246
247         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
248                                           &lsa_pipe);
249         if (!NT_STATUS_IS_OK(status)) {
250                 goto done;
251         }
252
253         b = lsa_pipe->binding_handle;
254
255         /* get a handle */
256
257         status = rpccli_lsa_open_policy(lsa_pipe, mem_ctx, True,
258                 LSA_POLICY_VIEW_LOCAL_INFORMATION, &pol);
259         if ( !NT_STATUS_IS_OK(status) )
260                 goto done;
261
262         /* Lookup list of trusted domains */
263
264         status = dcerpc_lsa_EnumTrustDom(b, mem_ctx,
265                                          &pol,
266                                          &enum_ctx,
267                                          &dom_list,
268                                          (uint32_t)-1,
269                                          &result);
270         if ( !NT_STATUS_IS_OK(status) )
271                 goto done;
272         if (!NT_STATUS_IS_OK(result)) {
273                 status = result;
274                 goto done;
275         }
276
277         *num_domains = dom_list.count;
278
279         *domain_names = talloc_zero_array(mem_ctx, char *, *num_domains);
280         if (!*domain_names) {
281                 status = NT_STATUS_NO_MEMORY;
282                 goto done;
283         }
284
285         *sids = talloc_zero_array(mem_ctx, struct dom_sid, *num_domains);
286         if (!*sids) {
287                 status = NT_STATUS_NO_MEMORY;
288                 goto done;
289         }
290
291         for (i=0; i< *num_domains; i++) {
292                 (*domain_names)[i] = discard_const_p(char, dom_list.domains[i].name.string);
293                 (*sids)[i] = *dom_list.domains[i].sid;
294         }
295
296 done:
297         /* cleanup */
298         if (cli) {
299                 DEBUG(10,("enumerate_domain_trusts: shutting down connection...\n"));
300                 cli_shutdown( cli );
301         }
302
303         return NT_STATUS_IS_OK(status);
304 }
305
306 /********************************************************************
307  update the trustdom_cache if needed
308 ********************************************************************/
309
310 void update_trustdom_cache( void )
311 {
312         char **domain_names;
313         struct dom_sid *dom_sids;
314         uint32_t num_domains;
315         uint32_t last_check;
316         int time_diff;
317         TALLOC_CTX *mem_ctx = NULL;
318         time_t now = time(NULL);
319         int i;
320
321         /* get the timestamp.  We have to initialise it if the last timestamp == 0 */
322         if ( (last_check = trustdom_cache_fetch_timestamp()) == 0 )
323                 trustdom_cache_store_timestamp(0, now+TRUSTDOM_UPDATE_INTERVAL);
324
325         time_diff = (int) (now - last_check);
326
327         if ( (time_diff > 0) && (time_diff < TRUSTDOM_UPDATE_INTERVAL) ) {
328                 DEBUG(10,("update_trustdom_cache: not time to update trustdom_cache yet\n"));
329                 return;
330         }
331
332         /* note that we don't lock the timestamp. This prevents this
333            smbd from blocking all other smbd daemons while we
334            enumerate the trusted domains */
335         trustdom_cache_store_timestamp(now, now+TRUSTDOM_UPDATE_INTERVAL);
336
337         if ( !(mem_ctx = talloc_init("update_trustdom_cache")) ) {
338                 DEBUG(0,("update_trustdom_cache: talloc_init() failed!\n"));
339                 goto done;
340         }
341
342         /* get the domains and store them */
343
344         if ( enumerate_domain_trusts(mem_ctx, lp_workgroup(), &domain_names,
345                 &num_domains, &dom_sids)) {
346                 for ( i=0; i<num_domains; i++ ) {
347                         trustdom_cache_store(domain_names[i], &dom_sids[i]);
348                 }
349         } else {
350                 /* we failed to fetch the list of trusted domains - restore the old
351                    timestamp */
352                 trustdom_cache_store_timestamp(last_check,
353                                                last_check+TRUSTDOM_UPDATE_INTERVAL);
354         }
355
356 done:
357         talloc_destroy( mem_ctx );
358
359         return;
360 }