Linux Database Server: Postgresql and pgAdmin

2 12 2011

I hope that you use a Debian-based distro!

sudo apt-get install postgresql

Setup the postgres‘s password:

sudo -u postgres psql
\password

digit the new password, then press Ctrl+D to exit from psql.

Edit this file (adjust your version number, I’ve used 9.1 for write this guide)

sudo vi /etc/postgresql/9.1/main/postgresql.conf

and change these lines (caution with apices, don’t cut&paste):

#listen_addresses = ‘localhost’ –> listen_addresses = ‘*’

#password_encryption = on –> password_encryption = on

finally define who can access the server:

sudo vi /etc/postgresql/9.1/main/pg_hba.conf

add to the end of file:

host all all [ip address] [subnet mask] md5

here you can specify a single host or a complete subnet, for example:

host all all 192.168.160.0/24 md5

Now we can configure pgAdmin, that is a free and open source graphical user interface administration tool for PostgreSQL, which is supported by many computer platforms.

Install your version, I continue with a GNU/Linux Debian-based:

sudo apt-get install pgadmin3

Open pgAdmin and add your server:

  • Name: [any descriptive name]
  • Host: [ip address of the server]
  • Password: [your postgres's password]

End: here we are!





AuthFail python script

14 10 2011

I wanted to improve this script that I had originally written in bash and I took the opportunity to learn python (three days).

Please, comment! I need criticism… more precisely about the thread management, I understand that’s bad programming.

In fact the portscan takes about 4 minutes with 50 hosts… but work!

Usage of the script:

usage:
 python authfail.py FILE [FILE]

 Parse an auth.log FILE and return the ascending stats list with
 geolocalization about ip addresses that cause a sshd's auth failure.

 If you specify the [FILE] it checks if IP addresses which attacks
 came from and have sshd's port 22 open and save the results on it.

The auth.log file path is:

/var/log/auth.log

however may change…

This software is under GPLv3 license.

Here the source code:

"""
    Copyright (C) 2011  Simone Aonzo

    This program 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 3 of the License, or
    (at your option) any later version.

    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import threading, Queue
import urllib2
import socket
import socket
import sys
import re

# Keyword in auth.log for invalid login
authFail = "Failed password for invalid user"

# Regex of ip address (tnx evilsocket for compile suggest!)
ipRegEx = re.compile(r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b")

# Website that provide api
apiHostIp = "http://api.hostip.info/get_html.php?ip="

# Dictionary and List initializer
dictBase = {}
listAtt = []

# sshd port
SSHPORT = 22

#scan flag
SCAN = False

# Usage
help = """

	AuthFail 1.0 - by Six110

http://sixthevicious.wordpress.com/

========================================
	usage:
            python authfail.py FILE [FILE]

	Parse an auth.log FILE and return the ascending stats list with
	geolocalization about ip addresses that cause a sshd's auth failure.

	If you specify the [FILE] it checks if IP addresses which attacks
	came from and have sshd's port 22 open and save the results on it.

	This software is released under GPLv3 license.
"""

# Check if input string match the regexp
def ipFormatChk (ipStr):
   if ipRegEx.match(ipStr):
      return True
   else:
      return False

# Convert a list of tuple into the ip address string
def fromRegexToString (line):
	return (" ".join( ipRegEx.findall(line)[0] )).replace(" ",".")

# Class with data of the attacker
class Attacker(object):
	def __init__(self, ip, hits, country, city, isopenssh=None):
		self.ip = ip
		self.hits = hits
		self.country = country
		self.city = city
		self.isopenssh = isopenssh

# Class that implement portscanning with threading
class Scanner(threading.Thread):
    def __init__(self, inq, outq):
        threading.Thread.__init__(self)
        self.setDaemon(1)
        # queues for Attackers
        self.inq = inq
        self.outq = outq

    def run(self):
        while True:
            # Retrive attacker from queue
            a = self.inq.get()
            host, port = a.ip, SSHPORT
            sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                sd.connect((host, port))
            except socket.error:
				a.isopenssh = "False"
				self.outq.put(a)
            else:
				a.isopenssh = "True"
				self.outq.put(a)
				sd.close()

#======================================================================#

alen = len(sys.argv)

if (alen < 2) or (alen > 3):
	print help
	quit()

if (alen == 3):
	try:
		fileOUT = open (sys.argv[2], 'w')
		SCAN = True
	except:
		fileOUT = None
		print "Error! I can't write this file -> " + sys.argv[2]
else:
	fileOUT = None

try:
	fileIN = open(sys.argv[1], "r")
except:
	fileIN = None
	print "Error! I can't read this file -> " + sys.argv[1]
	sys.exit(1)

line = fileIN.readline()

# Read each line of the file
# if found an ip it search the dictionary for the entry
# if it's present, increment the counter
# otherwise add the ip and initialize the counter
while line:
	if (line.find(authFail) != -1):
		ipFound = fromRegexToString (line)
		if ( ipFound in dictBase):
			dictBase[ipFound] = dictBase.get(ipFound)+1
		else :
			dictBase[ipFound] = 1
	line = fileIN.readline()

# Close the input files
fileIN.close()

items = 0
# Create the classes and add them to the list counting the entries
for ip, hits in dictBase.iteritems():
	resp = urllib2.urlopen( apiHostIp+ip ).read()
	country = resp [ resp.find('Country: ')+9 : resp.find('\n') ]
	city = resp [ resp.find('City: ')+6 : resp.find('\n',resp.find('City: ')) ]
	listAtt.append( Attacker(ip, hits, country, city) )
	items += 1

# Free the dictionary
dictBase.clear()

# Start ssh scanner
if (SCAN):
	toscan = Queue.Queue()
	scanned = Queue.Queue()
	scanners = [Scanner(toscan, scanned) for i in range(items)]

	for scanner in scanners:
		scanner.start()
	for a in listAtt:
		toscan.put(a)
	listAtt.count
	for c in range(0,items):
		try:
			scanned.get(16)
		except Queue.Empty:
			c = items

# Redefines the sort function with the total order relation
# for confront two Attacker classes
listAtt.sort (lambda x, y: cmp(y.hits, x.hits) )

for a in listAtt:
	if ( fileOUT != None and SCAN == True and a.isopenssh == "True"):
		fileOUT.write(a.ip+"\n")
	print "\nIp: "+ a.ip + "\nHits: %d"% a.hits + "\nPort %s open: "%SSHPORT + str(a.isopenssh) + "\nCountry: %s"%a.country + "\nCity: %s\n"%a.city

# Close the output file
if (fileOUT != None):
	fileOUT.close()




Nmap – cheat sheet

9 10 2011

Every time I spend useless time to refresh my memory from nmap man page, so I create this little chat sheet.

Any suggestion will be appreciated!

If you specifie the class, it’ll search all ip in that class range:

w.x.y.z/c

Input from list of hosts/networks:

-iL filename

Output in (fname.nmap fname.xml fname.gnmap):

-oA fname

Increase verbosity level (use -vv or more for greater effect):

-v

Reverse DNS.

-sL

Force send TCP SYN packet (use raw socket, need root):

-sS

Use ACK scan (use on open and filtered ports):

-sA

if (unfiltered) ‘stateless firewall’ else if (all result filtered) ‘stateful firewall’

UDP scan:

-sU

Probe open ports to determine service/version info:

-sV

Enable OS detection:

-O

Enable OS detection, version detection, script scanning, and traceroute:

-A

Treat all hosts as online (skip ACK on 80,443 and ICMP PING,TIMESTAMP):

-Pn

Scan all possible ports:

-p1-65535

Scan <number> most common ports (http://nmap.org/presentations/BHDC08/):

--top-ports <number>




Reverse Engineering Android APK

22 09 2011

Vicious… yes!

Problem:

You’ve downloaded an APK somewhere and you want to extract images, xml and source. For simplicity we work with appname.apk

Resources:

  1. http://code.google.com/p/android-apktool/
  2. http://code.google.com/p/dex2jar/
  3. http://java.decompiler.free.fr/?q=jdgui


Extract images and xml:

  1. Launch from command line apktool passing appname.apk as first argument, then
  2. appname folder will be created and there you can find xml files and images.

Extract sources:

  1. Rename appname.apk in appname.zip, open it with your favorite archive manager, and extract the classes.dex file.
  2. In order to avoid path problem, I advice you  to copy the classes.dex file in dex2jar-* folder.
  3. Depending your operating system, launch from command line related dex2jar script passing classes.dex as first argument.
  4. Then, you’ll find the executable jar file classes_dex2jar.jar in the same directory.
  5. Open it with jd-gui and good luck!




Install VMware tools on Ubuntu

7 09 2011

1) Start the virtualization program and start installing a new machine with Ubuntu.

2) After installation run the terminal and type the following command line:

sudo apt-get install build-essential linux-headers-$(uname -r)

3) Select from the menu Vmware: “Install VMware Tools” and copy the file “vmwaretools-*.tar.gz”on your machine.

4) Extract the contents of the file “vmwaretools-*.tar.gz” with the command:

tar zxf vmwaretools-*.tar.gz

5) Move into the folder “vmware-tools-distrib” and start the installation with the command

sudo ./vmware-install.pl

6) Confirm all defaults values pressing “Enter”.

7) Reboot the virtual machine: installation has finished!





Metasploit The Penetration Tester’s Guide [pdf]

9 08 2011

Great work. But I prefer free information. Is it a crime?

You can buy this book or you can download the pdf here:

http://depositfiles.com/en/files/qntr6sr0y/25383_Metasploit.pdf

Or here:

http://www.fileserve.com/file/j8mf3A7





Install Magento on Ubuntu Server

1 08 2011

Why are there lots of guides with strange and mystical commands about installing Magento? It’s so easy!

I’m joking, but I want to reassume the guide you can find at its wiki.

Perform a clean install of Ubuntu Server (I suggest >= 10.04) then type (mark your MySql password!) :

sudo tasksel install lamp-server openssh-server
sudo apt-get install php5-curl php5-cli php5-gd php5-mcrypt

Now you can continue with a ssh connection.

For avoid a future security issue, edit this Apache configuration file:

sudo vi /etc/apache2/sites-enabled/000-default

and change all occurrences of:
AllowOverride None
with
AllowOverride All

Create the database and its new proprietary user (replace “magentoadmin” and “password” as you like) :

mysql -u root -p
CREATE DATABASE magento;
GRANT ALL PRIVILEGES ON magento.* TO 'magentoadmin'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;

Delete default index.html, download Magento, unpack and set permissions.
Here are commands, but I suggest to visit the official download page for updates (Full Release).

cd /var/www
sudo rm /var/www/index.html
sudo wget http://www.magentocommerce.com/downloads/assets/1.5.1.0/magento-1.5.1.0.tar.gz
sudo tar -zxvf magento-1.5.1.0.tar.gz
sudo chown -R www-data.www-data *
sudo mv magento/* magento/.htaccess .
sudo find . -type f -exec chmod 644 {} \;
sudo find . -type d -exec chmod 755 {} \;
sudo chmod o+w var var/.htaccess app/etc
sudo chmod 550 mage
sudo chmod -R o+w media var
sudo rm -rf magento/ magento-1.5.1.0.tar.gz
sudo service apache2 restart

Open your browser pointing the ip address of your server and finish the installation.

Any feedback will be appreciated…





Firefox 5: save and exit

10 07 2011

Why has Mozilla disabled this feature? I don’t know, but I found how restoring it.

in your address bar type:

about:config

Confirm, then search:

browser.showQuitWarning

and turn: true.





YouJizz bash video downloader

1 07 2011

“A friend” asks me how he could download a video from the famous porn site YouJizz.

I’ve created a simple bash script…I share it with you for a laugh :-)

After running it, you’ll find a .flv video in the directory where you launched the script.

#!/bin/bash
wget $1
wget $(grep 'so.addVariable("file","http:' $(echo $1 | cut -d '/' -f 5) | cut -d '"' -f 4)
rm $(echo $1 | cut -d '/' -f 5)

You can use it in this way:

./ujizz.sh urlcontainsvideo




How to: sniff (and decrypt) wifi packets

13 06 2011

Wifi networks are “better” for sniffing than switched ones, because you can capture every packet without any particular attacks (see ManInTheMiddle) modulo information loss.

Software:
- aircrack-ng suite (precisely airodump-ng)
- wireshark

Requirement:
- bssid, channel and encryption key of network (is your conscience clear?)
- wireless card that works in monitor mode

Enable monitor mode:

airmon-ng start <interface>

Start sniffing:

airodump-ng <monitorif> -c <channel> -d <bssid> -w <filename>

When you have captured enough packets, it’s wireshark time!
Open the .cap file with wireshark:

wireshark filename.cap

Go to:
Edit -> Preferences -> Protocols

Search:
IEEE 802.11

Check “Enable decryption“.

Specify the encryption key in the respective field.
Be careful with syntax! See this page:

http://wiki.wireshark.org/HowToDecrypt802.11

Click “Apply” then “OK“.
Now you can understand why open networks are so dangerous!

For lamers:
No, you can’t (well, not so easily) retrieve crypted data!
For this, there are various attack that I’ll not teach :-)

For geek:
See http POST command and guess what happens when you login at an insecure webpage.








Follow

Get every new post delivered to your Inbox.

Join 389 other followers