Saturday, October 22, 2016

Dirty Cow (CVE-2016-5195)

Dirty Cow is a newly discovered, but already a decade aged,  vulnerability which is present in almost all Linux distributions including your likely favorite Kali Linux. 


It is referenced as CVE-2016-5195 and called Dirty Cow as it is a race condition was found in the way the Linux kernel's memory subsystem handled the copy-on-write (COW) breakage of private read-only memory mappings. An unprivileged local user could use this flaw to gain write access to otherwise read-only memory mappings and thus increase their privileges on the system.(RedHat)


Solution:


Depending on your distribution, I think this vulnerability must have been fixed already. I will mention how to overcome it only on the latest Ubuntu release 16.04/10 LTS (check the bug) where new packages are released and the easiest way to get them is to update your sources.list file

sudo apt-get update

and then upgrade:

sudo apt-get dist-upgrade

Reboot your system so that the changes take effect.

Tuesday, July 26, 2016

Beyond design patterns

I came this morning across this issue posted on StackOverflow. The OP tries to build up a simple Tkinter GUI.

What is both funny and interesting to highlight is that the simplicity of the goals to fulfill became unexpectedly a little bit tricky or even complicated to fix because the OP relies on the MVC and Observer -the later one being often consequently a key component of the former-

The problem in itself can be resolved in 6 quick dirty lines of code on the fly.  I am not here to tell you design patterns are worthless,  but as a general rule of thumb I learned from my own experience, do not use them unless if really needed otherwise you would, probably, uselessly stumble in struggling to comply to them instead of effectively trying to implement the solution to the actual problem. Put it bluntly: be pragmatic!

As I deeply believe that the way we program reflects our state of mind, emotions,  personality and daily life attitude, I think one must wonder on the rule mentioned above especially by those who tend quickly and blindly to follow the mainstream way of thinking, believing or behaving without daring to put ahead their self confidence to think about what matters on their own.

This attitude would lead you to bear your own stuff, to develop your own design pattern and thus express better who you are through  dozens of thousands of apparently boring lines of code.

Thursday, March 3, 2016

Printing data in MySQL format using Python


(I originally posted what follows as an answer to a question on StacOverflow that remained unanswered during 2 years)

The aim is is to have Python output that looks in MySQL format:

mysql> SHOW COLUMNS FROM begueradj FROM begueradj;
+-----------------+-------------+------+-----+---------+-------+
| Field           | Type        | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| Reg_exp         | varchar(20) | NO   |     | NULL    |       |
| Token           | varchar(20) | NO   |     | NULL    |       |
| Integer_code    | int(2)      | NO   |     | NULL    |       |
| Attribute_value | varchar(2)  | NO   |     | NULL    |       |
+-----------------+-------------+------+-----+---------+-------+

It is good to see the world as a set of objects, so my solution will be done in a class where we need to save the connexion parameters to MySQL server within a Python dictionary in the class consutructor  __init__(self):

self.config = { 'user':'begueradj',
                'passwd':'begueradj',
                'host':'127.0.0.1',
                'db':'begueradj',
               }
 
Of course, one needs to change these parameters to his ones.
Of course, trying to do a hack by yourself is not necessarily the best idea. For my solution, I opted for the use of texttable which you can install by:
  • First download the compressed module.
  • Uncompress the file and change the directory to it.
  • Finally, type this command: sudo python setup.py install
After executing the MySQL query (self.sqlquery = """SELECT * FROM begueradj"""), you will need the MySQLCursor.description Property to get the columns' names in a tuple format:
# Get columns' names
self.columns = [i[0] for i in self.cursor.description]
Note that is useful to transform the tuples to lists as texttable module works on lists.

Python program:

I commented almost each line of my program solution below:
'''
Created on Mar 3, 2016

@author: begueradj
'''
import MySQLdb
import texttable

class Begueradj:
    """ Display MySQL table's content along with
    table's columns name as in pure MySQL format.
    """
    def __init__(self):
        """ Initialize MySQL server login parameters.
        Try to connect to communicate with MySQL database.
        """
        self.config = {'user':'begueradj',
                       'passwd':'begueradj',
                       'host':'127.0.0.1',
                       'db':'begueradj',
                       }
        # Try to log to MySQL server
        try:
            self.dbconnexion = MySQLdb.connect(**self.config)
        except MySQLdb.Error:
            print "Database connexion failure!"

        # Read the content of the MySQL table
        self.sqlquery = """SELECT * FROM beg"""

    def begueradj(self):
        """ Display MySQL table data.
        """
        self.cursor = self.dbconnexion.cursor()
        self.cursor.execute(self.sqlquery)

        # Get columns' names
        self.columns = [i[0] for i in self.cursor.description]

        self.tab = texttable.Texttable()
        self.tablerow = [[]]

       # Fetch all the rows from the query
        self.data = self.cursor.fetchall()

        # Must transform each tuple row to a list
        for r in self.data:
            self.tablerow.append(list(r))

        # Get the number of columns of the table
        self.tab.add_rows(self.tablerow)
        # Align displayed data within cells to left
        self.tab.set_cols_align(['l','l','l','l'])
        # Once again, convert each tuple  row to a list
        self.tab.header(list(self.columns))
        # Display the table (finally)
        print self.tab.draw()

        # Don't forget to close the connexion.
        self.dbconnexion.close()

# Main program
if __name__=="__main__":
    b=Begueradj()
    b.begueradj()

Demo:

enter image description here

Saturday, January 23, 2016

Simple Java persistence application for beginners (JEE, Spring MVC, Maven)

I posted  a very simple application on GitHub to help JEE beginners to grasp the main concepts of Java persistence by highlighting how to manipulate some basic operations. The application is in its version 1.0 but I am not planning to enrich it as it is not that important for me.

Link: https://github.com/begueradj/JPAlibSpringMVC

Wednesday, November 11, 2015

Numba installation and settings on Ubuntu 14.04 LTS

I followed pointlessly quite a lot of documentation to install and set correctly Numba on Ubuntu 14.04 LTS. So I want to share the solution I did to get function finally:

Installation:
sudo apt-get install zlib1g zlib1g-dev 
sudo apt-get install libedit libedit-dev 
sudo apt-get install llvm-3.5 llvm-3.5-dev llvm-dev
pip install enum34
pip install funcsigs
Important settings:

LLVM_CONFIG=/usr/bin/llvm-config-3.5 pip install llvmlite
LLVM_CONFIG=/usr/bin/llvm-config-3.5 pip install numba

Thursday, November 5, 2015

JavaScript malware detection techniques

(I previously published this article as an answer to a question posted on Information Security website under a profile I deleted)


First, we need to dive into the methods commonly used by JS malware:

  1. Server side polymorphism
Literally meaning many shapes, polymorphism is a technique used by malware authors to evade signatures based detectors. Polymorphism is qualified as being server sided when the engine which produces several but different copies of the malware is hosted on a compromised web server (Server-Side Polymorphism: Crime-Ware as a Service Model (CaaS)). simulated metamorphic encryption generator (SMEG) version 1.0 was the first engine developed to implement the notion of polymorphism for computer viruses on the early 1990's (Parallel analysis of polymorphic viral code using automated deduction system)

  1. Code obfuscation
The other common feature you may find in malicious JavaScript code is that obfuscation is always used. This common factor -obfuscation- does not make even things simpler: because innocuous JavaScript code also uses obfuscation (for instance, some developers for example do not want their personal pretty JavaScript function to be understood by others as you can easily read HTML and JS pages codes). Along with server side polymorphism, code obfuscation is a widely used technique by malware authors to circumvent antivirus scanners. A myriad of techniques could be used to obfuscate JavaScript codes such as string reversing, Unicode and base 64 encoding, string splitting and document object model (DOM) interaction (Malware with your Mocha? Obfuscation and anti­-emulation tricks in malicious JavaScript.).
  1. Code unfolding
Code unfolding is the mechanism with which a new code is introduced at run time. In JavaScript, this is made concrete by invoking functions like document.write() and eval() in order to execute obfuscated portions of code and functions. (Weaknesses in Defenses Against Web-Borne Malware)
  1. Heap spray
This attack targets mainly web browsers. The user controllable data can corrupt the heap by a remote execution code if the miscreant has compromised the user's computer to the point he can have access to this vulnerable memory area (BuBBle: A Javascript Engine Level Countermeasure against Heap-Spraying Attacks)
  1. Drive-by download
Drive-by download attacks consist in downloading and and executing or installing malicious programs without the user's consent. Such attacks occur by exploiting browsers' vulnerabilities, their add-ons or plugins such as ActiveX controls or unpatched useful software such as Acrobat Reader and Adobe Flash Player (Drive-by download attacjs: effect and detection methods, MSc Information Security)

  1. Multi execution paths
It is possible to trigger an action only if certain conditions are fulfilled. Such circumstances could be the arrival of a given date or the existence of a file on the system on which the malware is intended to be executed. An other quick and well known example could be a denial of service attack that must be fired only if the number of the botnet's nodes has reached a certain value. That is the notion of multi execution paths (Exploring Multiple Execution Paths for Malware Analysis)
  1. Implicit conditionals
This technique is mainly used against dynamic approach detectors. The main idea for this process is to execute a set of instructions by hiding the condition that fires it (Weaknesses in Defenses Against Web-Borne. Malware)
Given these common features and tactics used by JaaScript malware, if you want to detect this type of malware as you asked, you need first to study the state of the art of the methods used to detect that. Various methods have been developed so as to detect web (JavaScript) malware. We can divide them into two main categories as follows:
  1. Machine learning based classifiers
    • Features: HTML and JavaScript codes distinguishing features extraction. These features are then evaluated to train a machine learning for classifier generation. The premise of this approach is that malicious webpages are likely to be different from benign ones (Thesis: Effective Analysis, Characterization, and Detection of Malicious Web Pages)
    • Advantages: Lightweight approach, useful to deal with a bulk of websites analysis.
    • Drawbacks: Obsolete against obfuscated JavaScript code and totally useless against new malicious code patters or zero attacks.

  2. Dynamic methods
    • Features: Based on the dynamic behavior analysis, these techniques are implemented using either proxies where a page is rendered to the visitor only after its safety is checked, or a sandboxing environment relying on honeyclients (Same thesis: Effective Analysis, Characterization, and Detection of Malicious Web Pages).
    • Advantages: Efficient against zero day attacks and obfuscated code.
    • Drawbacks: Resources and time consuming. Sandboxing environments rely on low interaction honeyclients which themselves are based on virus signatures, and thus suffer from the same disadvantages as the static methods' ones.
  3.  

What you have tried to do belongs to the first category.

Now, after you are well informed about all this, it can be useful for you to study some available tools dedicated for this purpose in order to implement your own technique. So let me mention you three important tools among so many others:

  1. Zozzle
Zoozle relies on Bayesian classification abstract syntax tree (AST) . It is legitimately classified as mostly static web malware detector because it embeds another engine that supervises the JavaScript code execution at run time. Its authors claim that it has a very low false positive rate of 0.0003% and is able to process over one megabyte of HTML and JavaScript code per second. This tool is intended to be used as a browser plugin; its aim is to protect browsers against heap spray attack. It is time to point out how ZOZZLE operates.
How ZOZZLE operates? The following figure summarizes its core (ZOZZLE: Fast and Precise In-Browser JavaScript Malware Detection):
enter image description here
  • Extraction and labeling phase: The classifier needs training data. This data is extracted from obfuscated JavaScript code. Instead of developing an efficient de-obfuscation technique, Compile function interception calls is performed. Compile function is located in jscript.dll library. It is a smart way to obtain plain JavaScript code because it is called each time <SCRIPT> and <IFRAME> tags, or eval() and document.write() functions have been called, which thing defines also the code context. Each code context is saved on the hard drive for further analysis.
  • Feature selection: JavaScript AST is used to tag each labeled context code for its safety or malignancy. The features are pre-selected using this formula: enter image description here
Where:
  • A: malicious context with feature
  • B: benign context with feature
  • C: malicious context without feature
  • D: benign context without feature
  • Classification: The Bayesian classifier is used for classification because even if it seems obsolete, in practice it gives good results and it is not time consuming.
    1. Profiler Profiler follows the static schema to detect web malware. It combines static features analysis of HTML and JavaScript code, including unified resource locator (URL)s. Then it uses machine learning techniques to teach a classifier that decides if a webpage embeds malicious content or not. Suspicious webpages are not processed by this tool. It rather forwards them to third party technologies such as Wepawet (Prophiler: A Fast Filter for the Large-Scale Detection of Malicious Web Pages)
    2. SpyProxy
SpyProxy follows the dynamic analysis principles. It monitors the active content of webpages within a virtual machine before deciding to render them to the visitor or not. The architecture of SpyProxy is illustrated through this figure (SpyProxy: Execution-based Detection of Malicious Web Content):
enter image description here
  • (a): The proxy performs a static analysis over the requested page. In the case it judges is likely to be malicious, if forwards it to the virtual machine. basically only pages with active content are forwarded to the virtual machine (VM).
  • (b): The virtual machine loads the malicious pages to monitor their activities.
  • (c): Only benign pages are rendered back to the proxy which forwards them in turn to the user's browser.
    1. Iceshield
ICESHIELD performs in-line dynamic code analysis using a set of heuristics to verify attack attempts. Its authors take an inventory of the attacks that usually target the DOM properties of a website that are performed by injecting JavaScript into the website's source code. ICESHIELD supervises the running JavaScript code by predefining a set of rules related to functions calls and applying heuristics on them in the hope to determinate whether the script is malicious or not (IceShield: Detection and Mitigation of Malicious Websites with a Frozen DOM).