ServiceController.php 9.78 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
<?php
/**
 *    Copyright (C) 2015 Deciso B.V.
 *
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without
 *    modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 *    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 *    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 *    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *    POSSIBILITY OF SUCH DAMAGE.
 *
 */
namespace OPNsense\IDS\Api;

31
use \Phalcon\Filter;
32
use \OPNsense\Base\Filters\QueryFilter;
33 34
use \OPNsense\Base\ApiControllerBase;
use \OPNsense\Core\Backend;
Ad Schellevis's avatar
Ad Schellevis committed
35
use \OPNsense\IDS\IDS;
36 37
use \OPNsense\Cron\Cron;
use \OPNsense\Core\Config;
38 39 40 41 42 43 44

/**
 * Class ServiceController
 * @package OPNsense\IDS
 */
class ServiceController extends ApiControllerBase
{
Ad Schellevis's avatar
Ad Schellevis committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    /**
     * start ids service
     * @return array
     */
    public function startAction()
    {
        if ($this->request->isPost()) {
            $backend = new Backend();
            $response = trim($backend->configdRun("ids start"));
            return array("response" => $response);
        } else {
            return array("response" => array());
        }
    }

    /**
     * stop ids service
     * @return array
     */
    public function stopAction()
    {
        if ($this->request->isPost()) {
            $backend = new Backend();
            $response = trim($backend->configdRun("ids stop"));
            return array("response" => $response);
        } else {
            return array("response" => array());
        }
    }

    /**
     * restart ids service
     * @return array
     */
    public function restartAction()
    {
        if ($this->request->isPost()) {
            $backend = new Backend();
            $response = $backend->configdRun("ids restart");
            return array("response" => $response);
        } else {
            return array("response" => array());
        }
    }

    /**
     * retrieve status of squid proxy
     * @return array
     * @throws \Exception
     */
    public function statusAction()
    {
        $backend = new Backend();
        $mdlIDS = new IDS();
        $response = $backend->configdRun("ids status");

        if (strpos($response, "not running") > 0) {
            if ((string)$mdlIDS->general->enabled == 1) {
                $status = "stopped";
            } else {
                $status = "disabled";
            }
        } elseif (strpos($response, "is running") > 0) {
            $status = "running";
        } elseif ((string)$mdlIDS->general->enabled == 0) {
            $status = "disabled";
        } else {
            $status = "unkown";
        }

        return array("status" => $status);
    }
117 118

    /**
Ad Schellevis's avatar
Ad Schellevis committed
119
     * reconfigure IDS
120 121 122
     */
    public function reconfigureAction()
    {
Ad Schellevis's avatar
Ad Schellevis committed
123
        $status = "failed";
124 125 126
        if ($this->request->isPost()) {
            // close session for long running action
            $this->sessionClose();
Ad Schellevis's avatar
Ad Schellevis committed
127 128
            $mdlIDS = new IDS();
            $runStatus = $this->statusAction();
129 130 131
            // we should always have a cron item configured for IDS, let's create one upon first reconfigure.
            if ((string)$mdlIDS->general->UpdateCron == "") {
                $mdlCron = new Cron();
Ad Schellevis's avatar
Ad Schellevis committed
132
                // update cron relation (if this doesn't break consistency)
133 134 135 136 137 138
                $mdlIDS->general->UpdateCron = $mdlCron->newDailyJob("IDS", "ids update", "ids rule updates", "0");

                if ($mdlCron->performValidation()->count() == 0) {
                    $mdlCron->serializeToConfig();
                    // save data to config, do not validate because the current in memory model doesn't know about the
                    // cron item just created.
139
                    $mdlIDS->serializeToConfig($validateFullModel = false, $disable_validation = true);
140 141 142
                    Config::getInstance()->save();
                }
            }
Ad Schellevis's avatar
Ad Schellevis committed
143 144 145 146 147 148 149 150 151

            if ($runStatus['status'] == "running" && (string)$mdlIDS->general->enabled == 0) {
                $this->stopAction();
            }

            $backend = new Backend();
            $bckresult = trim($backend->configdRun("template reload OPNsense.IDS"));

            if ($bckresult == "OK") {
152 153 154 155 156 157 158 159
                if ((string)$mdlIDS->general->enabled == 1) {
                    $bckresult = trim($backend->configdRun("ids install rules"));
                    if ($bckresult == "OK") {
                        if ($runStatus['status'] == 'running') {
                            $status = $this->restartAction()['response'];
                        } else {
                            $status = $this->startAction()['response'];
                        }
Ad Schellevis's avatar
Ad Schellevis committed
160
                    } else {
161
                        $status = "error installing ids rules (".$bckresult.")";
Ad Schellevis's avatar
Ad Schellevis committed
162 163
                    }
                } else {
164
                    $status = "OK";
Ad Schellevis's avatar
Ad Schellevis committed
165 166 167 168
                }
            } else {
                $status = "error generating ids template (".$bckresult.")";
            }
169 170

        }
Ad Schellevis's avatar
Ad Schellevis committed
171
        return array("status" => $status);
172
    }
173

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    /**
     * download and update rules
     * @param null|string $wait wait for update to complete (default) or run in background and return message id
     * @return array
     * @throws \Exception
     */
    public function updateRulesAction($wait = null)
    {
        $status = "failed";
        if ($this->request->isPost()) {
            // close session for long running action
            $this->sessionClose();
            $backend = new Backend();
            // we have to trigger a template reload to be sure we have the right download configuration
            // ideally we should only regenerate the download config, but that's not supported at the moment.
            // (not sure if it should be supported)
            $bckresult = trim($backend->configdRun("template reload OPNsense.IDS"));

            if ($bckresult == "OK") {
                if ($wait != null) {
                    $detach = true;
                } else {
                    $detach = false;
                }

                $status = $backend->configdRun("ids update", $detach);
            } else {
                $status = "template error";
            }
        }

        return array("status" => $status);
    }

208
    /**
209
     * query suricata alerts
210 211 212 213 214 215
     * @return array
     */
    public function queryAlertsAction()
    {
        if ($this->request->isPost()) {
            $this->sessionClose();
216 217 218
            // create filter to sanitize input data
            $filter = new Filter();
            $filter->add('query', new QueryFilter());
219 220 221 222 223 224

            // fetch query parameters
            $itemsPerPage = $this->request->getPost('rowCount', 'int', 9999);
            $currentPage = $this->request->getPost('current', 'int', 1);

            if ($this->request->getPost('searchPhrase', 'string', '') != "") {
225 226
                $filterTag = $filter->sanitize($this->request->getPost('searchPhrase'), "query");
                $searchPhrase = 'alert,src_ip/"*'.$filterTag .'*"';
227 228 229 230
            } else {
                $searchPhrase = '';
            }

231 232 233 234 235 236 237

            if ($this->request->getPost('fileid', 'string', '') != "") {
                $fileid = $this->request->getPost('fileid', 'int', -1);
            } else {
                $fileid = null;
            }

238 239
            $backend = new Backend();
            $response = $backend->configdpRun("ids query alerts", array($itemsPerPage,
240
                ($currentPage-1)*$itemsPerPage, $searchPhrase,$fileid));
241 242 243 244 245 246 247 248 249 250
            $result = json_decode($response, true);
            if ($result != null) {
                $result['rowCount'] = count($result['rows']);
                $result['total'] = $result['total_rows'];
                $result['current'] = (int)$currentPage;
                return $result;
            }
        }
        return array();
    }
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269

    /**
     * fetch alert detailed info
     * @param $alertId alert id, position in log file
     * @return array alert info
     */
    public function getAlertInfoAction($alertId)
    {
        $backend = new Backend();
        $filter = new Filter();
        $id = $filter->sanitize($alertId, "int");
        $response = $backend->configdpRun("ids query alerts", array(1, 0, "filepos/".$id));
        $result = json_decode($response, true);
        if ($result != null && count($result['rows']) > 0) {
            return $result['rows'][0];
        } else {
            return array();
        }
    }
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

    /**
     * list all available logs
     * @return array list of alert logs
     * @throws \Exception
     */
    public function getAlertLogsAction()
    {
        $backend = new Backend();
        $response = $backend->configdRun("ids list alertlogs");
        $result = json_decode($response, true);
        if ($result != null) {
            $logs = array();
            foreach ($result as $log) {
                $log['modified'] = date('Y/m/d G:i', $log['modified']);
                $logs[] = $log;
            }
            return $logs;
        } else {
            return array();
        }
    }
292
}