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