document cve id's for posterity
[squirrelmail.git] / class / deliver / Deliver_SMTP.class.php
1 <?php
2
3 /**
4 * Deliver_SMTP.class.php
5 *
6 * SMTP delivery backend for the Deliver class.
7 *
8 * @copyright 1999-2011 The SquirrelMail Project Team
9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
10 * @version $Id$
11 * @package squirrelmail
12 */
13
14 /** @ignore */
15 if (!defined('SM_PATH')) define('SM_PATH','../../');
16
17 /** This of course depends upon Deliver */
18 include_once(SM_PATH . 'class/deliver/Deliver.class.php');
19
20 /**
21 * Deliver messages using SMTP
22 * @package squirrelmail
23 */
24 class Deliver_SMTP extends Deliver {
25 /**
26 * Array keys are uppercased ehlo keywords
27 * array key values are ehlo params. If ehlo-param contains space, it is splitted into array.
28 * @var array ehlo
29 * @since 1.5.1
30 */
31 var $ehlo = array();
32 /**
33 * @var string domain
34 * @since 1.5.1
35 */
36 var $domain = '';
37 /**
38 * SMTP STARTTLS rfc: "Both the client and the server MUST know if there
39 * is a TLS session active."
40 * Variable should be set to true, when encryption is turned on.
41 * @var boolean
42 * @since 1.5.1
43 */
44 var $tls_enabled = false;
45 /**
46 * Private var
47 * var stream $stream
48 * @todo don't pass stream resource in class method arguments.
49 */
50 //var $stream = false;
51 /** @var string delivery error message */
52 var $dlv_msg = '';
53 /** @var integer delivery error number from server */
54 var $dlv_ret_nr = '';
55 /** @var string delivery error message from server */
56 var $dlv_server_msg = '';
57
58 function preWriteToStream(&$s) {
59 if ($s) {
60 if ($s{0} == '.') $s = '.' . $s;
61 $s = str_replace("\n.","\n..",$s);
62 }
63 }
64
65 function initStream($message, $domain, $length=0, $host='', $port='', $user='', $pass='', $authpop=false, $pop_host='') {
66 global $use_smtp_tls,$smtp_auth_mech;
67
68 if ($authpop) {
69 $this->authPop($pop_host, '', $user, $pass);
70 }
71
72 $rfc822_header = $message->rfc822_header;
73
74 $from = $rfc822_header->from[0];
75 $to = $rfc822_header->to;
76 $cc = $rfc822_header->cc;
77 $bcc = $rfc822_header->bcc;
78 $content_type = $rfc822_header->content_type;
79
80 // MAIL FROM: <from address> MUST be empty in cae of MDN (RFC2298)
81 if ($content_type->type0 == 'multipart' &&
82 $content_type->type1 == 'report' &&
83 isset($content_type->properties['report-type']) &&
84 $content_type->properties['report-type']=='disposition-notification') {
85 // reinitialize the from object because otherwise the from header somehow
86 // is affected. This $from var is used for smtp command MAIL FROM which
87 // is not the same as what we put in the rfc822 header.
88 $from = new AddressStructure();
89 $from->host = '';
90 $from->mailbox = '';
91 }
92
93 if ($use_smtp_tls == 1) {
94 if ((check_php_version(4,3)) && (extension_loaded('openssl'))) {
95 $stream = @fsockopen('tls://' . $host, $port, $errorNumber, $errorString);
96 $this->tls_enabled = true;
97 } else {
98 /**
99 * don't connect to server when user asks for smtps and
100 * PHP does not support it.
101 */
102 $errorNumber = '';
103 $errorString = _("Secure SMTP (TLS) is enabled in SquirrelMail configuration, but used PHP version does not support it.");
104 }
105 } else {
106 $stream = @fsockopen($host, $port, $errorNumber, $errorString);
107 }
108
109 if (!$stream) {
110 // reset tls state var to default value, if connection fails
111 $this->tls_enabled = false;
112 // set error messages
113 $this->dlv_msg = $errorString;
114 $this->dlv_ret_nr = $errorNumber;
115 $this->dlv_server_msg = _("Can't open SMTP stream.");
116 return(0);
117 }
118 // get server greeting
119 $tmp = fgets($stream, 1024);
120 if ($this->errorCheck($tmp, $stream)) {
121 return(0);
122 }
123
124 /*
125 * If $_SERVER['HTTP_HOST'] is set, use that in our HELO to the SMTP
126 * server. This should fix the DNS issues some people have had
127 */
128 if (sqgetGlobalVar('HTTP_HOST', $HTTP_HOST, SQ_SERVER)) { // HTTP_HOST is set
129 // optionally trim off port number
130 if($p = strrpos($HTTP_HOST, ':')) {
131 $HTTP_HOST = substr($HTTP_HOST, 0, $p);
132 }
133 $helohost = $HTTP_HOST;
134 } else { // For some reason, HTTP_HOST is not set - revert to old behavior
135 $helohost = $domain;
136 }
137
138 // if the host is an IPv4 address, enclose it in brackets
139 //
140 if (preg_match('/^\d+\.\d+\.\d+\.\d+$/', $helohost))
141 $helohost = '[' . $helohost . ']';
142
143 /* Lets introduce ourselves */
144 fputs($stream, "EHLO $helohost\r\n");
145 // Read ehlo response
146 $tmp = $this->parse_ehlo_response($stream);
147 if ($this->errorCheck($tmp,$stream)) {
148 // fall back to HELO if EHLO is not supported (error 5xx)
149 if ($this->dlv_ret_nr{0} == '5') {
150 fputs($stream, "HELO $helohost\r\n");
151 $tmp = fgets($stream,1024);
152 if ($this->errorCheck($tmp,$stream)) {
153 return(0);
154 }
155 } else {
156 return(0);
157 }
158 }
159
160 /**
161 * Implementing SMTP STARTTLS (rfc2487) in php 5.1.0+
162 * http://www.php.net/stream-socket-enable-crypto
163 */
164 if ($use_smtp_tls === 2) {
165 if (function_exists('stream_socket_enable_crypto')) {
166 // don't try starting tls, when client thinks that it is already active
167 if ($this->tls_enabled) {
168 $this->dlv_msg = _("TLS session is already activated.");
169 return 0;
170 } elseif (!array_key_exists('STARTTLS',$this->ehlo)) {
171 // check for starttls in ehlo response
172 $this->dlv_msg = _("SMTP STARTTLS is enabled in SquirrelMail configuration, but used SMTP server does not support it");
173 return 0;
174 }
175
176 // issue starttls command
177 fputs($stream, "STARTTLS\r\n");
178 // get response
179 $tmp = fgets($stream,1024);
180 if ($this->errorCheck($tmp,$stream)) {
181 return 0;
182 }
183
184 // start crypto on connection. suppress function errors.
185 if (@stream_socket_enable_crypto($stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
186 // starttls was successful (rfc2487 5.2 Result of the STARTTLS Command)
187 // get new EHLO response
188 fputs($stream, "EHLO $helohost\r\n");
189 // Read ehlo response
190 $tmp = $this->parse_ehlo_response($stream);
191 if ($this->errorCheck($tmp,$stream)) {
192 // don't revert to helo here. server must support ESMTP
193 return 0;
194 }
195 // set information about started tls
196 $this->tls_enabled = true;
197 } else {
198 /**
199 * stream_socket_enable_crypto() call failed.
200 */
201 $this->dlv_msg = _("Unable to start TLS.");
202 return 0;
203 // Bug: can't get error message. See comments in sqimap_create_stream().
204 }
205 } else {
206 // php install does not support stream_socket_enable_crypto() function
207 $this->dlv_msg = _("SMTP STARTTLS is enabled in SquirrelMail configuration, but used PHP version does not support functions that allow to enable encryption on open socket.");
208 return 0;
209 }
210 }
211
212 // FIXME: check ehlo response before using authentication
213
214 // Try authentication by a plugin
215 $smtp_auth_args = array(
216 'auth_mech' => $smtp_auth_mech,
217 'user' => $user,
218 'pass' => $pass,
219 'host' => $host,
220 'port' => $port,
221 'stream' => $stream,
222 );
223 if (boolean_hook_function('smtp_auth', $smtp_auth_args, 1)) {
224 // authentication succeeded
225 } else if (( $smtp_auth_mech == 'cram-md5') or ( $smtp_auth_mech == 'digest-md5' )) {
226 // Doing some form of non-plain auth
227 if ($smtp_auth_mech == 'cram-md5') {
228 fputs($stream, "AUTH CRAM-MD5\r\n");
229 } elseif ($smtp_auth_mech == 'digest-md5') {
230 fputs($stream, "AUTH DIGEST-MD5\r\n");
231 }
232
233 $tmp = fgets($stream,1024);
234
235 if ($this->errorCheck($tmp,$stream)) {
236 return(0);
237 }
238
239 // At this point, $tmp should hold "334 <challenge string>"
240 $chall = substr($tmp,4);
241 // Depending on mechanism, generate response string
242 if ($smtp_auth_mech == 'cram-md5') {
243 $response = cram_md5_response($user,$pass,$chall);
244 } elseif ($smtp_auth_mech == 'digest-md5') {
245 $response = digest_md5_response($user,$pass,$chall,'smtp',$host);
246 }
247 fputs($stream, $response);
248
249 // Let's see what the server had to say about that
250 $tmp = fgets($stream,1024);
251 if ($this->errorCheck($tmp,$stream)) {
252 return(0);
253 }
254
255 // CRAM-MD5 is done at this point. If DIGEST-MD5, there's a bit more to go
256 if ($smtp_auth_mech == 'digest-md5') {
257 // $tmp contains rspauth, but I don't store that yet. (No need yet)
258 fputs($stream,"\r\n");
259 $tmp = fgets($stream,1024);
260
261 if ($this->errorCheck($tmp,$stream)) {
262 return(0);
263 }
264 }
265 // CRAM-MD5 and DIGEST-MD5 code ends here
266 } elseif ($smtp_auth_mech == 'none') {
267 // No auth at all, just send helo and then send the mail
268 // We already said hi earlier, nothing more is needed.
269 } elseif ($smtp_auth_mech == 'login') {
270 // The LOGIN method
271 fputs($stream, "AUTH LOGIN\r\n");
272 $tmp = fgets($stream, 1024);
273
274 if ($this->errorCheck($tmp, $stream)) {
275 return(0);
276 }
277 fputs($stream, base64_encode ($user) . "\r\n");
278 $tmp = fgets($stream, 1024);
279 if ($this->errorCheck($tmp, $stream)) {
280 return(0);
281 }
282
283 fputs($stream, base64_encode($pass) . "\r\n");
284 $tmp = fgets($stream, 1024);
285 if ($this->errorCheck($tmp, $stream)) {
286 return(0);
287 }
288 } elseif ($smtp_auth_mech == "plain") {
289 /* SASL Plain */
290 $auth = base64_encode("$user\0$user\0$pass");
291
292 $query = "AUTH PLAIN\r\n";
293 fputs($stream, $query);
294 $read=fgets($stream, 1024);
295
296 if (substr($read,0,3) == '334') { // OK so far..
297 fputs($stream, "$auth\r\n");
298 $read = fgets($stream, 1024);
299 }
300
301 $results=explode(" ",$read,3);
302 $response=$results[1];
303 $message=$results[2];
304 } else {
305 /* Right here, they've reached an unsupported auth mechanism.
306 This is the ugliest hack I've ever done, but it'll do till I can fix
307 things up better tomorrow. So tired... */
308 if ($this->errorCheck("535 Unable to use this auth type",$stream)) {
309 return(0);
310 }
311 }
312
313 /* Ok, who is sending the message? */
314 $fromaddress = (strlen($from->mailbox) && $from->host) ?
315 $from->mailbox.'@'.$from->host : '';
316 fputs($stream, 'MAIL FROM:<'.$fromaddress.">\r\n");
317 $tmp = fgets($stream, 1024);
318 if ($this->errorCheck($tmp, $stream)) {
319 return(0);
320 }
321
322 /* send who the recipients are */
323 for ($i = 0, $cnt = count($to); $i < $cnt; $i++) {
324 if (!$to[$i]->host) $to[$i]->host = $domain;
325 if (strlen($to[$i]->mailbox)) {
326 fputs($stream, 'RCPT TO:<'.$to[$i]->mailbox.'@'.$to[$i]->host.">\r\n");
327 $tmp = fgets($stream, 1024);
328 if ($this->errorCheck($tmp, $stream)) {
329 return(0);
330 }
331 }
332 }
333
334 for ($i = 0, $cnt = count($cc); $i < $cnt; $i++) {
335 if (!$cc[$i]->host) $cc[$i]->host = $domain;
336 if (strlen($cc[$i]->mailbox)) {
337 fputs($stream, 'RCPT TO:<'.$cc[$i]->mailbox.'@'.$cc[$i]->host.">\r\n");
338 $tmp = fgets($stream, 1024);
339 if ($this->errorCheck($tmp, $stream)) {
340 return(0);
341 }
342 }
343 }
344
345 for ($i = 0, $cnt = count($bcc); $i < $cnt; $i++) {
346 if (!$bcc[$i]->host) $bcc[$i]->host = $domain;
347 if (strlen($bcc[$i]->mailbox)) {
348 fputs($stream, 'RCPT TO:<'.$bcc[$i]->mailbox.'@'.$bcc[$i]->host.">\r\n");
349 $tmp = fgets($stream, 1024);
350 if ($this->errorCheck($tmp, $stream)) {
351 return(0);
352 }
353 }
354 }
355 /* Lets start sending the actual message */
356 fputs($stream, "DATA\r\n");
357 $tmp = fgets($stream, 1024);
358 if ($this->errorCheck($tmp, $stream)) {
359 return(0);
360 }
361 return $stream;
362 }
363
364 function finalizeStream($stream) {
365 fputs($stream, "\r\n.\r\n"); /* end the DATA part */
366 $tmp = fgets($stream, 1024);
367 $this->errorCheck($tmp, $stream);
368 if ($this->dlv_ret_nr != 250) {
369 return(0);
370 }
371 fputs($stream, "QUIT\r\n"); /* log off */
372 fclose($stream);
373 return true;
374 }
375
376 /* check if an SMTP reply is an error and set an error message) */
377 function errorCheck($line, $smtpConnection) {
378
379 $err_num = substr($line, 0, 3);
380 $this->dlv_ret_nr = $err_num;
381 $server_msg = substr($line, 4);
382
383 while(substr($line, 0, 4) == ($err_num.'-')) {
384 $line = fgets($smtpConnection, 1024);
385 $server_msg .= substr($line, 4);
386 }
387
388 if ( ((int) $err_num{0}) < 4) {
389 return false;
390 }
391
392 switch ($err_num) {
393 case '421': $message = _("Service not available, closing channel");
394 break;
395 case '432': $message = _("A password transition is needed");
396 break;
397 case '450': $message = _("Requested mail action not taken: mailbox unavailable");
398 break;
399 case '451': $message = _("Requested action aborted: error in processing");
400 break;
401 case '452': $message = _("Requested action not taken: insufficient system storage");
402 break;
403 case '454': $message = _("Temporary authentication failure");
404 break;
405 case '500': $message = _("Syntax error; command not recognized");
406 break;
407 case '501': $message = _("Syntax error in parameters or arguments");
408 break;
409 case '502': $message = _("Command not implemented");
410 break;
411 case '503': $message = _("Bad sequence of commands");
412 break;
413 case '504': $message = _("Command parameter not implemented");
414 break;
415 case '530': $message = _("Authentication required");
416 break;
417 case '534': $message = _("Authentication mechanism is too weak");
418 break;
419 case '535': $message = _("Authentication failed");
420 break;
421 case '538': $message = _("Encryption required for requested authentication mechanism");
422 break;
423 case '550': $message = _("Requested action not taken: mailbox unavailable");
424 break;
425 case '551': $message = _("User not local; please try forwarding");
426 break;
427 case '552': $message = _("Requested mail action aborted: exceeding storage allocation");
428 break;
429 case '553': $message = _("Requested action not taken: mailbox name not allowed");
430 break;
431 case '554': $message = _("Transaction failed");
432 break;
433 default: $message = _("Unknown response");
434 break;
435 }
436
437 $this->dlv_msg = $message;
438 $this->dlv_server_msg = $server_msg;
439
440 return true;
441 }
442
443 function authPop($pop_server='', $pop_port='', $user, $pass) {
444 if (!$pop_port) {
445 $pop_port = 110;
446 }
447 if (!$pop_server) {
448 $pop_server = 'localhost';
449 }
450 $popConnection = @fsockopen($pop_server, $pop_port, $err_no, $err_str);
451 if (!$popConnection) {
452 error_log("Error connecting to POP Server ($pop_server:$pop_port)"
453 . " $err_no : $err_str");
454 return false;
455 } else {
456 $tmp = fgets($popConnection, 1024); /* banner */
457 if (substr($tmp, 0, 3) != '+OK') {
458 return false;
459 }
460 fputs($popConnection, "USER $user\r\n");
461 $tmp = fgets($popConnection, 1024);
462 if (substr($tmp, 0, 3) != '+OK') {
463 return false;
464 }
465 fputs($popConnection, 'PASS ' . $pass . "\r\n");
466 $tmp = fgets($popConnection, 1024);
467 if (substr($tmp, 0, 3) != '+OK') {
468 return false;
469 }
470 fputs($popConnection, "QUIT\r\n"); /* log off */
471 fclose($popConnection);
472 }
473 return true;
474 }
475
476 /**
477 * Parses ESMTP EHLO response (rfc1869)
478 *
479 * Reads SMTP response to EHLO command and fills class variables
480 * (ehlo array and domain string). Returns last line.
481 * @param stream $stream smtp connection stream.
482 * @return string last ehlo line
483 * @since 1.5.1
484 */
485 function parse_ehlo_response($stream) {
486 // don't cache ehlo information
487 $this->ehlo=array();
488 $ret = '';
489 $firstline = true;
490 /**
491 * ehlo mailclient.example.org
492 * 250-mail.example.org
493 * 250-PIPELINING
494 * 250-SIZE 52428800
495 * 250-DATAZ
496 * 250-STARTTLS
497 * 250-AUTH LOGIN PLAIN
498 * 250 8BITMIME
499 */
500 while ($line=fgets($stream, 1024)){
501 // match[1] = first symbol after 250
502 // match[2] = domain or ehlo-keyword
503 // match[3] = greeting or ehlo-param
504 // match space after keyword in ehlo-keyword CR LF
505 if (preg_match("/^250(-|\s)(\S*)\s+(\S.*)\r\n/",$line,$match)||
506 preg_match("/^250(-|\s)(\S*)\s*\r\n/",$line,$match)) {
507 if ($firstline) {
508 // first ehlo line (250[-\ ]domain SP greeting)
509 $this->domain = $match[2];
510 $firstline=false;
511 } elseif (!isset($match[3])) {
512 // simple one word extension
513 $this->ehlo[strtoupper($match[2])]='';
514 } elseif (!preg_match("/\s/",trim($match[3]))) {
515 // extension with one option
516 // yes, I know about ctype extension. no, i don't want to depend on it
517 $this->ehlo[strtoupper($match[2])]=trim($match[3]);
518 } else {
519 // ehlo-param with spaces
520 $this->ehlo[strtoupper($match[2])]=explode(' ',trim($match[3]));
521 }
522 if ($match[1]==' ') {
523 // stop while cycle, if we reach last 250 line
524 $ret = $line;
525 break;
526 }
527 } else {
528 // this is not 250 response
529 $ret = $line;
530 break;
531 }
532 }
533 return $ret;
534 }
535 }