# -*- Fundamental -*-
#
# (C) 2002 Michel Arboi <arboi@bigfoot.com>
# $Revision: 1.17 $

function smtp_send_socket(socket, from, to, body)
{
  # display(string("smtp_send_socket from=", from, " to=", to, "\n"));
  # Just to be sure
  send(socket: socket, data: string("RSET\r\n"));
  buff = recv_line(socket: socket, length: 2048);
  # Here, we might test the return code
  send(socket: socket, data: string("MAIL FROM: ", from, "\r\n"));
  buff = recv_line(socket: socket, length: 2048);
  if (! ereg(pattern:"^2[0-9][0-9] ", string:buff)) { return (0); }
  
  send(socket: socket, data: string("RCPT TO: ", to, "\r\n"));
  buff = recv_line(socket: socket, length: 2048);
  if (! ereg(pattern:"^2[0-9][0-9] ", string:buff)) { return (0); }

  send(socket: socket, data: string("DATA\r\n"));
  buff = recv_line(socket: socket, length: 2048);
  if (! ereg(pattern:"^3[0-9][0-9] ", string:buff)) { return (0); }

  # Make sure that every line ends up with \r\n
  # This is not useful yet, as only two scripts send data to the SMTP server
  #body = ereg_replace(string: body, pattern: string("([^\r])\n"), replace: string("\\1\r\n"));
  send(socket: socket, data: body);
  send(socket: socket, data: string("\r\n.\r\n"));
  buff = recv_line(socket: socket, length: 2048);
  if (! ereg(pattern:"^2[0-9][0-9] ", string:buff)) { return (0); }
  return(1);
}

function smtp_send_port(port, from, to, body)
{
  s = open_sock_tcp(port);
  if (! s) return (0);

  buff = recv_line(socket: s, length: 2048);
  send(socket: s, data: string("HELO nessus\r\n"));
  buff = recv_line(socket: s, length: 2048);
  # We should test the code
  ret = smtp_send_socket(socket: s, from: from, to: to, body: body);
  send(socket: s, data: string("QUIT\r\n"));
  close(s);
  return (ret);
}

function smtp_from_header()
{
 fromaddr = get_kb_item("SMTP/headers/From");
 if (!fromaddr) fromaddr = "nessus@example.com";
 return (fromaddr);
}

function smtp_to_header()
{
 toaddr = get_kb_item("SMTP/headers/To");
 if (!toaddr) toaddr = string("postmaster@[", get_host_ip(), "]");
 return (toaddr);
}

function get_smtp_banner(port)
{
  __sb = string("smtp/banner/", port);
  __banner = get_kb_item(__sb);
  if(__banner) return (__banner);
  if(! get_port_state(port)) return (0);
  __soc = open_sock_tcp(port);
  if (! __soc) return (0);
  __banner =  smtp_recv_banner(socket: __soc);
  close(__soc);
  if(! __banner ) return(NULL);
  
  set_kb_item(name: __sb, value: __banner);
  return(__banner);
}


function smtp_recv_banner(socket)
{
 __ret = "";
 __n = 0;
 __r = recv_line(socket:socket, length:65535);
 __ret = __r;
 if(strlen(__r) < 4) 
  return(__r);
  
 while(ereg(pattern:"^220-", string:__r))
 {
  __n = __n + 1;
  __r = recv_line(socket:socket, length:65535);
  if(__n > 1024)
   return(NULL);
 __ret = string(__ret, __r);
 }
 return(__ret);
}
