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