Email.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <?php
  2. /**
  3. * PHPIDS
  4. *
  5. * Requirements: PHP5, SimpleXML
  6. *
  7. * Copyright (c) 2008 PHPIDS group (https://phpids.org)
  8. *
  9. * PHPIDS is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU Lesser General Public License as published by
  11. * the Free Software Foundation, version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * PHPIDS is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public License
  20. * along with PHPIDS. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. * PHP version 5.1.6+
  23. *
  24. * @category Security
  25. * @package PHPIDS
  26. * @author Mario Heiderich <mario.heiderich@gmail.com>
  27. * @author Christian Matthies <ch0012@gmail.com>
  28. * @author Lars Strojny <lars@strojny.net>
  29. * @license http://www.gnu.org/licenses/lgpl.html LGPL
  30. * @link http://php-ids.org/
  31. */
  32. require_once 'IDS/Log/Interface.php';
  33. /**
  34. * Email logging wrapper
  35. *
  36. * The Email wrapper is designed to send reports via email. It implements the
  37. * singleton pattern.
  38. *
  39. * @category Security
  40. * @package PHPIDS
  41. * @author Christian Matthies <ch0012@gmail.com>
  42. * @author Mario Heiderich <mario.heiderich@gmail.com>
  43. * @author Lars Strojny <lars@strojny.net>
  44. * @copyright 2007-2009 The PHPIDS Group
  45. * @license http://www.gnu.org/licenses/lgpl.html LGPL
  46. * @version Release: $Id:Email.php 517 2007-09-15 15:04:13Z mario $
  47. * @link http://php-ids.org/
  48. */
  49. class IDS_Log_Email implements IDS_Log_Interface
  50. {
  51. /**
  52. * Recipient container
  53. *
  54. * @var array
  55. */
  56. protected $recipients = array();
  57. /**
  58. * Mail subject
  59. *
  60. * @var string
  61. */
  62. protected $subject = null;
  63. /**
  64. * Additional mail headers
  65. *
  66. * @var string
  67. */
  68. protected $headers = null;
  69. /**
  70. * Safemode switch
  71. *
  72. * Using this switch it is possible to enable safemode, which is a spam
  73. * protection based on the alert frequency.
  74. *
  75. * @var boolean
  76. */
  77. protected $safemode = true;
  78. /**
  79. * Urlencode for result strings
  80. *
  81. * This switch is true by default. Setting it to false removes
  82. * the 'better safe than sorry' urlencoding for the result string in
  83. * the report mails. Enhances readability but maybe XSSes email clients.
  84. *
  85. * @var boolean
  86. */
  87. protected $urlencode = true;
  88. /**
  89. * Send rate
  90. *
  91. * If safemode is enabled, this property defines how often reports will be
  92. * sent out. Default value is 15, which means that a mail will be sent on
  93. * condition that the last email has not been sent earlier than 15 seconds ago.
  94. *
  95. * @var integer
  96. */
  97. protected $allowed_rate = 15;
  98. /**
  99. * PHPIDS temp directory
  100. *
  101. * When safemod is enabled, a path to a temp directory is needed to
  102. * store some information. Default is IDS/tmp/
  103. *
  104. * @var string
  105. */
  106. protected $tmp_path = 'IDS/tmp/';
  107. /**
  108. * File prefix for tmp files
  109. *
  110. * @var string
  111. */
  112. protected $file_prefix = 'PHPIDS_Log_Email_';
  113. /**
  114. * Holds current remote address
  115. *
  116. * @var string
  117. */
  118. protected $ip = 'local/unknown';
  119. /**
  120. * Instance container
  121. *
  122. * @var array
  123. */
  124. protected static $instance = array();
  125. /**
  126. * Constructor
  127. *
  128. * @param mixed $config IDS_Init instance | array
  129. *
  130. * @return void
  131. */
  132. protected function __construct($config)
  133. {
  134. if ($config instanceof IDS_Init) {
  135. $this->recipients = $config->config['Logging']['recipients'];
  136. $this->subject = $config->config['Logging']['subject'];
  137. $this->headers = $config->config['Logging']['header'];
  138. $this->envelope = $config->config['Logging']['envelope'];
  139. $this->safemode = $config->config['Logging']['safemode'];
  140. $this->urlencode = $config->config['Logging']['urlencode'];
  141. $this->allowed_rate = $config->config['Logging']['allowed_rate'];
  142. $this->tmp_path = $config->getBasePath()
  143. . $config->config['General']['tmp_path'];
  144. } elseif (is_array($config)) {
  145. $this->recipients[] = $config['recipients'];
  146. $this->subject = $config['subject'];
  147. $this->additionalHeaders = $config['header'];
  148. }
  149. // determine correct IP address and concat them if necessary
  150. $this->ip = $_SERVER['REMOTE_ADDR'] .
  151. (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ?
  152. ' (' . $_SERVER['HTTP_X_FORWARDED_FOR'] . ')' : '');
  153. }
  154. /**
  155. * Returns an instance of this class
  156. *
  157. * This method allows the passed argument to be either an instance of
  158. * IDS_Init or an array.
  159. *
  160. * @param mixed $config IDS_Init | array
  161. * @param string $classname the class name to use
  162. *
  163. * @return object $this
  164. */
  165. public static function getInstance($config, $classname = 'IDS_Log_Email')
  166. {
  167. if (!self::$instance) {
  168. self::$instance = new $classname($config);
  169. }
  170. return self::$instance;
  171. }
  172. /**
  173. * Permitting to clone this object
  174. *
  175. * For the sake of correctness of a singleton pattern, this is necessary
  176. *
  177. * @return void
  178. */
  179. private function __clone()
  180. {
  181. }
  182. /**
  183. * Detects spam attempts
  184. *
  185. * To avoid mail spam through this logging class this function is used
  186. * to detect such attempts based on the alert frequency.
  187. *
  188. * @return boolean
  189. */
  190. protected function isSpamAttempt()
  191. {
  192. /*
  193. * loop through all files in the tmp directory and
  194. * delete garbage files
  195. */
  196. $dir = $this->tmp_path;
  197. $numPrefixChars = strlen($this->file_prefix);
  198. $files = scandir($dir);
  199. foreach ($files as $file) {
  200. if (is_file($dir . DIRECTORY_SEPARATOR . $file)) {
  201. if (substr($file, 0, $numPrefixChars) == $this->file_prefix) {
  202. $lastModified = filemtime($dir . DIRECTORY_SEPARATOR . $file);
  203. if ((time() - $lastModified) > 3600) {
  204. unlink($dir . DIRECTORY_SEPARATOR . $file);
  205. }
  206. }
  207. }
  208. }
  209. /*
  210. * end deleting garbage files
  211. */
  212. $remoteAddr = $this->ip;
  213. $userAgent = $_SERVER['HTTP_USER_AGENT'];
  214. $filename = $this->file_prefix . md5($remoteAddr.$userAgent) . '.tmp';
  215. $file = $dir . DIRECTORY_SEPARATOR . $filename;
  216. if (!file_exists($file)) {
  217. $handle = fopen($file, 'w');
  218. fwrite($handle, time());
  219. fclose($handle);
  220. return false;
  221. }
  222. $lastAttack = file_get_contents($file);
  223. $difference = time() - $lastAttack;
  224. if ($difference > $this->allowed_rate) {
  225. unlink($file);
  226. } else {
  227. return true;
  228. }
  229. return false;
  230. }
  231. /**
  232. * Prepares data
  233. *
  234. * Converts given data into a format that can be read in an email.
  235. * You might edit this method to your requirements.
  236. *
  237. * @param mixed $data the report data
  238. *
  239. * @return string
  240. */
  241. protected function prepareData($data)
  242. {
  243. $format = "The following attack has been detected by PHPIDS\n\n";
  244. $format .= "IP: %s \n";
  245. $format .= "Date: %s \n";
  246. $format .= "Impact: %d \n";
  247. $format .= "Affected tags: %s \n";
  248. $attackedParameters = '';
  249. foreach ($data as $event) {
  250. $attackedParameters .= $event->getName() . '=' .
  251. ((!isset($this->urlencode) ||$this->urlencode)
  252. ? urlencode($event->getValue())
  253. : $event->getValue()) . ", ";
  254. }
  255. $format .= "Affected parameters: %s \n";
  256. $format .= "Request URI: %s \n";
  257. $format .= "Origin: %s \n";
  258. return sprintf($format,
  259. $this->ip,
  260. date('c'),
  261. $data->getImpact(),
  262. join(' ', $data->getTags()),
  263. trim($attackedParameters),
  264. htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, 'UTF-8'),
  265. $_SERVER['SERVER_ADDR']);
  266. }
  267. /**
  268. * Sends the report to registered recipients
  269. *
  270. * @param object $data IDS_Report instance
  271. *
  272. * @throws Exception if data is no string
  273. * @return boolean
  274. */
  275. public function execute(IDS_Report $data)
  276. {
  277. if ($this->safemode) {
  278. if ($this->isSpamAttempt()) {
  279. return false;
  280. }
  281. }
  282. /*
  283. * In case the data has been modified before it might
  284. * be necessary to convert it to string since it's pretty
  285. * senseless to send array or object via e-mail
  286. */
  287. $data = $this->prepareData($data);
  288. if (is_string($data)) {
  289. $data = trim($data);
  290. // if headers are passed as array, we need to make a string of it
  291. if (is_array($this->headers)) {
  292. $headers = "";
  293. foreach ($this->headers as $header) {
  294. $headers .= $header . "\r\n";
  295. }
  296. } else {
  297. $headers = $this->headers;
  298. }
  299. if (!empty($this->recipients)) {
  300. if (is_array($this->recipients)) {
  301. foreach ($this->recipients as $address) {
  302. $this->send(
  303. $address,
  304. $data,
  305. $headers,
  306. $this->envelope
  307. );
  308. }
  309. } else {
  310. $this->send(
  311. $this->recipients,
  312. $data,
  313. $headers,
  314. $this->envelope
  315. );
  316. }
  317. }
  318. } else {
  319. throw new Exception(
  320. 'Please make sure that data returned by
  321. IDS_Log_Email::prepareData() is a string.'
  322. );
  323. }
  324. return true;
  325. }
  326. /**
  327. * Sends an email
  328. *
  329. * @param string $address email address
  330. * @param string $data the report data
  331. * @param string $headers the mail headers
  332. * @param string $envelope the optional envelope string
  333. *
  334. * @return boolean
  335. */
  336. protected function send($address, $data, $headers, $envelope = null)
  337. {
  338. if (!$envelope || strpos(ini_get('sendmail_path'),' -f') !== false) {
  339. return mail($address,
  340. $this->subject,
  341. $data,
  342. $headers);
  343. } else {
  344. return mail($address,
  345. $this->subject,
  346. $data,
  347. $headers,
  348. '-f' . $envelope);
  349. }
  350. }
  351. }
  352. /**
  353. * Local variables:
  354. * tab-width: 4
  355. * c-basic-offset: 4
  356. * End:
  357. * vim600: sw=4 ts=4 expandtab
  358. */