Quantcast
Channel: Security Tools – Security List Network™
Viewing all 443 articles
Browse latest View live

mod_wallz and Web-Firewall Released.

$
0
0

mod_wallz is a : Apache mod to mitigate Layer 7 DDoS attacks.
Web-Firewall is a The firewall project for mitigating HTTP Layer 7 DDoS attack through PHP.
Php Script for web-Firewall:

<?php
/* Layer 7 HTTP GET DDoS protection script */
/* Prerequisites: iptables, PHP, Apache, openssl */
	$CFAK = "scrubbed"; // Cloudflare API Key
	$CFEMAIL= "scrubbed"; // Cloudflare Email
	$TTL = 3600; //Time in seconds for channelge TTL 1 hour is default
	if(empty($_SERVER['HTTP_CF_IPCOUNTRY'])){
		$CLOUDFLARE= false;
	}else{
		$CLOUDFLARE= true;
	}
	function ban($ip){
		global $CFAK, $CFEMAIL, $CLOUDFLARE;
		if(!$CLOUDFLARE){return false;}
		$url = 'https://www.cloudflare.com/api_json.html';
		$f = array(
			'a' => "ban",
			'tkn' => $CFAK,
			'email' => $CFEMAIL,
			"key" => $ip
		);
		$f = array_merge($p,$f);
		foreach($f as $k=>$v) { $fs .= $k.'='.$v.'&'; }
		rtrim($fs, '&');
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL, $url);
		curl_setopt($ch,CURLOPT_POST, count($f));
		curl_setopt($ch,CURLOPT_POSTFIELDS, $fs);
		$r = curl_exec($ch);
		curl_close($ch);
		return $r;
	}
	function kill($m=1){
		ban($_SERVER['REMOTE_ADDR']);
		header("HTTP/1.0 403 Forbidden");
		echo "You have been denied.";
		die();
	}
	function checkLegit(){
		echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><script>
				function getCookie(cname) {
			var name = cname + "=";
			var ca = document.cookie.split(";");
			for (var i = 0; i < ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0) == " ") c = c.substring(1);
				if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
			}
			return "";
		}
		$.get("'.$_SERVER['PHP_SELF'].'?_wf=" & getCookie("wf_ini"), function (d) {
			$("#token").html(d);
			$.get("'.$_SERVER['PHP_SELF'].'?_wf_ACK=" & $("#token").html(), function (r) {
			if(r == "Ok"){
				alert("Press Ok to continue...");
				location.reload();
			}else{
				$("#token").html("Failed bot challenge......");
            }
			});
		});
		</script><div id="tkn_hdr">Token:</div><div id="token">[Nothing]</div>';
		$CID = substr(bin2hex(openssl_random_pseudo_bytes(192)), 1, 32);
		setcookie("wf_ini",$CID.time(),time()+10);
		file_put_contents("/tmp/_wf.id",$_SERVER['REMOTE_ADDR']."&".$CID.time()+10 ."\n",FILE_APPEND);
		die();
	}
	function verCookie(){
		$va = explode(":",explode("\n",file_get_contents("/tmp/_wf.wl")));
		if(in_array($_SERVER['REMOTE_ADDR'].":".htmlspecialchars_decode($_COOKIE['wf_twl']),$va[0].":".$va[1])){
			return true;
		}elseif(in_array(htmlspecialchars_decode($_COOKIE['wf_twl']),explode(":",explode("\n",file_get_contents("/tmp/_wf.wl")))[1])){
			setcookie("wf_twl",'',1);
			echo "Different-origin violation. This incidence has been forgiven.";
			die();
		}else{
			setcookie("wf_twl",'',1);
			ban($_SERVER['REMOTE_ADDR']);
			die();
		}
	}
	function setwfCookie(){
		$CID = substr(bin2hex(openssl_random_pseudo_bytes(192)), 1, 32);
		setcookie("wf_twl",$CID,$time+$TTL);
		file_put_contents("/tmp/_wf.wl",$_SERVER['REMOTE_ADDR'].":".$CID.":".time());
	}
	setwfCookie();
	echo var_dump(verCookie());

install.sh Script:

#!/bin/bash
echo "Beta code-upload means unless you know how to re-make this installation script, you won't be able to install this."
## THIS REPO IS CURRENTLY USED TO BACKUP MY CODE, NOT PUBLISHING.
## MAN, do not install this for now, this is highly likely to ruin your server (and your day) since its still pretty much Pre-Alpha, it's not even working.
## Alternatively, if you want to fuck your server up, uncomment the line below.
#apxs -i -a -c mod_wallz.c

wallz.conf Script:

LoadModule wallz_module modules/mod_wallz.so
<IfModule mod_wallz.c>
# Nullis in derpis
</IfModule>

mod_wallz.c Script :

#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_request.h"
module AP_MODULE_DECLARE_DATA   wallz_module =
{ 
    STANDARD20_MODULE_STUFF,
    create_dir_conf,
    merge_dir_conf,
    create_svr_conf,
    merge_svr_conf,
    directives,
    register_hooks
};
LoadModule wallz_module modules/mod_wallz.so

Source : https://github.com/LolDatSec


RemoteWriteMonitor – A tool to help malware analysts tell that the sample is injecting code into other process.

$
0
0

RemoteWriteMonitor is a tool to help malware analysts tell that the sample is injecting code to another process. This tool is designed to find a possible remote code injection and execution without use of NtCreateThread/Ex(), APC or thread context manipulation.

Output on DebugView would look like this:

Output on DebugView would look like this:

Supported Platform(s) :
– Windows 7 SP1 and 8.1 (x86/x64)

Latest version v-1.2:
– Use default certificate
– Fixed build config error on the Win8.1 x64 target

Usage:
Once you have installed it, you may execute the sample and see output from the driver if any.
The driver reports when any process newly created after the installation called NtWriteVirtualMemory() or NtMapViewOfSection() against another process and saves what was written or mapped into the remote process. Output can be seen with DebugView and are all saved under the C:\Windows\RemoteWriteMonitor\ directory. Written and mapped data is stored as <SHA1>.bin apart from a log file.
‘injector’ could be used to test the driver’s function. Injecting and executing code into notepad.exe can be done by the following commands:

>notepad && tasklist | findstr notepad
notepad.exe                   3368 Console                    1      4,564 K

>injector 3368 section context
Remote Address   : 00180000
Waiting for the thread get executed.
Remote Thread ID : 1912

>injector 3368 alloc context
Remote Address   : 001B0000
Remote Thread ID : 2156

 

Caveats:
+ It reports all those API calls regardless of its memory protection, contents being written and whether it gets executed. Thus, you should only focus on output related to the sample you are analyzing as it reports a lot of legit activities too.
— It was designed so because it is far more difficult to track all written regions and reports only when it is executed.
+ It does not monitor any of processes existed when the driver was installed. Thus, the second injection will not be reported if the sample injects code into explorer.exe, and then the injected code in the explorer.exe injects code into another process.
+ Saved memory contents may or may not be the same as what was executed because the driver only takes dump at occurrence of those API calls. This is particularly true in the case of ZwMapViewOfSection().
— These are limitations but will be fine for letting analysts know injection may be happening.

Download :
Bin.zip (49.6 KB)
v1.2.zip
v1.2.tar.gz
Source :https://github.com/tandasat

Locker Decrypter – Python tool to decrypt files encrypted by Locker malware.

$
0
0

Locker is probably one of the worst malware which exists as of today. It is variant of Cryptolocker family of malware, and so called ransomware, which encrypts victim’s important files (such as photos and documents) based on file extension.
you might be aware the private key is used in the RSACryptoServiceProvider class .net and files are encrypted with AES-256 bit using the RijndaelManaged class.
This is the structure of the encrypted files:
– 32 bit integer, header length
– byte array, header (length is previous int)

*decrypt byte array using RSA & private key.
Decrypted byte array contains:
– 32 bit integer, IV length
– byte array, IV (length is in previous int)
– 32 bit integer, key length
– byte array, Key (length is in previous int)

Dependencies:
This tool requires Python 2 (tested with 2.7, Python 3 does not work as someone would need to port the rijndael.py).
+ untangle
+ pycrypto

How to decrypt my files with infected locker Malware:
First you have to dig either RSA public key or Bitcoin address from vitcim’s computer. The files containing relevant information typically reside in C:\ProgramData\rkcl directory.
+ data.aa0 – Contains list of encrypted files
+ data.aa6 – Contains the bitcoin address
+ data.aa7 – Contains the public key
Use either RSA public key or Bitcoin address to find the private key from the csv-file referred above and to save it to file private_key.xml:
Then run the tool in a directory where you want to decrypt your files:
The tool automatically tries to determine which of the files were actually encrypted and which were not.

lockerdecrypter.py ( Added Rijndael reference implementation and class to implement cryptoblock-chain) Script:

#!/usr/bin/env python

import untangle
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Util.number import bytes_to_long
from base64 import b64decode
import io
from struct import unpack
import sys
import os

from rijndael import rijndael
from cbc import zeropad, cbc


class DecryptError(Exception):
    pass


def decrypt_file(encrypted_filename, decrypted_filename, rsa_cipher):
    with open(encrypted_filename, 'rb') as encrypted_file:
        # Get the file size by seeking into end
        encrypted_file.seek(0, io.SEEK_END)
        file_size = encrypted_file.tell()

        # Some checks
        encrypted_file.seek(0)
        if 0 != encrypted_file.tell() or file_size < 4:
            raise DecryptError()

        header_size = unpack('I', encrypted_file.read(4))[0]
        
        if header_size > file_size:
            raise DecryptError()

        # Read and decrypt header
        header = encrypted_file.read(header_size)
        
        try:
            decrypted_header = cipher.decrypt(header)
        except:
            raise DecryptError()

        # Read initialization vector and key from header
        aes_iv_length = unpack('I', decrypted_header[0:4])[0]
        aes_iv_start = 4
        aes_iv = decrypted_header[aes_iv_start:aes_iv_start + aes_iv_length]
        aes_key_length_start = aes_iv_start + aes_iv_length
        aes_key_length = unpack('I', 
            decrypted_header[aes_key_length_start:aes_key_length_start + 4])[0]
        aes_key_start = aes_key_length_start + 4
        aes_key = decrypted_header[aes_key_start:aes_key_start + aes_key_length]

        # Read encrypted file into memory
        ciphertext = encrypted_file.read()

        # Initialize cipher and crypto-block-chain
        rjn_cipher = rijndael(aes_key, 32)
        padding = zeropad(32)
        cbc_cipher = cbc(padding, rjn_cipher, aes_iv)

        # Decrypt the file
        decrypted_ct = cbc_cipher.decrypt(ciphertext)

        with open(decrypted_filename, 'wb') as decrypted_file:
            decrypted_file.write(decrypted_ct)


def decrypt_directory(directory_to_decrypt, rsa_cipher):
    for root, dirs, filenames in os.walk(directory_to_decrypt):
        for filename in filenames:
            # Construct full filepath
            full_filepath = os.path.join(root, filename)
            full_filepath_decrypted = full_filepath + '.decrypted'

            # Do not try to decrypt symlinks
            if not os.path.islink(full_filepath):
                # Try to decrypt the file
                try:
                    decrypt_file(full_filepath, full_filepath_decrypted, rsa_cipher)
                    os.rename(full_filepath, full_filepath + '.orig')
                    os.rename(full_filepath_decrypted, full_filepath)
                    print(full_filepath + ' decrypted')
                except DecryptError:
                    print(full_filepath + ' could not decrypt')


if __name__ == "__main__":

    if len(sys.argv) < 3:
        sys.exit("Usage: %s <private_key.xml> <directory_to_decrypt>" % sys.argv[0])

    private_key_xml_filename = sys.argv[1]
    directory_to_decrypt = sys.argv[2]

    # Parse XML file containing private key components
    priv_key_dom = untangle.parse(private_key_xml_filename)

    # Get private key components from XML
    n = priv_key_dom.RSAKeyValue.Modulus.cdata
    e = priv_key_dom.RSAKeyValue.Exponent.cdata
    d = priv_key_dom.RSAKeyValue.D.cdata

    # Decode base64 RSA components and convert them from bytes to big integer
    rsa_components = tuple(map(bytes_to_long, map(b64decode, (n, e, d))))

    # Construct RSA Key object
    rsa_key = RSA.construct(rsa_components)

    # Construct new PCKS1_OAEP cipher using the RSA key
    cipher = PKCS1_OAEP.new(rsa_key)

    decrypt_directory(directory_to_decrypt, cipher)

rijndael.py Script :

"""
A pure python (slow) implementation of rijndael with a decent interface
To include -
from rijndael import rijndael
To do a key setup -
r = rijndael(key, block_size = 16)
key must be a string of length 16, 24, or 32
blocksize must be 16, 24, or 32. Default is 16
To use -
ciphertext = r.encrypt(plaintext)
plaintext = r.decrypt(ciphertext)
If any strings are of the wrong length a ValueError is thrown
"""

# ported from the Java reference code by Bram Cohen, April 2001
# this code is public domain, unless someone makes 
# an intellectual property claim against the reference 
# code, in which case it can be made public domain by 
# deleting all the comments and renaming all the variables

import copy
import string

shifts = [[[0, 0], [1, 3], [2, 2], [3, 1]],
          [[0, 0], [1, 5], [2, 4], [3, 3]],
          [[0, 0], [1, 7], [3, 5], [4, 4]]]

# [keysize][block_size]
num_rounds = {16: {16: 10, 24: 12, 32: 14}, 24: {16: 12, 24: 12, 32: 14}, 32: {16: 14, 24: 14, 32: 14}}

A = [[1, 1, 1, 1, 1, 0, 0, 0],
     [0, 1, 1, 1, 1, 1, 0, 0],
     [0, 0, 1, 1, 1, 1, 1, 0],
     [0, 0, 0, 1, 1, 1, 1, 1],
     [1, 0, 0, 0, 1, 1, 1, 1],
     [1, 1, 0, 0, 0, 1, 1, 1],
     [1, 1, 1, 0, 0, 0, 1, 1],
     [1, 1, 1, 1, 0, 0, 0, 1]]

# produce log and alog tables, needed for multiplying in the
# field GF(2^m) (generator = 3)
alog = [1]
for i in range(255):
    j = (alog[-1] << 1) ^ alog[-1]
    if j & 0x100 != 0:
        j ^= 0x11B
    alog.append(j)

log = [0] * 256
for i in range(1, 255):
    log[alog[i]] = i

# multiply two elements of GF(2^m)
def mul(a, b):
    if a == 0 or b == 0:
        return 0
    return alog[(log[a & 0xFF] + log[b & 0xFF]) % 255]

# substitution box based on F^{-1}(x)
box = [[0] * 8 for i in range(256)]
box[1][7] = 1
for i in range(2, 256):
    j = alog[255 - log[i]]
    for t in range(8):
        box[i][t] = (j >> (7 - t)) & 0x01

B = [0, 1, 1, 0, 0, 0, 1, 1]

# affine transform:  box[i] <- B + A*box[i]
cox = [[0] * 8 for i in range(256)]
for i in range(256):
    for t in range(8):
        cox[i][t] = B[t]
        for j in range(8):
            cox[i][t] ^= A[t][j] * box[i][j]

# S-boxes and inverse S-boxes
S =  [0] * 256
Si = [0] * 256
for i in range(256):
    S[i] = cox[i][0] << 7
    for t in range(1, 8):
        S[i] ^= cox[i][t] << (7-t)
    Si[S[i] & 0xFF] = i

# T-boxes
G = [[2, 1, 1, 3],
    [3, 2, 1, 1],
    [1, 3, 2, 1],
    [1, 1, 3, 2]]

AA = [[0] * 8 for i in range(4)]

for i in range(4):
    for j in range(4):
        AA[i][j] = G[i][j]
        AA[i][i+4] = 1

for i in range(4):
    pivot = AA[i][i]
    if pivot == 0:
        t = i + 1
        while AA[t][i] == 0 and t < 4:
            t += 1
            assert t != 4, 'G matrix must be invertible'
            for j in range(8):
                AA[i][j], AA[t][j] = AA[t][j], AA[i][j]
            pivot = AA[i][i]
    for j in range(8):
        if AA[i][j] != 0:
            AA[i][j] = alog[(255 + log[AA[i][j] & 0xFF] - log[pivot & 0xFF]) % 255]
    for t in range(4):
        if i != t:
            for j in range(i+1, 8):
                AA[t][j] ^= mul(AA[i][j], AA[t][i])
            AA[t][i] = 0

iG = [[0] * 4 for i in range(4)]

for i in range(4):
    for j in range(4):
        iG[i][j] = AA[i][j + 4]

def mul4(a, bs):
    if a == 0:
        return 0
    r = 0
    for b in bs:
        r <<= 8
        if b != 0:
            r = r | mul(a, b)
    return r

T1 = []
T2 = []
T3 = []
T4 = []
T5 = []
T6 = []
T7 = []
T8 = []
U1 = []
U2 = []
U3 = []
U4 = []

for t in range(256):
    s = S[t]
    T1.append(mul4(s, G[0]))
    T2.append(mul4(s, G[1]))
    T3.append(mul4(s, G[2]))
    T4.append(mul4(s, G[3]))

    s = Si[t]
    T5.append(mul4(s, iG[0]))
    T6.append(mul4(s, iG[1]))
    T7.append(mul4(s, iG[2]))
    T8.append(mul4(s, iG[3]))

    U1.append(mul4(t, iG[0]))
    U2.append(mul4(t, iG[1]))
    U3.append(mul4(t, iG[2]))
    U4.append(mul4(t, iG[3]))

# round constants
rcon = [1]
r = 1
for t in range(1, 30):
    r = mul(2, r)
    rcon.append(r)

del A
del AA
del pivot
del B
del G
del box
del log
del alog
del i
del j
del r
del s
del t
del mul
del mul4
del cox
del iG

class rijndael:
    def __init__(self, key, block_size = 16):
        if block_size != 16 and block_size != 24 and block_size != 32:
            raise ValueError('Invalid block size: ' + str(block_size))
        if len(key) != 16 and len(key) != 24 and len(key) != 32:
            raise ValueError('Invalid key size: ' + str(len(key)))
        self.block_size = block_size

        ROUNDS = num_rounds[len(key)][block_size]
        BC = block_size // 4
        # encryption round keys
        Ke = [[0] * BC for i in range(ROUNDS + 1)]
        # decryption round keys
        Kd = [[0] * BC for i in range(ROUNDS + 1)]
        ROUND_KEY_COUNT = (ROUNDS + 1) * BC
        KC = len(key) // 4

        # copy user material bytes into temporary ints
        tk = []
        for i in range(0, KC):
            tk.append((ord(key[i * 4]) << 24) | (ord(key[i * 4 + 1]) << 16) |
                (ord(key[i * 4 + 2]) << 8) | ord(key[i * 4 + 3]))

        # copy values into round key arrays
        t = 0
        j = 0
        while j < KC and t < ROUND_KEY_COUNT:
            Ke[t // BC][t % BC] = tk[j]
            Kd[ROUNDS - (t // BC)][t % BC] = tk[j]
            j += 1
            t += 1
        tt = 0
        rconpointer = 0
        while t < ROUND_KEY_COUNT:
            # extrapolate using phi (the round key evolution function)
            tt = tk[KC - 1]
            tk[0] ^= (S[(tt >> 16) & 0xFF] & 0xFF) << 24 ^  \
                     (S[(tt >>  8) & 0xFF] & 0xFF) << 16 ^  \
                     (S[ tt        & 0xFF] & 0xFF) <<  8 ^  \
                     (S[(tt >> 24) & 0xFF] & 0xFF)       ^  \
                     (rcon[rconpointer]    & 0xFF) << 24
            rconpointer += 1
            if KC != 8:
                for i in range(1, KC):
                    tk[i] ^= tk[i-1]
            else:
                for i in range(1, KC // 2):
                    tk[i] ^= tk[i-1]
                tt = tk[KC // 2 - 1]
                tk[KC // 2] ^= (S[ tt        & 0xFF] & 0xFF)       ^ \
                               (S[(tt >>  8) & 0xFF] & 0xFF) <<  8 ^ \
                               (S[(tt >> 16) & 0xFF] & 0xFF) << 16 ^ \
                               (S[(tt >> 24) & 0xFF] & 0xFF) << 24
                for i in range(KC // 2 + 1, KC):
                    tk[i] ^= tk[i-1]
            # copy values into round key arrays
            j = 0
            while j < KC and t < ROUND_KEY_COUNT:
                Ke[t // BC][t % BC] = tk[j]
                Kd[ROUNDS - (t // BC)][t % BC] = tk[j]
                j += 1
                t += 1
        # inverse MixColumn where needed
        for r in range(1, ROUNDS):
            for j in range(BC):
                tt = Kd[r][j]
                Kd[r][j] = U1[(tt >> 24) & 0xFF] ^ \
                           U2[(tt >> 16) & 0xFF] ^ \
                           U3[(tt >>  8) & 0xFF] ^ \
                           U4[ tt        & 0xFF]
        self.Ke = Ke
        self.Kd = Kd

    def encrypt(self, plaintext):
        if len(plaintext) != self.block_size:
            raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(plaintext)))
        Ke = self.Ke

        BC = self.block_size // 4
        ROUNDS = len(Ke) - 1
        if BC == 4:
            SC = 0
        elif BC == 6:
            SC = 1
        else:
            SC = 2
        s1 = shifts[SC][1][0]
        s2 = shifts[SC][2][0]
        s3 = shifts[SC][3][0]
        a = [0] * BC
        # temporary work array
        t = []
        # plaintext to ints + key
        for i in range(BC):
            t.append((ord(plaintext[i * 4    ]) << 24 |
                      ord(plaintext[i * 4 + 1]) << 16 |
                      ord(plaintext[i * 4 + 2]) <<  8 |
                      ord(plaintext[i * 4 + 3])        ) ^ Ke[0][i])
        # apply round transforms
        for r in range(1, ROUNDS):
            for i in range(BC):
                a[i] = (T1[(t[ i           ] >> 24) & 0xFF] ^
                        T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^
                        T3[(t[(i + s2) % BC] >>  8) & 0xFF] ^
                        T4[ t[(i + s3) % BC]        & 0xFF]  ) ^ Ke[r][i]
            t = copy.copy(a)
        # last round is special
        result = []
        for i in range(BC):
            tt = Ke[ROUNDS][i]
            result.append((S[(t[ i           ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF)
            result.append((S[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF)
            result.append((S[(t[(i + s2) % BC] >>  8) & 0xFF] ^ (tt >>  8)) & 0xFF)
            result.append((S[ t[(i + s3) % BC]        & 0xFF] ^  tt       ) & 0xFF)
        return ''.join(map(chr, result))

    def decrypt(self, ciphertext):
        if len(ciphertext) != self.block_size:
            raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(ciphertext)))
        Kd = self.Kd

        BC = self.block_size // 4
        ROUNDS = len(Kd) - 1
        if BC == 4:
            SC = 0
        elif BC == 6:
            SC = 1
        else:
            SC = 2
        s1 = shifts[SC][1][1]
        s2 = shifts[SC][2][1]
        s3 = shifts[SC][3][1]
        a = [0] * BC
        # temporary work array
        t = [0] * BC
        # ciphertext to ints + key
        for i in range(BC):
            t[i] = (ord(ciphertext[i * 4    ]) << 24 |
                    ord(ciphertext[i * 4 + 1]) << 16 |
                    ord(ciphertext[i * 4 + 2]) <<  8 |
                    ord(ciphertext[i * 4 + 3])        ) ^ Kd[0][i]
        # apply round transforms
        for r in range(1, ROUNDS):
            for i in range(BC):
                a[i] = (T5[(t[ i           ] >> 24) & 0xFF] ^
                        T6[(t[(i + s1) % BC] >> 16) & 0xFF] ^
                        T7[(t[(i + s2) % BC] >>  8) & 0xFF] ^
                        T8[ t[(i + s3) % BC]        & 0xFF]  ) ^ Kd[r][i]
            t = copy.copy(a)
        # last round is special
        result = []
        for i in range(BC):
            tt = Kd[ROUNDS][i]
            result.append((Si[(t[ i           ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF)
            result.append((Si[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF)
            result.append((Si[(t[(i + s2) % BC] >>  8) & 0xFF] ^ (tt >>  8)) & 0xFF)
            result.append((Si[ t[(i + s3) % BC]        & 0xFF] ^  tt       ) & 0xFF)
        return ''.join(map(chr, result))

def encrypt(key, block):
    return rijndael(key, len(block)).encrypt(block)

def decrypt(key, block):
    return rijndael(key, len(block)).decrypt(block)

 
cbc.py (Added Rijndael reference implementation and class to implement crypto-block-chain) SCript:

class zeropad:

    def __init__(self, block_size):
        assert block_size > 0 and block_size < 256
        self.block_size = block_size

    def pad(self, pt):
        ptlen = len(pt)
        padsize = self.block_size - ((ptlen + self.block_size - 1) % self.block_size + 1)
        return pt + "\0" * padsize

    def unpad(self, ppt):
        assert len(ppt) % self.block_size == 0
        offset = len(ppt)
        if (offset == 0):
            return ''
        end = offset - self.block_size + 1
        while (offset > end):
            offset -= 1;
            if (ppt[offset] != "\0"):
                return ppt[:offset + 1]
        assert false

class cbc:

    def __init__(self, padding, cipher, iv):
        assert padding.block_size == cipher.block_size;
        assert len(iv) == cipher.block_size;
        self.padding = padding
        self.cipher = cipher
        self.iv = iv

    def encrypt(self, pt):
        ppt = self.padding.pad(pt)
        offset = 0
        ct = ''
        v = self.iv
        while (offset < len(ppt)):
            block = ppt[offset:offset + self.cipher.block_size]
            block = self.xorblock(block, v)
            block = self.cipher.encrypt(block)
            ct += block
            offset += self.cipher.block_size
            v = block
        return ct;

    def decrypt(self, ct):
        assert len(ct) % self.cipher.block_size == 0
        ppt = ''
        offset = 0
        v = self.iv
        while (offset < len(ct)):
            block = ct[offset:offset + self.cipher.block_size]
            decrypted = self.cipher.decrypt(block)
            ppt += self.xorblock(decrypted, v)
            offset += self.cipher.block_size
            v = block
        pt = self.padding.unpad(ppt)
        return pt;

    def xorblock(self, b1, b2):
        # sorry, not very Pythonesk
        i = 0
        r = '';
        while (i < self.cipher.block_size):
             r += chr(ord(b1[i]) ^ ord(b2[i]))
             i += 1
        return r

Source : https://github.com/mikatammi

Decrypts the config file for the Fake-TextSecure Online Banking Trojan.

$
0
0

Decrypt the config file of “FakeToken” / “FakeTextsecure” Online Banking Trojans.
+ The Config is blowfish encrypted
+ The Config is a XML file and contains URLs and Phonenumbers of the attacker
+ “FakeTextSecure” uses the Textsecure open source app to disguise itself

Prequisites:
+ Python 3.x
+ Pycrypto: https://www.dlitz.net/software/pycrypto/

Tested on Windows 8.1 and Ubuntu 14.04

Usage
– decrypt_config.py:
– Copy blfs.key and config.cfg from /res/raw folder in APK
– run decrypt_config.py blfs.key config.cfg

decrypt_banksersecure.py:
– Specify an APK or a directory of APKs as an argument for -i or –input
– run python decrypt_bankersecure.py -i <APK_or_Directory>

decrypt_config.py Script:

import base64
from Crypto.Cipher import Blowfish
import sys

"""
Decrypts the config file for the Fake-TextSecure Online Banking Trojan.
@author: bachmann.s 2014
"""

if len(sys.argv) != 3:
    print("Usage: %s blfs.key config.cfg" % sys.argv[0])
    sys.exit(1)
    
iv = "12345678"
key = "".join(list(map(lambda x: x[2:], map(hex, map(ord, open(sys.argv[1]).read())))))[:50]
ciphertext = base64.b64decode(open(sys.argv[2]).read())

cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)

print(cipher.decrypt(ciphertext).decode("UTF-8"))

decrypt_bankersecure.py Script:

__author__ = 'bachmann.s & elias.t'

import base64
from Crypto.Cipher import Blowfish
import zipfile
import sys
from os.path import isdir
from os.path import exists
from os.path import join
from os.path import split
from os import listdir
from argparse import ArgumentParser

blfs = 'res/raw/blfs.key'
config = 'res/raw/config.cfg'
iv = "12345678"

def decrypt_config(file_path):
    '''
    This is an APK reader that reads out config and blfs.key.
    Prints the APK name along with the decrypted config data.
    :param file_path: APK file to read and decrypt its config.cfg
    :return: nothing
    '''
    try:
        arch = zipfile.ZipFile(file_path, 'r')
        key = "".join(list(map(lambda x: x[2:], map(hex, map(ord, (arch.open(blfs,'r').read()).decode("utf-8"))))))[:50]
        ciphertext = base64.b64decode(arch.read('res/raw/config.cfg'))
        cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
        print("\n" + ''.join(split(file_path)[-1:]) + ":")
        print(cipher.decrypt(ciphertext).decode("UTF-8"))
    except zipfile.BadZipfile:
        print(file_path + r" is not a ZIP file!")
        return
    except KeyError:
        print(file_path + r" is either not the Trojan-Banker APK/n"
                          r"or the filename(s) are not the same anymore.")
        print("Unexpected error: " + sys.exc_info())
        raise

def process_folder(folder_path):
    '''
    Runs decrypt_config() on all APKs
    in the directory where folder_path
    points to
    :param folder_path: folder to analyze
    :return: nothing
    '''
    folder_entries = listdir(folder_path)
    # check if the folder is empty
    if len(folder_entries) != 0:
        for entry in folder_entries:
            absolute_path = join(folder_path, entry)
            if isdir(absolute_path):
                process_folder(absolute_path)
            elif exists(path):
                decrypt_config(absolute_path)

if __name__ == "__main__":
    '''
    Tested on Windows 8.1 and Ubuntu 14.04
    '''
    parser = ArgumentParser(description="Decrypts the config.cfg file of Trojan-Banker.")
    parser.add_argument('-i', '--input', nargs='+',
                        help='Input APK file for analysis.', required=True)

    # if the path is a folder or a file
    args = parser.parse_args()

    if args.input:
        print("Analyzing APK(s)...")
        for path in args.input:
            # if it is a folder then process all files that are APK files
            if isdir(path):
                process_folder(path)
            # otherwise process the single file
            elif exists(path):
                decrypt_config(path)
    pass

Source : https://github.com/IKARUSSoftwareSecurity

Updates RATDecoders v-13.06.2015: Python Decoders for Common Remote Access Trojans.

$
0
0

Change and updates 13.06.2015 NjRat,  Rat Config Extractor :
+ njRat Config Extractor v-0.2
+ Predator Logger Config Extractor v-0.2
+ jRAT Rat Config Extractor v-0.3
+ Create Hawkeye Config Extractor v-0.1

jRat Rat Config Extractor

jRat Rat Config Extractor

Ratdecoders : a collection of Python Scripts that will extract and decode the configuration settings from common rats.

 see the allocated address of the memory in the EAX register: 0x40B61B

see the allocated address of the memory in the EAX register: 0x40B61B

Here is a list of the currently supported RATS:
– Adwind
– Albertino Advanced RAT
– Arcom
– BlackNix
– BlackShades
– Blue Banana
– Bozok
– ClientMesh
– CyberGate
– DarkComet
– drakddoser
– DarkRat
– Graeme
– jRat
– LostDoor
– LuxNet
– njRat
– Pandora
– PoisionIvy
– Punisher
– SpyGate
– SmallNet
– Unrecom
– Vantom
– Vertex
– VirusRat
– xtreme

Upcoming RATS :
– NetWire
– Gh0st
– Plasma
– Any Other Rats i can find.

Requirements :
There are several modules that are required and each script is different, Please check the individual scripts. This list is a complete listing of all the Python Modules across all decoders

pefile – https://code.google.com/p/pefile/
pycrypto – https://pypi.python.org/pypi/pycrypto/2.6.1
pype32 – https://github.com/crackinglandia/pype32

ToDo :
There will be more decoders coming Finish the Recursive mode on several of the Decoders

Reference :
Malware.lu for the initial xtreme Rat Writeup – https://code.google.com/p/malware-lu/wiki/en_xtreme_RAT

Fireye for their Poison Ivy and Xtreme rat WriteUps (Even though they ignored my tweet and reply ) – http://www.fireeye.com/blog/technical/2014/02/xtremerat-nuisance-or-threat.html

Shawn Denbow and Jesse Herts for their paper here – http://www.matasano.com/research/PEST-CONTROL.pdf

Download : Master.zip  | Clone Url | Our Post Before
Source : https://github.com/kevthehermit

Updates Process Hacker v-2.35: multi-purpose tool that helps you monitor system resources, debug software and detect malware.

$
0
0

Changelog v-2.35:
* HIGHLIGHTS:
* New rich pop-up UI when hovering the cursor over a tray icon, showing the most active processes
* Completely new Memory tab for processes, with heap, stack and working set usage
* Process Hacker now takes 32-bit dumps of 32-bit processes on 64-bit Windows
* NOTE: When using the portable (.zip) release, the entire archive must be extracted
* Updated DotNetTools plugin:
* Process Hacker now displays managed stack traces for 32-bit .NET processes on 64-bit Windows
* Added AppDomain column for threads in .NET programs
* OTHER CHANGES:
* Added customizable bytes per row setting for memory editor
* Dramatically faster handle listing and search when running without administrative privileges
* Added trigger and delayed start information to service list
* Added file information to service list tooltips
* Balloon tips for process/service notifications are now clickable
* Added handle names for unnamed File objects
* Added I/O Priority to tray icon process menu
* Added warning for users who attempt to start the 32-bit version on 64-bit Windows
* Updated ExtendedServices plugin:
* Added service protection and SID information
* Updated ExtendedTools plugin:
* Added tray icon mini info window support
* Improved automatic GPU node selection
* Fixed a bug in phsvc that caused hangs when automatically elevating actions
* Fixed hang when viewing handle security for certain File objects
* Fixed lack of information on startup when using slower refresh intervals
* Fixed Read/Write Address crash
* Fixed service non-polling mode on Windows 8 and above
* Fixed file dialog crash in Windows PE environments
* Fixed string scanning false positive case
* Fixed process window detection for Modern UI apps
* Fixed handle list selection bug when disabling “Hide unnamed handles”

A free, powerful, multi-purpose tool that helps you monitor system resources, debug software and detect malware.

Process Hacker

Process Hacker

Many of you have probably used Process Explorer in the past. Process Hacker has several advantages:
– Process Hacker is open source and can be modified or redistributed.
– Process Hacker is more customizable.
– Process Hacker shows services, network connections, disk activity, and much more!
– Process Hacker is better for debugging and reverse engineering.
== Settings ==
If you are running Process Hacker from a USB drive, you may want to save Process Hacker’s settings there as well. To do this, create a blank file named “ProcessHacker.exe.settings.xml” in the same directory as ProcessHacker.exe. You can do this using Windows Explorer:
1. Make sure “Hide extensions for known file types” is unticked in Tools > Folder options > View.
2. Right-click in the folder and choose New > Text Document.
3. Rename the file to ProcessHacker.exe.settings.xml (delete the “.txt”
extension).

System requirements:
+ Windows XP (SP2)/Vista/7/8, 32-bit or 64-bit.
+ Intel Itanium platforms are not supported.

Download : processhacker-2.35-setup.exe (2.0 MB)
Source : http://svn.code.sf.net/p/processhacker/code/ | Our post Before

Empire : PowerShell post-exploitation agent v-1.0.0 released.

$
0
0

Empire is a pure PowerShell post-exploitation agent built on cryptologically-secure communications and a flexible architecture. Empire implements the ability to run PowerShell agents without needing powershell.exe, rapidly deployable post-exploitation modules ranging from key loggers to Mimikatz, and adaptable communications to evade network detection, all wrapped up in a usability-focused framework.

Empire Module Menu

Empire Module Menu

Initial Setup:
Run the ./setup/install.sh script. This will install the few dependencies and run the ./setup/setup_database.py script. The setup_database.py file contains various setting that you can manually modify, and then initializes the ./data/empire.db backend database. No additional configuration should be needed- hopefully everything works out of the box.
Running ./empire will start Empire, and ./empire –debug will generate a verbose debug log at ./empire.debug. The included ./data/reset.sh will reset/reinitialize the database and launch Empire in debug mode.

Download : Empire.zip (1.45 MB)  | Clone Url
Source : http://www.powershellempire.com | https://github.com/PowerShellEmpire

Updates RATDecoders v-2015/08/19: Python Decoders for Common Remote Access Trojans.

$
0
0

changelog 2015/08/19:
– QSpy Config Decoder
+__description__ = ‘QSpy Rat Config Extractor’
+__author__ = ‘Kevin Breen http://techanarchy.net http://malwareconfig.com’
+__version__ = ‘0.1’
+__date__ = ‘2015/08/19′
– Fix for updates to pype32

jRat Rat Config Extractor

jRat Rat Config Extractor

Ratdecoders : a collection of Python Scripts that will extract and decode the configuration settings from common rats.

 see the allocated address of the memory in the EAX register: 0x40B61B

see the allocated address of the memory in the EAX register: 0x40B61B

Here is a list of the currently supported RATS:
– Adwind
– Albertino Advanced RAT
– Arcom
– BlackNix
– BlackShades
– Blue Banana
– Bozok
– ClientMesh
– CyberGate
– DarkComet
– drakddoser
– DarkRat
– Graeme
– jRat
– LostDoor
– LuxNet
– njRat
– Pandora
– PoisionIvy
– Punisher
– SpyGate
– SmallNet
– Unrecom
– Vantom
– Vertex
– VirusRat
– xtreme

Upcoming RATS :
– NetWire
– Gh0st
– Plasma
– Any Other Rats i can find.

Requirements :
There are several modules that are required and each script is different, Please check the individual scripts. This list is a complete listing of all the Python Modules across all decoders

pefile – https://code.google.com/p/pefile/
pycrypto – https://pypi.python.org/pypi/pycrypto/2.6.1
pype32 – https://github.com/crackinglandia/pype32

ToDo :
There will be more decoders coming Finish the Recursive mode on several of the Decoders

Reference :
Malware.lu for the initial xtreme Rat Writeup – https://code.google.com/p/malware-lu/wiki/en_xtreme_RAT

Fireye for their Poison Ivy and Xtreme rat WriteUps (Even though they ignored my tweet and reply ) – http://www.fireeye.com/blog/technical/2014/02/xtremerat-nuisance-or-threat.html

Shawn Denbow and Jesse Herts for their paper here – http://www.matasano.com/research/PEST-CONTROL.pdf

Download : Master.zip  | Clone Url | Our Post Before
Source : https://github.com/kevthehermit


Updates Security Union v-12.04.53 : is a Linux distro for IDS, NSM, and log management.

$
0
0

Changelog v-12.04.5.3:
+ tcpudpflow: remove connection_state_remove event handler
+ ossec_agent: Add source of syslog as destination IP for Sguil alert
+ sosetup: allow user to enable/disable Snorby
+ web-page: add groupby:site to ELSA HTTP SQL Injection query
+ web-page: add SSL Top Subjects query
+ add Windows and Cisco parsers
+ update shellshock module for Bro 2.4
+ NSM: update SpoolDir and LogDir in broctl.cfg
+ NSM: add stderr redirect to stdout on adduser
+ and many more..

Security Onion is a Linux distro for IDS (Intrusion Detection) and NSM (Network Security Monitoring). It’s based on Ubuntu and contains Snort, Suricata, Bro, Sguil, Squert, Snorby, ELSA, Xplico, NetworkMiner, and many other security tools. The easy-to-use Setup wizard allows you to build an army of distributed sensors for your enterprise in minutes!

Pivot between multiple data types with Sguil and send pcaps to Wireshark and NetworkMiner

Pivot between multiple data types with Sguil and send pcaps to Wireshark and NetworkMiner

Security Onion 12.04 Update Procedure
Initiating an update over SSH
If you’re updating your Security Onion box over an SSH connection and your connection drops, then your update process may be left in an inconsistent state. It is therefore recommended to run byobu so that your session will continue to run on the Security Onion box even if your connection drops. Byobu is very handy and we recommend running it all the time to avoid forgetting about it before an update.

# install byobu
sudo apt-get install byobu
# enable byobu
byobu-enable
# you’re now ready to update

Download latest version : securityonion-12.04.53.iso (1.5 GB)
Find Other Version |
Source : http://blog.securityonion.net/p/securityonion.html
Our Post Before : http://seclist.us/updates-security-union-v-12-04-4-20140222-is-a-linux-distro-for-ids-nsm-and-log-management.html

mac4n6 : Collection of forensics artifacs location for Mac OS X and iOS.

$
0
0

This is a collection for OS X and iOS artifacts location, trying to collect more information for each artifact, not just a path! From Mac4n6 Group.

The goal is that the information collected have to be “machine parsable” and mostly “human readable/writable”, reusable by any application, library, etc. (am I too optimistic?). That is why as main collaboration tool for the collection, we use a shared spreadsheet so that anyone can add new artifacts, there is no need to know how to code to contribute to this project (so, no excuses!). From here, two (simple) scripts will convert the csv file into:
+ yaml artifact library file, so that other applications can use it. No crapy/fancy xml things.
+ ForensicsWiki page, one of the point of reference for forensics practitioners.
This way the effort is centralized and made only once.

Mac OS X Forensics Artifacts
Here is the shared spreadsheet for the OSX artifacts:
+ https://docs.google.com/spreadsheet/ccc?key=0An7-sa0Wh9_TdGpNQ1gydVo2a3dPbTQtb1AtVzR1bFE&usp=sharing#gid=4

Mac OS X Forensics Artifacts

Mac OS X Forensics Artifacts

Here is the link to the ForensicsWiki page updated from the above spreadsheet
+ http://forensicswiki.org/wiki/Mac_OS_X_10.9_-_Artifacts_Location

iOS Forensics Artifacts
Here is the shared spreadsheet for the iOS artifacts (way too much initial phase still):
+ https://docs.google.com/spreadsheet/ccc?key=0An7-sa0Wh9_TdFVTTWJ3MzZMb2pGWF93RzRLWGd1YlE&usp=sharing

iOS Forensics Artifacts v0.1

iOS Forensics Artifacts v0.1

Download : mac4n6.zip  | Clone Url
Source : https://github.com/pstirparo

Killrk is a Azazel and Jynx2 rootkit removal script.

$
0
0

userland Azazel and Jynx2 rootkit removal script
this script is designed to remove Azazel and Jynx2 from the system. the script utilizes very simple flaws in the rootkits and uses the flaws to bypass the rootkit file protections.

killrk

killrk

azazel
Azazel comes with a flaw that allows a user to call symlink() on any protected rootkit files. by utilizing this flaw, we can bypass basic file protection, allowing us to read from files and write to them to. the script initially checks to see if the Azazel shared object file (libselinux.so) exists, then creates a temporary symbolic link to ld.so.preload in /tmp, then writes a temporary value to ld.so.preload via this symbolic link so that the rootkit’s shared object file is no longer being loaded. it then proceeds to remove other miscellaneous rootkit files, and copies the shared object file to /tmp.
how to patch this? overwrite the symlink() and symlinkat() library symbols and protect your files from those two calls.

Sample Usage Azazel Rootkit

Sample Usage Azazel Rootkit

jynx2
unlike Azazel, this presented some issues. since Jynx2 uses magic GIDs to hide the majority of rootkit files and directories, we can’t just use a symlink() vulnerability to bypass rootkit file protection. we have to utilize the previously existing reality.so library that Jynx2 installs in its installation directory in order to temporarily bypass rootkit file protection. this more or less works the same as the Azazel removal part of the script, except this time we need to use reality.so. this option also copies both jynx2.so and reality.so to /tmp.
how to patch this? stop using external libraries to call the previous symbols. do it internally via the rootkit’s core library itself.

killrk.sh Script:

#!/bin/bash

# azazel, best left as default

AZAZEL_INSTALL="/lib"

# end azazel


# jynx2 settings, again, best left as default

JYNX2_INSTALL="/XxJynx"

# end jyxn2

GREEN="\033[0;32m"
RED="\033[0;31m"
RESET_COLOR="\033[0m"

usage()
{
    printf "Usage: $0 [option]\n"
    printf "\tazazel -- removes the userland azazel rootkit\n"
    printf "\tjynx2 -- removes the similar (to azazel) userland rootkit\n\n"
}

azazel()
{
    printf "${GREEN}/+/${RESET_COLOR} removing azazel rootkit\n\n"

    if [ ! -f "$AZAZEL_INSTALL/libselinux.so" ]; then
        printf "${RED}/-/${RESET_COLOR} azazel shared object file not found in $AZAZEL_INSTALL/\n
        \tit was either installed elsewhere or azazel is not installed\n
        \texiting\n"
        exit
    fi

    printf "${GREEN}/+/${RESET_COLOR} shared object file was found in $AZAZEL_INSTALL/, azazel has been located\n
    \tcreating symbolic link to ld_preload file\n\n"

    ln -sf /etc/ld.so.preload /tmp/tmp_ld_preload

    printf "${GREEN}/+/${RESET_COLOR} symbolic link created, now removing the library\n"

    echo 0 > /tmp/tmp_ld_preload
    rm -rf /etc/ld.so.preload

    printf "${GREEN}/+/${RESET_COLOR} copying the shared object file to /tmp\n\n"

    cp $AZAZEL_INSTALL/libselinux.so /tmp/libselinux_azazel.so
    rm -rf $AZAZEL_INSTALL/libselinux.so /tmp/tmp_ld_preload

    printf "${GREEN}/+/${RESET_COLOR} azazel rootkit has been removed\n"
}

jynx2()
{
    printf "${GREEN}/+/${RESET_COLOR} removing jynx2 rootkit\n\n"

    export LD_PRELOAD="$JYNX2_INSTALL/reality.so"

    if [[ $(strings $LD_PRELOAD) == *"opendir"* ]]; then
        printf "${GREEN}/+/${RESET_COLOR} shared object files were found in $JYNX2_INSTALL/, jynx2 has been located\n
        creating symbolic link to ld_preload file\n\n"
    else
        printf "${RED}/-/${RESET_COLOR} shared object files not found in $JYNX2_INSTALL/
        it was either installed elsewhere or jynx2 is not installed
        exiting\n"
        exit
    fi

    LD_PRELOAD=$JYNX2_INSTALL/reality.so ln -sf /etc/ld.so.preload /tmp/tmp_ld_preload

    printf "${GREEN}/+/${RESET_COLOR} symbolic link created, now removing the library\n\n"

    echo 0 > /tmp/tmp_ld_preload
    rm -rf /etc/ld.so.preload

    printf "${GREEN}/+/${RESET_COLOR} copying the shared object files to /tmp\n\n"

    cp $JYNX2_INSTALL/jynx2.so /tmp/jynx2.so
    cp $JYNX2_INSTALL/reality.so /tmp/reality.so

    rm -rf $JYNX2_INSTALL/jynx2.so $JYNX2_INSTALL/reality.so

    printf "${GREEN}/+/${RESET_COLOR} jynx2 rootkit has been removed\n"
}

if [ $(id -u) != 0 ]; then
    printf "${RED}/-/${RESET_COLOR} $0 not ran as root, exiting\n"
    exit
fi

if [ -z "$1" ]; then
    printf "${RED}/-/${RESET_COLOR} argument not given\n"
    usage
    exit
fi

if [ "$1" == "azazel" ]; then
    azazel
    exit
elif [ "$1" == "jynx2" ]; then
    jynx2
    exit
else
    printf "${RED}/-/${RESET_COLOR} $1 is not a valid option\n"
    usage
    exit
fi

Source : https://github.com/2tewben

Updates Dnstwist v-20150901- Generate and resolve domain variations to detect typo squatting, phishing and corporate espionage.

$
0
0

changelog v20150901:
+ Domains are validated after permutation process + Updated example reports

Dnstwist is a tools for Generate and resolve domain variations to detect typo squatting, phishing and corporate espionage.

Example Usage DNSTwist

Example Usage DNSTwist

Required modules
If you want dnstwist to develop full power, please make sure the following Python modules are present on your system. If missing, dnstwist will still work, but without some cool features.
+ Python GeoIP https://pypi.python.org/pypi/GeoIP/
+ A DNS toolkit for Python http://www.dnspython.org/
+ WHOIS https://pypi.python.org/pypi/whois

This tool has been tested on windows XP/7/Vista/8.1/10 and All Unix Environment.

Example report_google :

Processing 89 domains !...!.......!!..!!!.!....!.!.!!!!.!!!!!!!!!!!!!!!!!..!!!.!!!!!!..!!..!!.!!!!!!!!!!..!.!!!

Bitsquatting         foogle.com           64.111.126.107      
Bitsquatting         eoogle.com           -                   
Bitsquatting         coogle.com           -                   
Bitsquatting         ooogle.com           -                   
Bitsquatting         woogle.com           98.124.199.1        
Bitsquatting         gnogle.com           -                   
Bitsquatting         gmogle.com           -                   
Bitsquatting         gkogle.com           -                   
Bitsquatting         ggogle.com           -                   
Bitsquatting         gongle.com           -                   
Bitsquatting         gomgle.com           -                   
Bitsquatting         gokgle.com           -                   
Bitsquatting         goggle.com           104.156.226.89      
Bitsquatting         goofle.com           69.89.22.115        
Bitsquatting         gooele.com           -                   
Bitsquatting         goocle.com           -                   
Bitsquatting         gooole.com           98.124.199.1        
Bitsquatting         goowle.com           54.68.76.21         
Bitsquatting         googme.com           199.59.243.120      
Bitsquatting         googne.com           -                   
Bitsquatting         googhe.com           199.59.243.120      
Bitsquatting         googde.com           -                   
Bitsquatting         googld.com           -                   
Bitsquatting         googlg.com           -                   
Bitsquatting         googla.com           -                   
Bitsquatting         googlm.com           98.126.223.220      
Bitsquatting         googlu.com           -                   
Homoglyph            g0ogle.com           98.124.198.1        
Homoglyph            go0gle.com           -                   
Homoglyph            googie.com           209.237.151.18      
Repetition           ggoogle.com          46.28.247.113       
Repetition           gooogle.com          46.28.247.109       
Repetition           gooogle.com          46.28.247.93        
Repetition           googgle.com          -                   
Repetition           googlle.com          96.126.106.126      
Repetition           googlee.com          46.28.247.114       
Replacement          ogogle.com           46.28.247.109       
Replacement          google.com           46.28.247.99        
Replacement          gogole.com           46.28.247.94        
Replacement          goolge.com           46.28.247.119       
Replacement          googel.com           46.28.247.84        
Omission             oogle.com            109.123.198.149     
Omission             gogle.com            46.28.247.94        
Omission             gogle.com            46.28.247.108       
Omission             goole.com            87.106.83.127       
Omission             googe.com            162.243.20.86       
Omission             googl.com            46.28.247.98        
Insertion            g0oogle.com          185.2.66.16         
Insertion            go0ogle.com          5.39.99.51          
Insertion            gpoogle.com          64.15.205.100       
Insertion            gopogle.com          209.15.13.134       
Insertion            gloogle.com          -                   
Insertion            gologle.com          -                   
Insertion            gkoogle.com          50.63.202.7         
Insertion            gokogle.com          103.224.182.253     
Insertion            gioogle.com          208.87.34.163       
Insertion            goiogle.com          -                   
Insertion            g9oogle.com          185.53.177.8        
Insertion            go9ogle.com          199.59.243.120      
Insertion            go0ogle.com          5.39.99.51          
Insertion            goo0gle.com          103.224.182.244     
Insertion            gopogle.com          209.15.13.134       
Insertion            goopgle.com          69.162.80.56        
Insertion            gologle.com          -                   
Insertion            goolgle.com          -                   
Insertion            gokogle.com          103.224.182.253     
Insertion            gookgle.com          103.224.182.210     
Insertion            goiogle.com          -                   
Insertion            gooigle.com          -                   
Insertion            go9ogle.com          199.59.243.120      
Insertion            goo9gle.com          185.2.66.16         
Insertion            gooygle.com          -                   
Insertion            googyle.com          103.224.182.252     
Insertion            goohgle.com          83.64.127.75        
Insertion            googhle.com          5.39.99.51          
Insertion            goobgle.com          103.224.182.249     
Insertion            googble.com          69.163.201.152      
Insertion            goovgle.com          199.59.243.120      
Insertion            googvle.com          103.224.182.243     
Insertion            goofgle.com          208.73.210.200      
Insertion            googfle.com          103.224.182.241     
Insertion            gootgle.com          103.224.182.244     
Insertion            googtle.com          -                   
Insertion            googkle.com          -                   
Insertion            googlke.com          98.124.198.1        
Insertion            googole.com          -                   
Insertion            googloe.com          209.15.13.134       
Insertion            googple.com          199.59.243.120      
Insertion            googlpe.com          103.224.182.243

Example report_twitter :

Processing 113 domains !!..!!!!.!!!!!...!.!.!.!.!..!.!..!!.!!!!!!!!!!!!.!!.!!!!!!!!!!!.!!!!!!!!!!!!!!!!!!!!!!...!.!!!.!!.!.!..!!!.!.!!.!

Bitsquatting         uwitter.com          72.52.4.120         
Bitsquatting         vwitter.com          54.68.76.21         
Bitsquatting         pwitter.com          -                   
Bitsquatting         dwitter.com          -                   
Bitsquatting         tvitter.com          5.22.149.135        
Bitsquatting         tuitter.com          208.73.210.200      
Bitsquatting         tsitter.com          50.63.202.35        
Bitsquatting         tgitter.com          192.40.56.146       
Bitsquatting         twhtter.com          -                   
Bitsquatting         twktter.com          103.224.182.241     
Bitsquatting         twmtter.com          54.68.76.21         
Bitsquatting         twatter.com          208.82.16.68        
Bitsquatting         twytter.com          184.168.221.96      
Bitsquatting         twiuter.com          185.53.177.8        
Bitsquatting         twivter.com          -                   
Bitsquatting         twipter.com          -                   
Bitsquatting         twidter.com          -                   
Bitsquatting         twituer.com          72.52.4.119         
Bitsquatting         twitver.com          -                   
Bitsquatting         twitper.com          162.255.119.246     
Bitsquatting         twitder.com          -                   
Bitsquatting         twittdr.com          72.52.4.119         
Bitsquatting         twittgr.com          -                   
Bitsquatting         twittar.com          96.126.106.126      
Bitsquatting         twittmr.com          -                   
Bitsquatting         twittur.com          198.187.31.153      
Bitsquatting         twittes.com          -                   
Bitsquatting         twittep.com          -                   
Bitsquatting         twittev.com          184.187.12.126      
Bitsquatting         twittez.com          -                   
Bitsquatting         twitteb.com          54.68.76.21         
Homoglyph            tvvitter.com         -                   
Homoglyph            twltter.com          -                   
Repetition           ttwitter.com         95.211.117.206      
Repetition           twwitter.com         95.211.117.206      
Repetition           twiitter.com         -                   
Repetition           twittter.com         199.59.148.82       
Repetition           twittter.com         199.59.148.82       
Repetition           twitteer.com         62.116.130.8        
Repetition           twitterr.com         95.211.117.206      
Replacement          wtitter.com          95.211.117.206      
Replacement          tiwtter.com          54.75.246.166       
Replacement          twtiter.com          208.73.210.200      
Replacement          twitter.com          199.16.156.198      
Replacement          twitetr.com          95.211.117.206      
Replacement          twittre.com          95.211.117.206      
Omission             witter.com           66.147.244.205      
Omission             titter.com           84.22.98.192        
Omission             twtter.com           -                   
Omission             twiter.com           199.16.156.70       
Omission             twiter.com           199.16.156.70       
Omission             twittr.com           -                   
Omission             twitte.com           66.33.208.125       
Insertion            t3witter.com         198.40.51.109       
Insertion            tw3itter.com         50.63.202.8         
Insertion            tewitter.com         95.211.117.206      
Insertion            tweitter.com         69.162.80.53        
Insertion            tswitter.com         31.170.164.149      
Insertion            twsitter.com         184.168.221.29      
Insertion            tawitter.com         69.162.80.54        
Insertion            twaitter.com         184.168.221.8       
Insertion            tqwitter.com         95.211.117.206      
Insertion            twqitter.com         199.59.243.120      
Insertion            t2witter.com         -                   
Insertion            tw2itter.com         50.63.202.12        
Insertion            tw9itter.com         199.59.243.120      
Insertion            twi9tter.com         185.53.179.6        
Insertion            twoitter.com         208.73.211.178      
Insertion            twiotter.com         103.224.182.241     
Insertion            twkitter.com         184.168.221.11      
Insertion            twiktter.com         185.53.177.9        
Insertion            twjitter.com         184.168.221.96      
Insertion            twijtter.com         199.59.243.120      
Insertion            twuitter.com         103.224.182.243     
Insertion            twiutter.com         95.211.117.206      
Insertion            tw8itter.com         184.168.221.21      
Insertion            twi8tter.com         185.53.179.9        
Insertion            twi6tter.com         184.171.252.34      
Insertion            twit6ter.com         208.73.211.178      
Insertion            twiytter.com         162.218.54.42       
Insertion            twityter.com         8.5.1.37            
Insertion            twigtter.com         199.59.243.120      
Insertion            twitgter.com         50.63.202.15        
Insertion            twiftter.com         72.52.4.119         
Insertion            twitfter.com         148.251.19.202      
Insertion            twirtter.com         116.212.117.220     
Insertion            twitrter.com         -                   
Insertion            twi5tter.com         -                   
Insertion            twit5ter.com         -                   
Insertion            twit6ter.com         208.73.210.200      
Insertion            twitt6er.com         -                   
Insertion            twityter.com         8.5.1.37            
Insertion            twittyer.com         185.53.178.6        
Insertion            twitgter.com         50.63.202.15        
Insertion            twittger.com         -                   
Insertion            twitfter.com         148.251.19.202      
Insertion            twittfer.com         208.73.210.214      
Insertion            twitrter.com         -                   
Insertion            twittrer.com         69.162.80.53        
Insertion            twit5ter.com         -                   
Insertion            twitt5er.com         198.40.51.109       
Insertion            twitt4er.com         -                   
Insertion            twitte4r.com         -                   
Insertion            twittrer.com         69.162.80.53        
Insertion            twitterr.com         95.211.117.206      
Insertion            twittder.com         208.73.210.217      
Insertion            twittedr.com         -                   
Insertion            twittser.com         208.73.210.214      
Insertion            twittesr.com         -                   
Insertion            twittwer.com         103.1.175.248       
Insertion            twittewr.com         199.59.243.120      
Insertion            twitt3er.com         -                   
Insertion            twitte3r.com         50.63.202.12

Example report_facebook :

Processing 120 domains ..!!!!!!.!!!!..!!!!.!!!!!!!!!.!..!.!!.!.....!!!!!!!!...!.!!!!!!!!!!!!.!.!...!!!...!!.!!.....!.!!!!.!!!!.!!!!!!!!!!.!!.!!

Bitsquatting         gacebook.com         -                   
Bitsquatting         dacebook.com         -                   
Bitsquatting         bacebook.com         116.212.117.220     
Bitsquatting         nacebook.com         68.65.123.248       
Bitsquatting         vacebook.com         103.224.182.241     
Bitsquatting         fccebook.com         103.224.182.252     
Bitsquatting         fecebook.com         146.148.34.125      
Bitsquatting         ficebook.com         103.224.182.245     
Bitsquatting         fqcebook.com         -                   
Bitsquatting         fabebook.com         208.87.150.50       
Bitsquatting         faaebook.com         174.139.64.188      
Bitsquatting         fagebook.com         199.59.243.120      
Bitsquatting         fakebook.com         98.131.4.39         
Bitsquatting         fasebook.com         -                   
Bitsquatting         facdbook.com         -                   
Bitsquatting         facgbook.com         185.53.179.9        
Bitsquatting         facabook.com         208.87.150.50       
Bitsquatting         facmbook.com         8.5.1.31            
Bitsquatting         facubook.com         199.59.243.120      
Bitsquatting         facecook.com         -                   
Bitsquatting         facefook.com         199.59.243.120      
Bitsquatting         facejook.com         103.224.182.251     
Bitsquatting         facerook.com         75.126.102.246      
Bitsquatting         facebnok.com         103.224.182.252     
Bitsquatting         facebmok.com         54.68.76.21         
Bitsquatting         facebkok.com         96.126.106.126      
Bitsquatting         facebgok.com         54.68.76.21         
Bitsquatting         facebonk.com         23.254.217.113      
Bitsquatting         facebomk.com         208.73.210.214      
Bitsquatting         facebokk.com         -                   
Bitsquatting         facebogk.com         54.68.76.21         
Bitsquatting         facebooj.com         -                   
Bitsquatting         facebooi.com         -                   
Bitsquatting         facebooo.com         162.255.119.114     
Bitsquatting         facebooc.com         -                   
Homoglyph            faceb0ok.com         199.59.243.120      
Homoglyph            facebo0k.com         75.126.104.241      
Repetition           ffacebook.com        -                   
Repetition           faacebook.com        173.252.120.6       
Repetition           faccebook.com        -                   
Repetition           faceebook.com        -                   
Repetition           facebbook.com        -                   
Repetition           faceboook.com        -                   
Repetition           faceboook.com        -                   
Repetition           facebookk.com        127.0.0.1           
Replacement          afcebook.com         96.126.106.126      
Replacement          fcaebook.com         173.252.120.6       
Replacement          faecbook.com         52.0.7.30           
Replacement          facbeook.com         96.126.106.126      
Replacement          faceobok.com         173.252.120.6       
Replacement          facebook.com         173.252.120.6       
Replacement          faceboko.com         185.53.177.20       
Omission             acebook.com          -                   
Omission             fcebook.com          -                   
Omission             faebook.com          -                   
Omission             facbook.com          173.252.120.6       
Omission             faceook.com          -                   
Omission             facebok.com          173.252.120.6       
Omission             facebok.com          173.252.120.6       
Omission             faceboo.com          173.252.120.6       
Insertion            fqacebook.com        185.53.177.9        
Insertion            faqcebook.com        72.52.4.119         
Insertion            fwacebook.com        103.224.182.214     
Insertion            fawcebook.com        209.15.13.134       
Insertion            fsacebook.com        68.65.123.151       
Insertion            fascebook.com        208.73.210.217      
Insertion            fzacebook.com        74.200.250.181      
Insertion            fazcebook.com        199.59.243.120      
Insertion            faxcebook.com        184.168.221.15      
Insertion            facxebook.com        -                   
Insertion            fadcebook.com        103.224.182.241     
Insertion            facdebook.com        -                   
Insertion            fafcebook.com        208.73.210.200      
Insertion            facfebook.com        -                   
Insertion            favcebook.com        -                   
Insertion            facvebook.com        -                   
Insertion            fac4ebook.com        103.224.182.214     
Insertion            face4book.com        209.15.13.134       
Insertion            facrebook.com        103.224.182.252     
Insertion            facerbook.com        -                   
Insertion            facdebook.com        -                   
Insertion            facedbook.com        -                   
Insertion            facsebook.com        74.200.250.181      
Insertion            facesbook.com        103.224.182.241     
Insertion            facwebook.com        -                   
Insertion            facewbook.com        208.73.211.178      
Insertion            fac3ebook.com        198.12.15.244       
Insertion            face3book.com        -                   
Insertion            facevbook.com        -                   
Insertion            facebvook.com        -                   
Insertion            facegbook.com        -                   
Insertion            facebgook.com        -                   
Insertion            facehbook.com        199.59.243.120      
Insertion            facebhook.com        -                   
Insertion            facenbook.com        72.52.4.119         
Insertion            facebnook.com        103.224.182.241     
Insertion            faceb0ook.com        103.224.182.214     
Insertion            facebo0ok.com        146.148.34.125      
Insertion            facebpook.com        -                   
Insertion            facebopok.com        103.224.182.241     
Insertion            faceblook.com        103.224.182.241     
Insertion            facebolok.com        208.73.210.217      
Insertion            facebkook.com        199.59.243.120      
Insertion            facebokok.com        -                   
Insertion            facebiook.com        103.224.182.241     
Insertion            faceboiok.com        146.148.34.125      
Insertion            faceb9ook.com        208.91.196.126      
Insertion            facebo9ok.com        185.53.177.20       
Insertion            facebo0ok.com        54.210.47.225       
Insertion            faceboo0k.com        103.224.182.214     
Insertion            facebopok.com        103.224.182.241     
Insertion            faceboopk.com        103.224.182.252     
Insertion            facebolok.com        208.73.210.214      
Insertion            faceboolk.com        146.148.34.125      
Insertion            facebokok.com        -                   
Insertion            facebookk.com        127.0.0.1           
Insertion            faceboiok.com        146.148.34.125      
Insertion            facebooik.com        -                   
Insertion            facebo9ok.com        185.53.177.20       
Insertion            faceboo9k.com        208.73.210.217

Dnstwist Script.py:

#!/usr/bin/env python
#
# dnstwist by marcin@ulikowski.pl
# Generate and resolve domain variations to detect typo squatting,
# phishing and corporate espionage.
#
#
# dnstwist is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# dnstwist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with dnstwist.  If not, see <http://www.gnu.org/licenses/>.

__author__ = 'Marcin Ulikowski'
__version__ = '20150901'
__email__ = 'marcin@ulikowski.pl'

import re
import sys
import socket
import signal
import argparse
try:
	import dns.resolver
	module_dnspython = True
except:
	module_dnspython = False
	pass
try:
	import GeoIP
	module_geoip = True
except:
	module_geoip = False
	pass
try:
	import whois
	module_whois = True
except:
	module_whois = False
	pass

def sigint_handler(signal, frame):
	sys.exit(0)

# Internationalized domains not supported
def validate_domain(domain):
	if len(domain) > 255:
		return False
	if domain[-1] == '.':
		domain = domain[:-1]
	allowed = re.compile('\A([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}\Z', re.IGNORECASE)
	return allowed.match(domain)

def bitsquatting(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]
	masks = [1, 2, 4, 8, 16, 32, 64, 128]

	for i in range(0, len(dom)):
		c = dom[i]
		for j in range(0, len(masks)):
			b = chr(ord(c) ^ masks[j])
			o = ord(b)
			if (o >= 48 and o <= 57) or (o >= 97 and o <= 122) or o == 45:
				out.append(dom[:i] + b + dom[i+1:] + '.' + tld)

	return out

def homoglyph(domain):
	glyphs = {
	'd':['b', 'cl'], 'm':['n', 'rn'], 'l':['1', 'i'], 'o':['0'],
	'w':['vv'], 'n':['m'], 'b':['d'], 'i':['l'], 'g':['q'], 'q':['g']
	}
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for ws in range(0, len(dom)):
		for i in range(0, (len(dom)-ws)+1):
			win = dom[i:i+ws]

			j = 0
			while j < ws:
				c = win[j]
				if c in glyphs:
					for g in range(0, len(glyphs[c])):
						win = win[:j] + glyphs[c][g] + win[j+1:]

						if len(glyphs[c][g]) > 1:
							j += len(glyphs[c][g]) - 1
						out.append(dom[:i] + win + dom[i+ws:] + '.' + tld)

				j += 1

	return list(set(out))

def repetition(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)):
		if dom[i].isalpha():
			out.append(dom[:i] + dom[i] + dom[i] + dom[i+1:] + '.' + tld)

	return out

def transposition(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)-1):
		if dom[i+1] != dom[i]:
			out.append(dom[:i] + dom[i+1] + dom[i] + dom[i+2:] + '.' + tld)

	return out

def replacement(domain):
	keys = {
	'1':'2q', '2':'3wq1', '3':'4ew2', '4':'5re3', '5':'6tr4', '6':'7yt5', '7':'8uy6', '8':'9iu7', '9':'0oi8', '0':'po9',
	'q':'12wa', 'w':'3esaq2', 'e':'4rdsw3', 'r':'5tfde4', 't':'6ygfr5', 'y':'7uhgt6', 'u':'8ijhy7', 'i':'9okju8', 'o':'0plki9', 'p':'lo0',
	'a':'qwsz', 's':'edxzaw', 'd':'rfcxse', 'f':'tgvcdr', 'g':'yhbvft', 'h':'ujnbgy', 'j':'ikmnhu', 'k':'olmji', 'l':'kop',
	'z':'asx', 'x':'zsdc', 'c':'xdfv', 'v':'cfgb', 'b':'vghn', 'n':'bhjm', 'm':'njk'
	}
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)):
		if dom[i] in keys:
			for c in range(0, len(keys[dom[i]])):
				out.append(dom[:i] + keys[dom[i]][c] + dom[i+1:] + '.' + tld)

	return out

def omission(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)):
		out.append(dom[:i] + dom[i+1:] + '.' + tld)

	return out

def hyphenation(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(1, len(dom)):
		if dom[i] not in ['-', '.'] and dom[i-1] not in ['-', '.']:
			out.append(dom[:i] + '-' + dom[i:] + '.' + tld)

	return out

def subdomain(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(1, len(dom)-4):
		if dom[i] not in ['-', '.'] and dom[i-1] not in ['-', '.']:
			out.append(dom[:i] + '.' + dom[i:] + '.' + tld)

	return out

def insertion(domain):
	keys = {
	'1':'2q', '2':'3wq1', '3':'4ew2', '4':'5re3', '5':'6tr4', '6':'7yt5', '7':'8uy6', '8':'9iu7', '9':'0oi8', '0':'po9',
	'q':'12wa', 'w':'3esaq2', 'e':'4rdsw3', 'r':'5tfde4', 't':'6ygfr5', 'y':'7uhgt6', 'u':'8ijhy7', 'i':'9okju8', 'o':'0plki9', 'p':'lo0',
	'a':'qwsz', 's':'edxzaw', 'd':'rfcxse', 'f':'tgvcdr', 'g':'yhbvft', 'h':'ujnbgy', 'j':'ikmnhu', 'k':'olmji', 'l':'kop',
	'z':'asx', 'x':'zsdc', 'c':'xdfv', 'v':'cfgb', 'b':'vghn', 'n':'bhjm', 'm':'njk'
	}
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(1, len(dom)-1):
		if dom[i] in keys:
			for c in range(0, len(keys[dom[i]])):
				out.append(dom[:i] + keys[dom[i]][c] + dom[i] + dom[i+1:] + '.' + tld)
				out.append(dom[:i] + dom[i] + keys[dom[i]][c] + dom[i+1:] + '.' + tld)

	return out

def fuzz_domain(domain):
	domains = []

	for i in bitsquatting(domain):
		domains.append({ 'type':'Bitsquatting', 'domain':i })
	for i in homoglyph(domain):
		domains.append({ 'type':'Homoglyph', 'domain':i })
	for i in repetition(domain):
		domains.append({ 'type':'Repetition', 'domain':i })
	for i in transposition(domain):
		domains.append({ 'type':'Transposition', 'domain':i })
	for i in replacement(domain):
		domains.append({ 'type':'Replacement', 'domain':i })
	for i in omission(domain):
		domains.append({ 'type':'Omission', 'domain':i })
	for i in hyphenation(domain):
		domains.append({ 'type':'Hyphenation', 'domain':i })
	for i in insertion(domain):
		domains.append({ 'type':'Insertion', 'domain':i })
	for i in subdomain(domain):
		domains.append({ 'type':'Subdomain', 'domain':i })

	domains[:] = [x for x in domains if validate_domain(x['domain'])]

	return domains

def main():
	parser = argparse.ArgumentParser(
	description='''Find similar-looking domains that adversaries can use to attack you.  
	Can detect fraud, phishing attacks and corporate espionage. Useful as an additional 
	source of targeted threat intelligence.''',
	epilog='''Questions? Complaints? You can reach the author at <marcin@ulikowski.pl>'''
	)

	parser.add_argument('domain', help='domain name to check (e.g., ulikowski.pl)')
	parser.add_argument('-c', '--csv', action='store_true', help='print output in CSV format')
	parser.add_argument('-r', '--registered', action='store_true', help='show only registered domain names')
	parser.add_argument('-w', '--whois', action='store_true', help='perform WHOIS lookup for creation/modification date (slow)')

	if len(sys.argv) < 2:
		parser.print_help()
		sys.exit(0)

	args = parser.parse_args()

	if not args.csv:
		sys.stdout.write('dnstwist (' + __version__ + ') by ' + __email__ + '\n\n')
	
	if not validate_domain(args.domain):
		sys.stderr.write('ERROR: invalid domain name!\n')
		sys.exit(-1)

	domains = fuzz_domain(args.domain.lower())

	if not module_dnspython:
		sys.stderr.write('NOTICE: missing dnspython module - DNS functionality is limited!\n')
		sys.stderr.flush()

	if not module_geoip:
		sys.stderr.write('NOTICE: missing GeoIP module - geographical location not available!\n')
		sys.stderr.flush()

	if not module_whois and args.whois:
		sys.stderr.write('NOTICE: missing whois module - WHOIS database not available!\n')
		sys.stderr.flush()

	if module_whois and args.whois and not args.csv:
		sys.stderr.write('Be advised: some WHOIS servers limit the number of queries and a longer fun with this tool may end up with a temporary ban to the service.\n\n')
		sys.stderr.flush()

	if not args.csv:
		sys.stdout.write('Processing ' + str(len(domains)) + ' domains ')
		sys.stdout.flush()

	signal.signal(signal.SIGINT, sigint_handler)

	total_hits = 0

	for i in range(0, len(domains)):
		if module_dnspython:
			resolv = dns.resolver.Resolver()
			resolv.lifetime = 1
			resolv.timeout = 1

			try:
				ns = resolv.query(domains[i]['domain'], 'NS')
				domains[i]['ns'] = str(ns[0])[:-1]
			except:
				pass

			if 'ns' in domains[i]:
				try:
					ns = resolv.query(domains[i]['domain'], 'A')
					domains[i]['a'] = str(ns[0])
				except:
					pass
	
				try:
					ns = resolv.query(domains[i]['domain'], 'AAAA')
					domains[i]['aaaa'] = str(ns[0])
				except:
					pass

				try:
					mx = resolv.query(domains[i]['domain'], 'MX')
					domains[i]['mx'] = str(mx[0].exchange)[:-1]
				except:
					pass
		else:
			try:
				ip = socket.getaddrinfo(domains[i]['domain'], 80)
			except:
				pass
			else:
				for j in ip:
					if '.' in j[4][0]:
						domains[i]['a'] = j[4][0]
						break
				for j in ip:
					if ':' in j[4][0]:
						domains[i]['aaaa'] = j[4][0]
						break

		if module_whois and args.whois:
			if 'ns' in domains[i] or 'a' in domains[i]:
				try:
					whoisdb = whois.query(domains[i]['domain'])
					domains[i]['created'] = str(whoisdb.creation_date).replace(' ', 'T')
					domains[i]['updated'] = str(whoisdb.last_updated).replace(' ', 'T')
				except:
					pass

		if module_geoip:
			if 'a' in domains[i]:
				gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
				try:
					country = gi.country_name_by_addr(domains[i]['a'])
				except:
					pass
				else:
					if country:
						domains[i]['country'] = country

		if not args.csv:
			if 'a' in domains[i] or 'ns' in domains[i]:
				sys.stdout.write('!')
				sys.stdout.flush()
				total_hits += 1
			else:
				sys.stdout.write('.')
				sys.stdout.flush()

	if not args.csv:
		sys.stdout.write(' ' + str(total_hits) + ' hit(s)\n\n')

	if args.csv:
		sys.stdout.write("type,domain,a,aaaa,mx,ns,country,created,updated\n")

	for i in domains:
		info = ''

		if 'a' in i:
			info += i['a']
			if 'country' in i:
				info += '/' + i['country']
		elif 'ns' in i:
			info += 'NS:' + i['ns']
		if 'aaaa' in i:
			info += ' ' + i['aaaa']
		if 'mx' in i:
			info += ' MX:' + i['mx']
		if 'created' in i and 'updated' in i and i['created'] == i['updated']:
				info += ' Created/Updated:' + i['created']
		else:
			if 'created' in i:
				info += ' Created:' + i['created']
			if 'updated' in i:
				info += ' Updated:' + i['updated']

		if not info:
			info = '-'

		if (args.registered and info != '-') or not args.registered:
			if not args.csv:
				sys.stdout.write('%-15s %-15s %s\n' % (i['type'], i['domain'], info))
				sys.stdout.flush()
			else:
				print(
				'%s,%s,%s,%s,%s,%s,%s,%s,%s' % (i.get('type'), i.get('domain'), i.get('a', ''),
				i.get('aaaa', ''), i.get('mx', ''), i.get('ns', ''), i.get('country', ''),
				i.get('created', ''), i.get('updated', ''))
				)

	return 0

if __name__ == '__main__':
	main()

Updates IPV6 and Small Bug Fixes:

#!/usr/bin/env python
#
# dnstwist by marcin@ulikowski.pl
# Generate and resolve domain variations to detect typo squatting,
# phishing and corporate espionage.
#
#
# dnstwist is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# dnstwist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with dnstwist.  If not, see <http://www.gnu.org/licenses/>.

__author__ = 'Marcin Ulikowski'
__version__ = '20150619'
__email__ = 'marcin@ulikowski.pl'

import re
import sys
import socket
import signal
try:
	import dns.resolver
	module_dnspython = True
except:
	module_dnspython = False
	pass
try:
	import GeoIP
	module_geoip = True
except:
	module_geoip = False
	pass

def sigint_handler(signal, frame):
	print('You pressed Ctrl+C!')
	sys.exit(0)

# Internationalized domains not supported
def validate_domain(domain):
	if len(domain) > 255:
		return False
	if domain[-1] == ".":
		domain = domain[:-1]
	allowed = re.compile('\A([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}\Z', re.IGNORECASE)
	return allowed.match(domain)

def bitsquatting(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]
	masks = [1, 2, 4, 8, 16, 32, 64, 128]

	for i in range(0, len(dom)):
		c = dom[i]
		for j in range(0, len(masks)):
			b = chr(ord(c) ^ masks[j])
			o = ord(b)
			if (o >= 48 and o <= 57) or (o >= 97 and o <= 122) or o == 45:
				out.append(dom[:i] + b + dom[i+1:] + '.' + tld)

	return out

def homoglyph(domain):
	glyphs = {
	'd':['b', 'cl'], 'm':['n', 'rn'], 'l':['1', 'i'], 'o':['0'],
	'w':['vv'], 'n':['m'], 'b':['d'], 'i':['l'], 'g':['q'], 'q':['g']
	}
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for ws in range(0, len(dom)):
		for i in range(0, (len(dom)-ws)+1):
			win = dom[i:i+ws]

			j = 0
			while j < ws:
				c = win[j]
				if c in glyphs:
					for g in range(0, len(glyphs[c])):
						win = win[:j] + glyphs[c][g] + win[j+1:]

						if len(glyphs[c][g]) > 1:
							j += len(glyphs[c][g]) - 1
						out.append(dom[:i] + win + dom[i+ws:] + '.' + tld)

				j += 1

	return list(set(out))

def repetition(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)):
		if dom[i].isalpha():
			out.append(dom[:i] + dom[i] + dom[i] + dom[i+1:] + '.' + tld)

	return out

def transposition(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)-1):
		out.append(dom[:i] + dom[i+1] + dom[i] + dom[i+2:] + '.' + tld)

	return out

def replacement(domain):
	keys = {
	'1':'2q', '2':'3wq1', '3':'4ew2', '4':'5re3', '5':'6tr4', '6':'7yt5', '7':'8uy6', '8':'9iu7', '9':'0oi8', '0':'po9',
	'q':'12wa', 'w':'3esaq2', 'e':'4rdsw3', 'r':'5tfde4', 't':'6ygfr5', 'y':'7uhgt6', 'u':'8ijhy7', 'i':'9okju8', 'o':'0plki9', 'p':'lo0',
	'a':'qwsz', 's':'edxzaw', 'd':'rfcxse', 'f':'tgvcdr', 'g':'yhbvft', 'h':'ujnbgy', 'j':'ikmnhu', 'k':'olmji', 'l':'kop',
	'z':'asx', 'x':'zsdc', 'c':'xdfv', 'v':'cfgb', 'b':'vghn', 'n':'bhjm', 'm':'njk'
	}
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)):
		if dom[i] in keys:
			for c in range(0, len(keys[dom[i]])):
				out.append(dom[:i] + keys[dom[i]][c] + dom[i+1:] + '.' + tld)

	return out


def omission(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)):
		out.append(dom[:i] + dom[i+1:] + '.' + tld)

	return out

def insertion(domain):
	keys = {
	'1':'2q', '2':'3wq1', '3':'4ew2', '4':'5re3', '5':'6tr4', '6':'7yt5', '7':'8uy6', '8':'9iu7', '9':'0oi8', '0':'po9',
	'q':'12wa', 'w':'3esaq2', 'e':'4rdsw3', 'r':'5tfde4', 't':'6ygfr5', 'y':'7uhgt6', 'u':'8ijhy7', 'i':'9okju8', 'o':'0plki9', 'p':'lo0',
	'a':'qwsz', 's':'edxzaw', 'd':'rfcxse', 'f':'tgvcdr', 'g':'yhbvft', 'h':'ujnbgy', 'j':'ikmnhu', 'k':'olmji', 'l':'kop',
	'z':'asx', 'x':'zsdc', 'c':'xdfv', 'v':'cfgb', 'b':'vghn', 'n':'bhjm', 'm':'njk'
	}
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(1, len(dom)-1):
		if dom[i] in keys:
			for c in range(0, len(keys[dom[i]])):
				out.append(dom[:i] + keys[dom[i]][c] + dom[i] + dom[i+1:] + '.' + tld)
				out.append(dom[:i] + dom[i] + keys[dom[i]][c] + dom[i+1:] + '.' + tld)

	return out

def fuzz_domain(domain):
	domains = []

	for i in bitsquatting(domain):
		domains.append({ 'type':'Bitsquatting', 'domain':i })
	for i in homoglyph(domain):
		domains.append({ 'type':'Homoglyph', 'domain':i })
	for i in repetition(domain):
		domains.append({ 'type':'Repetition', 'domain':i })
	for i in transposition(domain):
		domains.append({ 'type':'Transposition', 'domain':i })
	for i in replacement(domain):
		domains.append({ 'type':'Replacement', 'domain':i })
	for i in omission(domain):
		domains.append({ 'type':'Omission', 'domain':i })
	for i in insertion(domain):
		domains.append({ 'type':'Insertion', 'domain':i })

	return domains

def main():
	if len(sys.argv) == 3:
		output_csv = True
	else:
		output_csv = False

	if not output_csv:
		print('dnstwist (' + __version__ + ') by ' + __email__)

		if len(sys.argv) < 2:
			print('Usage: ' + sys.argv[0] + ' example.com [csv]')
			sys.exit()
	
	if not validate_domain(sys.argv[1]):
		sys.stderr.write('ERROR: invalid domain name !\n')
		sys.exit(-1)

	domains = fuzz_domain(sys.argv[1].lower())

	if not module_dnspython:
		sys.stderr.write('NOTICE: missing dnspython module - DNS functionality is limited !\n')
		sys.stderr.flush()

	if not module_geoip:
		sys.stderr.write('NOTICE: missing GeoIP module - geographical location not available !\n')
		sys.stderr.flush()

	if not output_csv:
		sys.stdout.write('Processing ' + str(len(domains)) + ' domains ')
		sys.stdout.flush()

	signal.signal(signal.SIGINT, sigint_handler)

	for i in range(0, len(domains)):
		try:
			ip = socket.getaddrinfo(domains[i]['domain'], 80)
		except:
			pass
		else:
			for j in ip:
				if '.' in j[4][0]:
					domains[i]['a'] = j[4][0]
					break
			for j in ip:
				if ':' in j[4][0]:
					domains[i]['aaaa'] = j[4][0]
					break

		if module_dnspython:
			resolv = dns.resolver.Resolver()
			resolv.lifetime = 1
			resolv.timeout = 1

			try:
				ns = resolv.query(domains[i]['domain'], 'NS')
				domains[i]['ns'] = str(ns[0])[:-1]
			except:
				pass

			if 'ns' in domains[i]:
				try:
					mx = resolv.query(domains[i]['domain'], 'MX')
					domains[i]['mx'] = str(mx[0].exchange)[:-1]
				except:
					pass

		if module_geoip:
			gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
			try:
				country = gi.country_name_by_addr(domains[i]['a'])
			except:
				pass
			else:
				if country:
					domains[i]['country'] = country

		if not output_csv:
			if 'a' in domains[i] or 'ns' in domains[i]:
				sys.stdout.write('!')
				sys.stdout.flush()
			else:
				sys.stdout.write('.')
				sys.stdout.flush()

	if not output_csv:
		sys.stdout.write('\n\n')

	for i in domains:
		if not output_csv:
			zone = ''

			if 'a' in i:
				zone += i['a']
				if 'country' in i:
					zone += '/' + i['country']
			elif 'ns' in i:
				zone += 'NS:' + i['ns']
			if 'aaaa' in i:
				zone += ' ' + i['aaaa']
			if 'mx' in i:
				zone += ' MX:' + i['mx']
			if not zone:
				zone = '-'

			sys.stdout.write('%-15s %-15s %s\n' % (i['type'], i['domain'], zone))
			sys.stdout.flush()
		else:
			print(
			'%s,%s,%s,%s,%s,%s,%s' % (i.get('type'), i.get('domain'), i.get('a', ''),
			i.get('aaaa', ''), i.get('mx', ''), i.get('ns', ''), i.get('country', ''))
			)

	return 0

if __name__ == '__main__':
	main()

Source : https://github.com/elceef |   Our Post Before

Bash Scanner – A fast way to scan your server for outdated software and potential exploits.

$
0
0

Bash Scanner is a fast and reliable way to scan your server for outdated software and potential exploits.

Bash Scanner Usage

Bash Scanner Usage

Extended reports:
After an initial scan, you will be asked to create an account on the PatrolServer dashboard (which is totally optional, you are free to use the tool without an account). The benefit of creating a sustainable account is detailed reporting, together with documentation on how to secure your server.

Continuous scanning:
The script will ask you if it should set a cronjob, this simply means your server software will be in sync for daily scans. And you will be reported by email when your current software becomes outdated.

Download : bash-scanner.zip(21.5KB)  | Clone Url
Source : https://patrolserver.com/

Find DNS Attacker ~ scripts to gets loging data via STDIN and performs pattern matching to identify any attacker.

$
0
0

findAttacker – This scripts gets BING loging data via STDIN and performs pattern matching to identify any attacker.
Latest Version : 0.1.4 ;Changed whitelisting algorithm.

FindAttacker-v0.1.4

FindAttacker-v0.1.4

Tested on Kali-Sana, Windows xp/7/8.1/10, All Debian Base, Free BSD.
Script:

#!/usr/bin/perl
#
#
# findAttacker  -    This scripts gets BING loging data via STDIN and performs pattern matching
#                    to identify any attacker. 
#
# Author            Emre Erkunt
#                   (emre.erkunt@superonline.net)
#
# History :
# -----------------------------------------------------------------------------------------------
# Version               Editor          Date            Description
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# 0.0.1_AR              EErkunt         20150210        Initial ALPHA Release
# 0.0.1                 EErkunt         20150210        Initial Live Release
# 0.0.2                 EErkunt         20150210        Added logging functionality
#                                                       Added mail notification system via SMTP
#                                                       Ensured that only one copy runs
#                                                       Added time based exit
# 0.0.3                 EErkunt         20150211        Added additional logging
# 0.0.4                 EErkunt         20150211        Smarter blocking/suspcious marking
# 0.0.5                 EErkunt         20150211        Reading daemon log in the script
# 0.0.6                 EErkunt         20150213        Parsing LIVE traffic instead of error log
# 0.1.0                 EErkunt         20150216        Changed the pattern matching algorithm 
#                                                       by linked lists.
# 0.1.1                 EErkunt         20150218        Improved whitelisting algorithm
# 0.1.2                 EErkunt         20150311        Fixed a problem that script blocks empty
#                                                       records.
# 0.1.3                 EErkunt         20150311        Added minimum letter count for block action
# 0.1.4                 EErkunt         20150403        Changed whitelisting algorithm
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#
# Needed Libraries
#
use POSIX;
use Fcntl ':flock';
use Net::SMTP;
use Getopt::Std;
use Data::Dumper;
use Sys::Hostname;
use Socket;

my %opt;
my $arguments   = "q";
getopts( $arguments, \%opt ) or usage();

our $defaultLogLevel = "DEBUG";
our $logFilename = "/var/log/findAttacker.log";
#
# Main Loop
#
# Beware, dragons beneath here! Go away.
#
our %patternData;

my $i = 0;
our $threshold = 50;
my $blockThreshold = 100;
my $exitThreshold = 10;
my $maxTimeRunning = 120;
my $chunkSize = 1000;
our $keepTopInArray = 10;
my $minBlockLetter = 3;
my $interface = "eth0";
my $filter = "src _LOCALIP_ and dst port 53";
my $daemonLog = "/var/log/daemon.log";
my $version = "0.1.4";
our $defaultLogLevel = "DEBUG";
our $logFilename = "/var/log/findAttacker.log";
our @emailList = ( "emre.erkunt\@superonline.net",
		   "team-sol-n-co-st\@superonline.net",
		   "cem.kokten\@superonline.net"
				 );
our $SMTPServer = "85.29.60.242";

$| = 1;
our @ignoreList;
our @whiteList;

# 
# Ensures only 1 copy runs at a time
INIT {
        open  LH, $0 or logMe("FATAL", "Can't open $0 for locking!\nError: $!\n");
        flock LH, LOCK_EX|LOCK_NB or die "$0 is already running!\n";
    }
	

open(IGNORELIST, "/etc/findAttacker/ignoreList.list") or logMe("FATAL", "Can not find any ignore list /etc/findAttacker/ignoreList.list");
while(<IGNORELIST>) {
	chomp($_);
	push(@ignoreList, $_);
}
close(IGNORELIST);

open(WHITELIST, "/etc/findAttacker/whiteList.list") or logMe("FATAL", "Can not find any ignore list /etc/findAttacker/whiteList.list");
while(<WHITELIST>) {
	chomp($_);
	push(@whiteList, $_);
}
close(WHITELIST);

my $addr =inet_ntoa((gethostbyname(hostname))[4]);
$filter =~ s/_LOCALIP_/$addr/g;

our @blocked;
our $linkedData = {};
my $count = 0;
my $goExit = 0;
my $startedTime = time();
my $percentage = 0;
our $swirlCount = 1;
our $swirlTime  = time();

print "findAttacker v".$version."\n";
print "Detection started on listening outgoing DNS related data for $addr with ".scalar(@ignoreList)." TLD ignores.\n";
print "Suspicious threshold is $threshold, enforcement threshold is $blockThreshold.\n";
logMe("INFO", "findAttacker v".$version." has started with ".scalar(@ignoreList)." TLD ignores.");
# open(DAEMONFILE, "/usr/bin/tail --retry --follow=name $daemonLog |") or logMe("FATAL", "Can not open daemon.log");
open(DAEMONFILE, "/usr/sbin/tcpdump -i $interface -nn \"$filter\" 2>&1 |") or logMe("FATAL", "Can tap interface!");
print " ";
while(<DAEMONFILE>) {
	# Feb 10 09:57:48 cdns-06sgtz-02 named[29521]: error (FORMERR) resolving 'service.supercell.net/AAAA/IN': 205.251.197.147#53
	# if ( $_ =~ /\w+ \d* \d\d:\d\d:\d\d .* named\[\d*\]: error \(.*\) resolving '(.*)\/\w*\/IN': (.*)#53/ ) {
	
	# 10:39:24.699156 IP 212.252.133.52.55789 > 213.74.1.1.53: 40371+ A? llcccqozo.www.9888hh.com. (42)
	# 15:20:58.478522 IP 82.222.179.62.8861 > 182.140.167.188.53: 9576 [1au] A? kjkbsngjmpahwxmz.vip.jingzi.cc. (59)
	
	if ( $_ =~ /\d*:\d*:\d*\.\d* IP \d*\.\d*\.\d*\.\d*\.\d* > \d*\.\d*\.\d*\.\d*\.\d*: \d*[\s%\[\]A?1auSRVPTOXMNYervFailtype1895CNEzoneIb2&3=0x]+ (.*)\. \(\d*\)/ ) {
		# findPattern($1);
		findLinkedPattern($1);
		$i++;
		
		if ( $i%100 eq 0 ) {
			&swirl();
			if ( ( time()-$startedTime > $maxTimeRunning ) and $goExit eq 0 ) {
				$goExit = 1;
				logMe("INFO", "Exceed running time limit ( $maxTimeRunning ), exiting.");
			}
		}
		
		# Block Domains
		if ( $i%$chunkSize eq 0 ) {
			$percentage += sprintf("%d", (100/$exitThreshold));
			my %patterns = findMostLinkedOne();
			foreach my $suspiciousPattern ( keys %patterns ) {
				if ( length($suspiciousPattern) ) {
					if ( length($suspiciousPattern) > $minBlockLetter ) {
						if ( $patterns{$suspiciousPattern} > $blockThreshold ) {
							if ( !in_array(\@blocked, $suspiciousPattern) ) {
									print "\b==! BLOCKED pattern : $suspiciousPattern ( $patterns{$suspiciousPattern}/$blockThreshold match count )\n ";
									push(@blocked, $suspiciousPattern);
									system("/sbin/iptables -A INPUT -i eth0 -p udp -m udp --dport 53 -m string --string \"".$suspiciousPattern."\" --algo bm --from 20 --to 100 -j DROP");
									logMe("INFO", "Pattern $pattern has been blocked !");
							}
						} elsif ( $patterns{$suspiciousPattern} > $threshold ) {
							print "\b==> Found suspicious pattern : $suspiciousPattern ( Hit ".sprintf("%.1f", ($patterns{$suspiciousPattern}/$threshold) * 100)."% suspcious ratio, ".sprintf("%.1f", ($patterns{$suspiciousPattern}/$blockThreshold) * 100)."% blocked ratio with $patterns{$suspiciousPattern} match count )\n ";
						}
					}
				}
			}
			
			$count++;
			if ( $count >= $exitThreshold or $goExit ) {
				print "\bOperation completed with ".scalar(@blocked)." blocked patterns.\n";
				logMe("INFO", "Operation completed with ".scalar(@blocked)." blocked patterns in $i total FQDNs."); 
				if ( scalar(@blocked) ) {
					notifyViaEmail()
				}
				close(DAEMONFILE);
				exit;
			}
		}
	}
}
close(DAEMONFILE);


# 
# Relation functions
#
sub findPattern( $ ) {
	my $FQDN = shift;
	
	# print "-?> $FQDN\n";
	my @octets = split(/\./, $FQDN);
	foreach my $octet ( @octets ) {
		if ( !in_array(\@ignoreList, $octet) ) {
			if ( !in_array(\@blocked, $octet) ) {
				if ( $patternData{$octet} ) {
					$patternData{$octet}++;
				} else {
					$patternData{$octet} = 1;
				}
				# print "--> $octet = $patternData{$octet}\n";
			} else {
				print "$octet is already blocked.\n";
			}
		}
	}
}

sub findLinkedPattern( $ ) {
	my $FQDN = shift;
	
	# print "<-- $FQDN -->\n";
	my @octets = split(/\./, $FQDN);
	my $whiteListed = 0;
	
	foreach my $whiteList ( @whiteList ) {
		#
		# Check for whitelisting
		if ($FQDN =~ /.*$whiteList.*/ ) {
			# print "WHITELISTED: $whiteList in $FQDN\n";
			return;
		}
	}
	# print "FILTERING : $FQDN\n";
		
	#
	# Re-structure Array
	my @tmpOctets;
	for ( my $i = (scalar(@octets)-1); $i>=0; $i-- ) {
		if ( !in_array(\@ignoreList, $octets[$i]) ) {
			if ( !in_array(\@blocked, $octets[$i]) ) {	
				push(@tmpOctets, $octets[$i]);
			} else {
				# print "[$i] Already blocked $octets[$i]\n";
			}
		} else {
			# print "[$i] Ignored $octets[$i]\n";
		}
		if ($octets[$i] =~ /^\d*$/) {
			# print "[$i] Ignored number $octets[$i]\n";
		} elsif ($octets[$i] =~ /\?/) {
			# print "[$i] Ignored invalid FQDN octet $octets[$i]\n";
		}
	}
	if ( $whiteListed > 0 ) {
		# print "** FQDN $FQDN is whitelisted!\n";
		undef @octets;
	} else {
		# print "** Array reduced to ".scalar(@tmpOctets)." from ".scalar(@octets).". New FQDN is ".join(".", @tmpOctets)."\n";
		@octets = @tmpOctets;
	}
	
	#
	# First establish connections
	for ( my $i = 0; $i < (scalar(@octets)); $i++ ) {
		if ( $i == 0 ) {
			#
			# I am gROOT!
			# print "[$i] Processing $octets[$i] ( ROOT )\n";
			if ( $linkedData->{"ROOT"}->{$octets[$i]} ) {
				# print "-> [$i] Pattern $octets[$i] already exist.\n";
				$linkedData->{"ROOT"}->{$octets[$i]}++;
			} else {
				# print "-> [$i] Creating pattern $octets[$i].\n";
				$linkedData->{"ROOT"}->{$octets[$i]} = 1;
			}
		} else {
			#
			# Links some connections to the root
			# print "-> [$i] Linking ".$octets[$i]." -> ".$octets[$i-1]."\n";
			if ( $linkedData->{$octets[$i-1]}->{$octets[$i]} ) {
				$linkedData->{$octets[$i-1]}->{$octets[$i]}++;
			} else {
				$linkedData->{$octets[$i-1]}->{$octets[$i]} = 1;
			}
		}
	}
	
	# print Data::Dumper->Dump([\$linkedData]);
	# print "</- $FQDN -/>\n\n";
}

sub findMostLinkedOne {
	# print "*************** FINDING THE MOST LINKED ONE\n";
	#print Data::Dumper->Dump([\$linkedData]);
	my %linkCount;
	my $output;
	foreach my $octet ( keys %{$linkedData->{"ROOT"}} ) {
		$output = $octet." : " if ( $opt{q} );
		my @childs = keys(%{$linkedData->{$octet}});
		my %visited = ();
		$linkCount{$octet} = 1;
		my $childCount = 0;
		foreach my $subOctet ( @childs ) {
			next if exists $visited{$subOctet};
			$output .= "[$subOctet] " if ( $opt{q} );
			if ( $linkedData->{$subOctet} ) { push(@childs, $subOctet); }
			$visited{$subOctet} = 1;
			$childCount++;
		}
		$linkCount{$octet} += $childCount;
		$output .= "($linkCount{$octet})\n" if ( $opt{q} );
		if ( $opt{q} and $linkCount{$octet} > $threshold ) {
			print $output;
		}
		# print ".";
	}
	# print "\n";
	
	my $count = 0;
	my %return;
	foreach my $octet ( sort { $linkCount{$b} <=> $linkCount{$a} } keys %linkCount ) {
		# print "$linkCount{$octet} - $octet\n";
		$count++;
		$return{$octet} = $linkCount{$octet};
		if ( $count > $keepTopInArray ) {
			last;
		}
	}	
	
	return %return;
	# print "FINDING THE MOST LINKED ONE ***************\n\n";
}

sub in_array {
     my ($arr,$search_for) = @_;
     my %items = map {$_ => 1} @$arr; 
     return (exists($items{$search_for}))?1:0;
}

sub logMe( $ $ ) {
	my $logLevel = shift;
    my $logMessage = shift;
    my $now = POSIX::strftime("%Y-%d-%m %T", localtime);
    
    my $level = 5;
    my $quit  = 0;
	
	if    ( $logLevel =~ /debug/i ) 	{ $level = 10; }
	elsif ( $logLevel =~ /info/i ) 		{ $level = 5; }
	elsif ( $logLevel =~ /warning/i ) 	{ $level = 1; }
	elsif ( $logLevel =~ /err/i ) 		{ $level = 0; }
	elsif ( $logLevel =~ /fatal/i ) 	{ $level = -1; }
	else 								{ die $logLevel." can not be found in logLevels!!\n"; }
    
    if ( $level >= $defaultLogLevel ) {
        open(LOGFILE, ">> ".$logFilename) or die ("Can not open log file $logFilename for writing!");
        my @lines = split("\n", $logMessage);
        foreach my $msg ( @lines ) {
            chomp($msg);
            if ( $msg ) {
                print LOGFILE "[".$now."] ".$logLevel." ".$msg."\n";
				# print "[".$now."] ".$logLevel." ".$msg."\n";
                print "\n\nFATAL ERROR :" if($level < 0);
                print $msg."\n" if ($level < 0 );
            }
        }
        close(LOGFILE);
        exit if ($level < 0);
    }
}

sub swirl() {
	
	my $diff = 1;
	my $now = time();	
	
	if    ( $swirlCount%8 eq 0 ) 	{ print "\b|"; $swirlCount++; }
	elsif ( $swirlCount%8 eq 1 ) 	{ print "\b/"; $swirlCount++; }
	elsif ( $swirlCount%8 eq 2 ) 	{ print "\b-"; $swirlCount++; }
	elsif ( $swirlCount%8 eq 3 ) 	{ print "\b\\"; $swirlCount++; }
	elsif ( $swirlCount%8 eq 4 ) 	{ print "\b|"; $swirlCount++; }
	elsif ( $swirlCount%8 eq 5 ) 	{ print "\b/"; $swirlCount++; }
	elsif ( $swirlCount%8 eq 6 ) 	{ print "\b-"; $swirlCount++; }
	elsif ( $swirlCount%8 eq 7 ) 	{ print "\b\\"; $swirlCount++; }

	return;
	
}

sub notifyViaEmail() {
	# print "Sending email via $SMTPServer\n";
	my $smtp = 	Net::SMTP->new($SMTPServer, Timeout => 60);
	# print "Sending from : findDNSAttacker\@alarms.superonline.net\n";
	$smtp->mail("findDNSAttacker\@alarms.superonline.net");
	foreach my $to (@emailList) {
		print "=> To: $to\n";
		$smtp->to($to);
	}
	
	$smtp->data();
	# print "==> DATA START <==\n";
	my $data = "From: findDNSAttacker\@alarms.superonline.net\n";
	foreach my $to (@emailList) {
		$data .= "To: ".$to."\n";
	}
	my $hostname = `/bin/hostname`;
	$data .= "Subject: BLOCKED DOMAIN NOTIFICATION on $hostname\n";
	$data .="\n";
	chomp($hostname);
	$data .= "ALARM NOTIFICATION ON $hostname\n\n";
	$data .= "The patterns listed below has been blocked ;\n";
	foreach my $pattern ( @blocked ) {
		$data .= "   * $pattern\n";
	}
	$data .= "\n\n";
	$data .= "Current iptables rules looks like ;\n";
	open(IPTABLES, "/sbin/iptables -L -n -v |") or die("Can not run iptables");
	while(<IPTABLES>) {
		$data .= $_;
	}
	close(IPTABLES);
	# print $data."\n";
	# print "==> DATA END <==\nSending email..";
	$smtp->datasend($data);
	$smtp->dataend();
	$smtp->quit;
	# print "Sent!\n";
	logMe("INFO", "Notification emails sent to ".join(",", @emailList)." addresses.");
}

Or Git Clone URl

Source: https://github.com/eerkunt

NoCrack ~ A new kind of password vault that fools the brute-force attacker by charning out decoy passwords.

$
0
0

Nocrack is A new kind of password vault that fools the brute-force attacker by charning out decoy passwords.
Latest change:
Fixed the parsing problem, when the top level composition rule is missing in the learned/parsed (sub)-grammar. Hopefully, now it should be able to arse any password/master password.
TODO:
1) Update the vault_dist.py with the data about updated grammar (G->WG|DG|W|D.., W->W1|W2.. etc.)
2) The random parsetree is wrong. Need to fix that. Till now, it parses the most probable parse tree.
3) Need to test the decoy output of the updated grammar.

Restart Client : ./honey_client
-getpass : get the saved password for a domain
-import : import existing vault, in given format
-refresh : refresh your token. If you dont have access to the account
-genpass : generate random password
-read : read your vault from the server.
-getdomainhash : get the mapping of domains to index. Advanced level command!
-test : Just a test framework for testing getpass function.
-register : register
-write : write/upload your vault on the server
-addpass : Add password to your vault. It will automatically initialize the vault.
-export : export the vault,
-verify : verify your email id. token you will get in your email after ‘-register’
-getall : Prints all the password in the vault

A new kind of password vault that fools the brute-force attacker by charning out decoy passwords.

A new kind of password vault that fools the brute-force attacker by charning out decoy passwords.

restart server:
+ python server/honey_server.py

Nocrack - restart honey server

Nocrack – restart honey server

~INSTALLATION~
DEPENDANCIES
– python 2.7.x or more (http://stackoverflow.com/a/5507373/1792013)
– python-dev
– (check requirement.txt)
$ pip install -r requirement.txt
$ git clone -b vault1.1 git@bitbucket.org:rchatterjee/honeyencryption.git

# ============= BUILD DAWG ================
# you need to run this only if you want to use new password leaks. Default set of grammar and dictionaries are provided with the code.
# Also note, if you want to use these function make necessary changes in honeyvault_config.py and update the required paths
$ python buildPCFG.py –build-dawg
$ python buildPCFG.py –build-pcfg
$ python buildPCFG.py –build-all

# ============= Honey ENCODING/ENCRYPTING ==========
$ ./honey_client
(Follow the options provided by this)
# to start the server run –
$ python server/honey_server.py
(For more details check honey_client_doc.txt)

Download : Using Git Clone Url
Source : https://github.com/rchatterjee


Privilege-Escalation ~ This contains common local exploits and enumeration scripts.

$
0
0

Privilege-Escalation This contains common OSCP local exploits and enumeration collection scripts.
On Linux Folder:
– Post Exploitation Script;
— Linux Privilege Escalation Script Bash.sh
— Linux Privilege Escalation Script Bash.py
— Linux Privilege Escalation Script Bash.pl
– Python <= 2.4.2 realpath() Local Stack Overflow.py

Local Linux Enumeration & Privilege Escalation Script-py

Local Linux Enumeration & Privilege Escalation Script-py

On Windows Folder:
The Sysinternals Troubleshooting Utilities have been rolled up into a single Suite of tools. This file contains the individual troubleshooting tools and help files.
The Suite is a bundling of the following selected Sysinternals Utilities:

AccessChk - AccessChk is a command-line tool for viewing the effective permissions on files, registry keys, services, processes, kernel objects, and more.

AccessEnum - This simple yet powerful security tool shows you who has what access to directories, files and Registry keys on your systems. Use it to find holes in your permissions.

AdExplorer - Active Directory Explorer is an advanced Active Directory (AD) viewer and editor.

AdInsight - An LDAP (Light-weight Directory Access Protocol) real-time monitoring tool aimed at troubleshooting Active Directory client applications.

AdRestore - Undelete Server 2003 Active Directory objects.

Autologon - Bypass password screen during logon.

Autoruns - See what programs are configured to startup automatically when your system boots and you login. Autoruns also shows you the full list of Registry and file locations where applications can configure auto-start settings.

BgInfo - This fully-configurable program automatically generates desktop backgrounds that include important information about the system including IP addresses, computer name, network adapters, and more.

CacheSet - CacheSet is a program that allows you to control the Cache Manager's working set size using functions provided by NT. It's compatible with all versions of NT.

ClockRes - View the resolution of the system clock, which is also the maximum timer resolution.

Contig - Wish you could quickly defragment your frequently used files? Use Contig to optimize individual files, or to create new files that are contiguous.

Coreinfo - Coreinfo is a new command-line utility that shows you the mapping between logical processors and the physical processor, NUMA node, and socket on which they reside, as well as the cache’s assigned to each logical processor.

Ctrl2cap - This is a kernel-mode driver that demonstrates keyboard input filtering just above the keyboard class driver in order to turn caps-locks into control keys. Filtering at this level allows conversion and hiding of keys before NT even "sees" them. Ctrl2cap also shows how to use NtDisplayString() to print messages to the initialization blue-screen.

Download all archive : 

DebugView - Another first from Sysinternals: This program intercepts calls made to DbgPrint by device drivers and OutputDebugString made by Win32 programs. It allows for viewing and recording of debug session output on your local machine or across the Internet without an active debugger.

Desktops - This new utility enables you to create up to four virtual desktops and to use a tray interface or hotkeys to preview what’s on each desktop and easily switch between them.

Disk2vhd - Disk2vhd simplifies the migration of physical systems into virtual machines (p2v).

DiskExt - Display volume disk-mappings.

Diskmon - This utility captures all hard disk activity or acts like a software disk activity light in your system tray.

DiskView - Graphical disk sector utility.

Disk Usage (DU) - View disk usage by directory.

EFSDump - View information for encrypted files.

Handle - This handy command-line utility will show you what files are open by which processes, and much more.

Hex2dec - Convert hex numbers to decimal and vice versa.

Junction - Create Win2K NTFS symbolic links.

LDMDump - Dump the contents of the Logical Disk Manager's on-disk database, which describes the partitioning of Windows 2000 Dynamic disks.

ListDLLs - List all the DLLs that are currently loaded, including where they are loaded and their version numbers. Version 2.0 prints the full path names of loaded modules.

LiveKd - Use Microsoft kernel debuggers to examine a live system.

LoadOrder - See the order in which devices are loaded on your WinNT/2K system.

LogonSessions - List the active logon sessions on a system.

MoveFile - Allows you to schedule move and delete commands for the next reboot.

NTFSInfo - Use NTFSInfo to see detailed information about NTFS volumes, including the size and location of the Master File Table (MFT) and MFT-zone, as well as the sizes of the NTFS meta-data files.

PageDefrag - Defragment your paging files and Registry hives.

PendMoves - Enumerate the list of file rename and delete commands that will be executed the next boot.

PipeList - Displays the named pipes on your system, including the number of maximum instances and active instances for each pipe.

PortMon- Monitor serial and parallel port activity with this advanced monitoring tool. It knows about all standard serial and parallel IOCTLs and even shows you a portion of the data being sent and received. Version 3.x has powerful new UI enhancements and advanced filtering capabilities.

ProcDump - This new command-line utility is aimed at capturing process dumps of otherwise difficult to isolate and reproduce CPU spikes. It also serves as a general process dump creation utility and can also monitor and generate process dumps when a process has a hung window or unhandled exception.

Process Explorer - Find out what files, registry keys and other objects processes have open, which DLLs they have loaded, and more. This uniquely powerful utility will even show you who owns each process.

Process Monitor - Monitor file system, Registry, process, thread and DLL activity in real-time.

ProcFeatures - This applet reports processor and Windows support for Physical Address Extensions and No Execute buffer overflow protection.

PsExec - Execute processes on remote systems.

PsFile - See what files are opened remotely.

PsGetSid - Displays the SID of a computer or a user.

PsInfo - Obtain information about a system.

PsKill - Terminate local or remote processes.

PsList - Show information about processes and threads.

PsLoggedOn - Show users logged on to a system.

PsLogList - Dump event log records.

PsPasswd - Changes account passwords.

PsService - View and control services.

PsShutdown - Shuts down and optionally reboots a computer.

PsSuspend - Suspend and resume processes.

RAMMap - An advanced physical memory usage analysis utility that presents usage information in different ways on its several different tabs.

RegDelNull - Scan for and delete Registry keys that contain embedded null-characters that are otherwise undeleteable by standard Registry-editing tools.

RegJump - Jump to the registry path you specify in Regedit.

RootkitRevealer - Scan your system for rootkit-based malware.

SDelete - Securely overwrite your sensitive files and cleanse your free space of previously deleted files using this DoD-compliant secure delete program.

ShareEnum - Scan file shares on your network and view their security settings to close security holes.

ShellRunas - Launch programs as a different user via a convenient shell context-menu entry.

Sigcheck - Dump file version information and verify that images on your system are digitally signed.

Streams - Reveal NTFS alternate streams.

Strings - Search for ANSI and UNICODE strings in binaryimages.

Sync - Flush cached data to disk.

TCPView - Active socket command-line viewer.

VMMap - VMMap is a process virtual and physical memory analysis utility.

VolumeId - Set Volume ID of FAT or NTFS drives.

Whois - See who owns an Internet address.

WinObj - The ultimate Object Manager namespace viewer is here.

ZoomIt - Presentation utility for zooming and drawing on the screen.

Download : Privileges-Escalation.zip (13.3 MB)  | Clone Url
Source : https://github.com/AusJock

Linux Malware Detect(LMD) version-1.5 released.

$
0
0

Linux Malware Detect (LMD) is a malware scanner for Linux released under the GNU GPLv2 license, that is designed around the threats faced in shared hosted environments. It uses threat data from network edge intrusion detection systems to extract malware that is actively being used in attacks and generates signatures for detection. In addition, threat data is also derived from user submissions with the LMD checkout feature and from malware community resources. The signatures that LMD uses are MD5 file hashes and HEX pattern matches, they are also easily exported to any number of detection tools such as ClamAV.

The driving force behind LMD is that there is currently limited availability of open source/restriction free tools for Linux systems that focus on malware detection and more important that get it right. Many of the AV products that perform malware detection on Linux have a very poor track record of detecting threats, especially those targeted at shared hosted environments.

Maldet

Maldet

The threat landscape in shared hosted environments is unique from that of the standard AV products detection suite in that they are detecting primarily OS level trojans, rootkits and traditional file-infecting viruses but missing the ever increasing variety of malware on the user account level which serves as an attack platform.

Using the CYMRU malware hash registry, which provides malware detection data for 30 major AV packages, we can demonstrate this short coming in current threat detection. The following is an analysis of 8,883 MD5 hashes that ship in LMD 1.5 and the percentage of major AV products that currently detect the hashes.

KNOWN MALWARE: 1951
% AV DETECT (AVG): 58
% AV DETECT (LOW): 10
% AV DETECT (HIGH): 100
UNKNOWN MALWARE: 6931

What this information means, is that of the 8,883 hashes, 78% or 6,931 malware threats are NOT detected by top-30 AV products. The 1,951 detected malware threats that are known have an average detection rate of 58% among top-30 AV products with a low and high detection rate of 10% and 100% respectively. This clearly demonstrates the significant lapse in user space malware detection that top-30 AV products currently provide. It is for this reason LMD was created, to fill a void, specifically for shared hosted environments.

[ FEATURES ] :
– MD5 file hash detection for quick threat identification
– HEX based pattern matching for identifying threat variants
– statistical analysis component for detection of obfuscated threats (e.g: base64)
– integrated detection of ClamAV to use as scanner engine for improved performance
– integrated signature update feature with -u|–update
– integrated version update feature with -d|–update-ver
– scan-recent option to scan only files that have been added/changed in X days
– scan-all option for full path based scanning
– checkout option to upload suspected malware to rfxn.com for review / hashing
– full reporting system to view current and previous scan results
– quarantine queue that stores threats in a safe fashion with no permissions
– quarantine batching option to quarantine the results of a current or past scans
– quarantine restore option to restore files to original path, owner and perms
– quarantine suspend account option to Cpanel suspend or shell revoke users
– cleaner rules to attempt removal of malware injected strings
– cleaner batching option to attempt cleaning of previous scan reports
– cleaner rules to remove base64 and gzinflate(base64 injected malware
– daily cron based scanning of all changes in last 24h in user homedirs
– daily cron script compatible with stock RH style systems, Cpanel & Ensim
– kernel based inotify real time file scanning of created/modified/moved files
– kernel inotify monitor that can take path data from STDIN or FILE
– kernel inotify monitor convenience feature to monitor system users
– kernel inotify monitor can be restricted to a configurable user html root
– kernel inotify monitor with dynamic sysctl limits for optimal performance
– kernel inotify alerting through daily and/or optional weekly reports
– HTTP upload scanning through mod_security2 inspectFile hook
– e-mail alert reporting after every scan execution (manual & daily)
– path, extension and signature based ignore options
– background scanner option for unattended scan operations
– verbose logging & output of all actions

Changelog v1.5.1 | Sep 19 2015:
[Fix] when clamdscan was running as a non-root user, would generate lstat errors for all file find results leading
to potential false positive hits/quarantines
[Fix] the permissions of the $tmpdir path can cause clamd when running as a non-root user to fail on startup due
as a result of lstat errors on the custom user signature files stored under $tmpdir
[Fix] clamd.conf configurations containing FollowDirectorySymlinks/FollowFileSymlinks set to false results in the
rfxn.* and lmd.user.* links causing clamd startup failures; corrected by updating clamav_linksigs() to copy
signatures into clamav data paths instead of linking them

Linux Malware Detection (LMD)

Linux Malware Detection (LMD)

Download : linux-malware-detect-1.5.tar.gz(54.6KB)  | llinux-malware-detect-1.5.zip(71.1 KB)
Source : rfxn

Dnstwist v-20150920 ~ Generate and resolve domain variations to detect typo squatting, phishing and corporate espionage.

$
0
0

Changelog v-20150920:
+New feature: fetch web pages and compare fuzzy hashes to evaluate similarity + Other minor changes

Dnstwist version-2092015

Dnstwist version-2092015

Dnstwist is a tools for Generate and resolve domain variations to detect typo squatting, phishing and corporate espionage.

dnstwist console

dnstwist console

Features
There are several good reasons to give it a try:
+ Wide range of domain fuzzing algorithms
+ Resolving domain names to IPv4 and IPv6
+ Queries for NS and MX records
+ Optional: Evaluating web page similarity with fuzzy hashes
+ Optional: GeoIP location information
+ Optional: Banner grabbing for HTTP and SMTP services
+ Optional: WHOIS lookups for creation and modification date
+ Optional: Output in CSV format

Required modules
If you want dnstwist to develop full power, please make sure the following Python modules are present on your system. If missing, dnstwist will still work, but without some cool features.
+ Python GeoIP https://pypi.python.org/pypi/GeoIP/
+ A DNS toolkit for Python http://www.dnspython.org/
+ WHOIS https://pypi.python.org/pypi/whois

This tool has been tested on windows XP/7/Vista/8.1/10 and All Unix Environment.

Dnstwist Script.py :

#!/usr/bin/env python
#
# dnstwist
#
# Generate and resolve domain variations to detect typo squatting,
# phishing and corporate espionage.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__author__ = 'Marcin Ulikowski'
__version__ = '20150920'
__email__ = 'marcin@ulikowski.pl'

import re
import sys
import socket
import signal
import argparse
try:
	import dns.resolver
	module_dnspython = True
except:
	module_dnspython = False
	pass
try:
	import GeoIP
	module_geoip = True
except:
	module_geoip = False
	pass
try:
	import whois
	module_whois = True
except:
	module_whois = False
	pass
try:
	import ssdeep
	module_ssdeep = True
except:
	module_ssdeep = False
try:
	import requests
	module_requests = True
except:
	module_requests = False
	pass

if sys.platform != 'win32' and sys.stdout.isatty():
	FG_RED = '\x1b[31m'
	FG_YELLOW = '\x1b[33m'
	FG_GREEN = '\x1b[32m'
	FG_MAGENTA = '\x1b[35m'
	FG_CYAN = '\x1b[36m'
	FG_BLUE = '\x1b[34m'
	FG_RESET = '\x1b[39m'

	ST_BRIGHT = '\x1b[1m'
	ST_RESET = '\x1b[0m'
else:
	FG_RED = ''
	FG_YELLOW = ''
	FG_GREEN = ''
	FG_MAGENTA = ''
	FG_CYAN = ''
	FG_BLUE = ''
	FG_RESET = ''

	ST_BRIGHT = ''
	ST_RESET = ''

def display(text):
	global args
	if not args.csv:
		sys.stdout.write(text)
		sys.stdout.flush()

def display_csv(text):
	global args
	if args.csv:
		sys.stdout.write(text)

def sigint_handler(signal, frame):
	sys.stdout.write(FG_RESET + ST_RESET)
	sys.exit(0)

# Internationalized domains not supported
def validate_domain(domain):
	if len(domain) > 255:
		return False
	if domain[-1] == '.':
		domain = domain[:-1]
	allowed = re.compile('\A([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}\Z', re.IGNORECASE)
	return allowed.match(domain)

def http_banner(ip, vhost):
	try:
		http = socket.socket()
		http.settimeout(1)
		http.connect((ip, 80))
		http.send('HEAD / HTTP/1.1\r\nHost: %s\r\n\r\n' % str(vhost))
		response = http.recv(1024)
		http.close()
	except:
		pass
	else:
		if '\r\n' in response: sep = '\r\n'
		else: sep = '\n'
		headers = response.split(sep)
		for field in headers:
			if field.startswith('Server: '):
				return field[8:]
		return 'HTTP %s' % headers[0].split(' ')[1]

def smtp_banner(mx):
	try:
		smtp = socket.socket()
		smtp.settimeout(1)
		smtp.connect((mx, 25))
		response = smtp.recv(1024)
		smtp.close()
	except:
		pass
	else:
		if '\r\n' in response: sep = '\r\n'
		else: sep = '\n'
		hello = response.split(sep)[0]
		if hello.startswith('220'):
			return hello[4:].strip()
		return hello[:40]

def bitsquatting(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]
	masks = [1, 2, 4, 8, 16, 32, 64, 128]

	for i in range(0, len(dom)):
		c = dom[i]
		for j in range(0, len(masks)):
			b = chr(ord(c) ^ masks[j])
			o = ord(b)
			if (o >= 48 and o <= 57) or (o >= 97 and o <= 122) or o == 45:
				out.append(dom[:i] + b + dom[i+1:] + '.' + tld)

	return out

def homoglyph(domain):
	glyphs = {
	'd':['b', 'cl'], 'm':['n', 'nn', 'rn'], 'l':['1', 'i'], 'o':['0'],
	'w':['vv'], 'n':['m'], 'b':['d'], 'i':['1', 'l'], 'g':['q'], 'q':['g']
	}
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for ws in range(0, len(dom)):
		for i in range(0, (len(dom)-ws)+1):
			win = dom[i:i+ws]

			j = 0
			while j < ws:
				c = win[j]
				if c in glyphs:
					for g in glyphs[c]:
						win = win[:j] + g + win[j+1:]

						if len(g) > 1:
							j += len(g) - 1
						out.append(dom[:i] + win + dom[i+ws:] + '.' + tld)

				j += 1

	return list(set(out))

def repetition(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)):
		if dom[i].isalpha():
			out.append(dom[:i] + dom[i] + dom[i] + dom[i+1:] + '.' + tld)

	return list(set(out))

def transposition(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)-1):
		if dom[i+1] != dom[i]:
			out.append(dom[:i] + dom[i+1] + dom[i] + dom[i+2:] + '.' + tld)

	return out

def replacement(domain):
	keys = {
	'1':'2q', '2':'3wq1', '3':'4ew2', '4':'5re3', '5':'6tr4', '6':'7yt5', '7':'8uy6', '8':'9iu7', '9':'0oi8', '0':'po9',
	'q':'12wa', 'w':'3esaq2', 'e':'4rdsw3', 'r':'5tfde4', 't':'6ygfr5', 'y':'7uhgt6', 'u':'8ijhy7', 'i':'9okju8', 'o':'0plki9', 'p':'lo0',
	'a':'qwsz', 's':'edxzaw', 'd':'rfcxse', 'f':'tgvcdr', 'g':'yhbvft', 'h':'ujnbgy', 'j':'ikmnhu', 'k':'olmji', 'l':'kop',
	'z':'asx', 'x':'zsdc', 'c':'xdfv', 'v':'cfgb', 'b':'vghn', 'n':'bhjm', 'm':'njk'
	}
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)):
		if dom[i] in keys:
			for c in range(0, len(keys[dom[i]])):
				out.append(dom[:i] + keys[dom[i]][c] + dom[i+1:] + '.' + tld)

	return out

def omission(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(0, len(dom)):
		out.append(dom[:i] + dom[i+1:] + '.' + tld)

	return list(set(out))

def hyphenation(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(1, len(dom)):
		if dom[i] not in ['-', '.'] and dom[i-1] not in ['-', '.']:
			out.append(dom[:i] + '-' + dom[i:] + '.' + tld)

	return out

def subdomain(domain):
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(1, len(dom)):
		if dom[i] not in ['-', '.'] and dom[i-1] not in ['-', '.']:
			out.append(dom[:i] + '.' + dom[i:] + '.' + tld)

	return out

def insertion(domain):
	keys = {
	'1':'2q', '2':'3wq1', '3':'4ew2', '4':'5re3', '5':'6tr4', '6':'7yt5', '7':'8uy6', '8':'9iu7', '9':'0oi8', '0':'po9',
	'q':'12wa', 'w':'3esaq2', 'e':'4rdsw3', 'r':'5tfde4', 't':'6ygfr5', 'y':'7uhgt6', 'u':'8ijhy7', 'i':'9okju8', 'o':'0plki9', 'p':'lo0',
	'a':'qwsz', 's':'edxzaw', 'd':'rfcxse', 'f':'tgvcdr', 'g':'yhbvft', 'h':'ujnbgy', 'j':'ikmnhu', 'k':'olmji', 'l':'kop',
	'z':'asx', 'x':'zsdc', 'c':'xdfv', 'v':'cfgb', 'b':'vghn', 'n':'bhjm', 'm':'njk'
	}
	out = []
	dom = domain.rsplit('.', 1)[0]
	tld = domain.rsplit('.', 1)[1]

	for i in range(1, len(dom)-1):
		if dom[i] in keys:
			for c in range(0, len(keys[dom[i]])):
				out.append(dom[:i] + keys[dom[i]][c] + dom[i] + dom[i+1:] + '.' + tld)
				out.append(dom[:i] + dom[i] + keys[dom[i]][c] + dom[i+1:] + '.' + tld)

	return out

def fuzz_domain(domain):
	domains = []

	domains.append({ 'type':'Original*', 'domain':domain })

	for i in bitsquatting(domain):
		domains.append({ 'type':'Bitsquatting', 'domain':i })
	for i in homoglyph(domain):
		domains.append({ 'type':'Homoglyph', 'domain':i })
	for i in repetition(domain):
		domains.append({ 'type':'Repetition', 'domain':i })
	for i in transposition(domain):
		domains.append({ 'type':'Transposition', 'domain':i })
	for i in replacement(domain):
		domains.append({ 'type':'Replacement', 'domain':i })
	for i in omission(domain):
		domains.append({ 'type':'Omission', 'domain':i })
	for i in hyphenation(domain):
		domains.append({ 'type':'Hyphenation', 'domain':i })
	for i in insertion(domain):
		domains.append({ 'type':'Insertion', 'domain':i })
	for i in subdomain(domain):
		domains.append({ 'type':'Subdomain', 'domain':i })

	domains[:] = [x for x in domains if validate_domain(x['domain'])]

	return domains

def main():
	parser = argparse.ArgumentParser(
	description='''Find similar-looking domains that adversaries can use to attack you.  
	Can detect fraud, phishing attacks and corporate espionage. Useful as an additional 
	source of targeted threat intelligence.''',
	epilog='''Questions? Complaints? You can reach the author at <marcin@ulikowski.pl>'''
	)

	parser.add_argument('domain', help='domain name to check')
	parser.add_argument('-c', '--csv', action='store_true', help='print output in CSV format')
	parser.add_argument('-r', '--registered', action='store_true', help='show only registered domain names')
	parser.add_argument('-w', '--whois', action='store_true', help='perform lookup for WHOIS creation/modification date (slow)')
	parser.add_argument('-g', '--geoip', action='store_true', help='perform lookup for GeoIP location')
	parser.add_argument('-b', '--banners', action='store_true', help='determine HTTP and SMTP service banners')
	parser.add_argument('-s', '--ssdeep', action='store_true', help='fetch web pages and compare fuzzy hashes to evaluate similarity')

	if len(sys.argv) < 2:
		parser.print_help()
		sys.exit(0)

	global args
	args = parser.parse_args()

	display(ST_BRIGHT + FG_MAGENTA + 
'''     _           _            _     _   
  __| |_ __  ___| |___      _(_)___| |_ 
 / _` | '_ \/ __| __\ \ /\ / / / __| __|
| (_| | | | \__ \ |_ \ V  V /| \__ \ |_ 
 \__,_|_| |_|___/\__| \_/\_/ |_|___/\__| %s
''' % __version__ + FG_RESET)
	
	if not validate_domain(args.domain):
		sys.stderr.write('ERROR: invalid domain name!\n')
		sys.exit(-1)

	domains = fuzz_domain(args.domain.lower())

	if not module_dnspython:
		sys.stderr.write('NOTICE: Missing module: dnspython - DNS features limited!\n')
	if not module_geoip and args.geoip:
		sys.stderr.write('NOTICE: Missing module: GeoIP - geographical location not available!\n')
	if not module_whois and args.whois:
		sys.stderr.write('NOTICE: Missing module: whois - database not accessible!\n')
	if not module_ssdeep and args.ssdeep:
		sys.stderr.write('NOTICE: Missing module: ssdeep - fuzzy hashes not available!\n')
	if not module_requests and args.ssdeep:
		sys.stderr.write('NOTICE: Missing module: Requests - web page downloads not possible!\n')

	if args.ssdeep and module_ssdeep and module_requests:
		display('Fetching web page from: http://' + args.domain.lower() + '/ [following redirects] ... ')
		try:
			req = requests.get('http://' + args.domain.lower(), timeout=2)
		except:
			display('Failed!\n')
			args.ssdeep = False			
			pass
		else:
			display('%d %s (%d bytes)\n' % (req.status_code, req.reason, len(req.text)))
			orig_domain_ssdeep = ssdeep.hash(req.text)

	display('Processing %d domains ' % len(domains))

	signal.signal(signal.SIGINT, sigint_handler)

	total_hits = 0

	for i in range(0, len(domains)):
		if module_dnspython:
			resolv = dns.resolver.Resolver()
			resolv.lifetime = 1
			resolv.timeout = 1

			try:
				ns = resolv.query(domains[i]['domain'], 'NS')
				domains[i]['ns'] = str(ns[0])[:-1].lower()
			except:
				pass

			if 'ns' in domains[i]:
				try:
					ns = resolv.query(domains[i]['domain'], 'A')
					domains[i]['a'] = str(ns[0])
				except:
					pass
	
				try:
					ns = resolv.query(domains[i]['domain'], 'AAAA')
					domains[i]['aaaa'] = str(ns[0])
				except:
					pass

				try:
					mx = resolv.query(domains[i]['domain'], 'MX')
					domains[i]['mx'] = str(mx[0].exchange)[:-1].lower()
				except:
					pass
		else:
			try:
				ip = socket.getaddrinfo(domains[i]['domain'], 80)
			except:
				pass
			else:
				for j in ip:
					if '.' in j[4][0]:
						domains[i]['a'] = j[4][0]
						break
				for j in ip:
					if ':' in j[4][0]:
						domains[i]['aaaa'] = j[4][0]
						break

		if module_whois and args.whois:
			if 'ns' in domains[i] or 'a' in domains[i]:
				try:
					whoisdb = whois.query(domains[i]['domain'])
					domains[i]['created'] = str(whoisdb.creation_date).replace(' ', 'T')
					domains[i]['updated'] = str(whoisdb.last_updated).replace(' ', 'T')
				except:
					pass

		if module_geoip and args.geoip:
			if 'a' in domains[i]:
				gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
				try:
					country = gi.country_name_by_addr(domains[i]['a'])
				except:
					pass
				else:
					if country:
						domains[i]['country'] = country

		if args.banners:
			if 'a' in domains[i]:
				banner = http_banner(domains[i]['a'], domains[i]['domain'])
				if banner:
					domains[i]['banner-http'] = banner
			if 'mx' in domains[i]:
				banner = smtp_banner(domains[i]['mx'])
				if banner:
					domains[i]['banner-smtp'] = banner

		if module_ssdeep and module_requests and args.ssdeep:
			if 'a' in domains[i]:
				try:
					req = requests.get('http://' + domains[i]['domain'], timeout=1)
					fuzz_domain_ssdeep = ssdeep.hash(req.text)
				except:
					pass
				else:
					domains[i]['ssdeep'] = ssdeep.compare(orig_domain_ssdeep, fuzz_domain_ssdeep)

		if 'a' in domains[i] or 'ns' in domains[i]:
			display(FG_YELLOW + '!' + FG_RESET)
			total_hits += 1
		else:
			display('.')

	display(' %d hit(s)\n\n' % total_hits)

	display_csv('Generator,Domain,A,AAAA,MX,NS,Country,Created,Updated,SSDEEP\n')

	for i in domains:
		info = ''

		if 'a' in i:
			info += i['a']
			if 'country' in i:
				info += FG_CYAN + '/' + i['country'] + FG_RESET
			if 'banner-http' in i:
				info += ' %sHTTP:%s"%s"%s' % (FG_GREEN, FG_CYAN, i['banner-http'], FG_RESET)
		elif 'ns' in i:
			info += '%sNS:%s%s%s' % (FG_GREEN, FG_CYAN, i['ns'], FG_RESET)

		if 'aaaa' in i:
			info += ' ' + i['aaaa']

		if 'mx' in i:
			info += ' %sMX:%s%s%s' % (FG_GREEN, FG_CYAN, i['mx'], FG_RESET)
			if 'banner-smtp' in i:
				info += ' %sSMTP:%s"%s"%s' % (FG_GREEN, FG_CYAN, i['banner-smtp'], FG_RESET)

		if 'created' in i and 'updated' in i and i['created'] == i['updated']:
			info += ' %sCreated/Updated:%s%s%s' % (FG_GREEN, FG_CYAN, i['created'], FG_RESET)
		else:
			if 'created' in i:
				info += ' %sCreated:%s%s%s' % (FG_GREEN, FG_CYAN, i['created'], FG_RESET)
			if 'updated' in i:
				info += ' %sUpdated:%s%s%s' % (FG_GREEN, FG_CYAN, i['updated'], FG_RESET)

		if 'ssdeep' in i:
			if i['ssdeep'] > 0:
				info += ' %sSSDEEP:%s%d%%%s' % (FG_GREEN, FG_CYAN, i['ssdeep'], FG_RESET)

		if not info:
			info = '-'

		if (args.registered and info != '-') or not args.registered:
			display('%s%-15s%s %-15s %s\n' % (FG_BLUE, i['type'], FG_RESET, i['domain'], info))
			display_csv(
			'%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % (i.get('type'), i.get('domain'), i.get('a', ''),
			i.get('aaaa', ''), i.get('mx', ''), i.get('ns', ''), i.get('country', ''),
			i.get('created', ''), i.get('updated', ''), str(i.get('ssdeep', '')))
			)

	display(FG_RESET + ST_RESET)

	return 0

if __name__ == '__main__':
	main()

Source : https://github.com/elceef |   Our Post Before

Uproot ~ a Host Based Intrusion Detection System (HIDS) for leveraging WMI Permanent Event Subscriptions.

$
0
0

Uproot is a Host Based Intrusion Detection System (HIDS) that leverages Permanent Windows Management Instrumentation (WMI) Event Susbcriptions to detect malicious activity on a network. For more details on WMI Event Subscriptions please see the WMIEventing Module.

Uproot is a Host Based Intrusion Detection System (HIDS) that leverages Permanent Windows Management Instrumentation (WMI) Event Susbcriptions

Uproot is a Host Based Intrusion Detection System (HIDS) that leverages Permanent Windows Management Instrumentation (WMI) Event Susbcriptions

For best results, it is recommended to use Uproot’s AS_GenericHTTP consumer and an Uproot Listening Post to forward events via syslog to a log aggregator such as Splunk.
Note: Uproot was designed for a controller with >= PowerShell v3 compatibility. The module can be used with PowerShell v2, but will be missing a great deal of functionality. Although, Microsoft has consistently included WMI in Microsoft Windows since Windows NT 4.0 and Windows 95. Because of this, Uproot can be used with Windows OS endpoints from Windows NT 4.0 forward.

Latest change 9/24/2015:
+ Updated WMIEventing Tests;
1_WmiEventFilter.Tests.ps1
2_WmiEventConsumer.Tests.ps1
3_WmiEventSubscription.Tests.ps1

Uproot Listening Post :
The Uproot project includes a service executable that can be used as a Listening Post (LP) (a point in the network that aggregates and forwards on events). The Listening Post receives HTTP POST requests, converts the recieved data to Syslog, and forwards the data to any specified location (ex. Splunk).
You can have multiple Listening Posts throughout your network to allow for load distribution, or to work with firewall restrictions.

Below is a list of Cmdlets to install/configure an Uproot Listening Post:

Get-UprootLP - Lists Uproot Listening Posts on a local or remote computer.
New-UprootLP - Creates a new Uproot Listening Post on a local or remote computer.
Remove-UprootLP - Removes the Uproot Listening Post from a local or remote computer.
Restart-UprootLP - Restarts the Uproot Listening Post on a local or remote computer with new configs.
Start-UprootLP - Starts the Uproot Listening Post on a local or remote computer.
Stop-UprootLP - Stops the Uproot Listening Post on a local or remote computer.

NOTE: To avoid creating a privilege escalation vulnerability, we recommend that you move uprootd.exe to C:\Windows\system32\ before using New-UprootLP

Module Installation:

1. (new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex
2. Set-ExecutionPolicy RemoteSigned
3. install-module PsUrl
4. install-module -ModuleUrl https://github.com/Invoke-IR/Uproot/archive/master.zip
5. Import-Module Uproot
6. Get-Command -Module Uproot

Source : https://github.com/Invoke-IR

Updates Tools : a Collection security and hacking tools; likes exploits, proof of concepts, shellcodes, scripts, and more.

$
0
0

latest change 9/25/2015 tools added :
+ dnsspider.py v0.7 : A very fast multithreaded bruteforcer of subdomains that leverages a wordlist and/or character permutation.
+ CHANGELOG dnsspider v0.7:
– upgraded built-in wordlist (more than 2k)
– remove annoying timeout warnings
– remove color output when logging to file

Dnsspider : A very fast multithreaded bruteforcer of subdomains that leverages a wordlist and/or character permutation

Dnsspider : A very fast multithreaded bruteforcer of subdomains that leverages a wordlist and/or character permutation

This section offers a selection of our fully featured security and hacking tools from NullSecurity.
+ Automation :
This section includes automation tools and wrapper scripts for well-known and public security tools to make your life easier. You can adjust the scripts fast and easily according to your own needs. Mostly written in bourne shell.
+ Backdoor :
Backdoors and rootkits for kernel and userland, network, hardware and software. Once you have gone through all the hard work making sure you can get on the system. Make sure you can always get back in.
+ Binary :
ELF and PE binary related tools. This section includes packers, runtime crypters, including our famous (thanks trusted sec team) hyperion tool from our very own belial and other stuff.
+ Cracker :
Tools for cracking network and software login masks. Not been able to find an exploit to give you RCE? Too lazy to SE? So go smash down the front doors and rummage around with our cracking and brute force tools.
+ Cryptography :
Encrypt all the things! With privacy issues moving up most people agenda with items like PRISM in the news cryptography it one of todays hot topics. It’s also pretty useful for exfiltrating data from your target environment, connecting to that C2 box and keeping your loot away from prying eyes.
+ DDoS :
(D)DoS tools if you wanna by like those n00bs at anonymous or simulate everyones favourite underground extortionists.
+ Exploit :
Proof of Concept tools and, if we are feeling particularly generous, fully working exploits because there is nothing more fun that RCE, except dinner with noptrix of course.
+ Fuzzer :
Didn’t find the exploit you wanted in our exploit section well try one of our fuzzers and write you own god damn code.
+ Keylogger :
When you really need to know those credentials you keep seeing the user enter or are too lazy to go searching for every new piece of useful information just try one of our keyloggers and get the user to do the hard work for you!
+ LogCleaner :
Just because our mothers raised us right, we always clean up after ourselves and pwnage is no exception. These logcleaners also help in not getting caught on that important engagement.
+ Misc :
This section includes miscellanous files. Often, you will find non-security related stuff here.
+ Resersing :
Whether figuring out how that new piece of malware you just discovered works or hunting for the next 0day from $vendor, our reversing toolz will help you on your way.
+ Scanner
Can’t find any useful hints on shodan? Google dorks not dishing up the goods? Hell get one of our scanners out and track down your targets in 2 shakes of a lol-cat’s tail.
+ Shellcode
Just because our fuzzer worked or the PoC was fantastic doesn’t mean that running calc is gonna put a smile on your face. If you got RCE try our shellcodes to actually do something useful.
+ Wireless
Why wireless? It works and you don’t have to wear your favorite nullsecurity hoody to hide you face from the camera in reception. Hack all the thingz!

Downlaod : Master.zip  | Clone Url
Source : http://nullsecurity.net/ | Our Post Before

Viewing all 443 articles
Browse latest View live