<?php
header('Cache-Control: no-store');

// Includes
include_once("include/create_session.php");
include_once("include/config.php");
include_once("include/opendb.php");
include_once("include/functions.php");

$rule_name = '';
if(isset($_GET['rule_name'])) {
  if(preg_match("/^[A-Za-z0-9\_]*$/", $_GET['rule_name'])) {
    $rule_name = $_GET['rule_name'];
  }
}

// Generate last moddified
if($rule_name){
  $res = mysqli_query($conn, "SELECT UNIX_TIMESTAMP(MAX(f.first_seen)) AS lm FROM tbl_files AS f INNER JOIN tbl_procdumps_yara AS z ON z.fk_sha256_hash = f.sha256_hash WHERE fp = '0' AND rule_name = '".validateinput($rule_name)."'");
  $res = mysqli_fetch_array($res, MYSQLI_ASSOC);
  if(!empty($res['lm'])) {
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $res['lm']).' GMT');
  }
}
?>
<!doctype html>
<html lang="en" prefix="og: http://ogp.me/ns#">
  <head>
    <meta charset="utf-8">
    <meta name="robots" content="all" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <?php
    if($rule_name) {
        echo "<link rel=\"canonical\" href=\"https://bazaar.abuse.ch/browse/yara/$rule_name/\" />\n";
        echo "    <title>MalwareBazaar | $rule_name (YARA rule)</title>\n";
        echo "    <meta name=\"description\" content=\"Malware samples matching YARA rule $rule_name\" />\n";
        echo "    <meta name=\"keywords\" content=\"malware, sample, binaries, binary, download, hash, YARA, rule $rule_name\" />\n";
        ?>
        <!-- Twitter Card -->
        <meta name="twitter:card" content="summary">
        <meta name="twitter:title" content="MalwareBazaar - YARA hunting">
        <meta name="twitter:description" content="Hunt for malware samples matching the following YARA rule: <?php echo $rule_name; ?>">
        <meta name="twitter:url" content="https://bazaar.abuse.ch/browse/yara/<?php echo $rule_name; ?>/">
        <meta name="twitter:image" content="https://bazaar.abuse.ch/images/abusech_twitter.png">
        <?php
    }
    else {
      echo "<title>MalwareBazaar | Browse</title>\n";
    }
    ?>
    <link rel="icon" href="/favicon.ico">
    <!-- Bootstrap core CSS -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome CSS -->
    <link href="/css/all.min.css" rel="stylesheet">
    <!-- Datatables CSS -->
    <link href="/css/datatables.min.css" rel="stylesheet">
    <!-- Custom styles -->
    <link href="/css/jumbotron.css" rel="stylesheet">
    <link href="/css/custom.css" rel="stylesheet">
    <!-- Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-5GQV3CJ17N"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-5GQV3CJ17N');
    </script>
  </head>

  <body>
    <header class="fixed-top">
      <nav class="navbar navbar-expand-md navbar-dark bg-grey">
        <div class="container">
          <a class="navbar-brand" href="/">
            <img src="/images/malwarebazaar_logo.svg" style="height: 50px" alt="MalwareBazaar">
          </a>
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarsExampleDefault">
            <ul class="navbar-nav ml-auto">
              <li class="nav-item active">
                <a class="nav-link" href="/browse/" title="Browse MalwareBazaar database"><i class="fa fa-fw fa-search"></i> Browse</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="/upload/" title="Upload a malware sample"><i class="fas fa-fw fa-cloud-upload-alt"></i> Upload</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="/hunting/" title="Live Hunting Alerts"><i class="far fa-bell"></i> Hunting Alerts</a>
              </li>
              <li class="nav-item dropdown">
                 <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                   <i class="fas fa-database"></i> Access Data
                 </a>
                 <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                   <a class="dropdown-item" href="/api/" title="API"><i class="fa fa-fw fa-code"></i> API</a>
                   <a class="dropdown-item" href="/export/" title="Export"><i class="fas fa-file-export"></i> Export</a>
                 </div>
              </li>
            <li class="nav-item dropdown">
               <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                 <i class="fab fa-readme"></i> Resources
               </a>
               <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                 <a class="dropdown-item" href="/about/" title="About"><i class="fa fa-fw fa-archway"></i> About</a>
                 <a class="dropdown-item" href="https://community.abuse.ch/?platform=malwarebazaar#leaderboard" title="Community Hubs"><i class="fas fa-users"></i> Community Hub</a>
                 <a class="dropdown-item" href="/statistics/" title="Statistics"><i class="fa fa-fw fa-chart-pie"></i> Statistics</a>
                 <a class="dropdown-item" href="/faq/" title="FAQ"><i class="fas fa-question-circle"></i> FAQ</a>
               </div>
            </li>
              <?php
              user_info();
              ?>
            </ul>
          </div>
        </div>
      </nav>
    </header>

    <!-- breadcrumb -->
    <div class="container">
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="/browse/">Browse</a></li>
          <li class="breadcrumb-item active" aria-current="page">YARA Rule</li>
        </ol>
      </nav>
    </div>

    <!-- Main content -->
    <main class="container">
      <h1 class="mt-5">MalwareBazaar Database</h1>
      <?php
      if($rule_name) {
        // Check if rule_name exists
        $res = mysqli_query($conn, "SELECT rule_name, author, description, (SELECT MIN(first_seen) FROM tbl_files AS f INNER JOIN tbl_procdumps_yara AS y ON y.fk_sha256_hash = f.sha256_hash WHERE y.rule_name = '".validateinput($rule_name)."' LIMIT 1) AS fs, (SELECT MAX(first_seen) FROM tbl_files AS f INNER JOIN tbl_procdumps_yara AS y ON y.fk_sha256_hash = f.sha256_hash WHERE y.rule_name = '".validateinput($rule_name)."' LIMIT 1) AS ls FROM tbl_files AS f INNER JOIN tbl_procdumps_yara AS y ON y.fk_sha256_hash = f.sha256_hash WHERE y.rule_name = '".validateinput($rule_name)."' AND fp = '0' LIMIT 1");
        if(mysqli_num_rows($res)) {
          $row = mysqli_fetch_array($res);
          if($row['ls'] != $row['fs']) {
            $last_seen = $row['ls']. " UTC";
          }
          else {
            $last_seen = 'never';
          }
          $cnt = mysqli_query($conn, "SELECT count(distinct(fk_sha256_hash)) AS sample_cnt FROM tbl_procdumps_yara WHERE rule_name = '".validateinput($rule_name)."'");
          $cnt = mysqli_fetch_array($cnt);
          ?>
          <p>This page shows some basic information the YARA rule <code><?php echo $rule_name; ?></code> including corresponding malware samples.</p>
          <h2>Database Entry</h2>
          <hr>
          <table class="table table-sm table-bordered">
            <tbody>
              <tr class="table-success"><th scope="row">YARA Rule:</th><td><?php echo $rule_name; ?> <div class="btn-group"><button class="btn btn-secondary btn-xs dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="far fa-bell"></i> Alert</button><div class="dropdown-menu"><a class="dropdown-item" href="/hunting/yara/<?php echo $rule_name; ?>/"><i class="fas fa-cat"></i> Create hunting rule</a></div></div></td></tr>
              <?php
              if($row['author']) {
              ?>
              <tr><th scope="row">Author:</th><td><?php echo $row['author']; ?></td></tr>
              <?php
              }
              ?>
              <?php
              if($row['description']) {
              ?>
              <tr><th scope="row">Description:</th><td><?php echo $row['description']; ?></td></tr>
              <?php
              }
              ?>
              <tr><th scope="row">Firstseen:</th><td><?php echo $row['fs']; ?> UTC</td></tr>
              <tr><th scope="row">Lastseen:</th><td><?php echo $last_seen; ?></td></tr>
              <tr><th scope="row">Sightings:</th><td><?php echo number_format($cnt['sample_cnt'],0,'',"'"); ?></td></tr>
            </tbody>
          </table>

          <div style="height: 200px">
        		<canvas id="yarachart"></canvas>
        	</div>

          <h2>Malware Samples</h2>
          <hr>
          <p>The table below shows all malware samples that matching this particular YARA rule (<strong>max 1000</strong>).</p>
          <table id="yara_table" class="table table-sm table-hover table-bordered">
            <thead>
              <tr><th>Firstseen (UTC)</th><th>SHA256 hash</th><th>Tags</th><th>Signature</th><th>Reporter</th></tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        <?php
        }
        else {
          ?>
          <div class="alert alert-primary" role="alert">
            No records found
          </div>
          <?php
        }
      }
      else {
      ?>
      <div class="alert alert-primary" role="alert">
        No records found
      </div>
      <?php
      }
      ?>
    </main>

    <!-- Footer -->
    <footer class="footer">
      <div class="content-container">
        <div class="d-block d-md-flex align-items-center">
          <div class="d-flex gap-4 social-links">
            <a href="https://x.com/abuse_ch" rel="noopener" target="_blank">
              <svg
                height="24"
                width="24"
                fill="white"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 512 512"
              >
                <path
                  d="M389.2 48h70.6L305.6 224.2 487 464H345L233.7 318.6 106.5 464H35.8L200.7 275.5 26.8 48H172.4L272.9 180.9 389.2 48zM364.4 421.8h39.1L151.1 88h-42L364.4 421.8z"
                />
              </svg>
            </a>
            <a
              href="https://www.linkedin.com/company/abuse-ch/"
              rel="noopener"
              target="_blank"
            >
              <svg
                height="24"
                width="24"
                fill="white"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 448 512"
              >
                <path
                  d="M416 32H31.9C14.3 32 0 46.5 0 64.3v383.4C0 465.5 14.3 480 31.9 480H416c17.6 0 32-14.5 32-32.3V64.3c0-17.8-14.4-32.3-32-32.3zM135.4 416H69V202.2h66.5V416zm-33.2-243c-21.3 0-38.5-17.3-38.5-38.5S80.9 96 102.2 96c21.2 0 38.5 17.3 38.5 38.5 0 21.3-17.2 38.5-38.5 38.5zm282.1 243h-66.4V312c0-24.8-.5-56.7-34.5-56.7-34.6 0-39.9 27-39.9 54.9V416h-66.4V202.2h63.7v29.2h.9c8.9-16.8 30.6-34.5 62.9-34.5 67.2 0 79.7 44.3 79.7 101.9V416z"
                />
              </svg>
            </a>
            <a href="https://ioc.exchange/@abuse_ch" rel="noopener" target="_blank">
              <svg
                height="24"
                width="24"
                fill="white"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 448 512"
              >
                <path
                  d="M433 179.1c0-97.2-63.7-125.7-63.7-125.7-62.5-28.7-228.6-28.4-290.5 0 0 0-63.7 28.5-63.7 125.7 0 115.7-6.6 259.4 105.6 289.1 40.5 10.7 75.3 13 103.3 11.4 50.8-2.8 79.3-18.1 79.3-18.1l-1.7-36.9s-36.3 11.4-77.1 10.1c-40.4-1.4-83-4.4-89.6-54a102.5 102.5 0 0 1 -.9-13.9c85.6 20.9 158.7 9.1 178.8 6.7 56.1-6.7 105-41.3 111.2-72.9 9.8-49.8 9-121.5 9-121.5zm-75.1 125.2h-46.6v-114.2c0-49.7-64-51.6-64 6.9v62.5h-46.3V197c0-58.5-64-56.6-64-6.9v114.2H90.2c0-122.1-5.2-147.9 18.4-175 25.9-28.9 79.8-30.8 103.8 6.1l11.6 19.5 11.6-19.5c24.1-37.1 78.1-34.8 103.8-6.1 23.7 27.3 18.4 53 18.4 175z"
                />
              </svg>
            </a>
            <a
              href="https://bsky.app/profile/abuse-ch.bsky.social"
              rel="noopener"
              target="_blank"
            >
              <svg
                height="24"
                width="24"
                fill="white"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 512 512"
              >
                <path
                  d="M111.8 62.2C170.2 105.9 233 194.7 256 242.4c23-47.6 85.8-136.4 144.2-180.2c42.1-31.6 110.3-56 110.3 21.8c0 15.5-8.9 130.5-14.1 149.2C478.2 298 412 314.6 353.1 304.5c102.9 17.5 129.1 75.5 72.5 133.5c-107.4 110.2-154.3-27.6-166.3-62.9l0 0c-1.7-4.9-2.6-7.8-3.3-7.8s-1.6 3-3.3 7.8l0 0c-12 35.3-59 173.1-166.3 62.9c-56.5-58-30.4-116 72.5-133.5C100 314.6 33.8 298 15.7 233.1C10.4 214.4 1.5 99.4 1.5 83.9c0-77.8 68.2-53.4 110.3-21.8z"
                />
              </svg>
            </a>
          </div>
          <div class="footer-policies md:flex-row col">
            <a href="https://abuse.ch/terms-and-conditions/" class="nav-link-w">Terms and Conditions</a>
            <span class="d-md-block d-none">|</span>
            <a href="https://abuse.ch/terms-of-use/" class="nav-link-w">Terms of Use</a>
            <span class="d-md-block d-none">|</span>
            <a href="https://abuse.ch/privacy-policy/" class="nav-link-w">Privacy Policy</a>
            <span class="d-md-block d-none">|</span>
            <a href="https://abuse.ch/cookie-policy/" class="nav-link-w">Cookie Policy</a>
          </div>
        </div>
      </div>
    </footer>
    <!-- JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="/js/jquery-3.5.1.min.js"></script>
    <script src="/js/popper.min.js"></script>
    <script src="/js/bootstrap.min.js"></script>
    <script src="/js/clipboard.min.js"></script>
    <script src="/js/Chart.bundle.min.js"></script>
    <script src="/js/bazaar_charts.js"></script>
    <script src="/js/datatables.min.js"></script>
    <!-- Initialize datatables -->
    <script>
    $(document).ready(function() {
        $('#yara_table').DataTable( {
          "order": [[ 0, "desc" ]],
          "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
          "pageLength": 50,
          "ajax": {
            "url": '/ajax/',
            "type": "POST",
            "data": {
              "query": "yara",
              "rule_name": "<?php echo $rule_name; ?>"
            }
          },
          "columns": [
            { "data": "first_seen" },
            { "data": "sha256_hash" },
            { "data": "tags" },
            { "data": "signature" },
            { "data": "reporter" },
          ]
        } );
    } );
    </script>
    <!-- Initialize ClipboardJS -->
    <script>
      var clipboard = new ClipboardJS('.clipboard');

      clipboard.on('success', function(e) {
        e.clearSelection();
      });
    </script>
    <script>
    var ctx = document.getElementById('yarachart').getContext('2d');
    var myChart = new Chart(ctx, {

        type: 'line',
        data: {
            datasets: [{
              label: '# of malware samples',
              backgroundColor: '#2980B9'
            }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true,
                      precision:0
                  }
              }]
          }
        }
    });
    GetChartDataYara('<?php echo $rule_name; ?>');
    </script>
  </body>
</html>
