ctdb-scripts: Ignore shellcheck SC2181 warning (use of $?)
[metze/samba/wip.git] / source3 / libsmb / samlogon_cache.c
1 /*
2    Unix SMB/CIFS implementation.
3    Net_sam_logon info3 helpers
4    Copyright (C) Alexander Bokovoy              2002.
5    Copyright (C) Andrew Bartlett                2002.
6    Copyright (C) Gerald Carter                  2003.
7    Copyright (C) Tim Potter                     2003.
8    Copyright (C) Guenther Deschner              2008.
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 "replace.h"
25 #include "samlogon_cache.h"
26 #include "system/filesys.h"
27 #include "system/time.h"
28 #include "lib/util/debug.h"
29 #include "lib/util/talloc_stack.h"
30 #include "source3/lib/util_path.h"
31 #include "librpc/gen_ndr/ndr_krb5pac.h"
32 #include "../libcli/security/security.h"
33 #include "util_tdb.h"
34
35 #define NETSAMLOGON_TDB "netsamlogon_cache.tdb"
36
37 static TDB_CONTEXT *netsamlogon_tdb = NULL;
38
39 /***********************************************************************
40  open the tdb
41  ***********************************************************************/
42
43 bool netsamlogon_cache_init(void)
44 {
45         bool first_try = true;
46         char *path = NULL;
47         int ret;
48         struct tdb_context *tdb;
49
50         if (netsamlogon_tdb) {
51                 return true;
52         }
53
54         path = cache_path(NETSAMLOGON_TDB);
55         if (path == NULL) {
56                 return false;
57         }
58 again:
59         tdb = tdb_open_log(path, 0, TDB_DEFAULT|TDB_INCOMPATIBLE_HASH,
60                            O_RDWR | O_CREAT, 0600);
61         if (tdb == NULL) {
62                 DEBUG(0,("tdb_open_log('%s') - failed\n", path));
63                 goto clear;
64         }
65
66         ret = tdb_check(tdb, NULL, NULL);
67         if (ret != 0) {
68                 tdb_close(tdb);
69                 DEBUG(0,("tdb_check('%s') - failed\n", path));
70                 goto clear;
71         }
72
73         netsamlogon_tdb = tdb;
74         talloc_free(path);
75         return true;
76
77 clear:
78         if (!first_try) {
79                 talloc_free(path);
80                 return false;
81         }
82         first_try = false;
83
84         DEBUG(0,("retry after truncate for '%s'\n", path));
85         ret = truncate(path, 0);
86         if (ret == -1) {
87                 DBG_ERR("truncate failed: %s\n", strerror(errno));
88                 talloc_free(path);
89                 return false;
90         }
91
92         goto again;
93 }
94
95 /***********************************************************************
96  Clear cache getpwnam and getgroups entries from the winbindd cache
97 ***********************************************************************/
98
99 void netsamlogon_clear_cached_user(const struct dom_sid *user_sid)
100 {
101         char keystr[DOM_SID_STR_BUFLEN];
102
103         if (!netsamlogon_cache_init()) {
104                 DEBUG(0,("netsamlogon_clear_cached_user: cannot open "
105                         "%s for write!\n",
106                         NETSAMLOGON_TDB));
107                 return;
108         }
109
110         /* Prepare key as DOMAIN-SID/USER-RID string */
111         dom_sid_string_buf(user_sid, keystr, sizeof(keystr));
112
113         DEBUG(10,("netsamlogon_clear_cached_user: SID [%s]\n", keystr));
114
115         tdb_delete_bystring(netsamlogon_tdb, keystr);
116 }
117
118 /***********************************************************************
119  Store a netr_SamInfo3 structure in a tdb for later user
120  username should be in UTF-8 format
121 ***********************************************************************/
122
123 bool netsamlogon_cache_store(const char *username, struct netr_SamInfo3 *info3)
124 {
125         uint8_t dummy = 0;
126         TDB_DATA data = { .dptr = &dummy, .dsize = sizeof(dummy) };
127         char keystr[DOM_SID_STR_BUFLEN];
128         bool result = false;
129         struct dom_sid  user_sid;
130         TALLOC_CTX *tmp_ctx = talloc_stackframe();
131         DATA_BLOB blob;
132         enum ndr_err_code ndr_err;
133         struct netsamlogoncache_entry r;
134         int ret;
135
136         if (!info3) {
137                 return false;
138         }
139
140         if (!netsamlogon_cache_init()) {
141                 DEBUG(0,("netsamlogon_cache_store: cannot open %s for write!\n",
142                         NETSAMLOGON_TDB));
143                 return false;
144         }
145
146         /*
147          * First write a record with just the domain sid for
148          * netsamlogon_cache_domain_known. Use TDB_INSERT to avoid
149          * overwriting potentially other data. We're just interested
150          * in the existence of that record.
151          */
152         dom_sid_string_buf(info3->base.domain_sid, keystr, sizeof(keystr));
153
154         ret = tdb_store_bystring(netsamlogon_tdb, keystr, data, TDB_INSERT);
155
156         if ((ret == -1) && (tdb_error(netsamlogon_tdb) != TDB_ERR_EXISTS)) {
157                 DBG_WARNING("Could not store domain marker for %s: %s\n",
158                             keystr, tdb_errorstr(netsamlogon_tdb));
159                 TALLOC_FREE(tmp_ctx);
160                 return false;
161         }
162
163         sid_compose(&user_sid, info3->base.domain_sid, info3->base.rid);
164
165         /* Prepare key as DOMAIN-SID/USER-RID string */
166         dom_sid_string_buf(&user_sid, keystr, sizeof(keystr));
167
168         DEBUG(10,("netsamlogon_cache_store: SID [%s]\n", keystr));
169
170         /* Prepare data */
171
172         if (info3->base.full_name.string == NULL) {
173                 struct netr_SamInfo3 *cached_info3;
174                 const char *full_name = NULL;
175
176                 cached_info3 = netsamlogon_cache_get(tmp_ctx, &user_sid);
177                 if (cached_info3 != NULL) {
178                         full_name = cached_info3->base.full_name.string;
179                 }
180
181                 if (full_name != NULL) {
182                         info3->base.full_name.string = talloc_strdup(info3, full_name);
183                 }
184         }
185
186         /* only Samba fills in the username, not sure why NT doesn't */
187         /* so we fill it in since winbindd_getpwnam() makes use of it */
188
189         if (!info3->base.account_name.string) {
190                 info3->base.account_name.string = talloc_strdup(info3, username);
191         }
192
193         r.timestamp = time(NULL);
194         r.info3 = *info3;
195
196         if (DEBUGLEVEL >= 10) {
197                 NDR_PRINT_DEBUG(netsamlogoncache_entry, &r);
198         }
199
200         ndr_err = ndr_push_struct_blob(&blob, tmp_ctx, &r,
201                                        (ndr_push_flags_fn_t)ndr_push_netsamlogoncache_entry);
202         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
203                 DEBUG(0,("netsamlogon_cache_store: failed to push entry to cache\n"));
204                 TALLOC_FREE(tmp_ctx);
205                 return false;
206         }
207
208         data.dsize = blob.length;
209         data.dptr = blob.data;
210
211         if (tdb_store_bystring(netsamlogon_tdb, keystr, data, TDB_REPLACE) == 0) {
212                 result = true;
213         }
214
215         TALLOC_FREE(tmp_ctx);
216
217         return result;
218 }
219
220 /***********************************************************************
221  Retrieves a netr_SamInfo3 structure from a tdb.  Caller must
222  free the user_info struct (talloced memory)
223 ***********************************************************************/
224
225 struct netr_SamInfo3 *netsamlogon_cache_get(TALLOC_CTX *mem_ctx, const struct dom_sid *user_sid)
226 {
227         struct netr_SamInfo3 *info3 = NULL;
228         TDB_DATA data;
229         char keystr[DOM_SID_STR_BUFLEN];
230         enum ndr_err_code ndr_err;
231         DATA_BLOB blob;
232         struct netsamlogoncache_entry r;
233
234         if (!netsamlogon_cache_init()) {
235                 DEBUG(0,("netsamlogon_cache_get: cannot open %s for write!\n",
236                         NETSAMLOGON_TDB));
237                 return NULL;
238         }
239
240         /* Prepare key as DOMAIN-SID/USER-RID string */
241         dom_sid_string_buf(user_sid, keystr, sizeof(keystr));
242         DEBUG(10,("netsamlogon_cache_get: SID [%s]\n", keystr));
243         data = tdb_fetch_bystring( netsamlogon_tdb, keystr );
244
245         if (!data.dptr) {
246                 return NULL;
247         }
248
249         info3 = talloc_zero(mem_ctx, struct netr_SamInfo3);
250         if (!info3) {
251                 goto done;
252         }
253
254         blob = data_blob_const(data.dptr, data.dsize);
255
256         ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &r,
257                                       (ndr_pull_flags_fn_t)ndr_pull_netsamlogoncache_entry);
258
259         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
260                 DEBUG(0,("netsamlogon_cache_get: failed to pull entry from cache\n"));
261                 tdb_delete_bystring(netsamlogon_tdb, keystr);
262                 TALLOC_FREE(info3);
263                 goto done;
264         }
265
266         if (DEBUGLEVEL >= 10) {
267                 NDR_PRINT_DEBUG(netsamlogoncache_entry, &r);
268         }
269
270         info3 = (struct netr_SamInfo3 *)talloc_memdup(mem_ctx, &r.info3,
271                                                       sizeof(r.info3));
272
273  done:
274         SAFE_FREE(data.dptr);
275
276         return info3;
277 }
278
279 bool netsamlogon_cache_have(const struct dom_sid *sid)
280 {
281         char keystr[DOM_SID_STR_BUFLEN];
282         bool ok;
283
284         if (!netsamlogon_cache_init()) {
285                 DBG_WARNING("Cannot open %s\n", NETSAMLOGON_TDB);
286                 return false;
287         }
288
289         dom_sid_string_buf(sid, keystr, sizeof(keystr));
290
291         ok = tdb_exists(netsamlogon_tdb, string_term_tdb_data(keystr));
292         return ok;
293 }
294
295 struct netsamlog_cache_forall_state {
296         TALLOC_CTX *mem_ctx;
297         int (*cb)(const char *sid_str,
298                   time_t when_cached,
299                   struct netr_SamInfo3 *,
300                   void *private_data);
301         void *private_data;
302 };
303
304 static int netsamlog_cache_traverse_cb(struct tdb_context *tdb,
305                                        TDB_DATA key,
306                                        TDB_DATA data,
307                                        void *private_data)
308 {
309         struct netsamlog_cache_forall_state *state =
310                 (struct netsamlog_cache_forall_state *)private_data;
311         TALLOC_CTX *mem_ctx = NULL;
312         DATA_BLOB blob;
313         const char *sid_str = NULL;
314         struct dom_sid sid;
315         struct netsamlogoncache_entry r;
316         enum ndr_err_code ndr_err;
317         int ret;
318         bool ok;
319
320         if (key.dsize == 0) {
321                 return 0;
322         }
323         if (key.dptr[key.dsize - 1] != '\0') {
324                 return 0;
325         }
326         if (data.dptr == NULL) {
327                 return 0;
328         }
329         sid_str = (char *)key.dptr;
330
331         ok = string_to_sid(&sid, sid_str);
332         if (!ok) {
333                 DBG_ERR("String to SID failed for %s\n", sid_str);
334                 return -1;
335         }
336
337         if (sid.num_auths != 5) {
338                 return 0;
339         }
340
341         mem_ctx = talloc_new(state->mem_ctx);
342         if (mem_ctx == NULL) {
343                 return -1;
344         }
345
346         blob = data_blob_const(data.dptr, data.dsize);
347
348         ndr_err = ndr_pull_struct_blob(
349                 &blob, state->mem_ctx, &r,
350                 (ndr_pull_flags_fn_t)ndr_pull_netsamlogoncache_entry);
351
352         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
353                 DBG_ERR("failed to pull entry from cache\n");
354                 return -1;
355         }
356
357         ret = state->cb(sid_str, r.timestamp, &r.info3, state->private_data);
358
359         TALLOC_FREE(mem_ctx);
360         return ret;
361 }
362
363 int netsamlog_cache_for_all(int (*cb)(const char *sid_str,
364                                       time_t when_cached,
365                                       struct netr_SamInfo3 *,
366                                       void *private_data),
367                             void *private_data)
368 {
369         int ret;
370         TALLOC_CTX *mem_ctx = NULL;
371         struct netsamlog_cache_forall_state state;
372
373         if (!netsamlogon_cache_init()) {
374                 DBG_ERR("Cannot open %s\n", NETSAMLOGON_TDB);
375                 return -1;
376         }
377
378         mem_ctx = talloc_init("netsamlog_cache_for_all");
379         if (mem_ctx == NULL) {
380                 return -1;
381         }
382
383         state = (struct netsamlog_cache_forall_state) {
384                 .mem_ctx = mem_ctx,
385                 .cb = cb,
386                 .private_data = private_data,
387         };
388
389         ret = tdb_traverse_read(netsamlogon_tdb,
390                                 netsamlog_cache_traverse_cb,
391                                 &state);
392
393         TALLOC_FREE(state.mem_ctx);
394         return ret;
395 }