/* 
   Unix SMB/Netbios implementation.
   Version 1.9.
   SMB client
   Copyright (C) Andrew Tridgell              1994-1998
   Copyright (C) Luke Kenneth Casson Leighton 1996-1998
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "includes.h"
#include "ntdom_proto.h"
#include "rpc_validate.h"
#include "valid.h"

extern int DEBUGLEVEL;

static struct cli_state smbcli;
struct cli_state *smb_cli = &smbcli;
extern pstring global_myname;

FILE *out_hnd;

/****************************************************************************
initialise smb client structure
****************************************************************************/
static void client_init(void)
{
	bzero(smb_cli, sizeof(smb_cli));
	cli_initialise(smb_cli);
}

/****************************************************************************
make smb client connection
****************************************************************************/
static BOOL client_connect(struct client_info *info)
{
	struct nmb_name calling;
	struct nmb_name called;

	make_nmb_name(&called , dns_to_netbios_name(info->dest_host ), info->name_type, "");
	make_nmb_name(&calling, dns_to_netbios_name(info->myhostname), 0x0            , "");

	if (!cli_establish_connection(smb_cli, 
	                          info->dest_host, &info->dest_ip, 
	                          &calling, &called,
	                          info->share, info->svc_type,
	                          False, True))
	{
		DEBUG(0,("client_init: connection failed\n"));
		cli_shutdown(smb_cli);
		return False;
	}

	DEBUG(0,("client_init: connection succeeded\n"));

	return True;
}

/****************************************************************************
 validates a user.
 ****************************************************************************/
int Valid_User(char *USERNAME, char *PASSWORD, char *SERVERLIST, char *DOMAIN)
{
	BOOL ret;
	int res = 0;
	struct client_info cli_info;

	out_hnd = stdout;

	client_init();

	cli_info.dest_ip.s_addr = 0;
	cli_info.name_type = 0x20;

	safe_strcpy(cli_info.service, "", sizeof(cli_info.service)-1);
	cli_info.dom.level3_dom[0] = 0;
	cli_info.dom.level5_dom[0] = 0;

	DEBUG(3,("%s pam_ntdom (version %s) login.  user:%s domain:%s\n",
	          timestring(),VERSION,USERNAME,DOMAIN));

	if(!get_myname(global_myname, NULL))
	{
		fprintf(stderr, "Failed to get my hostname.\n");
		return NTV_SERVER_ERROR;
	}

	strupper(global_myname);
	safe_strcpy(cli_info.myhostname, global_myname,
	                                 sizeof(cli_info.myhostname)-1);

	/* initial IPC$ connection is made anonymously */
	pwd_set_nullpwd(&(smb_cli->pwd));
	smb_cli->user_name[0] = 0;
	safe_strcpy(smb_cli->domain,DOMAIN, sizeof(smb_cli->domain)-1);

	/* anonymous connection is made to IPC$ */
	safe_strcpy(cli_info.share, "IPC$", sizeof(cli_info.share)-1);
	safe_strcpy(cli_info.svc_type, "IPC", sizeof(cli_info.svc_type)-1);

	fstrcpy(cli_info.mach_acct, cli_info.myhostname);
	strupper(cli_info.mach_acct);
	safe_strcat(cli_info.mach_acct, "$", sizeof(cli_info.mach_acct)-1);

	if (res == NTV_NO_ERROR)
	{
		res = domain_client_validate(&cli_info, smb_cli,
		             USERNAME, DOMAIN,
		             SERVERLIST,
                             PASSWORD, strlen(PASSWORD),
                             PASSWORD, strlen(PASSWORD)) ?
		      NTV_NO_ERROR : NTV_LOGON_ERROR;
	}

	if (res != NTV_NO_ERROR)
	{
		fprintf(stderr, "Server %s rejected the login of %s to domain %s.\n",
		                 cli_info.dest_host,
		                 USERNAME,
		                 smb_cli->domain);
	}

	return res;
}
/***********************************************************************
 Do the same as security=server, but using NT Domain calls and a session
 key from the workstation trust account password.
************************************************************************/

BOOL domain_client_validate( struct client_info *cli_info,
				struct cli_state *cli,
				char *user, char *mydomain, char *server_list, 
				char *smb_apasswd, int smb_apasslen, 
				char *smb_ntpasswd, int smb_ntpasslen)
{
	uint16 fnum;
	unsigned char local_challenge[8];
	unsigned char local_lm_response[24];
	unsigned char local_nt_reponse[24];
	unsigned char trust_passwd[16];
	NET_ID_INFO_CTR ctr;
	NET_USER_INFO_3 info3;
	uint32 smb_uid_low;
	fstring domain;

	/*
	 * check that the passwords given were encrypted.
	 */

	if(((smb_apasslen  != 24) && (smb_apasslen  != 0)) || 
	   ((smb_ntpasslen != 24) && (smb_ntpasslen != 0)))
	{
		/*
		 * Not encrypted - do so.
		 */

		DEBUG(3,("domain_client_validate: User passwords not in encrypted format.\n"));
		generate_random_buffer( local_challenge, 8, False);
		SMBencrypt( (uchar *)smb_apasswd, local_challenge, local_lm_response);
		SMBNTencrypt((uchar *)smb_ntpasswd, local_challenge, local_nt_reponse);
		smb_apasslen = 24;
		smb_ntpasslen = 24;
		smb_apasswd = (char *)local_lm_response;
		smb_ntpasswd = (char *)local_nt_reponse;
	}

	/*
	 * Get the workstation trust account password.
	 */
	if (!trust_get_passwd( trust_passwd, mydomain, global_myname))
	{
		return False;
	}

	/*
	 * At this point, smb_apasswd points to the lanman response to
	 * the challenge in local_challenge, and smb_ntpasswd points to
	 * the NT response to the challenge in local_challenge. Ship
	 * these over the secure channel to a domain controller and
	 * see if they were valid.
	 */

	if (!cli_connect_serverlist(cli, server_list))
	{
		DEBUG(0,("domain_client_validate: Domain password server not available.\n"));
		return False;
	}

	cmd_lsa_query_info(cli_info);
	safe_strcpy(domain, cli_info->dom.level5_dom, sizeof(domain)-1);

	if (domain[0] == 0)
	{
		fprintf(stderr, "Could not connect to LSA on %s (it may not be a Domain Controller)\n",
		                 cli_info->dest_host);
		return False;
	}

	/*
	* Ok - we have an anonymous connection to the IPC$ share.
	* Now start the NT Domain stuff :-).
	*/

	if (!cli_nt_session_open(cli, PIPE_NETLOGON, &fnum))
	{
		DEBUG(0,("domain_client_validate: unable to open the domain client session to \
		machine %s. Error was : %s.\n", cli->desthost, cli_errstr(cli)));
		cli_nt_session_close(cli, fnum);
		cli_ulogoff(cli);
		cli_shutdown(cli);
		return False; 
	}

	if(cli_nt_setup_creds(cli, fnum,
	   cli->mach_acct, global_myname, trust_passwd, SEC_CHAN_WKSTA) != 0x0)
	{
		DEBUG(0,("domain_client_validate: unable to setup the PDC credentials to machine \
		%s. Error was : %s.\n", cli->desthost, cli_errstr(cli)));
		cli_nt_session_close(cli, fnum);
		cli_ulogoff(cli);
		cli_shutdown(cli);
		return False;
	}

	/* We really don't care what LUID we give the user. */
	generate_random_buffer( (unsigned char *)&smb_uid_low, 4, False);

	if (!cli_nt_login_network(cli, fnum, domain, user, smb_uid_low, (char *)local_challenge,
	                          ((smb_apasslen != 0) ? smb_apasswd : NULL),
	                          ((smb_ntpasslen != 0) ? smb_ntpasswd : NULL),
	                          &ctr, &info3))
	{
		DEBUG(0,("domain_client_validate: unable to validate password for user %s in domain \
		%s to Domain controller %s. Error was %s.\n", user, domain, cli->desthost, cli_errstr(cli)));
		cli_nt_session_close(cli, fnum);
		cli_ulogoff(cli);
		cli_shutdown(cli);
		return False;
	}

	/*
	 * Here, if we really want it, we have lots of info about the user in info3.
	 * LKCLXXXX - really important to check things like "is this user acct
	 * locked out / disabled" etc!!!!
	 */

#if 0
	/* 
	* We don't actually need to do this - plus it fails currently with
	* NT_STATUS_INVALID_INFO_CLASS - we need to know *exactly* what to
	* send here. JRA.
	*/

	if (!cli_nt_logoff(cli, fnum, &ctr))
	{
		DEBUG(0,("domain_client_validate: unable to log off user %s in domain \
		%s to Domain controller %s. Error was %s.\n", user, domain, cli->desthost, cli_errstr(cli)));        
		cli_nt_session_close(cli, fnum);
		cli_ulogoff(cli);
		cli_shutdown(cli);
		return False;
	}
#endif /* 0 */

	cli_nt_session_close(cli, fnum);
	cli_ulogoff(cli);
	cli_shutdown(cli);
	return True;
}

