idmap-autorid: Use talloc_tos() in idmap_autorid_id_to_sid
[samba.git] / source3 / winbindd / idmap_autorid.c
1 /*
2  *  idmap_autorid: static map between Active Directory/NT RIDs
3  *  and RFC 2307 accounts
4  *
5  *  based on the idmap_rid module, but this module defines the ranges
6  *  for the domains by automatically allocating a range for each domain
7  *
8  *  Copyright (C) Christian Ambach, 2010-2011
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
25 #include "includes.h"
26 #include "winbindd.h"
27 #include "dbwrap.h"
28 #include "idmap.h"
29 #include "../libcli/security/dom_sid.h"
30
31 #undef DBGC_CLASS
32 #define DBGC_CLASS DBGC_IDMAP
33
34 #define HWM "NEXT RANGE"
35 #define CONFIGKEY "CONFIG"
36
37 struct autorid_global_config {
38         uint32_t minvalue;
39         uint32_t rangesize;
40         uint32_t maxranges;
41 };
42
43 struct autorid_domain_config {
44         struct dom_sid sid;
45         uint32_t domainnum;
46         struct autorid_global_config *globalcfg;
47 };
48
49 /* handle to the tdb storing domain <-> range assignments */
50 static struct db_context *autorid_db;
51
52 static NTSTATUS idmap_autorid_get_domainrange(struct db_context *db,
53                                               void *private_data)
54 {
55         NTSTATUS ret;
56         uint32_t domainnum, hwm;
57         char *sidstr, *numstr;
58         struct autorid_domain_config *cfg;
59
60         cfg = (struct autorid_domain_config *)private_data;
61         sidstr = dom_sid_string(talloc_tos(), &(cfg->sid));
62
63         if (!sidstr) {
64                 return NT_STATUS_NO_MEMORY;
65         }
66
67         if (!dbwrap_fetch_uint32(db, sidstr, &domainnum)) {
68                 DEBUG(10, ("Acquiring new range for domain %s\n", sidstr));
69
70                 /* fetch the current HWM */
71                 if (!dbwrap_fetch_uint32(db, HWM, &hwm)) {
72                         DEBUG(1, ("Fatal error while fetching current "
73                                   "HWM value!\n"));
74                         ret = NT_STATUS_INTERNAL_ERROR;
75                         goto error;
76                 }
77
78                 /* do we have a range left? */
79                 if (hwm >= cfg->globalcfg->maxranges) {
80                         DEBUG(1, ("No more domain ranges available!\n"));
81                         ret = NT_STATUS_NO_MEMORY;
82                         goto error;
83                 }
84
85                 /* increase the HWM */
86                 ret = dbwrap_change_uint32_atomic(db, HWM, &domainnum, 1);
87                 if (!NT_STATUS_IS_OK(ret)) {
88                         DEBUG(1, ("Fatal error while fetching a new "
89                                   "domain range value!\n"));
90                         goto error;
91                 }
92
93                 /* store away the new mapping in both directions */
94                 ret = dbwrap_trans_store_uint32(db, sidstr, domainnum);
95                 if (!NT_STATUS_IS_OK(ret)) {
96                         DEBUG(1, ("Fatal error while storing new "
97                                   "domain->range assignment!\n"));
98                         goto error;
99                 }
100
101                 numstr = talloc_asprintf(db, "%u", domainnum);
102                 if (!numstr) {
103                         ret = NT_STATUS_NO_MEMORY;
104                         goto error;
105                 }
106
107                 ret = dbwrap_trans_store_bystring(db, numstr,
108                                                   string_term_tdb_data(sidstr),
109                                                   TDB_INSERT);
110                 if (!NT_STATUS_IS_OK(ret)) {
111                         talloc_free(numstr);
112                         DEBUG(1, ("Fatal error while storing "
113                                   "new domain->range assignment!\n"));
114                         goto error;
115                 }
116                 talloc_free(numstr);
117                 DEBUG(5, ("Acquired new range #%d for domain %s\n",
118                           domainnum, sidstr));
119         }
120
121         DEBUG(10, ("Using range #%d for domain %s\n", domainnum, sidstr));
122         cfg->domainnum = domainnum;
123
124         talloc_free(sidstr);
125         return NT_STATUS_OK;
126
127       error:
128         talloc_free(sidstr);
129         return ret;
130
131 }
132
133 static NTSTATUS idmap_autorid_id_to_sid(struct autorid_global_config *cfg,
134                                         struct id_map *map)
135 {
136         uint32_t range;
137         TDB_DATA data;
138         char *keystr;
139         struct dom_sid sid;
140
141         /* can this be one of our ids? */
142         if (map->xid.id < cfg->minvalue) {
143                 DEBUG(10, ("id %d is lower than minimum value, "
144                            "ignoring mapping request\n", map->xid.id));
145                 map->status = ID_UNKNOWN;
146                 return NT_STATUS_OK;
147         }
148
149         if (map->xid.id > (cfg->minvalue + cfg->rangesize * cfg->maxranges)) {
150                 DEBUG(10, ("id %d is outside of maximum id value, "
151                            "ignoring mapping request\n", map->xid.id));
152                 map->status = ID_UNKNOWN;
153                 return NT_STATUS_OK;
154         }
155
156         /* determine the range of this uid */
157         range = ((map->xid.id - cfg->minvalue) / cfg->rangesize);
158
159         keystr = talloc_asprintf(talloc_tos(), "%u", range);
160         if (!keystr) {
161                 return NT_STATUS_NO_MEMORY;
162         }
163
164         data = dbwrap_fetch_bystring(autorid_db, talloc_tos(), keystr);
165         TALLOC_FREE(keystr);
166
167         if (!data.dptr) {
168                 DEBUG(4, ("id %d belongs to range %d which does not have "
169                           "domain mapping, ignoring mapping request\n",
170                           map->xid.id, range));
171                 return NT_STATUS_OK;
172         }
173
174         string_to_sid(&sid, (const char *)data.dptr);
175         TALLOC_FREE(data.dptr);
176
177         sid_compose(map->sid, &sid,
178                     (map->xid.id - cfg->minvalue -
179                      range * cfg->rangesize));
180
181         /* We **really** should have some way of validating
182            the SID exists and is the correct type here.  But
183            that is a deficiency in the idmap_rid design. */
184
185         map->status = ID_MAPPED;
186         return NT_STATUS_OK;
187 }
188
189 /**********************************
190  Single sid to id lookup function.
191 **********************************/
192
193 static NTSTATUS idmap_autorid_sid_to_id(struct autorid_global_config *global,
194                                         struct autorid_domain_config *domain,
195                                         struct id_map *map)
196 {
197         uint32_t rid;
198
199         sid_peek_rid(map->sid, &rid);
200
201         /* if the rid is higher than the size of the range, we cannot map it */
202         if (rid >= global->rangesize) {
203                 map->status = ID_UNKNOWN;
204                 DEBUG(2, ("RID %d is larger then size of range (%d), "
205                           "user cannot be mapped\n", rid, global->rangesize));
206                 return NT_STATUS_UNSUCCESSFUL;
207         }
208         map->xid.id = global->minvalue +
209             (global->rangesize * domain->domainnum)+rid;
210
211         /* We **really** should have some way of validating
212            the SID exists and is the correct type here.  But
213            that is a deficiency in the idmap_rid design. */
214
215         map->status = ID_MAPPED;
216
217         return NT_STATUS_OK;
218 }
219
220 /**********************************
221  lookup a set of unix ids.
222 **********************************/
223
224 static NTSTATUS idmap_autorid_unixids_to_sids(struct idmap_domain *dom,
225                                               struct id_map **ids)
226 {
227         struct autorid_global_config *globalcfg;
228         TALLOC_CTX *ctx;
229         NTSTATUS ret;
230         int i;
231
232         /* initialize the status to avoid surprise */
233         for (i = 0; ids[i]; i++) {
234                 ids[i]->status = ID_UNKNOWN;
235         }
236
237         globalcfg = talloc_get_type(dom->private_data,
238                                     struct autorid_global_config);
239
240         ctx = talloc_new(dom);
241         if (!ctx) {
242                 DEBUG(0, ("Out of memory!\n"));
243                 return NT_STATUS_NO_MEMORY;
244         }
245
246         for (i = 0; ids[i]; i++) {
247
248                 ret = idmap_autorid_id_to_sid(globalcfg, ids[i]);
249
250                 if ((!NT_STATUS_IS_OK(ret)) &&
251                     (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
252                         /* some fatal error occurred, log it */
253                         DEBUG(3, ("Unexpected error resolving an ID "
254                                   " (%d)\n", ids[i]->xid.id));
255                         goto failure;
256                 }
257         }
258
259         talloc_free(ctx);
260         return NT_STATUS_OK;
261
262       failure:
263         talloc_free(ctx);
264         return ret;
265
266 }
267
268 /**********************************
269  lookup a set of sids.
270 **********************************/
271
272 static NTSTATUS idmap_autorid_sids_to_unixids(struct idmap_domain *dom,
273                                               struct id_map **ids)
274 {
275         struct autorid_global_config *global;
276         NTSTATUS ret;
277         int i;
278
279         /* initialize the status to avoid surprise */
280         for (i = 0; ids[i]; i++) {
281                 ids[i]->status = ID_UNKNOWN;
282         }
283
284         global = talloc_get_type(dom->private_data,
285                                  struct autorid_global_config);
286
287         for (i = 0; ids[i]; i++) {
288                 struct winbindd_tdc_domain *domain;
289                 struct autorid_domain_config domaincfg;
290                 uint32_t rid;
291
292                 ZERO_STRUCT(domaincfg);
293
294                 sid_copy(&domaincfg.sid, ids[i]->sid);
295                 if (!sid_split_rid(&domaincfg.sid, &rid)) {
296                         DEBUG(4, ("Could not determine domain SID from %s, "
297                                   "ignoring mapping request\n",
298                                   sid_string_dbg(ids[i]->sid)));
299                         continue;
300                 }
301
302                 /*
303                  * Check if the domain is around
304                  */
305                 domain = wcache_tdc_fetch_domainbysid(talloc_tos(),
306                                                       &domaincfg.sid);
307                 if (domain == NULL) {
308                         DEBUG(10, ("Ignoring unknown domain sid %s\n",
309                                    sid_string_dbg(&domaincfg.sid)));
310                         continue;
311                 }
312                 TALLOC_FREE(domain);
313
314                 domaincfg.globalcfg = global;
315
316                 ret = dbwrap_trans_do(autorid_db,
317                                       idmap_autorid_get_domainrange,
318                                       &domaincfg);
319
320                 if (!NT_STATUS_IS_OK(ret)) {
321                         DEBUG(3, ("Could not determine range for domain, "
322                                   "check previous messages for reason\n"));
323                         goto failure;
324                 }
325
326                 ret = idmap_autorid_sid_to_id(global, &domaincfg, ids[i]);
327
328                 if ((!NT_STATUS_IS_OK(ret)) &&
329                     (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
330                         /* some fatal error occurred, log it */
331                         DEBUG(3, ("Unexpected error resolving a SID (%s)\n",
332                                   sid_string_dbg(ids[i]->sid)));
333                         goto failure;
334                 }
335         }
336         return NT_STATUS_OK;
337
338       failure:
339         return ret;
340
341 }
342
343 /*
344  * open and initialize the database which stores the ranges for the domains
345  */
346 static NTSTATUS idmap_autorid_db_init(void)
347 {
348         int32_t hwm;
349
350         if (autorid_db) {
351                 /* its already open */
352                 return NT_STATUS_OK;
353         }
354
355         /* Open idmap repository */
356         autorid_db = db_open(NULL, state_path("autorid.tdb"), 0,
357                              TDB_DEFAULT, O_RDWR | O_CREAT, 0644);
358
359         if (!autorid_db) {
360                 DEBUG(0, ("Unable to open idmap_autorid database '%s'\n",
361                           state_path("autorid.tdb")));
362                 return NT_STATUS_UNSUCCESSFUL;
363         }
364
365         /* Initialize high water mark for the currently used range to 0 */
366         hwm = dbwrap_fetch_int32(autorid_db, HWM);
367         if ((hwm < 0)) {
368                 if (!NT_STATUS_IS_OK
369                     (dbwrap_trans_store_int32(autorid_db, HWM, 0))) {
370                         DEBUG(0,
371                               ("Unable to initialise HWM in autorid "
372                                "database\n"));
373                         return NT_STATUS_INTERNAL_DB_ERROR;
374                 }
375         }
376
377         return NT_STATUS_OK;
378 }
379
380 static struct autorid_global_config *idmap_autorid_loadconfig(TALLOC_CTX * ctx)
381 {
382
383         TDB_DATA data;
384         struct autorid_global_config *cfg;
385         unsigned long minvalue, rangesize, maxranges;
386
387         data = dbwrap_fetch_bystring(autorid_db, ctx, CONFIGKEY);
388
389         if (!data.dptr) {
390                 DEBUG(10, ("No saved config found\n"));
391                 return NULL;
392         }
393
394         cfg = TALLOC_ZERO_P(ctx, struct autorid_global_config);
395         if (!cfg) {
396                 return NULL;
397         }
398
399         if (sscanf((char *)data.dptr,
400                    "minvalue:%lu rangesize:%lu maxranges:%lu",
401                    &minvalue, &rangesize, &maxranges) != 3) {
402                 DEBUG(1,
403                       ("Found invalid configuration data"
404                        "creating new config\n"));
405                 return NULL;
406         }
407
408         cfg->minvalue = minvalue;
409         cfg->rangesize = rangesize;
410         cfg->maxranges = maxranges;
411
412         DEBUG(10, ("Loaded previously stored configuration "
413                    "minvalue:%d rangesize:%d\n",
414                    cfg->minvalue, cfg->rangesize));
415
416         return cfg;
417
418 }
419
420 static NTSTATUS idmap_autorid_saveconfig(struct autorid_global_config *cfg)
421 {
422
423         NTSTATUS status;
424         TDB_DATA data;
425         char *cfgstr;
426
427         cfgstr =
428             talloc_asprintf(talloc_tos(),
429                             "minvalue:%u rangesize:%u maxranges:%u",
430                             cfg->minvalue, cfg->rangesize, cfg->maxranges);
431
432         if (!cfgstr) {
433                 return NT_STATUS_NO_MEMORY;
434         }
435
436         data = string_tdb_data(cfgstr);
437
438         status = dbwrap_trans_store_bystring(autorid_db, CONFIGKEY,
439                                              data, TDB_REPLACE);
440
441         talloc_free(cfgstr);
442
443         return status;
444 }
445
446 static NTSTATUS idmap_autorid_initialize(struct idmap_domain *dom,
447                                          const char *params)
448 {
449         struct autorid_global_config *config;
450         struct autorid_global_config *storedconfig = NULL;
451         NTSTATUS status;
452         uint32_t hwm;
453
454         config = TALLOC_ZERO_P(dom, struct autorid_global_config);
455         if (!config) {
456                 DEBUG(0, ("Out of memory!\n"));
457                 return NT_STATUS_NO_MEMORY;
458         }
459
460         status = idmap_autorid_db_init();
461         if (!NT_STATUS_IS_OK(status)) {
462                 goto error;
463         }
464
465         config->minvalue = dom->low_id;
466         config->rangesize = lp_parm_int(-1, "autorid", "rangesize", 100000);
467
468         if (config->rangesize < 2000) {
469                 DEBUG(1, ("autorid rangesize must be at least 2000\n"));
470                 status = NT_STATUS_INVALID_PARAMETER;
471                 goto error;
472         }
473
474         config->maxranges = (dom->high_id - dom->low_id + 1) /
475             config->rangesize;
476
477         if (config->maxranges == 0) {
478                 DEBUG(1, ("allowed uid range is smaller then rangesize, "
479                           "increase uid range or decrease rangesize\n"));
480                 status = NT_STATUS_INVALID_PARAMETER;
481                 goto error;
482         }
483
484         /* check if the high-low limit is a multiple of the rangesize */
485         if ((dom->high_id - dom->low_id + 1) % config->rangesize != 0) {
486                 DEBUG(5, ("High uid-low uid difference of %d "
487                           "is not a multiple of the rangesize %d, "
488                           "limiting ranges to lower boundary number of %d\n",
489                           (dom->high_id - dom->low_id + 1), config->rangesize,
490                           config->maxranges));
491         }
492
493         DEBUG(10, ("Current configuration in config is "
494                    "minvalue:%d rangesize:%d maxranges:%d\n",
495                    config->minvalue, config->rangesize, config->maxranges));
496
497         /* read previously stored config and current HWM */
498         storedconfig = idmap_autorid_loadconfig(talloc_tos());
499
500         if (!dbwrap_fetch_uint32(autorid_db, HWM, &hwm)) {
501                 DEBUG(1, ("Fatal error while fetching current "
502                           "HWM value!\n"));
503                 status = NT_STATUS_INTERNAL_ERROR;
504                 goto error;
505         }
506
507         /* did the minimum value or rangesize change? */
508         if (storedconfig &&
509             ((storedconfig->minvalue != config->minvalue) ||
510              (storedconfig->rangesize != config->rangesize))) {
511                 DEBUG(1, ("New configuration values for rangesize or "
512                           "minimum uid value conflict with previously "
513                           "used values! Aborting initialization\n"));
514                 status = NT_STATUS_INVALID_PARAMETER;
515                 goto error;
516         }
517
518         /*
519          * has the highest uid value been reduced to setting that is not
520          * sufficient any more for already existing ranges?
521          */
522         if (hwm > config->maxranges) {
523                 DEBUG(1, ("New upper uid limit is too low to cover "
524                           "existing mappings! Aborting initialization\n"));
525                 status = NT_STATUS_INVALID_PARAMETER;
526                 goto error;
527         }
528
529         status = idmap_autorid_saveconfig(config);
530
531         if (!NT_STATUS_IS_OK(status)) {
532                 DEBUG(1, ("Failed to store configuration data!\n"));
533                 goto error;
534         }
535
536         DEBUG(5, ("%d domain ranges with a size of %d are available\n",
537                   config->maxranges, config->rangesize));
538
539         dom->private_data = config;
540
541         if (!NT_STATUS_IS_OK(status)) {
542                 goto error;
543         }
544
545         return NT_STATUS_OK;
546
547       error:
548         talloc_free(config);
549         talloc_free(storedconfig);
550
551         return status;
552 }
553
554 /*
555   Close the idmap tdb instance
556 */
557 static struct idmap_methods autorid_methods = {
558         .init = idmap_autorid_initialize,
559         .unixids_to_sids = idmap_autorid_unixids_to_sids,
560         .sids_to_unixids = idmap_autorid_sids_to_unixids,
561 };
562
563 NTSTATUS idmap_autorid_init(void)
564 {
565         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION,
566                                   "autorid", &autorid_methods);
567 }