2008年11月19日 星期三

檢查網頁上發送EMAIL時的內文

如果你在網路上有用到 PHP的mail function,那就必須注意一些 語法漏洞,避免被當成垃圾信跳板。

從網路上看了一些資料,歸結出下列函數供大家參考

mail($to, $subject, $message, $headers);

//$to = 'bob@example.com';  //$subject = 'Email Subject';  //$message = 'Enter your messages (HTML tags)'  // To send HTML mail, the Content-type header must be set $headers  = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "Organization: Sender Organization\r\n"; $headers .= "X-Priority: 3\r\n"; $headers .= "X-Mailer: PHP". phpversion() ."\r\n";
$headers .= 'To: Twist , Sanu ' . "\r\n"; $headers .= 'From: Birthday Reminder ' . "\r\n"; $headers .= 'Reply-To: Birthday Reminder ' . "\r\n"; $headers .= 'Cc: birthdayarchive@example.com' . "\r\n"; $headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";








非常嚴謹檢查EMAIL

function check_email_address($email) {
    if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
  return false;
    }
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++)
 {
  if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(
\\|\")]{0,62}\"))$", $local_array[$i]))
  {
   return false;
  }
    }
    if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))
 {
  $domain_array = explode(".", $email_array[1]);
  if (sizeof($domain_array) < 2) {
   return false;
  }
  for ($i = 0; $i < sizeof($domain_array); $i++)
  {
   if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
    return false;
   }
  }
    }
    return true;
}

檢查信件內文(MULTI-AREA)
function contains_bad_str($str_to_test) {
  $bad_strings = array(
                "content-type:"
                ,"mime-version:"
                ,"multipart/mixed"
    ,"Content-Transfer-Encoding:"
                ,"bcc:"
    ,"cc:"
    ,"to:"
  );
 
  foreach($bad_strings as $bad_string) {
    if(eregi($bad_string, strtolower($str_to_test))) {
      echo "發現危險字詞 $bad_string ,此字詞可能導致  injection 漏洞攻擊,故無法發送MAIL。";
      exit;
    }
  }
}

檢查單行(TEXT)資料
function contains_newlines($str_to_test) {
   if(preg_match("/(%0A|%0D|\\n+|\\r+)/i", $str_to_test) != 0) {
     echo "你所輸入的資料有關鍵字詞  $str_to_test 可能隱含 injection 漏洞攻擊,請重新檢查!!";
     exit;
   }
}
檢查