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

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(socket: socket, length: 2048);
  # Here, we might test the return code
  send(socket: socket, data: string("MAIL FROM: ", from, "\r\n"));
  buff = recv(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(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(socket: socket, length: 2048);
  if (! ereg(pattern:"^3[0-9][0-9] ", string:buff)) { return (0); }

  send(socket: socket, data: body);
  send(socket: socket, data: string(".\r\n"));
  buff = recv(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);

  send(socket: s, data: string("HELO nessus\r\n"));
  buff = recv(socket: s, length: 2048);
  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= recv_line(socket: __soc, length:1024);
  close(__soc);
  set_kb_item(name: __sb, value: __banner);
  return(__banner);
}
