Hacker writes Haka-Part 1

Source: Internet
Author: User
Tags kibana

Hacker writes Haka-Part 1

Haka is an open-source network security-oriented language that can be used to write security rules and Protocol delimiters. In this section, we focus on writing security rules.

0x00 what is Haka

Haka is an open-source network security-oriented language that allows you to specify and apply security policies on captured activity traffic. Haka is based on Lua. This is simple and lightweight (~ 200 kB) and fast (with an available JiT compiler) scripting language.

Haka can be used in two ways. First, Haka allows specified security rules to filter unwanted streams and report malicious activities. Haka provides a simple API for operating advanced data packets and streams. You can place data packets, create new data packets, and inject data packets. Haka also supports modifying running data packets. This is one of the main features of Haka, because users can see all the complex tasks, such as adjusting the packet size and setting the correct serial number. These are all completed on site and do not require agents at all.

Second, Haka also comes with a syntax that allows protocol specifications and underlying state machines. Haka supports two types of Protocols: Binary-based protocols (such as dns) and text-based protocols (such as http ). This specification includes packet-based protocols (such as ip addresses) and stream-based protocols (such as http ).

Haka is embedded in a modular framework, which includes several data packet capture modules (pcap and nfqueue), allowing end users to apply their own security policies on the traffic captured in real time, or reproduce the security policy on a data packet tracking file. This framework also provides the logging (syslog) and alarm module (syslog, elasticsearch ). Alarms follow an IDMED-like format. Finally, this framework also has ancillary modules, such as the pattern matching engine and a command disassembly module. These modules allow you to write precise security rules to detect obfuscated Trojans. Because Haka is designed as a module, you can use additional modules to expand its functions.

0x01 Haka tool suite

Haka provides a suite containing four tools:

Haka. This is the main program in the toolset. This is a daemon that monitors data packets in the background. Haka analyzes and filters these packets based on the specified security policy file. For example, the following configuration sample requires Haka to use the nfqueue module to capture data packets from the eth0 interface and filter these data packets using the policy file myrules. lua. This script usually loads user-defined or built-in protocol delimiters and defines a series of security rules. In addition, you can select the alarm and report modules and set some specific module options:

[general]# Select the haka configuration file to useconfiguration = "myrules.lua"# Optionally select the number of thread to use# By default, all system thread will be used#thread = 4[packet]# Select the capture model, nfqueue or pcapmodule = "packet/nfqueue"# Select the interfaces to listen to#interfaces = "any"interfaces = "eth0"# Select packet dumping for nfqueue#dump = yes#dump_input = "/tmp/input.pcap"#dump_output = "/tmp/output.pcap"[log]# Select the log modulemodule = "log/syslog"# Set the default logging level#level = "info,packet=debug"[alert]# Select the alert modulemodule = "alert/syslog"#module = "alert/file"#module = "alert/elasticsearch"# Disable alert on standard output#alert_on_stdout = no

Hakactl. This tool allows you to control a running Haka daemon. You can analyze captured data packets in real time, check logs, or simply shut down/restart the daemon process.

Hakapcap. This tool allows the pcap module to reproduce a policy file offline on the packet capture trace. For example, this method is useful for network analysis.

Hakabana. This tool allows you to use Kibana and Elasticsearch to visualize and monitor network traffic in real time. Hakabana consists of a series of custom security rules that push traffic information to an elastisserach server through Haka and allow the traffic to be obtained through the Kibana control panel. Another Control Panel can also visualize Haka alarms.

0x02 write security rules

Haka provides a simple way to write security rules to filter, modify, create, and inject packets and streams. When a malicious stream is detected, the user can report an alarm or discard the stream. You can define more complex solutions to cope with the impact of an attack. For example, you can trigger an http request to force the old browser to update or forge specific data packets to spoof the port scanning tool.

0x03 packet filtering

The following rule is a basic packet filtering rule that can intercept all connections to a certain network address.

local ipv4 = require("protocol/ipv4")local tcp = require("protocol/tcp_connection")  local net = ipv4.network("192.168.101.0/24")    haka.rule{    hook = tcp.events.new_connection,    eval = function (flow, pkt)        haka.log("tcp connection %s:%i -> %s:%i",            flow.srcip, flow.srcport,            flow.dstip, flow.dstport)           if net:contains(flow.dstip) then            haka.alert{                severity = "low",                description = "connection refused",                start_time = pkt.ip.raw.timestamp            }            flow:drop()        end    end}

The first line loads the required protocol delimiters, that is, ipv4 and tcp connection delimiters. The former is to process ipv4 packets. The latter is a stateful tcp strip, which maintains a connection table and manages tcp streams. The next line defines the network address that must be intercepted.

This security rule is defined by the haka. rule keyword. A security rule consists of a hook and an evaluation function eval. This hook is an event that triggers Security rule evaluation. In this example, this security rule is evaluated every time a tcp connection is created. Parameters passed to the evaluation function are determined based on the event. Taking the new_connection event as an example, eval obtains two parameters: flow and pkt. The first parameter contains detailed information about the connection, and the other parameter is a table containing all tcp (and lower-layer) packet fields.

In the core of security rules, we first record some information about the current connection (haka. log. Then, we checked whether the source address belongs to the previously defined range of unauthorized IP addresses. If the test succeeds, we will issue an alarm (haka. alert) and discard the connection. Note that we only report a small amount of details in the alert. You can add more information, such as source and target services.

We used the hakapcap tool to test our rule filter. lua in a pcap trace file filter. pcap:

$ hakapcap filter.lua filter.pcap

The output of Haka is shown below, and Haka dumps some information about the loaded detaching device and registered rules. The output shows that Haka successfully blocks the connection to the destination address 192.168.101.62:

In the above example, we have defined a separate rule to intercept connections. You can use the keyword haka. group to write a complete rule set similar to a firewall. Take this configuration as an example. If no security rule can authenticate traffic, you can select a default behavior (for example, intercept all connections ).

0x04 Packet Injection

In Haka, you can create and inject new data packets. The following rule creates an RST packet for spoofing Xmas nmap scanning. In the end, nmap considers all ports on the target end to be closed.

raw = require("protocol/raw")ipv4 = require("protocol/ipv4")tcp = require("protocol/tcp")haka.rule {    hook = tcp.events.receive_packet,    eval = function(pkt)        local flags = pkt.flags        -- test for xmas nmap scans        if flags.fin and flags.psh and flags.urg then            -- raw packet            local rstpkt = raw.create()            -- ip packet            rstpkt = ipv4.create(rstpkt)            rstpkt.ttl = pkt.ip.ttl            rstpkt.dst = pkt.ip.src            rstpkt.src = pkt.ip.dst            -- tcp packet            rstpkt = tcp.create(rstpkt)            rstpkt.srcport = pkt.dstport            rstpkt.dstport = pkt.srcport            rstpkt.flags.rst = true            rstpkt.flags.ack = true            rstpkt.ack_seq = pkt.seq + 1            -- inject forged packet and            -- drop malicious scanning packet            rstpkt:send()            pkt:drop()        end    end}
0x05 packet alerts

Packet modification is one of the most advanced features in Haka. Haka automatically processes all internal changes at the stream and data packet level: resets the data packet size and segment, resets the serial number, and so on. The example below demonstrates how easy it is to access and modify protocol fields. This rule modifies some http headers. More accurately, the user-agent header will be modified (if not set, added to the header list) and the accept-encoding header will be removed.

local http = require("protocol/http")http.install_tcp_rule(80)haka.rule{    hook = http.events.request,    eval = function (flow, request)        request.headers["User-Agent"] = "HAKA User Agent"        request.headers["Accept-Encoding"] = nil    end}

Blurring-the-web and inject_ponies are very interesting scripts. the requested web pages will be blurred and contaminated (injected with garbage) by modifying the http response traffic:

0x06 stream Filtering

Before explaining stream filtering, we should first explain how Haka manages packets and streams internally. In Haka, all data packets and streams are represented by virtual buffers (SEE. The virtual buffer zone is a unified view of non-adjacent memory blocks. These virtual buffers allow simple and effective modification of memory data. The virtual buffer uses a distributed list to represent non-adjacent data blocks, avoiding unnecessary memory blocks allocated and replicated. Haka provides an iterator to navigate through these memory blocks. These iterators can intercept and disable some functions. For example, when there is more available data in the stream, they can transparently restore the execution of these functions.

The following rules collect http streams and dump these streams on stdout. This rule is equivalent to the follow tcp stream function of Wireshark.

local ipv4 = require('protocol/ipv4')local tcp_connection = require('protocol/tcp_connection')haka.rule{    hook = tcp_connection.events.receive_data,        options = {            streamed = true        },    eval = function (flow, iter, dir)        local data = flow.ccdata or {}        flow.ccdata = data        while iter:wait() do            data[#data+1] = iter:sub('available'):asstring()        end        haka.log("%s -> %s:\n", flow.srcip, flow.dstip)        io.write(table.concat(data))     end}
0x07 interactive data packet filtering

This is my favorite Haka feature. This function allows you to check the traffic package of each data packet. The following rules prompt each http post request.

local http = require("protocol/http")http.install_tcp_rule(80)haka.rule {    hook = http.events.request_data,    eval = function (http, data)        haka.interactive_rule("interactive mode")(http, data)    end}haka.rule {    hook = http.events.request,    eval = function (http, request)        http:enable_data_modification()    end}

This shell can provide access to the complete Haka API to process packet content: read and write and modify packet fields, delete packets, record suspicious events, warnings, and so on. The Lua Control Panel supports Automatic completion. Therefore, it is a good start to go deep into the Haka API.

In the following data, Haka will crack the first POST request. HTTP data can be obtained through available input. In this example, the user creden。 are modified during running.

Note: It is best to use the interaction rules on the pcap file because the modification will cause extra delay.

0x08 advanced stream Filtering

Haka also has a pattern matching engine and some disassembly modules. Both modules are stream-based modules that allow us to detect malicious loads distributed across multiple data packets. The following rule uses a regular expression to detect nop sled. The stream option is enabled, that is, the matching function intercepts and waits for available data for matching. If nop sled is detected, we will issue a warning and dump the shellcode command. Note that the pattern matching function updates the iterator position and then points to shellcode.

local tcp = require("protocol/tcp_connection")local rem = require("regexp/pcre")local re = rem.re:compile("%x90{100,}")local asm = require("misc/asm")local dasm = asm.new_disassembler("x86", "32")haka.rule{    hook = tcp.events.receive_data,        options = {            streamed = true,    },    eval = function (flow, iter, direction)        if re:match(iter, false) then            -- raise an alert            haka.alert{                description = "nop sled detected",            }            -- dump instructions following nop sled            dasm:dump_instructions(iter)        end    end}

We replayed this rule in the famous network analysis challenge and got the following output. You can obtain detailed information about how to disassemble network traffic into commands.

To be continued...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.