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