Remove fstring from map_username. Create a more sane interface than the called-parame...
[kai/samba.git] / source3 / smbd / password.c
1 /*
2    Unix SMB/CIFS implementation.
3    Password and authentication handling
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Jeremy Allison 2007.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "smbd/globals.h"
23 #include "../librpc/gen_ndr/netlogon.h"
24
25 /* Fix up prototypes for OSX 10.4, where they're missing */
26 #ifndef HAVE_SETNETGRENT_PROTOTYPE
27 extern int setnetgrent(const char* netgroup);
28 #endif
29 #ifndef HAVE_GETNETGRENT_PROTOTYPE
30 extern int getnetgrent(char **host, char **user, char **domain);
31 #endif
32 #ifndef HAVE_ENDNETGRENT_PROTOTYPE
33 extern void endnetgrent(void);
34 #endif
35
36 enum server_allocated_state { SERVER_ALLOCATED_REQUIRED_YES,
37                                 SERVER_ALLOCATED_REQUIRED_NO,
38                                 SERVER_ALLOCATED_REQUIRED_ANY};
39
40 static user_struct *get_valid_user_struct_internal(
41                         struct smbd_server_connection *sconn,
42                         uint16 vuid,
43                         enum server_allocated_state server_allocated)
44 {
45         user_struct *usp;
46         int count=0;
47
48         if (vuid == UID_FIELD_INVALID)
49                 return NULL;
50
51         usp=sconn->smb1.sessions.validated_users;
52         for (;usp;usp=usp->next,count++) {
53                 if (vuid == usp->vuid) {
54                         switch (server_allocated) {
55                                 case SERVER_ALLOCATED_REQUIRED_YES:
56                                         if (usp->server_info == NULL) {
57                                                 continue;
58                                         }
59                                         break;
60                                 case SERVER_ALLOCATED_REQUIRED_NO:
61                                         if (usp->server_info != NULL) {
62                                                 continue;
63                                         }
64                                 case SERVER_ALLOCATED_REQUIRED_ANY:
65                                         break;
66                         }
67                         if (count > 10) {
68                                 DLIST_PROMOTE(sconn->smb1.sessions.validated_users,
69                                               usp);
70                         }
71                         return usp;
72                 }
73         }
74
75         return NULL;
76 }
77
78 /****************************************************************************
79  Check if a uid has been validated, and return an pointer to the user_struct
80  if it has. NULL if not. vuid is biased by an offset. This allows us to
81  tell random client vuid's (normally zero) from valid vuids.
82 ****************************************************************************/
83
84 user_struct *get_valid_user_struct(struct smbd_server_connection *sconn,
85                                    uint16 vuid)
86 {
87         return get_valid_user_struct_internal(sconn, vuid,
88                         SERVER_ALLOCATED_REQUIRED_YES);
89 }
90
91 bool is_partial_auth_vuid(struct smbd_server_connection *sconn, uint16 vuid)
92 {
93         return (get_partial_auth_user_struct(sconn, vuid) != NULL);
94 }
95
96 /****************************************************************************
97  Get the user struct of a partial NTLMSSP login
98 ****************************************************************************/
99
100 user_struct *get_partial_auth_user_struct(struct smbd_server_connection *sconn,
101                                           uint16 vuid)
102 {
103         return get_valid_user_struct_internal(sconn, vuid,
104                         SERVER_ALLOCATED_REQUIRED_NO);
105 }
106
107 /****************************************************************************
108  Invalidate a uid.
109 ****************************************************************************/
110
111 void invalidate_vuid(struct smbd_server_connection *sconn, uint16 vuid)
112 {
113         user_struct *vuser = NULL;
114
115         vuser = get_valid_user_struct_internal(sconn, vuid,
116                         SERVER_ALLOCATED_REQUIRED_ANY);
117         if (vuser == NULL) {
118                 return;
119         }
120
121         session_yield(vuser);
122
123         if (vuser->auth_ntlmssp_state) {
124                 TALLOC_FREE(vuser->auth_ntlmssp_state);
125         }
126
127         DLIST_REMOVE(sconn->smb1.sessions.validated_users, vuser);
128
129         /* clear the vuid from the 'cache' on each connection, and
130            from the vuid 'owner' of connections */
131         conn_clear_vuid_caches(sconn, vuid);
132
133         TALLOC_FREE(vuser);
134         sconn->smb1.sessions.num_validated_vuids--;
135 }
136
137 /****************************************************************************
138  Invalidate all vuid entries for this process.
139 ****************************************************************************/
140
141 void invalidate_all_vuids(struct smbd_server_connection *sconn)
142 {
143         if (sconn->using_smb2) {
144                 return;
145         }
146
147         while (sconn->smb1.sessions.validated_users != NULL) {
148                 invalidate_vuid(sconn,
149                                 sconn->smb1.sessions.validated_users->vuid);
150         }
151 }
152
153 static void increment_next_vuid(uint16_t *vuid)
154 {
155         *vuid += 1;
156
157         /* Check for vuid wrap. */
158         if (*vuid == UID_FIELD_INVALID) {
159                 *vuid = VUID_OFFSET;
160         }
161 }
162
163 /****************************************************
164  Create a new partial auth user struct.
165 *****************************************************/
166
167 int register_initial_vuid(struct smbd_server_connection *sconn)
168 {
169         user_struct *vuser;
170
171         /* Paranoia check. */
172         if(lp_security() == SEC_SHARE) {
173                 smb_panic("register_initial_vuid: "
174                         "Tried to register uid in security=share");
175         }
176
177         /* Limit allowed vuids to 16bits - VUID_OFFSET. */
178         if (sconn->smb1.sessions.num_validated_vuids >= 0xFFFF-VUID_OFFSET) {
179                 return UID_FIELD_INVALID;
180         }
181
182         if((vuser = talloc_zero(NULL, user_struct)) == NULL) {
183                 DEBUG(0,("register_initial_vuid: "
184                                 "Failed to talloc users struct!\n"));
185                 return UID_FIELD_INVALID;
186         }
187
188         /* Allocate a free vuid. Yes this is a linear search... */
189         while( get_valid_user_struct_internal(sconn,
190                         sconn->smb1.sessions.next_vuid,
191                         SERVER_ALLOCATED_REQUIRED_ANY) != NULL ) {
192                 increment_next_vuid(&sconn->smb1.sessions.next_vuid);
193         }
194
195         DEBUG(10,("register_initial_vuid: allocated vuid = %u\n",
196                 (unsigned int)sconn->smb1.sessions.next_vuid ));
197
198         vuser->vuid = sconn->smb1.sessions.next_vuid;
199
200         /*
201          * This happens in an unfinished NTLMSSP session setup. We
202          * need to allocate a vuid between the first and second calls
203          * to NTLMSSP.
204          */
205         increment_next_vuid(&sconn->smb1.sessions.next_vuid);
206         sconn->smb1.sessions.num_validated_vuids++;
207
208         DLIST_ADD(sconn->smb1.sessions.validated_users, vuser);
209         return vuser->vuid;
210 }
211
212 int register_homes_share(const char *username)
213 {
214         int result;
215         struct passwd *pwd;
216
217         result = lp_servicenumber(username);
218         if (result != -1) {
219                 DEBUG(3, ("Using static (or previously created) service for "
220                           "user '%s'; path = '%s'\n", username,
221                           lp_pathname(result)));
222                 return result;
223         }
224
225         pwd = Get_Pwnam_alloc(talloc_tos(), username);
226
227         if ((pwd == NULL) || (pwd->pw_dir[0] == '\0')) {
228                 DEBUG(3, ("No home directory defined for user '%s'\n",
229                           username));
230                 TALLOC_FREE(pwd);
231                 return -1;
232         }
233
234         DEBUG(3, ("Adding homes service for user '%s' using home directory: "
235                   "'%s'\n", username, pwd->pw_dir));
236
237         result = add_home_service(username, username, pwd->pw_dir);
238
239         TALLOC_FREE(pwd);
240         return result;
241 }
242
243 /**
244  *  register that a valid login has been performed, establish 'session'.
245  *  @param server_info The token returned from the authentication process.
246  *   (now 'owned' by register_existing_vuid)
247  *
248  *  @param session_key The User session key for the login session (now also
249  *  'owned' by register_existing_vuid)
250  *
251  *  @param respose_blob The NT challenge-response, if available.  (May be
252  *  freed after this call)
253  *
254  *  @param smb_name The untranslated name of the user
255  *
256  *  @return Newly allocated vuid, biased by an offset. (This allows us to
257  *   tell random client vuid's (normally zero) from valid vuids.)
258  *
259  */
260
261 int register_existing_vuid(struct smbd_server_connection *sconn,
262                         uint16 vuid,
263                         struct auth_serversupplied_info *server_info,
264                         DATA_BLOB response_blob,
265                         const char *smb_name)
266 {
267         fstring tmp;
268         user_struct *vuser;
269
270         vuser = get_partial_auth_user_struct(sconn, vuid);
271         if (!vuser) {
272                 goto fail;
273         }
274
275         /* Use this to keep tabs on all our info from the authentication */
276         vuser->server_info = talloc_move(vuser, &server_info);
277
278         /* This is a potentially untrusted username */
279         alpha_strcpy(tmp, smb_name, ". _-$", sizeof(tmp));
280
281         vuser->server_info->sanitized_username = talloc_strdup(
282                 vuser->server_info, tmp);
283
284         DEBUG(10,("register_existing_vuid: (%u,%u) %s %s %s guest=%d\n",
285                   (unsigned int)vuser->server_info->utok.uid,
286                   (unsigned int)vuser->server_info->utok.gid,
287                   vuser->server_info->unix_name,
288                   vuser->server_info->sanitized_username,
289                   vuser->server_info->info3->base.domain.string,
290                   vuser->server_info->guest ));
291
292         DEBUG(3, ("register_existing_vuid: User name: %s\t"
293                   "Real name: %s\n", vuser->server_info->unix_name,
294                   vuser->server_info->info3->base.full_name.string));
295
296         if (!vuser->server_info->ptok) {
297                 DEBUG(1, ("register_existing_vuid: server_info does not "
298                         "contain a user_token - cannot continue\n"));
299                 goto fail;
300         }
301
302         DEBUG(3,("register_existing_vuid: UNIX uid %d is UNIX user %s, "
303                 "and will be vuid %u\n", (int)vuser->server_info->utok.uid,
304                  vuser->server_info->unix_name, vuser->vuid));
305
306         if (!session_claim(sconn, vuser)) {
307                 DEBUG(1, ("register_existing_vuid: Failed to claim session "
308                         "for vuid=%d\n",
309                         vuser->vuid));
310                 goto fail;
311         }
312
313         /* Register a home dir service for this user if
314         (a) This is not a guest connection,
315         (b) we have a home directory defined
316         (c) there s not an existing static share by that name
317         If a share exists by this name (autoloaded or not) reuse it . */
318
319         vuser->homes_snum = -1;
320
321         if (!vuser->server_info->guest) {
322                 vuser->homes_snum = register_homes_share(
323                         vuser->server_info->unix_name);
324         }
325
326         if (srv_is_signing_negotiated(sconn) &&
327             !vuser->server_info->guest) {
328                 /* Try and turn on server signing on the first non-guest
329                  * sessionsetup. */
330                 srv_set_signing(sconn,
331                                 vuser->server_info->user_session_key,
332                                 response_blob);
333         }
334
335         /* fill in the current_user_info struct */
336         set_current_user_info(
337                 vuser->server_info->sanitized_username,
338                 vuser->server_info->unix_name,
339                 vuser->server_info->info3->base.domain.string);
340
341         return vuser->vuid;
342
343   fail:
344
345         if (vuser) {
346                 invalidate_vuid(sconn, vuid);
347         }
348         return UID_FIELD_INVALID;
349 }
350
351 /****************************************************************************
352  Add a name to the session users list.
353 ****************************************************************************/
354
355 void add_session_user(struct smbd_server_connection *sconn,
356                       const char *user)
357 {
358         struct passwd *pw;
359         char *tmp;
360
361         pw = Get_Pwnam_alloc(talloc_tos(), user);
362
363         if (pw == NULL) {
364                 return;
365         }
366
367         if (sconn->smb1.sessions.session_userlist == NULL) {
368                 sconn->smb1.sessions.session_userlist = SMB_STRDUP(pw->pw_name);
369                 goto done;
370         }
371
372         if (in_list(pw->pw_name,sconn->smb1.sessions.session_userlist,false)) {
373                 goto done;
374         }
375
376         if (strlen(sconn->smb1.sessions.session_userlist) > 128 * 1024) {
377                 DEBUG(3,("add_session_user: session userlist already "
378                          "too large.\n"));
379                 goto done;
380         }
381
382         if (asprintf(&tmp, "%s %s",
383                      sconn->smb1.sessions.session_userlist, pw->pw_name) == -1) {
384                 DEBUG(3, ("asprintf failed\n"));
385                 goto done;
386         }
387
388         SAFE_FREE(sconn->smb1.sessions.session_userlist);
389         sconn->smb1.sessions.session_userlist = tmp;
390  done:
391         TALLOC_FREE(pw);
392 }
393
394 /****************************************************************************
395  In security=share mode we need to store the client workgroup, as that's
396   what Vista uses for the NTLMv2 calculation.
397 ****************************************************************************/
398
399 void add_session_workgroup(struct smbd_server_connection *sconn,
400                            const char *workgroup)
401 {
402         if (sconn->smb1.sessions.session_workgroup) {
403                 SAFE_FREE(sconn->smb1.sessions.session_workgroup);
404         }
405         sconn->smb1.sessions.session_workgroup = smb_xstrdup(workgroup);
406 }
407
408 /****************************************************************************
409  In security=share mode we need to return the client workgroup, as that's
410   what Vista uses for the NTLMv2 calculation.
411 ****************************************************************************/
412
413 const char *get_session_workgroup(struct smbd_server_connection *sconn)
414 {
415         return sconn->smb1.sessions.session_workgroup;
416 }
417
418 /****************************************************************************
419  Check if a username is valid.
420 ****************************************************************************/
421
422 static bool user_ok(const char *user, int snum)
423 {
424         bool ret;
425
426         ret = True;
427
428         if (lp_invalid_users(snum)) {
429                 char **invalid = str_list_copy(talloc_tos(),
430                         lp_invalid_users(snum));
431                 if (invalid &&
432                     str_list_substitute(invalid, "%S", lp_servicename(snum))) {
433
434                         /* This is used in sec=share only, so no current user
435                          * around to pass to str_list_sub_basic() */
436
437                         if ( invalid && str_list_sub_basic(invalid, "", "") ) {
438                                 ret = !user_in_list(talloc_tos(), user,
439                                                     (const char **)invalid);
440                         }
441                 }
442                 TALLOC_FREE(invalid);
443         }
444
445         if (ret && lp_valid_users(snum)) {
446                 char **valid = str_list_copy(talloc_tos(),
447                         lp_valid_users(snum));
448                 if ( valid &&
449                      str_list_substitute(valid, "%S", lp_servicename(snum)) ) {
450
451                         /* This is used in sec=share only, so no current user
452                          * around to pass to str_list_sub_basic() */
453
454                         if ( valid && str_list_sub_basic(valid, "", "") ) {
455                                 ret = user_in_list(talloc_tos(), user,
456                                                    (const char **)valid);
457                         }
458                 }
459                 TALLOC_FREE(valid);
460         }
461
462         if (ret && lp_onlyuser(snum)) {
463                 char **user_list = str_list_make_v3(
464                         talloc_tos(), lp_username(snum), NULL);
465                 if (user_list &&
466                     str_list_substitute(user_list, "%S",
467                                         lp_servicename(snum))) {
468                         ret = user_in_list(talloc_tos(), user,
469                                            (const char **)user_list);
470                 }
471                 TALLOC_FREE(user_list);
472         }
473
474         return(ret);
475 }
476
477 /****************************************************************************
478  Validate a group username entry. Return the username or NULL.
479 ****************************************************************************/
480
481 static char *validate_group(struct smbd_server_connection *sconn,
482                             char *group, DATA_BLOB password,int snum)
483 {
484 #ifdef HAVE_NETGROUP
485         {
486                 char *host, *user, *domain;
487                 struct auth_context *actx = sconn->smb1.negprot.auth_context;
488                 bool enc = sconn->smb1.negprot.encrypted_passwords;
489                 setnetgrent(group);
490                 while (getnetgrent(&host, &user, &domain)) {
491                         if (user) {
492                                 if (user_ok(user, snum) &&
493                                     password_ok(actx, enc,
494                                                 get_session_workgroup(sconn),
495                                                 user,password)) {
496                                         endnetgrent();
497                                         return(user);
498                                 }
499                         }
500                 }
501                 endnetgrent();
502         }
503 #endif
504
505 #ifdef HAVE_GETGRENT
506         {
507                 struct group *gptr;
508                 struct auth_context *actx = sconn->smb1.negprot.auth_context;
509                 bool enc = sconn->smb1.negprot.encrypted_passwords;
510
511                 setgrent();
512                 while ((gptr = (struct group *)getgrent())) {
513                         if (strequal(gptr->gr_name,group))
514                                 break;
515                 }
516
517                 /*
518                  * As user_ok can recurse doing a getgrent(), we must
519                  * copy the member list onto the heap before
520                  * use. Bug pointed out by leon@eatworms.swmed.edu.
521                  */
522
523                 if (gptr) {
524                         char *member_list = NULL;
525                         size_t list_len = 0;
526                         char *member;
527                         int i;
528
529                         for(i = 0; gptr->gr_mem && gptr->gr_mem[i]; i++) {
530                                 list_len += strlen(gptr->gr_mem[i])+1;
531                         }
532                         list_len++;
533
534                         member_list = (char *)SMB_MALLOC(list_len);
535                         if (!member_list) {
536                                 endgrent();
537                                 return NULL;
538                         }
539
540                         *member_list = '\0';
541                         member = member_list;
542
543                         for(i = 0; gptr->gr_mem && gptr->gr_mem[i]; i++) {
544                                 size_t member_len = strlen(gptr->gr_mem[i])+1;
545
546                                 DEBUG(10,("validate_group: = gr_mem = "
547                                           "%s\n", gptr->gr_mem[i]));
548
549                                 safe_strcpy(member, gptr->gr_mem[i],
550                                         list_len - (member-member_list));
551                                 member += member_len;
552                         }
553
554                         endgrent();
555
556                         member = member_list;
557                         while (*member) {
558                                 if (user_ok(member,snum) &&
559                                     password_ok(actx, enc,
560                                                 get_session_workgroup(sconn),
561                                                 member,password)) {
562                                         char *name = talloc_strdup(talloc_tos(),
563                                                                 member);
564                                         SAFE_FREE(member_list);
565                                         return name;
566                                 }
567
568                                 DEBUG(10,("validate_group = member = %s\n",
569                                           member));
570
571                                 member += strlen(member) + 1;
572                         }
573
574                         SAFE_FREE(member_list);
575                 } else {
576                         endgrent();
577                         return NULL;
578                 }
579         }
580 #endif
581         return(NULL);
582 }
583
584 /****************************************************************************
585  Check for authority to login to a service with a given username/password.
586  Note this is *NOT* used when logging on using sessionsetup_and_X.
587 ****************************************************************************/
588
589 bool authorise_login(struct smbd_server_connection *sconn,
590                      int snum, fstring user, DATA_BLOB password,
591                      bool *guest)
592 {
593         bool ok = False;
594         struct auth_context *actx = sconn->smb1.negprot.auth_context;
595         bool enc = sconn->smb1.negprot.encrypted_passwords;
596
597 #ifdef DEBUG_PASSWORD
598         DEBUG(100,("authorise_login: checking authorisation on "
599                    "user=%s pass=%s\n", user,password.data));
600 #endif
601
602         *guest = False;
603
604         /* there are several possibilities:
605                 1) login as the given user with given password
606                 2) login as a previously registered username with the given
607                    password
608                 3) login as a session list username with the given password
609                 4) login as a previously validated user/password pair
610                 5) login as the "user =" user with given password
611                 6) login as the "user =" user with no password
612                    (guest connection)
613                 7) login as guest user with no password
614
615                 if the service is guest_only then steps 1 to 5 are skipped
616         */
617
618         /* now check the list of session users */
619         if (!ok) {
620                 char *auser;
621                 char *user_list = NULL;
622                 char *saveptr;
623
624                 if (sconn->smb1.sessions.session_userlist)
625                         user_list = SMB_STRDUP(sconn->smb1.sessions.session_userlist);
626                 else
627                         user_list = SMB_STRDUP("");
628
629                 if (!user_list)
630                         return(False);
631
632                 for (auser = strtok_r(user_list, LIST_SEP, &saveptr);
633                      !ok && auser;
634                      auser = strtok_r(NULL, LIST_SEP, &saveptr)) {
635                         fstring user2;
636                         fstrcpy(user2,auser);
637                         if (!user_ok(user2,snum))
638                                 continue;
639
640                         if (password_ok(actx, enc,
641                                         get_session_workgroup(sconn),
642                                         user2,password)) {
643                                 ok = True;
644                                 fstrcpy(user,user2);
645                                 DEBUG(3,("authorise_login: ACCEPTED: session "
646                                          "list username (%s) and given "
647                                          "password ok\n", user));
648                         }
649                 }
650
651                 SAFE_FREE(user_list);
652         }
653
654         /* check the user= fields and the given password */
655         if (!ok && lp_username(snum)) {
656                 TALLOC_CTX *ctx = talloc_tos();
657                 char *auser;
658                 char *user_list = talloc_strdup(ctx, lp_username(snum));
659                 char *saveptr;
660
661                 if (!user_list) {
662                         goto check_guest;
663                 }
664
665                 user_list = talloc_string_sub(ctx,
666                                 user_list,
667                                 "%S",
668                                 lp_servicename(snum));
669
670                 if (!user_list) {
671                         goto check_guest;
672                 }
673
674                 for (auser = strtok_r(user_list, LIST_SEP, &saveptr);
675                      auser && !ok;
676                      auser = strtok_r(NULL, LIST_SEP, &saveptr)) {
677                         if (*auser == '@') {
678                                 auser = validate_group(sconn,auser+1,
679                                                        password,snum);
680                                 if (auser) {
681                                         ok = True;
682                                         fstrcpy(user,auser);
683                                         DEBUG(3,("authorise_login: ACCEPTED: "
684                                                  "group username and given "
685                                                  "password ok (%s)\n", user));
686                                 }
687                         } else {
688                                 fstring user2;
689                                 fstrcpy(user2,auser);
690                                 if (user_ok(user2,snum) &&
691                                     password_ok(actx, enc,
692                                                 get_session_workgroup(sconn),
693                                                 user2,password)) {
694                                         ok = True;
695                                         fstrcpy(user,user2);
696                                         DEBUG(3,("authorise_login: ACCEPTED: "
697                                                  "user list username and "
698                                                  "given password ok (%s)\n",
699                                                  user));
700                                 }
701                         }
702                 }
703         }
704
705   check_guest:
706
707         /* check for a normal guest connection */
708         if (!ok && GUEST_OK(snum)) {
709                 struct passwd *guest_pw;
710                 fstring guestname;
711                 fstrcpy(guestname,lp_guestaccount());
712                 guest_pw = Get_Pwnam_alloc(talloc_tos(), guestname);
713                 if (guest_pw != NULL) {
714                         fstrcpy(user,guestname);
715                         ok = True;
716                         DEBUG(3,("authorise_login: ACCEPTED: guest account "
717                                  "and guest ok (%s)\n", user));
718                 } else {
719                         DEBUG(0,("authorise_login: Invalid guest account "
720                                  "%s??\n",guestname));
721                 }
722                 TALLOC_FREE(guest_pw);
723                 *guest = True;
724         }
725
726         if (ok && !user_ok(user, snum)) {
727                 DEBUG(0,("authorise_login: rejected invalid user %s\n",user));
728                 ok = False;
729         }
730
731         return(ok);
732 }