r13539: Add 128 bit creds processing client and server. Thanks to Andrew Bartlett's
[nivanova/samba-autobuild/.git] / source3 / rpc_server / srv_netlog_nt.c
1 /* 
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell              1992-1997,
5  *  Copyright (C) Luke Kenneth Casson Leighton 1996-1997,
6  *  Copyright (C) Paul Ashton                       1997.
7  *  Copyright (C) Jeremy Allison               1998-2001.
8  *  Copyright (C) Andrew Bartlett                   2001.
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 2 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, write to the Free Software
22  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24
25 /* This is the implementation of the netlogon pipe. */
26
27 #include "includes.h"
28
29 extern userdom_struct current_user_info;
30
31 #undef DBGC_CLASS
32 #define DBGC_CLASS DBGC_RPC_SRV
33
34 /*************************************************************************
35  init_net_r_req_chal:
36  *************************************************************************/
37
38 static void init_net_r_req_chal(NET_R_REQ_CHAL *r_c,
39                                 DOM_CHAL *srv_chal, NTSTATUS status)
40 {
41         DEBUG(6,("init_net_r_req_chal: %d\n", __LINE__));
42         memcpy(r_c->srv_chal.data, srv_chal->data, sizeof(srv_chal->data));
43         r_c->status = status;
44 }
45
46 /*************************************************************************
47  error messages cropping up when using nltest.exe...
48  *************************************************************************/
49
50 #define ERROR_NO_SUCH_DOMAIN   0x54b
51 #define ERROR_NO_LOGON_SERVERS 0x51f
52 #define NO_ERROR               0x0
53
54 /*************************************************************************
55  net_reply_logon_ctrl:
56  *************************************************************************/
57
58 NTSTATUS _net_logon_ctrl(pipes_struct *p, NET_Q_LOGON_CTRL *q_u, 
59                        NET_R_LOGON_CTRL *r_u)
60 {
61         uint32 flags = 0x0;
62         uint32 pdc_connection_status = 0x00; /* Maybe a win32 error code? */
63         
64         /* Setup the Logon Control response */
65
66         init_net_r_logon_ctrl(r_u, q_u->query_level, flags, 
67                               pdc_connection_status);
68
69         return r_u->status;
70 }
71
72 /****************************************************************************
73 Send a message to smbd to do a sam synchronisation
74 **************************************************************************/
75
76 static void send_sync_message(void)
77 {
78         TDB_CONTEXT *tdb;
79
80         tdb = tdb_open_log(lock_path("connections.tdb"), 0,
81                            TDB_DEFAULT, O_RDONLY, 0);
82
83         if (!tdb) {
84                 DEBUG(3, ("send_sync_message(): failed to open connections "
85                           "database\n"));
86                 return;
87         }
88
89         DEBUG(3, ("sending sam synchronisation message\n"));
90         
91         message_send_all(tdb, MSG_SMB_SAM_SYNC, NULL, 0, False, NULL);
92
93         tdb_close(tdb);
94 }
95
96 /*************************************************************************
97  net_reply_logon_ctrl2:
98  *************************************************************************/
99
100 NTSTATUS _net_logon_ctrl2(pipes_struct *p, NET_Q_LOGON_CTRL2 *q_u, NET_R_LOGON_CTRL2 *r_u)
101 {
102         uint32 flags = 0x0;
103         uint32 pdc_connection_status = 0x0;
104         uint32 logon_attempts = 0x0;
105         uint32 tc_status;
106         fstring servername, domain, dc_name, dc_name2;
107         struct in_addr dc_ip;
108
109         /* this should be \\global_myname() */
110         unistr2_to_ascii(servername, &q_u->uni_server_name, sizeof(servername));
111
112         r_u->status = NT_STATUS_OK;
113         
114         tc_status = ERROR_NO_SUCH_DOMAIN;
115         fstrcpy( dc_name, "" );
116         
117         switch ( q_u->function_code ) {
118                 case NETLOGON_CONTROL_TC_QUERY:
119                         unistr2_to_ascii(domain, &q_u->info.info6.domain, sizeof(domain));
120                                 
121                         if ( !is_trusted_domain( domain ) )
122                                 break;
123                                 
124                         if ( !get_dc_name( domain, NULL, dc_name2, &dc_ip ) ) {
125                                 tc_status = ERROR_NO_LOGON_SERVERS;
126                                 break;
127                         }
128
129                         fstr_sprintf( dc_name, "\\\\%s", dc_name2 );
130                                 
131                         tc_status = NO_ERROR;
132                         
133                         break;
134                         
135                 case NETLOGON_CONTROL_REDISCOVER:
136                         unistr2_to_ascii(domain, &q_u->info.info6.domain, sizeof(domain));
137                                 
138                         if ( !is_trusted_domain( domain ) )
139                                 break;
140                                 
141                         if ( !get_dc_name( domain, NULL, dc_name2, &dc_ip ) ) {
142                                 tc_status = ERROR_NO_LOGON_SERVERS;
143                                 break;
144                         }
145
146                         fstr_sprintf( dc_name, "\\\\%s", dc_name2 );
147                                 
148                         tc_status = NO_ERROR;
149                         
150                         break;
151                         
152                 default:
153                         /* no idea what this should be */
154                         DEBUG(0,("_net_logon_ctrl2: unimplemented function level [%d]\n",
155                                 q_u->function_code));
156         }
157         
158         /* prepare the response */
159         
160         init_net_r_logon_ctrl2( r_u, q_u->query_level, flags, 
161                 pdc_connection_status, logon_attempts, tc_status, dc_name );
162
163         if (lp_server_role() == ROLE_DOMAIN_BDC)
164                 send_sync_message();
165
166         return r_u->status;
167 }
168
169 /*************************************************************************
170  net_reply_trust_dom_list:
171  *************************************************************************/
172
173 NTSTATUS _net_trust_dom_list(pipes_struct *p, NET_Q_TRUST_DOM_LIST *q_u, NET_R_TRUST_DOM_LIST *r_u)
174 {
175         const char *trusted_domain = "test_domain";
176         uint32 num_trust_domains = 1;
177
178         DEBUG(6,("_net_trust_dom_list: %d\n", __LINE__));
179
180         /* set up the Trusted Domain List response */
181         init_r_trust_dom(r_u, num_trust_domains, trusted_domain);
182
183         DEBUG(6,("_net_trust_dom_list: %d\n", __LINE__));
184
185         return r_u->status;
186 }
187
188 /***********************************************************************************
189  init_net_r_srv_pwset:
190  ***********************************************************************************/
191
192 static void init_net_r_srv_pwset(NET_R_SRV_PWSET *r_s,
193                                  DOM_CRED *srv_cred, NTSTATUS status)  
194 {
195         DEBUG(5,("init_net_r_srv_pwset: %d\n", __LINE__));
196
197         memcpy(&r_s->srv_cred, srv_cred, sizeof(r_s->srv_cred));
198         r_s->status = status;
199
200         DEBUG(5,("init_net_r_srv_pwset: %d\n", __LINE__));
201 }
202
203 /******************************************************************
204  gets a machine password entry.  checks access rights of the host.
205  ******************************************************************/
206
207 static BOOL get_md4pw(char *md4pw, char *mach_acct)
208 {
209         SAM_ACCOUNT *sampass = NULL;
210         const uint8 *pass;
211         BOOL ret;
212         uint32 acct_ctrl;
213
214 #if 0
215     /*
216      * Currently this code is redundent as we already have a filter
217      * by hostname list. What this code really needs to do is to 
218      * get a hosts allowed/hosts denied list from the SAM database
219      * on a per user basis, and make the access decision there.
220      * I will leave this code here for now as a reminder to implement
221      * this at a later date. JRA.
222      */
223
224         if (!allow_access(lp_domain_hostsdeny(), lp_domain_hostsallow(),
225                           client_name(), client_addr()))
226         {
227                 DEBUG(0,("get_md4pw: Workstation %s denied access to domain\n", mach_acct));
228                 return False;
229         }
230 #endif /* 0 */
231
232         if(!NT_STATUS_IS_OK(pdb_init_sam(&sampass)))
233                 return False;
234
235         /* JRA. This is ok as it is only used for generating the challenge. */
236         become_root();
237         ret=pdb_getsampwnam(sampass, mach_acct);
238         unbecome_root();
239  
240         if (ret==False) {
241                 DEBUG(0,("get_md4pw: Workstation %s: no account in domain\n", mach_acct));
242                 pdb_free_sam(&sampass);
243                 return False;
244         }
245
246         acct_ctrl = pdb_get_acct_ctrl(sampass);
247         if (!(acct_ctrl & ACB_DISABLED) &&
248             ((acct_ctrl & ACB_DOMTRUST) ||
249              (acct_ctrl & ACB_WSTRUST) ||
250              (acct_ctrl & ACB_SVRTRUST)) &&
251             ((pass=pdb_get_nt_passwd(sampass)) != NULL)) {
252                 memcpy(md4pw, pass, 16);
253                 dump_data(5, md4pw, 16);
254                 pdb_free_sam(&sampass);
255                 return True;
256         }
257         
258         DEBUG(0,("get_md4pw: Workstation %s: no account in domain\n", mach_acct));
259         pdb_free_sam(&sampass);
260         return False;
261
262 }
263
264 /*************************************************************************
265  _net_req_chal
266  *************************************************************************/
267
268 NTSTATUS _net_req_chal(pipes_struct *p, NET_Q_REQ_CHAL *q_u, NET_R_REQ_CHAL *r_u)
269 {
270         if (!p->dc) {
271                 p->dc = TALLOC_ZERO_P(p->pipe_state_mem_ctx, struct dcinfo);
272                 if (!p->dc) {
273                         return NT_STATUS_NO_MEMORY;
274                 }
275         } else {
276                 DEBUG(10,("_net_req_chal: new challenge requested. Clearing old state.\n"));
277                 ZERO_STRUCTP(p->dc);
278         }
279
280         rpcstr_pull(p->dc->remote_machine,
281                         q_u->uni_logon_clnt.buffer,
282                         sizeof(fstring),q_u->uni_logon_clnt.uni_str_len*2,0);
283
284         /* Remember the workstation name. This is what we'll use to look
285            up the secrets.tdb record later. */
286         fstrcpy(p->wks, p->dc->remote_machine);
287
288         /* Save the client challenge to the server. */
289         memcpy(p->dc->clnt_chal.data, q_u->clnt_chal.data, sizeof(q_u->clnt_chal.data));
290
291         /* Create a server challenge for the client */
292         /* Set this to a random value. */
293         generate_random_buffer(p->dc->srv_chal.data, 8);
294         
295         /* set up the LSA REQUEST CHALLENGE response */
296         init_net_r_req_chal(r_u, &p->dc->srv_chal, NT_STATUS_OK);
297         
298         p->dc->challenge_sent = True;
299
300         return NT_STATUS_OK;
301 }
302
303 /*************************************************************************
304  init_net_r_auth:
305  *************************************************************************/
306
307 static void init_net_r_auth(NET_R_AUTH *r_a, DOM_CHAL *resp_cred, NTSTATUS status)
308 {
309         memcpy(r_a->srv_chal.data, resp_cred->data, sizeof(resp_cred->data));
310         r_a->status = status;
311 }
312
313 /*************************************************************************
314  _net_auth. Create the initial credentials.
315  *************************************************************************/
316
317 NTSTATUS _net_auth(pipes_struct *p, NET_Q_AUTH *q_u, NET_R_AUTH *r_u)
318 {
319         fstring mach_acct;
320         fstring remote_machine;
321         DOM_CHAL srv_chal_out;
322
323         if (!p->dc || !p->dc->challenge_sent) {
324                 return NT_STATUS_ACCESS_DENIED;
325         }
326
327         rpcstr_pull(mach_acct, q_u->clnt_id.uni_acct_name.buffer,sizeof(fstring),
328                                 q_u->clnt_id.uni_acct_name.uni_str_len*2,0);
329         rpcstr_pull(remote_machine, q_u->clnt_id.uni_comp_name.buffer,sizeof(fstring),
330                                 q_u->clnt_id.uni_comp_name.uni_str_len*2,0);
331
332         if (!get_md4pw((char *)p->dc->mach_pw, mach_acct)) {
333                 DEBUG(0,("_net_auth: creds_server_check failed. Failed to "
334                         "get pasword for machine account %s "
335                         "from client %s\n",
336                         mach_acct, remote_machine ));
337                 return NT_STATUS_ACCESS_DENIED;
338         }
339
340         /* From the client / server challenges and md4 password, generate sess key */
341         creds_server_init(0,                    /* No neg flags. */
342                         p->dc,
343                         &p->dc->clnt_chal,      /* Stored client chal. */
344                         &p->dc->srv_chal,       /* Stored server chal. */
345                         (const char *)p->dc->mach_pw,
346                         &srv_chal_out); 
347
348         /* Check client credentials are valid. */
349         if (!creds_server_check(p->dc, &q_u->clnt_chal)) {
350                 DEBUG(0,("_net_auth: creds_server_check failed. Rejecting auth "
351                         "request from client %s machine account %s\n",
352                         remote_machine, mach_acct ));
353                 return NT_STATUS_ACCESS_DENIED;
354         }
355
356         fstrcpy(p->dc->mach_acct, mach_acct);
357         fstrcpy(p->dc->remote_machine, remote_machine);
358         p->dc->authenticated = True;
359
360         /* set up the LSA AUTH response */
361         /* Return the server credentials. */
362         init_net_r_auth(r_u, &srv_chal_out, NT_STATUS_OK);
363
364         return r_u->status;
365 }
366
367 /*************************************************************************
368  init_net_r_auth_2:
369  *************************************************************************/
370
371 static void init_net_r_auth_2(NET_R_AUTH_2 *r_a,
372                               DOM_CHAL *resp_cred, NEG_FLAGS *flgs, NTSTATUS status)
373 {
374         memcpy(r_a->srv_chal.data, resp_cred->data, sizeof(resp_cred->data));
375         memcpy(&r_a->srv_flgs, flgs, sizeof(r_a->srv_flgs));
376         r_a->status = status;
377 }
378
379 /*************************************************************************
380  _net_auth_2
381  *************************************************************************/
382
383 NTSTATUS _net_auth_2(pipes_struct *p, NET_Q_AUTH_2 *q_u, NET_R_AUTH_2 *r_u)
384 {
385         NEG_FLAGS srv_flgs;
386         fstring mach_acct;
387         fstring remote_machine;
388         DOM_CHAL srv_chal_out;
389
390         rpcstr_pull(mach_acct, q_u->clnt_id.uni_acct_name.buffer,sizeof(fstring),
391                                 q_u->clnt_id.uni_acct_name.uni_str_len*2,0);
392         rpcstr_pull(remote_machine, q_u->clnt_id.uni_comp_name.buffer,sizeof(fstring),
393                                 q_u->clnt_id.uni_comp_name.uni_str_len*2,0);
394
395         if (!p->dc || !p->dc->challenge_sent) {
396                 DEBUG(0,("_net_auth2: no challenge sent to client %s\n",
397                         remote_machine ));
398                 return NT_STATUS_ACCESS_DENIED;
399         }
400
401         if ( (lp_server_schannel() == True) &&
402              ((q_u->clnt_flgs.neg_flags & NETLOGON_NEG_SCHANNEL) == 0) ) {
403
404                 /* schannel must be used, but client did not offer it. */
405                 DEBUG(0,("_net_auth2: schannel required but client failed "
406                         "to offer it. Client was %s\n",
407                         mach_acct ));
408                 return NT_STATUS_ACCESS_DENIED;
409         }
410
411         if (!get_md4pw((char *)p->dc->mach_pw, mach_acct)) {
412                 DEBUG(0,("_net_auth2: failed to get machine password for "
413                         "account %s\n",
414                         mach_acct ));
415                 return NT_STATUS_ACCESS_DENIED;
416         }
417
418         /* From the client / server challenges and md4 password, generate sess key */
419         creds_server_init(q_u->clnt_flgs.neg_flags,
420                         p->dc,
421                         &p->dc->clnt_chal,      /* Stored client chal. */
422                         &p->dc->srv_chal,       /* Stored server chal. */
423                         (const char *)p->dc->mach_pw,
424                         &srv_chal_out); 
425
426         /* Check client credentials are valid. */
427         if (!creds_server_check(p->dc, &q_u->clnt_chal)) {
428                 DEBUG(0,("_net_auth2: creds_server_check failed. Rejecting auth "
429                         "request from client %s machine account %s\n",
430                         remote_machine, mach_acct ));
431                 return NT_STATUS_ACCESS_DENIED;
432         }
433
434         srv_flgs.neg_flags = 0x000001ff;
435
436         if (lp_server_schannel() != False) {
437                 srv_flgs.neg_flags |= NETLOGON_NEG_SCHANNEL;
438         }
439
440         /* set up the LSA AUTH 2 response */
441         init_net_r_auth_2(r_u, &srv_chal_out, &srv_flgs, NT_STATUS_OK);
442
443         fstrcpy(p->dc->mach_acct, mach_acct);
444         fstrcpy(p->dc->remote_machine, remote_machine);
445         fstrcpy(p->dc->domain, lp_workgroup() );
446
447         p->dc->authenticated = True;
448
449         /* Store off the state so we can continue after client disconnect. */
450         become_root();
451         secrets_store_schannel_session_info(p->mem_ctx, p->dc);
452         unbecome_root();
453
454         return r_u->status;
455 }
456
457 /*************************************************************************
458  _net_srv_pwset
459  *************************************************************************/
460
461 NTSTATUS _net_srv_pwset(pipes_struct *p, NET_Q_SRV_PWSET *q_u, NET_R_SRV_PWSET *r_u)
462 {
463         NTSTATUS status = NT_STATUS_ACCESS_DENIED;
464         fstring workstation;
465         SAM_ACCOUNT *sampass=NULL;
466         BOOL ret = False;
467         unsigned char pwd[16];
468         int i;
469         uint32 acct_ctrl;
470         DOM_CRED cred_out;
471         const uchar *old_pw;
472
473         DEBUG(5,("_net_srv_pwset: %d\n", __LINE__));
474
475         /* We need the workstation name for the creds lookup. */
476         rpcstr_pull(workstation,q_u->clnt_id.login.uni_comp_name.buffer,
477                     sizeof(workstation),q_u->clnt_id.login.uni_comp_name.uni_str_len*2,0);
478
479         if (!p->dc) {
480                 /* Restore the saved state of the netlogon creds. */
481                 become_root();
482                 ret = secrets_restore_schannel_session_info(p->pipe_state_mem_ctx,
483                                                         workstation,
484                                                         &p->dc);
485                 unbecome_root();
486                 if (!ret) {
487                         return NT_STATUS_INVALID_HANDLE;
488                 }
489         }
490
491         if (!p->dc || !p->dc->authenticated) {
492                 return NT_STATUS_INVALID_HANDLE;
493         }
494
495         DEBUG(3,("_net_srv_pwset: Server Password Set by Wksta:[%s] on account [%s]\n",
496                         workstation, p->dc->mach_acct));
497         
498         /* Step the creds chain forward. */
499         if (!creds_server_step(p->dc, &q_u->clnt_id.cred, &cred_out)) {
500                 DEBUG(2,("_net_srv_pwset: creds_server_step failed. Rejecting auth "
501                         "request from client %s machine account %s\n",
502                         p->dc->remote_machine, p->dc->mach_acct ));
503                 return NT_STATUS_INVALID_PARAMETER;
504         }
505
506         /* We must store the creds state after an update. */
507         become_root();
508         secrets_store_schannel_session_info(p->pipe_state_mem_ctx, p->dc);
509         pdb_init_sam(&sampass);
510         ret=pdb_getsampwnam(sampass, p->dc->mach_acct);
511         unbecome_root();
512
513         /* Ensure the account exists and is a machine account. */
514         
515         acct_ctrl = pdb_get_acct_ctrl(sampass);
516
517         if (!(ret 
518               && (acct_ctrl & ACB_WSTRUST ||
519                       acct_ctrl & ACB_SVRTRUST ||
520                       acct_ctrl & ACB_DOMTRUST))) {
521                 pdb_free_sam(&sampass);
522                 return NT_STATUS_NO_SUCH_USER;
523         }
524         
525         if (pdb_get_acct_ctrl(sampass) & ACB_DISABLED) {
526                 pdb_free_sam(&sampass);
527                 return NT_STATUS_ACCOUNT_DISABLED;
528         }
529
530         /* Woah - what does this to to the credential chain ? JRA */
531         cred_hash3( pwd, q_u->pwd, p->dc->sess_key, 0);
532
533         DEBUG(100,("Server password set : new given value was :\n"));
534         for(i = 0; i < sizeof(pwd); i++)
535                 DEBUG(100,("%02X ", pwd[i]));
536         DEBUG(100,("\n"));
537
538         old_pw = pdb_get_nt_passwd(sampass);
539
540         if (old_pw && memcmp(pwd, old_pw, 16) == 0) {
541                 /* Avoid backend modificiations and other fun if the 
542                    client changed the password to the *same thing* */
543
544                 ret = True;
545         } else {
546
547                 /* LM password should be NULL for machines */
548                 if (!pdb_set_lanman_passwd(sampass, NULL, PDB_CHANGED)) {
549                         pdb_free_sam(&sampass);
550                         return NT_STATUS_NO_MEMORY;
551                 }
552                 
553                 if (!pdb_set_nt_passwd(sampass, pwd, PDB_CHANGED)) {
554                         pdb_free_sam(&sampass);
555                         return NT_STATUS_NO_MEMORY;
556                 }
557                 
558                 if (!pdb_set_pass_changed_now(sampass)) {
559                         pdb_free_sam(&sampass);
560                         /* Not quite sure what this one qualifies as, but this will do */
561                         return NT_STATUS_UNSUCCESSFUL; 
562                 }
563                 
564                 become_root();
565                 r_u->status = pdb_update_sam_account (sampass);
566                 unbecome_root();
567         }
568
569         /* set up the LSA Server Password Set response */
570         init_net_r_srv_pwset(r_u, &cred_out, status);
571
572         pdb_free_sam(&sampass);
573         return r_u->status;
574 }
575
576 /*************************************************************************
577  _net_sam_logoff:
578  *************************************************************************/
579
580 NTSTATUS _net_sam_logoff(pipes_struct *p, NET_Q_SAM_LOGOFF *q_u, NET_R_SAM_LOGOFF *r_u)
581 {
582         fstring workstation;
583
584         if (!get_valid_user_struct(p->vuid))
585                 return NT_STATUS_NO_SUCH_USER;
586
587         if (!p->dc) {
588                 /* Restore the saved state of the netlogon creds. */
589                 BOOL ret;
590
591                 *workstation = '\0';
592                 rpcstr_pull_unistr2_fstring(workstation, &q_u->sam_id.client.login.uni_comp_name);
593
594                 become_root();
595                 secrets_restore_schannel_session_info(p->pipe_state_mem_ctx,
596                                                         workstation,
597                                                         &p->dc);
598                 unbecome_root();
599                 if (!ret) {
600                         return NT_STATUS_INVALID_HANDLE;
601                 }
602         }
603
604         if (!p->dc || !p->dc->authenticated) {
605                 return NT_STATUS_INVALID_HANDLE;
606         }
607
608         r_u->buffer_creds = 1; /* yes, we have valid server credentials */
609
610         /* checks and updates credentials.  creates reply credentials */
611         if (!creds_server_step(p->dc, &q_u->sam_id.client.cred, &r_u->srv_creds)) {
612                 DEBUG(2,("_net_sam_logoff: creds_server_step failed. Rejecting auth "
613                         "request from client %s machine account %s\n",
614                         p->dc->remote_machine, p->dc->mach_acct ));
615                 return NT_STATUS_INVALID_PARAMETER;
616         }
617
618         /* We must store the creds state after an update. */
619         become_root();
620         secrets_store_schannel_session_info(p->pipe_state_mem_ctx, p->dc);
621         unbecome_root();
622
623         r_u->status = NT_STATUS_OK;
624         return r_u->status;
625 }
626
627
628 /*******************************************************************
629  gets a domain user's groups from their already-calculated NT_USER_TOKEN
630  ********************************************************************/
631 static NTSTATUS nt_token_to_group_list(TALLOC_CTX *mem_ctx,
632                                        const DOM_SID *domain_sid,
633                                        size_t num_sids,
634                                        const DOM_SID *sids,
635                                        int *numgroups, DOM_GID **pgids) 
636 {
637         int i;
638
639         *numgroups=0;
640         *pgids = NULL;
641
642         for (i=0; i<num_sids; i++) {
643                 DOM_GID gid;
644                 if (!sid_peek_check_rid(domain_sid, &sids[i], &gid.g_rid)) {
645                         continue;
646                 }
647                 gid.attr = (SE_GROUP_MANDATORY|SE_GROUP_ENABLED_BY_DEFAULT|
648                             SE_GROUP_ENABLED);
649                 ADD_TO_ARRAY(mem_ctx, DOM_GID, gid, pgids, numgroups);
650                 if (*pgids == NULL) {
651                         return NT_STATUS_NO_MEMORY;
652                 }
653         }
654         return NT_STATUS_OK;
655 }
656
657 /*************************************************************************
658  _net_sam_logon
659  *************************************************************************/
660
661 static NTSTATUS _net_sam_logon_internal(pipes_struct *p,
662                                         NET_Q_SAM_LOGON *q_u,
663                                         NET_R_SAM_LOGON *r_u,
664                                         BOOL process_creds)
665 {
666         NTSTATUS status = NT_STATUS_OK;
667         NET_USER_INFO_3 *usr_info = NULL;
668         NET_ID_INFO_CTR *ctr = q_u->sam_id.ctr;
669         UNISTR2 *uni_samlogon_user = NULL;
670         UNISTR2 *uni_samlogon_domain = NULL;
671         UNISTR2 *uni_samlogon_workstation = NULL;
672         fstring nt_username, nt_domain, nt_workstation;
673         auth_usersupplied_info *user_info = NULL;
674         auth_serversupplied_info *server_info = NULL;
675         SAM_ACCOUNT *sampw;
676         struct auth_context *auth_context = NULL;
677                 
678         usr_info = TALLOC_P(p->mem_ctx, NET_USER_INFO_3);
679         if (!usr_info)
680                 return NT_STATUS_NO_MEMORY;
681
682         ZERO_STRUCTP(usr_info);
683
684         /* store the user information, if there is any. */
685         r_u->user = usr_info;
686         r_u->auth_resp = 1; /* authoritative response */
687         if (q_u->validation_level != 2 && q_u->validation_level != 3) {
688                 DEBUG(0,("_net_sam_logon: bad validation_level value %d.\n", (int)q_u->validation_level ));
689                 return NT_STATUS_ACCESS_DENIED;
690         }
691         /* We handle the return of USER_INFO_2 instead of 3 in the parse return. Sucks, I know... */
692         r_u->switch_value = q_u->validation_level; /* indicates type of validation user info */
693         r_u->buffer_creds = 1; /* Ensure we always return server creds. */
694  
695         if (!get_valid_user_struct(p->vuid))
696                 return NT_STATUS_NO_SUCH_USER;
697
698         /* We need the workstation name for the creds lookup. */
699     
700         switch (q_u->sam_id.logon_level) {
701         case INTERACTIVE_LOGON_TYPE:
702                 uni_samlogon_user = &ctr->auth.id1.uni_user_name;
703                 uni_samlogon_domain = &ctr->auth.id1.uni_domain_name;
704
705                 uni_samlogon_workstation = &ctr->auth.id1.uni_wksta_name;
706             
707                 DEBUG(3,("SAM Logon (Interactive). Domain:[%s].  ", lp_workgroup()));
708                 break;
709         case NET_LOGON_TYPE:
710                 uni_samlogon_user = &ctr->auth.id2.uni_user_name;
711                 uni_samlogon_domain = &ctr->auth.id2.uni_domain_name;
712                 uni_samlogon_workstation = &ctr->auth.id2.uni_wksta_name;
713             
714                 DEBUG(3,("SAM Logon (Network). Domain:[%s].  ", lp_workgroup()));
715                 break;
716         default:
717                 DEBUG(2,("SAM Logon: unsupported switch value\n"));
718                 return NT_STATUS_INVALID_INFO_CLASS;
719         } /* end switch */
720
721         rpcstr_pull(nt_username,uni_samlogon_user->buffer,sizeof(nt_username),uni_samlogon_user->uni_str_len*2,0);
722         rpcstr_pull(nt_domain,uni_samlogon_domain->buffer,sizeof(nt_domain),uni_samlogon_domain->uni_str_len*2,0);
723         rpcstr_pull(nt_workstation,uni_samlogon_workstation->buffer,sizeof(nt_workstation),uni_samlogon_workstation->uni_str_len*2,0);
724
725         DEBUG(3,("User:[%s@%s] Requested Domain:[%s]\n", nt_username, nt_workstation, nt_domain));
726
727         if (process_creds) {
728                 if (!p->dc) {
729                         /* Restore the saved state of the netlogon creds. */
730                         BOOL ret;
731
732                         become_root();
733                         secrets_restore_schannel_session_info(p->pipe_state_mem_ctx,
734                                                                 nt_workstation,
735                                                                 &p->dc);
736                         unbecome_root();
737                         if (!ret) {
738                                 return NT_STATUS_INVALID_HANDLE;
739                         }
740                 }
741
742                 if (!p->dc || !p->dc->authenticated) {
743                         return NT_STATUS_INVALID_HANDLE;
744                 }
745         }
746
747         if ( (lp_server_schannel() == True) && (p->auth.auth_type != PIPE_AUTH_TYPE_SCHANNEL) ) {
748                 /* 'server schannel = yes' should enforce use of
749                    schannel, the client did offer it in auth2, but
750                    obviously did not use it. */
751                 DEBUG(0,("_net_sam_logon: client %s not using schannel for netlogon\n",
752                         p->dc->remote_machine ));
753                 return NT_STATUS_ACCESS_DENIED;
754         }
755
756         if (process_creds) {
757                 /* checks and updates credentials.  creates reply credentials */
758                 if (!creds_server_step(p->dc, &q_u->sam_id.client.cred,  &r_u->srv_creds)) {
759                         DEBUG(2,("_net_sam_logon: creds_server_step failed. Rejecting auth "
760                                 "request from client %s machine account %s\n",
761                                 p->dc->remote_machine, p->dc->mach_acct ));
762                         return NT_STATUS_INVALID_PARAMETER;
763                 }
764
765                 /* We must store the creds state after an update. */
766                 become_root();
767                 secrets_store_schannel_session_info(p->pipe_state_mem_ctx, p->dc);
768                 unbecome_root();
769         }
770
771         fstrcpy(current_user_info.smb_name, nt_username);
772         sub_set_smb_name(nt_username);
773      
774         DEBUG(5,("Attempting validation level %d for unmapped username %s.\n", q_u->sam_id.ctr->switch_value, nt_username));
775
776         status = NT_STATUS_OK;
777         
778         switch (ctr->switch_value) {
779         case NET_LOGON_TYPE:
780         {
781                 const char *wksname = nt_workstation;
782                 
783                 if (!NT_STATUS_IS_OK(status = make_auth_context_fixed(&auth_context, ctr->auth.id2.lm_chal))) {
784                         return status;
785                 }
786
787                 /* For a network logon, the workstation name comes in with two
788                  * backslashes in the front. Strip them if they are there. */
789
790                 if (*wksname == '\\') wksname++;
791                 if (*wksname == '\\') wksname++;
792
793                 /* Standard challenge/response authenticaion */
794                 if (!make_user_info_netlogon_network(&user_info, 
795                                                      nt_username, nt_domain, 
796                                                      wksname,
797                                                      ctr->auth.id2.param_ctrl,
798                                                      ctr->auth.id2.lm_chal_resp.buffer,
799                                                      ctr->auth.id2.lm_chal_resp.str_str_len,
800                                                      ctr->auth.id2.nt_chal_resp.buffer,
801                                                      ctr->auth.id2.nt_chal_resp.str_str_len)) {
802                         status = NT_STATUS_NO_MEMORY;
803                 }       
804                 break;
805         }
806         case INTERACTIVE_LOGON_TYPE:
807                 /* 'Interactive' authentication, supplies the password in its
808                    MD4 form, encrypted with the session key.  We will convert
809                    this to challenge/response for the auth subsystem to chew
810                    on */
811         {
812                 const uint8 *chal;
813                 
814                 if (!NT_STATUS_IS_OK(status = make_auth_context_subsystem(&auth_context))) {
815                         return status;
816                 }
817                 
818                 chal = auth_context->get_ntlm_challenge(auth_context);
819
820                 if (!make_user_info_netlogon_interactive(&user_info, 
821                                                          nt_username, nt_domain, 
822                                                          nt_workstation, 
823                                                          ctr->auth.id1.param_ctrl,
824                                                          chal,
825                                                          ctr->auth.id1.lm_owf.data, 
826                                                          ctr->auth.id1.nt_owf.data, 
827                                                          p->dc->sess_key)) {
828                         status = NT_STATUS_NO_MEMORY;
829                 }
830                 break;
831         }
832         default:
833                 DEBUG(2,("SAM Logon: unsupported switch value\n"));
834                 return NT_STATUS_INVALID_INFO_CLASS;
835         } /* end switch */
836         
837         if ( NT_STATUS_IS_OK(status) ) {
838                 status = auth_context->check_ntlm_password(auth_context, 
839                         user_info, &server_info);
840         }
841
842         (auth_context->free)(&auth_context);    
843         free_user_info(&user_info);
844         
845         DEBUG(5, ("_net_sam_logon: check_password returned status %s\n", 
846                   nt_errstr(status)));
847
848         /* Check account and password */
849     
850         if (!NT_STATUS_IS_OK(status)) {
851                 /* If we don't know what this domain is, we need to 
852                    indicate that we are not authoritative.  This 
853                    allows the client to decide if it needs to try 
854                    a local user.  Fix by jpjanosi@us.ibm.com, #2976 */
855                 if ( NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER) 
856                      && !strequal(nt_domain, get_global_sam_name())
857                      && !is_trusted_domain(nt_domain) )
858                         r_u->auth_resp = 0; /* We are not authoritative */
859
860                 talloc_free(server_info);
861                 return status;
862         }
863
864         if (server_info->guest) {
865                 /* We don't like guest domain logons... */
866                 DEBUG(5,("_net_sam_logon: Attempted domain logon as GUEST "
867                          "denied.\n"));
868                 talloc_free(server_info);
869                 return NT_STATUS_LOGON_FAILURE;
870         }
871
872         /* This is the point at which, if the login was successful, that
873            the SAM Local Security Authority should record that the user is
874            logged in to the domain.  */
875     
876         {
877                 DOM_GID *gids = NULL;
878                 const DOM_SID *user_sid = NULL;
879                 const DOM_SID *group_sid = NULL;
880                 DOM_SID domain_sid;
881                 uint32 user_rid, group_rid; 
882
883                 int num_gids = 0;
884                 pstring my_name;
885                 fstring user_sid_string;
886                 fstring group_sid_string;
887                 unsigned char user_session_key[16];
888                 unsigned char lm_session_key[16];
889                 unsigned char pipe_session_key[16];
890
891                 sampw = server_info->sam_account;
892
893                 /* set up pointer indicating user/password failed to be
894                  * found */
895                 usr_info->ptr_user_info = 0;
896
897                 user_sid = pdb_get_user_sid(sampw);
898                 group_sid = pdb_get_group_sid(sampw);
899
900                 sid_copy(&domain_sid, user_sid);
901                 sid_split_rid(&domain_sid, &user_rid);
902
903                 if (!sid_peek_check_rid(&domain_sid, group_sid, &group_rid)) {
904                         DEBUG(1, ("_net_sam_logon: user %s\\%s has user sid "
905                                   "%s\n but group sid %s.\n"
906                                   "The conflicting domain portions are not "
907                                   "supported for NETLOGON calls\n",         
908                                   pdb_get_domain(sampw),
909                                   pdb_get_username(sampw),
910                                   sid_to_string(user_sid_string, user_sid),
911                                   sid_to_string(group_sid_string, group_sid)));
912                         return NT_STATUS_UNSUCCESSFUL;
913                 }
914                 
915                 
916                 if(server_info->login_server) {
917                         pstrcpy(my_name, server_info->login_server);
918                 } else {
919                         pstrcpy(my_name, global_myname());
920                 }
921
922                 status = nt_token_to_group_list(p->mem_ctx, &domain_sid,
923                                                 server_info->num_sids,
924                                                 server_info->sids,
925                                                 &num_gids, &gids);
926
927                 if (!NT_STATUS_IS_OK(status)) {
928                         return status;
929                 }
930
931                 if (server_info->user_session_key.length) {
932                         memcpy(user_session_key,
933                                server_info->user_session_key.data, 
934                                MIN(sizeof(user_session_key),
935                                    server_info->user_session_key.length));
936                         if (process_creds) {
937                                 /* Get the pipe session key from the creds. */
938                                 memcpy(pipe_session_key, p->dc->sess_key, 16);
939                         } else {
940                                 /* Get the pipe session key from the schannel. */
941                                 if (p->auth.auth_type != PIPE_AUTH_TYPE_SCHANNEL || p->auth.a_u.schannel_auth == NULL) {
942                                         return NT_STATUS_INVALID_HANDLE;
943                                 }
944                                 memcpy(pipe_session_key, p->auth.a_u.schannel_auth->sess_key, 16);
945                         }
946                         SamOEMhash(user_session_key, pipe_session_key, 16);
947                         memset(pipe_session_key, '\0', 16);
948                 }
949                 if (server_info->lm_session_key.length) {
950                         memcpy(lm_session_key,
951                                server_info->lm_session_key.data, 
952                                MIN(sizeof(lm_session_key),
953                                    server_info->lm_session_key.length));
954                         if (process_creds) {
955                                 /* Get the pipe session key from the creds. */
956                                 memcpy(pipe_session_key, p->dc->sess_key, 16);
957                         } else {
958                                 /* Get the pipe session key from the schannel. */
959                                 if (p->auth.auth_type != PIPE_AUTH_TYPE_SCHANNEL || p->auth.a_u.schannel_auth == NULL) {
960                                         return NT_STATUS_INVALID_HANDLE;
961                                 }
962                                 memcpy(pipe_session_key, p->auth.a_u.schannel_auth->sess_key, 16);
963                         }
964                         SamOEMhash(lm_session_key, pipe_session_key, 16);
965                         memset(pipe_session_key, '\0', 16);
966                 }
967                 
968                 init_net_user_info3(p->mem_ctx, usr_info, 
969                                     user_rid,
970                                     group_rid,   
971                                     pdb_get_username(sampw),
972                                     pdb_get_fullname(sampw),
973                                     pdb_get_homedir(sampw),
974                                     pdb_get_dir_drive(sampw),
975                                     pdb_get_logon_script(sampw),
976                                     pdb_get_profile_path(sampw),
977                                     pdb_get_logon_time(sampw),
978                                     get_time_t_max(),
979                                     get_time_t_max(),
980                                     pdb_get_pass_last_set_time(sampw),
981                                     pdb_get_pass_can_change_time(sampw),
982                                     pdb_get_pass_must_change_time(sampw),
983                                     
984                                     0, /* logon_count */
985                                     0, /* bad_pw_count */
986                                     num_gids,    /* uint32 num_groups */
987                                     gids    , /* DOM_GID *gids */
988                                     0x20    , /* uint32 user_flgs (?) */
989                                     server_info->user_session_key.length ? user_session_key : NULL,
990                                     server_info->lm_session_key.length ? lm_session_key : NULL,
991                                     my_name     , /* char *logon_srv */
992                                     pdb_get_domain(sampw),
993                                     &domain_sid);     /* DOM_SID *dom_sid */  
994                 ZERO_STRUCT(user_session_key);
995                 ZERO_STRUCT(lm_session_key);
996         }
997         talloc_free(server_info);
998         return status;
999 }
1000
1001 /*************************************************************************
1002  _net_sam_logon
1003  *************************************************************************/
1004
1005 NTSTATUS _net_sam_logon(pipes_struct *p, NET_Q_SAM_LOGON *q_u, NET_R_SAM_LOGON *r_u)
1006 {
1007         return _net_sam_logon_internal(p, q_u, r_u, True);
1008 }
1009  
1010 /*************************************************************************
1011  _net_sam_logon_ex - no credential chaining. Map into net sam logon.
1012  *************************************************************************/
1013
1014 NTSTATUS _net_sam_logon_ex(pipes_struct *p, NET_Q_SAM_LOGON_EX *q_u, NET_R_SAM_LOGON_EX *r_u)
1015 {
1016         NET_Q_SAM_LOGON q;
1017         NET_R_SAM_LOGON r;
1018
1019         ZERO_STRUCT(q);
1020         ZERO_STRUCT(r);
1021
1022         /* Only allow this if the pipe is protected. */
1023         if (p->auth.auth_type != PIPE_AUTH_TYPE_SCHANNEL) {
1024                 DEBUG(0,("_net_sam_logon_ex: client %s not using schannel for netlogon\n",
1025                         get_remote_machine_name() ));
1026                 return NT_STATUS_INVALID_PARAMETER;
1027         }
1028
1029         /* Map a NET_Q_SAM_LOGON_EX to NET_Q_SAM_LOGON. */
1030         q.validation_level = q_u->validation_level;
1031
1032         /* Map a DOM_SAM_INFO_EX into a DOM_SAM_INFO with no creds. */
1033         q.sam_id.client.login = q_u->sam_id.client;
1034         q.sam_id.logon_level = q_u->sam_id.logon_level;
1035         q.sam_id.ctr = q_u->sam_id.ctr;
1036
1037         r_u->status = _net_sam_logon_internal(p, &q, &r, False);
1038
1039         if (!NT_STATUS_IS_OK(r_u->status)) {
1040                 return r_u->status;
1041         }
1042
1043         /* Map the NET_R_SAM_LOGON to NET_R_SAM_LOGON_EX. */
1044         r_u->switch_value = r.switch_value;
1045         r_u->user = r.user;
1046         r_u->auth_resp = r.auth_resp;
1047         r_u->flags = 0; /* FIXME ! */
1048         return r_u->status;
1049 }
1050
1051 /*************************************************************************
1052  _ds_enum_dom_trusts
1053  *************************************************************************/
1054 #if 0   /* JERRY -- not correct */
1055 NTSTATUS _ds_enum_dom_trusts(pipes_struct *p, DS_Q_ENUM_DOM_TRUSTS *q_u,
1056                              DS_R_ENUM_DOM_TRUSTS *r_u)
1057 {
1058         NTSTATUS status = NT_STATUS_OK;
1059
1060         /* TODO: According to MSDN, the can only be executed against a 
1061            DC or domain member running Windows 2000 or later.  Need
1062            to test against a standalone 2k server and see what it 
1063            does.  A windows 2000 DC includes its own domain in the 
1064            list.  --jerry */
1065
1066         return status;
1067 }
1068 #endif  /* JERRY */