Showing posts with label Security. Show all posts
Showing posts with label Security. Show all posts

A Basic Port Scanner in Python, Java

One of the first tools you need for a penetration test is a Port Scanner. There are some very awesome port scanners out there like Nmap but did you ever wonder how to make one? Here's how: 


#! /usr/bin/env python
# PortScanner.py
# Author: Abdul Fatir
# E-Mail: abdulfatirs@gmail.com

from socket import *
HostName = raw_input("Host Name: ")
try:
	# gethostbyname(HostName) returns the IPv4 address of a website
	IPaddress = gethostbyname(HostName)
except:
	print "[-] Could not find host."
	quit()
portstring = raw_input("Ports (separated by commas):")
ports = portstring.split(",")
print "\n[*] Scan results for "+HostName+" ("+IPaddress+"):"
# setdefaulttimeout(1) sets the waiting time for website response to 1 seconds. This may result in closed port even though the port may be open if it takes more than 1 second.
setdefaulttimeout(1)
for port in ports:
	try:
		connection = socket(AF_INET,SOCK_STREAM)
		# socket.connect((IP,PORT)) connect to the IP at given port.
		connection.connect((IPaddress,int(port)))
		connection.send('hello\r\n')
		# socket.recv(BUFFER_SIZE) receives the server response
		data = connection.recv(8)
		# If we have reached this far that means the port is open.
		print "\t[+] "+port+"/tcp open"
	except:
		print "\t[-] "+port+"/tcp closed"
	finally:
		connection.close()

Download the python code from pastebin

Here is a similar example in Java:


import java.net.*;
import java.util.*;
import java.io.*;
import static java.lang.System.out;
public class PortScanner
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        out.print("HostName: ");
        String host=br.readLine();
        InetAddress address=null;
        try
        {
            address = InetAddress.getByName(host);
        }
        catch(UnknownHostException uhe)
        {
            out.print("[-] Could not find host.");
            System.exit(0);
        }
        out.print("Ports (separated by commas): ");
        String portstring = br.readLine();
        StringTokenizer ports = new StringTokenizer(portstring,",");
        out.println("[*] Scan results for "+host+" ("+address.getHostAddress()+"):");
        while(ports.hasMoreTokens())
        {
            int port = 0;
            try{
                port = Integer.parseInt(ports.nextToken());
                Socket conn=new Socket();
                conn.connect(new InetSocketAddress(host,port),1000);
                conn.close();
                out.println("\t[+] "+port+"/tcp open");
            }
            catch(SocketTimeoutException ste)
            {
                out.println("\t[-] "+port+"/tcp closed");
            }
        }
        
    }
}

Download the Java code from pastebin

Note: This is a very basic example and must not be used as a substitute for tools like Nmap.

Calculate MD5 Checksum of a File in Python

With increased MITM (Man In The Middle) attacks it is essential that you check the authenticity of files you download from the Internet. One of the ways of doing so is checking the MD5 sum of the file and comparing it with the checksum given on the download providers website.

Here's how to perform this task in Python:

#! /usr/bin/env python
# ChecksumChecker.py
# Author: Abdul Fatir
# E-Mail: abdulfatirs@gmail.com

from threading import Thread
import hashlib
import optparse

def getChecksum(file_path,check_hash):
 file_handle = open(file_path,"rb")
 _md5 = hashlib.md5()
 while True:
  _buffer = file_handle.read()
  if not _buffer:
   break
  _md5.update(_buffer)
 digest = _md5.hexdigest()
 print "[ ] File's MD5 checksum is: " digest
 if (check_hash != None):
  if(check_hash.lower() == digest):
   print "[ ] Hash matched: The file is authentic."
  else:
   print "[-] Hash mis-match: The file is not authentic."

def Main():
 parser = optparse.OptionParser('usage: %prog -f <filename> [-m <md5 hash>]')
 parser.add_option('-f', dest='file_path', type='string', help='Please specify a file')
 parser.add_option('-m', dest='check_hash', type='string')
 (options,arg) = parser.parse_args()
 if (options.file_path == None):
  print parser.usage
  exit(0)
 else:
  file_path = options.file_path
  check_hash = options.check_hash
 print "[*] Hashing file '"  file_path  "'...."
 hash_thread = Thread(target=getChecksum,args=(file_path,check_hash))
 hash_thread.start()
 hash_thread.join()
if __name__  == '__main__':
 Main()

Please don't copy paste this code, download it from pastebin.

Usage examples:

Suppose you downloaded a file named hello.exe which has an MD5 hash 5D41402ABC4B2A76B9719D911017C592 given on the Internet then to check if you downloaded the correct file use ChecksumChecker.py as follows:

$ python ChecksumChecker.py -f <path to hello.exe> -m 5D41402ABC4B2A76B9719D911017C592

To simply get the MD5 sum of a file, do:

$ python ChecksumChecker.py -f <path to hello.exe>

Note:

  1. This is a prototype. You can added more algorithms like SHA1 and SHA256 as per your requirements.
  2. This code executes in Python 2.7.x

Privacy Resurrected

Searching for stuff? Your government knows it. Sending a private message? The NSA knows it. You set up a WiFi router, the Google mobile van knows about your devices' MAC Addresses and other stuff. Now you know how the free WiFi tracking applications work. Privacy, dear noble people, is dead.

But wait, are all doors closed? Let's add life to the dying privacy of the world. What measures can we take to remain anonymous on the internet? But before going into the details let's know why websites track us and what they can do with our personal information.

  • Web giants like Google, Facebook and Twitter know about your browsing history so that they can frame personalized advertisements and generate more revenue for themselves.
  • Everything seems free on the internet nowadays but guess what, they're minting on your personal information. E-mail for spams and product advertisements, mobile number for telemarketing and the list goes on.

How to prevent websites from tracking you?

  • Enable sending a 'Do Not Track' request from your browser's privacy settings.
  • Install a tracker blocking program like Abine's Do Not Track Me.
  • Read the privacy statement of the websites and enable necessary features for your online privacy. Keep a check on what you share with third party applications on your social accounts.

How to remain anonymous on the internet?

Your IP Address is your fingerprint on the internet. Websites track your location on grounds of your IP address. So how do you prevent them from doing that? Simple, fake your IP. But how do you fake your identity?

  • Use an anonymous web proxy like hidemyass. There are other paid proxies known as elite proxies which can be use for enhanced anonymity. Use plugins like FoxyProxy in Firefox.
  • TOR everything, Yes this was the topic of a lecture in Black Hat 2013. Use the TOR browser bundle which spoofs your IP address and you appear to be browsing from an entirely different country altogether. Use plugins like CryptoCat, HTTPs Everywhere and Ad Block Plus.
  • Use A Virtual Private Network like CyberGhostVPN or purchase a premium VPN service and access the internet from behind the VPN.
  • If you are really concerned about privacy you know you are not 100% save anyway. To increase the level of safety wipe off Windows from your hard drive and use Tails, a Linux distribution dedicated to provide you online anonymity. It uses the TOR network for every connection you make to the internet.

Other safety measures

  • Don't trust the mail clients, encrypt your emails instead. There are many free text encryption mechanisms available on the internet which work with almost all famous mail clients. One such service is mailvelope.
  • Use the incognito mode of your web browser when using internet on public computers.
  • Provide websites your real information when it is needed for sure, use fake identities where it is not needed. Many websites require your personal information for registrations. Go to http://www.fakenamegenerator.com and use the fake information instead. But what about the e-mail activation process? You've a solution for everything. Use a disposable e-mail service like http://www.10minutemail.com which sets up a temporary email address for you which you can verify and dispose.
  • Use private cloud services like http://www.tonido.com/ to save your files on the internet privately.

Nothing on the internet is one hundred percent safety but by following these steps you can at least be sure of 99 %. You're now anonymous, enjoy the resurrected privacy.