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