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