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