503f8748b778db4e995498d8d89c69b089a051bb
[rusty/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 "system/filesys.h"
27 #include "winbindd.h"
28 #include "dbwrap/dbwrap.h"
29 #include "dbwrap/dbwrap_open.h"
30 #include "idmap.h"
31 #include "../libcli/security/dom_sid.h"
32 #include "util_tdb.h"
33
34 #undef DBGC_CLASS
35 #define DBGC_CLASS DBGC_IDMAP
36
37 #define HWM "NEXT RANGE"
38 #define CONFIGKEY "CONFIG"
39
40 struct autorid_global_config {
41         uint32_t minvalue;
42         uint32_t rangesize;
43         uint32_t maxranges;
44 };
45
46 struct autorid_domain_config {
47         fstring sid;
48         uint32_t domainnum;
49         struct autorid_global_config *globalcfg;
50 };
51
52 /* handle to the tdb storing domain <-> range assignments */
53 static struct db_context *autorid_db;
54
55 static NTSTATUS idmap_autorid_get_domainrange(struct db_context *db,
56                                               void *private_data)
57 {
58         NTSTATUS ret;
59         uint32_t domainnum, hwm;
60         char *numstr;
61         struct autorid_domain_config *cfg;
62
63         cfg = (struct autorid_domain_config *)private_data;
64
65         ret = dbwrap_fetch_uint32(db, cfg->sid, &domainnum);
66         if (!NT_STATUS_IS_OK(ret)) {
67                 DEBUG(10, ("Acquiring new range for domain %s\n", cfg->sid));
68
69                 /* fetch the current HWM */
70                 ret = dbwrap_fetch_uint32(db, HWM, &hwm);
71                 if (!NT_STATUS_IS_OK(ret)) {
72                         DEBUG(1, ("Fatal error while fetching current "
73                                   "HWM value: %s\n", nt_errstr(ret)));
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, cfg->sid, 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(cfg->sid), TDB_INSERT);
109
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, cfg->sid));
118         }
119
120         DEBUG(10, ("Using range #%d for domain %s\n", domainnum, cfg->sid));
121         cfg->domainnum = domainnum;
122
123         return NT_STATUS_OK;
124
125       error:
126         return ret;
127
128 }
129
130 static NTSTATUS idmap_autorid_id_to_sid(struct autorid_global_config *cfg,
131                                         struct id_map *map)
132 {
133         uint32_t range;
134         TDB_DATA data;
135         char *keystr;
136         struct dom_sid sid;
137         NTSTATUS status;
138
139         /* can this be one of our ids? */
140         if (map->xid.id < cfg->minvalue) {
141                 DEBUG(10, ("id %d is lower than minimum value, "
142                            "ignoring mapping request\n", map->xid.id));
143                 map->status = ID_UNKNOWN;
144                 return NT_STATUS_OK;
145         }
146
147         if (map->xid.id > (cfg->minvalue + cfg->rangesize * cfg->maxranges)) {
148                 DEBUG(10, ("id %d is outside of maximum id value, "
149                            "ignoring mapping request\n", map->xid.id));
150                 map->status = ID_UNKNOWN;
151                 return NT_STATUS_OK;
152         }
153
154         /* determine the range of this uid */
155         range = ((map->xid.id - cfg->minvalue) / cfg->rangesize);
156
157         keystr = talloc_asprintf(talloc_tos(), "%u", range);
158         if (!keystr) {
159                 return NT_STATUS_NO_MEMORY;
160         }
161
162         status = dbwrap_fetch_bystring(autorid_db, talloc_tos(), keystr, &data);
163         TALLOC_FREE(keystr);
164
165         if (!NT_STATUS_IS_OK(status)) {
166                 DEBUG(4, ("id %d belongs to range %d which does not have "
167                           "domain mapping, ignoring mapping request\n",
168                           map->xid.id, range));
169                 map->status = ID_UNKNOWN;
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                 struct dom_sid domainsid;
280
281                 ZERO_STRUCT(domaincfg);
282
283                 sid_copy(&domainsid, ids[i]->sid);
284                 if (!sid_split_rid(&domainsid, &rid)) {
285                         DEBUG(4, ("Could not determine domain SID from %s, "
286                                   "ignoring mapping request\n",
287                                   sid_string_dbg(ids[i]->sid)));
288                         continue;
289                 }
290
291                 /*
292                  * Check if the domain is around
293                  */
294                 domain = wcache_tdc_fetch_domainbysid(talloc_tos(),
295                                                       &domainsid);
296                 if (domain == NULL) {
297                         DEBUG(10, ("Ignoring unknown domain sid %s\n",
298                                    sid_string_dbg(&domainsid)));
299                         continue;
300                 }
301                 TALLOC_FREE(domain);
302
303                 domaincfg.globalcfg = global;
304                 sid_to_fstring(domaincfg.sid, &domainsid);
305
306                 ret = dbwrap_trans_do(autorid_db,
307                                       idmap_autorid_get_domainrange,
308                                       &domaincfg);
309
310                 if (!NT_STATUS_IS_OK(ret)) {
311                         DEBUG(3, ("Could not determine range for domain, "
312                                   "check previous messages for reason\n"));
313                         goto failure;
314                 }
315
316                 ret = idmap_autorid_sid_to_id(global, &domaincfg, ids[i]);
317
318                 if ((!NT_STATUS_IS_OK(ret)) &&
319                     (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
320                         /* some fatal error occurred, log it */
321                         DEBUG(3, ("Unexpected error resolving a SID (%s)\n",
322                                   sid_string_dbg(ids[i]->sid)));
323                         goto failure;
324                 }
325         }
326         return NT_STATUS_OK;
327
328       failure:
329         return ret;
330
331 }
332
333 /* initialize the given HWM to 0 if it does not exist yet */
334 static NTSTATUS idmap_autorid_init_hwm(const char *hwm) {
335
336         NTSTATUS status;
337         uint32_t hwmval;
338
339         status = dbwrap_fetch_uint32(autorid_db, hwm, &hwmval);
340         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND))  {
341                 status = dbwrap_trans_store_int32(autorid_db, hwm, 0);
342                 if (!NT_STATUS_IS_OK(status)) {
343                         DEBUG(0,
344                               ("Unable to initialise HWM (%s) in autorid "
345                                "database: %s\n", hwm, nt_errstr(status)));
346                         return NT_STATUS_INTERNAL_DB_ERROR;
347                 }
348         } else if (!NT_STATUS_IS_OK(status)) {
349                 DEBUG(0, ("unable to fetch HWM (%s) from autorid "
350                           "database: %s\n", hwm,  nt_errstr(status)));
351                 return status;
352         }
353
354         return NT_STATUS_OK;
355 }
356
357 /*
358  * open and initialize the database which stores the ranges for the domains
359  */
360 static NTSTATUS idmap_autorid_db_init(void)
361 {
362         NTSTATUS status;
363
364         if (autorid_db) {
365                 /* its already open */
366                 return NT_STATUS_OK;
367         }
368
369         /* Open idmap repository */
370         autorid_db = db_open(NULL, state_path("autorid.tdb"), 0,
371                              TDB_DEFAULT, O_RDWR | O_CREAT, 0644);
372
373         if (!autorid_db) {
374                 DEBUG(0, ("Unable to open idmap_autorid database '%s'\n",
375                           state_path("autorid.tdb")));
376                 return NT_STATUS_UNSUCCESSFUL;
377         }
378
379         /* Initialize high water mark for the currently used range to 0 */
380
381         status = idmap_autorid_init_hwm(HWM);
382         NT_STATUS_NOT_OK_RETURN(status);
383
384         return NT_STATUS_OK;
385 }
386
387 static struct autorid_global_config *idmap_autorid_loadconfig(TALLOC_CTX * ctx)
388 {
389
390         TDB_DATA data;
391         struct autorid_global_config *cfg;
392         unsigned long minvalue, rangesize, maxranges;
393         NTSTATUS status;
394
395         status = dbwrap_fetch_bystring(autorid_db, ctx, CONFIGKEY, &data);
396
397         if (!NT_STATUS_IS_OK(status)) {
398                 DEBUG(10, ("No saved config found\n"));
399                 return NULL;
400         }
401
402         cfg = talloc_zero(ctx, struct autorid_global_config);
403         if (!cfg) {
404                 return NULL;
405         }
406
407         if (sscanf((char *)data.dptr,
408                    "minvalue:%lu rangesize:%lu maxranges:%lu",
409                    &minvalue, &rangesize, &maxranges) != 3) {
410                 DEBUG(1,
411                       ("Found invalid configuration data"
412                        "creating new config\n"));
413                 return NULL;
414         }
415
416         cfg->minvalue = minvalue;
417         cfg->rangesize = rangesize;
418         cfg->maxranges = maxranges;
419
420         DEBUG(10, ("Loaded previously stored configuration "
421                    "minvalue:%d rangesize:%d\n",
422                    cfg->minvalue, cfg->rangesize));
423
424         return cfg;
425
426 }
427
428 static NTSTATUS idmap_autorid_saveconfig(struct autorid_global_config *cfg)
429 {
430
431         NTSTATUS status;
432         TDB_DATA data;
433         char *cfgstr;
434
435         cfgstr =
436             talloc_asprintf(talloc_tos(),
437                             "minvalue:%u rangesize:%u maxranges:%u",
438                             cfg->minvalue, cfg->rangesize, cfg->maxranges);
439
440         if (!cfgstr) {
441                 return NT_STATUS_NO_MEMORY;
442         }
443
444         data = string_tdb_data(cfgstr);
445
446         status = dbwrap_trans_store_bystring(autorid_db, CONFIGKEY,
447                                              data, TDB_REPLACE);
448
449         talloc_free(cfgstr);
450
451         return status;
452 }
453
454 static NTSTATUS idmap_autorid_initialize(struct idmap_domain *dom)
455 {
456         struct autorid_global_config *config;
457         struct autorid_global_config *storedconfig = NULL;
458         NTSTATUS status;
459         uint32_t hwm;
460
461         if (!strequal(dom->name, "*")) {
462                 DEBUG(0, ("idmap_autorid_initialize: Error: autorid configured "
463                           "for domain '%s'. But autorid can only be used for "
464                           "the default idmap configuration.\n", dom->name));
465                 return NT_STATUS_INVALID_PARAMETER;
466         }
467
468         config = talloc_zero(dom, struct autorid_global_config);
469         if (!config) {
470                 DEBUG(0, ("Out of memory!\n"));
471                 return NT_STATUS_NO_MEMORY;
472         }
473
474         status = idmap_autorid_db_init();
475         if (!NT_STATUS_IS_OK(status)) {
476                 goto error;
477         }
478
479         config->minvalue = dom->low_id;
480         config->rangesize = lp_parm_int(-1, "idmap config *", "rangesize", 100000);
481
482         if (config->rangesize < 2000) {
483                 DEBUG(1, ("autorid rangesize must be at least 2000\n"));
484                 status = NT_STATUS_INVALID_PARAMETER;
485                 goto error;
486         }
487
488         config->maxranges = (dom->high_id - dom->low_id + 1) /
489             config->rangesize;
490
491         if (config->maxranges == 0) {
492                 DEBUG(1, ("allowed uid range is smaller then rangesize, "
493                           "increase uid range or decrease rangesize\n"));
494                 status = NT_STATUS_INVALID_PARAMETER;
495                 goto error;
496         }
497
498         /* check if the high-low limit is a multiple of the rangesize */
499         if ((dom->high_id - dom->low_id + 1) % config->rangesize != 0) {
500                 DEBUG(5, ("High uid-low uid difference of %d "
501                           "is not a multiple of the rangesize %d, "
502                           "limiting ranges to lower boundary number of %d\n",
503                           (dom->high_id - dom->low_id + 1), config->rangesize,
504                           config->maxranges));
505         }
506
507         DEBUG(10, ("Current configuration in config is "
508                    "minvalue:%d rangesize:%d maxranges:%d\n",
509                    config->minvalue, config->rangesize, config->maxranges));
510
511         /* read previously stored config and current HWM */
512         storedconfig = idmap_autorid_loadconfig(talloc_tos());
513
514         status = dbwrap_fetch_uint32(autorid_db, HWM, &hwm);
515         if (!NT_STATUS_IS_OK(status)) {
516                 DEBUG(1, ("Fatal error while fetching current "
517                           "HWM value: %s\n", nt_errstr(status)));
518                 status = NT_STATUS_INTERNAL_ERROR;
519                 goto error;
520         }
521
522         /* did the minimum value or rangesize change? */
523         if (storedconfig &&
524             ((storedconfig->minvalue != config->minvalue) ||
525              (storedconfig->rangesize != config->rangesize))) {
526                 DEBUG(1, ("New configuration values for rangesize or "
527                           "minimum uid value conflict with previously "
528                           "used values! Aborting initialization\n"));
529                 status = NT_STATUS_INVALID_PARAMETER;
530                 goto error;
531         }
532
533         /*
534          * has the highest uid value been reduced to setting that is not
535          * sufficient any more for already existing ranges?
536          */
537         if (hwm > config->maxranges) {
538                 DEBUG(1, ("New upper uid limit is too low to cover "
539                           "existing mappings! Aborting initialization\n"));
540                 status = NT_STATUS_INVALID_PARAMETER;
541                 goto error;
542         }
543
544         status = idmap_autorid_saveconfig(config);
545
546         if (!NT_STATUS_IS_OK(status)) {
547                 DEBUG(1, ("Failed to store configuration data!\n"));
548                 goto error;
549         }
550
551         DEBUG(5, ("%d domain ranges with a size of %d are available\n",
552                   config->maxranges, config->rangesize));
553
554         dom->private_data = config;
555
556         goto done;
557
558 error:
559         talloc_free(config);
560
561 done:
562         talloc_free(storedconfig);
563
564         return status;
565 }
566
567 /*
568   Close the idmap tdb instance
569 */
570 static struct idmap_methods autorid_methods = {
571         .init = idmap_autorid_initialize,
572         .unixids_to_sids = idmap_autorid_unixids_to_sids,
573         .sids_to_unixids = idmap_autorid_sids_to_unixids,
574 };
575
576 NTSTATUS samba_init_module(void)
577 {
578         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION,
579                                   "autorid", &autorid_methods);
580 }