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