/**************************************************
OpengateM - MAC address authentication system 
 module for Authentication by FTPS
       (Explicit and Implicit FTP modes)

Copyright (C) 2006 Opengate Project Team
Written by Yoshiaki Watanabe

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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

Email: watanaby@is.saga-u.ac.jp
**************************************************/
/*
  Thanks to programs and documentations refered.
   Sample client application cli.cpp found in the OpenSSL site 
    (developed by Sampo Kellomaki and simplified by Wade Scholine) 
   Apache module mod_auth_pam.c by Ingo Luetkebohle
*/

#include "opengatemmng.h"

/*****************************************/
/* Auth by FTP on SSL - Explicit Mode    */
/*****************************************/
int authFtpse(char *userid, char *passwd)
{
  int		sockfd, n;
  char		recvline[BUFFMAXLN];
  int           authResult;
  char* serverAddr; /* auth server address */
  char* port;      /* auth server port */
  SSL_CTX    *ctx;
  SSL        *ssl;
  const SSL_METHOD *meth;

  /* get auth server address */
  serverAddr=GetConfValue("AuthServer/Address");

  if(isNull(serverAddr)){
    err_msg("ERR at %s#%d: Missing address for FTP server in config",
	    __FILE__,__LINE__);
    return DENY;
  }

  /* get auth server port */
  port=GetConfValue("AuthServer/Port");

  /* FTP server connect */
  if(isNull(port)){
    sockfd = Tcp_connect(serverAddr, "ftp"); /* use ftp port in explicit */
  }else{
    sockfd = Tcp_connect(serverAddr, port);
  }
  if(sockfd<0){
    err_msg("ERR at %s#%d: Ftpse server is not normal 0",__FILE__,__LINE__);
    return DENY;
  }

  /* get [220 <host> FTP server ..]*/
  if((n = readln(sockfd, recvline, BUFFMAXLN)) < 0) {
    err_msg("ERR at %s#%d: Ftpse server is not normal 1",__FILE__,__LINE__);
    Close(sockfd);
    return DENY;
  }
  if(strstr(recvline,"220")!=recvline){
    err_msg("ERR at %s#%d: Ftpse server is not normal 2",__FILE__,__LINE__);
    Close(sockfd);
    return DENY;
  }

  /* put [AUTH TLS] */
  Writefmt(sockfd, "AUTH TLS\r\n");

  /* get [234 AUTH TLS successful] */
  if((n = readln(sockfd, recvline, BUFFMAXLN)) < 0) {
    err_msg("ERR at %s#%d: Ftpse server is not normal 3",__FILE__,__LINE__);
    Close(sockfd);
    return DENY;
  }
  if(strstr(recvline,"234")!=recvline){
    err_msg("ERR at %s#%d: Ftpse server is not normal 4",__FILE__,__LINE__);
    Close(sockfd);
    return DENY;
  }

  /* ----------------------------------------------- */
  /* prepare SSL */
  SSLeay_add_ssl_algorithms();
  meth = SSLv23_client_method();
  SSL_load_error_strings();
  ctx = SSL_CTX_new (meth);
  if( ctx == NULL ){
    err_msg("ERR at %s#%d: SSL_CTX_new returns NULL",__FILE__,__LINE__);
    return DENY;
  }
  
  /* ----------------------------------------------- */
  /* start SSL negotiation. */
  
  ssl = SSL_new (ctx);
  if( ssl == NULL ){
    err_msg("ERR at %s#%d: SSL_new returns NULL",__FILE__,__LINE__);
    return DENY;
  }

  SSL_set_fd (ssl, sockfd);
  if( SSL_connect (ssl) == -1 ){
    err_msg("ERR at %s#%d: SSL_connect returns error",__FILE__,__LINE__);
    return DENY;
  }

  /* --------------------------------------------------- */
  /* DATA EXCHANGE - Send a message and receive a reply. */

  /* put [USER <userid>] */
  WritefmtSSL(ssl, "USER %s\r\n", userid);

  /* get [331 Password required ..] */
  if((n = readlnSSL(ssl, recvline, BUFFMAXLN)) < 0) {
    err_msg("ERR at %s#%d: Ftpse server is not normal 5",__FILE__,__LINE__);
    authResult=DENY;
    goto EXITPOINT;
  }

  /* if multi-line greeting [220 ...] exist, skip them. */
  while(strstr(recvline,"220")==recvline){
    if((n = readlnSSL(ssl, recvline, BUFFMAXLN)) < 0) {
      err_msg("ERR at %s#%d: Ftpse server is not normal 6",__FILE__,__LINE__);
      authResult=DENY;
      goto EXITPOINT;
    }
  }

  /* check [331 Password required ..] */
  if(strstr(recvline,"331")!=recvline){
    err_msg("ERR at %s#%d: Ftpse server is not normal 7",__FILE__,__LINE__);
    authResult=DENY;
    goto EXITPOINT;
  }

  /* put [PASS <password>] */
  WritefmtSSL(ssl, "PASS %s\r\n", passwd);

  /* get [230 User <userid> logged in] */
  if((n = readlnSSL(ssl, recvline, BUFFMAXLN)) < 0) {
    err_msg("ERR at %s#%d: Ftpse server is not normal 8",__FILE__,__LINE__);
    authResult=DENY;
    goto EXITPOINT;
  }
  if(strstr(recvline,"230")==recvline){
    authResult=ACCEPT;
  }else{
    authResult=DENY;
  }
  
  /* put [quit] */
  WritefmtSSL(ssl,"quit\r\n");

EXITPOINT:
  SSL_shutdown (ssl);  /* send SSL/TLS close_notify */

  /* Clean up. */
  Close(sockfd);
  SSL_free (ssl);
  SSL_CTX_free (ctx);

  return authResult;
}


/*****************************************/
/* Auth by FTP on SSL - Implicit Mode    */
/*****************************************/
int authFtpsi(char *userid, char *passwd)
{
  int		sockfd, n;
  char		recvline[BUFFMAXLN];
  int           authResult;
  char* serverAddr; /* auth server address */
  char* port;      /* auth server port */
  SSL_CTX    *ctx;
  SSL        *ssl;
  const SSL_METHOD *meth;

  /* get auth server address */
  serverAddr=GetConfValue("AuthServer/Address");

  if(isNull(serverAddr)){
    err_msg("ERR at %s#%d: Missing address for FTP server in config",
	    __FILE__,__LINE__);
    return DENY;
  }

  /* get auth server port */
  port=GetConfValue("AuthServer/Port");

  /* FTP server connect */
  if(port==NULL){
    sockfd = Tcp_connect(serverAddr, "ftps");
  }else{
    sockfd = Tcp_connect(serverAddr, port);
  }
  if(sockfd<0){
    err_msg("ERR at %s#%d: Ftpsi server is not normal 0",__FILE__,__LINE__);
    return DENY;
  }

  /* ----------------------------------------------- */
  /* prepare SSL */
  SSLeay_add_ssl_algorithms();
  meth = SSLv2_client_method();
  SSL_load_error_strings();
  ctx = SSL_CTX_new (meth);
  if( ctx == NULL ){
    err_msg("ERR at %s#%d: SSL_CTX_new returns NULL",__FILE__,__LINE__);
    return DENY;
  }
  
  /* ----------------------------------------------- */
  /* start SSL negotiation. */
  
  ssl = SSL_new (ctx);
  if( ssl == NULL ){
    err_msg("ERR at %s#%d: SSL_new returns NULL",__FILE__,__LINE__);
    return DENY;
  }

  SSL_set_fd (ssl, sockfd);
  if( SSL_connect (ssl) == -1 ){
    err_msg("ERR at %s#%d: SSL_connect returns error",__FILE__,__LINE__);
    return DENY;
  }

  /* --------------------------------------------------- */
  /* DATA EXCHANGE - Send a message and receive a reply. */

  /* get [220 <host> FTP server ..]*/
  if((n = readlnSSL(ssl, recvline, BUFFMAXLN)) < 0) {
    err_msg("ERR at %s#%d: Ftpsi server is not normal 1",__FILE__,__LINE__);
    authResult=DENY;
    goto EXITPOINT;
  }
  if(strstr(recvline,"220")!=recvline){
    err_msg("ERR at %s#%d: Ftpsi server is not normal 2",__FILE__,__LINE__);
    authResult=DENY;
    goto EXITPOINT;
  }

  /* put [USER <userid>] */
  WritefmtSSL(ssl, "USER %s\r\n", userid);

  /* get [331 Password required ..] */
  if((n = readlnSSL(ssl, recvline, BUFFMAXLN)) < 0) {
    err_msg("ERR at %s#%d: Ftpi server is not normal 3",__FILE__,__LINE__);
    authResult=DENY;
    goto EXITPOINT;
  }

  /* if multi-line greeting [220 ...] exist, skip them. */
  while(strstr(recvline,"220")==recvline){
    if((n = readlnSSL(ssl, recvline, BUFFMAXLN)) < 0) {
      err_msg("ERR at %s#%d: Ftpsi server is not normal 4",__FILE__,__LINE__);
      authResult=DENY;
      goto EXITPOINT;
    }
  }

  /* check [331 Password required ..] */
  if(strstr(recvline,"331")!=recvline){
    err_msg("ERR at %s#%d: Ftpsi server is not normal 5",__FILE__,__LINE__);
    authResult=DENY;
    goto EXITPOINT;
  }

  /* put [PASS <password>] */
  WritefmtSSL(ssl, "PASS %s\r\n", passwd);

  /* get [230 User <userid> logged in] */
  if((n = readlnSSL(ssl, recvline, BUFFMAXLN)) < 0) {
    err_msg("ERR at %s#%d: Ftpsi server is not normal 6",__FILE__,__LINE__);
    authResult=DENY;
    goto EXITPOINT;
  }
  if(strstr(recvline,"230")==recvline){
    authResult=ACCEPT;
  }else{
    authResult=DENY;
  }
  
  /* put [quit] */
  WritefmtSSL(ssl,"quit\r\n");

EXITPOINT:
  SSL_shutdown (ssl);  /* send SSL/TLS close_notify */

  /* Clean up. */
  Close(sockfd);
  SSL_free (ssl);
  SSL_CTX_free (ctx);

  return authResult;
}

/***************************/

int AuthFtpse(char *userid, char *passwd)
{
  int ret;

  if(debug>1) err_msg("DEBUG:=>authFtpse(%s,passwd)",userid);
  ret=authFtpse(userid,passwd);
  if(debug>1) err_msg("DEBUG:(%d)<=authFtpse( )",ret);

  return ret;
}

int AuthFtpsi(char *userid, char *passwd)
{
  int ret;

  if(debug>1) err_msg("DEBUG:=>authFtpsi(%s,passwd)",userid);
  ret=authFtpsi(userid,passwd);
  if(debug>1) err_msg("DEBUG:(%d)<=authFtpsi( )",ret);

  return ret;
}

