Sending Mail safely
Summary
PHP's mail()
function is exploitable for sending Spam, when insufficient argument checking is performed.
Solution: replace all calls to mail() through the SafeMail interface.
Note that regular form validation should be done beforehand, see Contact Forms.
Example
// Load the SafeMail feature (the 4 in SafeMail4 marks the file as PHP4 code rather than PHP5)
require_once "SafeMail4.class.php";
// For each message to send, create a SafeMail object and set all the parameters.
$message = new SafeMail();
$message->set_subject($_REQUEST['subject']);
// Send message to Gisela (or other hard coded recipient)
$message->add_recipient("gisela@spallek.com");
// Send message to all recipients given from the form.
// Warning: recipients given from the form must be checked.
// Use a whitelist and allow only recipients from this list.
$message->whitelist(file_get_contents("path/to/whitelist.txt")); // file contains one valid recipient per line
$message->add_recipient_check_whitelist(explode(",", $_REQUEST['to'])); // accepts only whitelisted recipients
// Set sender address; if no address is given or the address is invalid, use a hard coded (secure) sender address.
if (! $message->set_from($_REQUEST['from']))
$message->set_from("gisela@spallek.com");
// Set the message Body
$message->set_body("message text");
// Send the message
$message->send();
Notes
- Each function returns FALSE, if an argument is invalid, i. e.
- the subject contains illegal characters (e/g: "valid subject\nCC: spam@victim.com")
- the sender address is not a valid e-mail address
- one or more recipient addresses is not a valid e-mail address
- one or more recipient addresses is not whitelisted
These checks guarantee, that no spam hacks can be injected by a form user.
- The message is still sent if one or more parameters are rejected.
For example, if the sender address (user enters his e-mail address in the form as "from")
is not valid, the message is sent with the server's default sender address.
This is to ensure least performance.
- This is NOT a form validator, but a filter for PHP's mail() function.
Validate required fields through the html_form.php interface before sending
to force the form user entering valid data.
Files
- The
SafeMail4.class.php
file should if at all possible reside
in a global include path.
In London: /var/www/global/include/SafeMail4.class.php
Use require_once "SafeMail4.class.php"
to load the class file.
- Keep a whitelist per domain or per customer
it in the domain's/customer's home directory.
The whitelist must contain exactly one e-mail address per line.