Linux: Running Scripts on Startup

One of the easiest ways to run a script or command on startup is to use the crontab.

The crontab includes an entry string to let you run a script after reboot or on startup.

Enter the crontab.

crontab -e

Add an item to run on startup.

@reboot <COMMAND OR SCRIPT TO RUN>

My crontab entry is visible below. I used this to start all my scripts on my Pi creation.

Screen Shot 2014-01-26 at 12.30.43 PM

Other startup options include, writing an entry into the bashrc. For the Pi, you could also write an entry in /etc/rc.local. This article discusses actually creating an init.d script for those interested.

Soldering an LCD to the Raspberry Pi

Adafruit sells some really cute LCD screens for the Pi. I recently purchased such screen and decided to solder the screen directly to my Pi after seeing this guy’s cool pi project.

So to catch up on what I’ve done so far on my Pi, check out this post. The following steps discuss my experience soldering the pieces together.

Equipment

  • My Pi
  • Soldering Iron (Aoyue 937+ is about $63 on Amazon)
  • Solder ($8.16 Amazon Prime)
  • Battery Holder ($3.86)
  • 4 AA Batteries
  • Electric Tape
  • Double Sided Tape
  • A frame to hold it all

2014-01-23 19.42.58

Putting the Parts Together

2014-01-23 19.56.18

I first soldered the LCD power lines to the batter pack. The LCD runs on 6-12V. I found this cheap battery holder on Amazon that could hold four AA batteries or 6V total. The power lines are the two that did not come attached to one of the two RCA connectors. Solder the red to the positive (+) battery pack output and the black to the negative (-) output. Think as red surging hot with power and the black as dead or negative of surging power.

Not sure this is the best soldering technique but I normally tint the soldering iron tip with a bit of solder first then I set that tip against the connection point. Last, I’ll stick the wire into the hot solder on the iron touching the connection point before carefully removing the iron from the solder.

2014-01-23 20.31.13

I had batteries in the holder during this process so I could see the LCD powered on and ensure the wires were soldered correctly in place. Just be careful, don’t shock yourself.

Next, I cut off one of the RCA connectors. Basically one connector is a backup for the other, if there isn’t a signal coming in on one, the other is checked or used. It does not matter which one you choose to hook up to the screen. Make sure not to cut off too much wire during this process.

Following, I striped some of the insulator back off the wire then soldered it to the board. The picture below shows where I soldered everything on the under side of the Pi. Your colored cables might not be the same as mine. Test everything before you actually solder it onto the board. It’s easy just power on the Pi and test the wires to see what actually outputs video to the Pi.

2014-01-23 20.21.54

Tah dah! Now everything is hooked up! I then taped it all to a frame to make it pretty.

2014-01-23 22.02.11
Back
2014-01-23 22.01.52
Front

From here, you may be interested in having the Pi auto login (not advisable but I did it) and boot startx (the desktop GUI). This was the most helpful tutorial for accomplishing the auto boot stuff.

I’m pretty proud.

Handy-Dandy Terminal Shortcuts

Hey all, here are some handy terminal shortcuts I’ve stumbled upon in school and work. Maybe they’ll make your life easier as you go about entering commands in a Unix bash shell.

The + sign is not part of the key combination, it’s just to show what buttons to hit together.

CTRL + “u” -> Delete current text in prompt and move cursor to the beginning
CTRL + “k” -> Similar to the last, but instead it kills the input
CTRL + “y” -> Return the last killed input
CTRL + “a” -> Jump cursor to the beginning of your terminal input line
CTRL + “e” -> Jump cursor to the end of your terminal input line
CTRL + “f” -> Move cursor forward one character (similar to right arrow key)
CTRL + “b” -> Move cursor backward one character (similar to left arrow key)
CTRL + “d” -> Backwards Delete (For all you Mac users)
CTRL + “h” -> Forward Delete
CTRL + “r” -> Extremely useful, lets you look up a previous used command. Just press CTRL plus the letter “r” then begin typing the command, the promo will return the last command that used the term.
CTRL + “l” -> Clear screen

I’ll add to this list as I come upon more helpful terminal shortcuts.

My Ultimate Network Monitor/Enumeration Tool – Putting It All Together

Finally, all the parts come together. Look at my previous posts for all the pieces to building the LilDevil network monitor and enumeration tool.

The LilDevil

So this tool I created sits on a Raspberry Pi. Its purpose is to monitor and enumerate all devices currently connected to a network. In this case, it sits on my Guest network. Tomato Shibby is running on my router and I used its web interface to setup the network, along with limiting access. For all guests jointing this network, they are warned by the router’s splash page that tools such as this will be running. Its a free network and they really can’t expect anything different going on. In this case, its not malicious, but it is good practice to be wary of guest networks.

To be less suspicious, the hostname of the Raspberry Pi is RainbowDash 😉 This amuses me so much, the perfect disguise! If I saw a device named LilDevil running on a guest network I would be totally alarmed. I also themed the Pi accordingly, see the below screenshot. The coloring isn’t perfect, I blame VNC.

RainbowDash

The Pi runs a Django Restful server that stores mmap scan information about detected machines on the network. The Python 2.7 scripts for this are here. I had to make a few versions in order for things to work on Django 1.6.

In views.py, change

encoded = json.loads(request.raw_post_data)

to

encoded = json.loads(request.body)

Also, I had to make some changes in dirtBag.py, in order to get the ping sweep to work appropriate.

Change MIN and MAX to an integer instead of a string.

MIN="0"
MAX="12"

to

MIN=0
MAX=12

Here is a copy of the new main function.

def main():
    global results
    while 1:
        new = ""
        for x in range(MIN,MAX):
            new = new + commands.getoutput("ping -c 1 -t 1 "+PREFIX+"."+str(x) + " | grep 'from'") #Ping sweep the network to find connected devices
        tmp = re.findall(PREFIX+".(d+)", str(new)) #Pull out IP addresses from the ping results
        if tmp != results:
            for ip in tmp:
                if ip not in results:
                    gotcha = commands.getoutput('nmap -v -A -Pn '+PREFIX+'.'+ip)
                    sendDevice(gotcha)
            for r in results:
                if r not in tmp:
                    removeDevice(PREFIX+'.'+r)
            results = tmp

The information is up to date on all devices currently connected. It may be nice in the future to include a log of all scans but for now, I’m really only interested in connected machines.

Data is then displayed in a visible GUI. The below screenshot shows the tool windows along with the GUI. Currently, no devices were connected to the network.

Screen Shot 2014-01-17 at 9.27.49 PM

 

Ahhh it detected a device… in this case, itself.

Screen Shot 2014-01-19 at 7.58.55 PM

There you have it! A portable network enumeration tool. There are so many versions of this everywhere, but this is just something I coded up for fun. I plan to add to the Pi later for kicks.

Playing with the Pi: Portable Server

I want to use my Kali Raspberry Pi as a RESTful proxy server. Nice thing is, the little pi is portable!

My favorite web framework… still Django! While searching the web, I found a lot of extra crap people reported as necessary for the install. It really is an easy process… at least Kali.

Install Django on the Pi
This was actually very easy. Make sure everything is updated on the device.

sudo apt-get update

Following, install pip. This python package manager will be used to download Django.

sudo apt-get install -y python-pip

Follow up with Django.

sudo pip install django

Easy sauce, not a hard install at all. This installed Django 1.6. Here is a great tutorial on how to build your first app.

Build Your Own Wireless Access Point

Why buy an expensive router when you can build a cheap one from old hardware?

Equipment

This is what I used:

  • Ubuntu Desktop 12.04
  • hostapd v0.7.3
  • dhcp3-server
  • HP Compaq DC 7800 Small Form Factor PC
  • Penguin Wireless N PCIe Card v3 SKU NPCIEV3 ($50-$70)
  • Ethernet cable
  • Monitor, VGA cable, mouse and keyboard

Setup

Hardware

  1. The Wireless network card must first be installed. Open up the computer and locate the PCI slot. Insert the network card into the PCI slot.
  2. PC Slot

  3. Ensure the two cables are reachable to the outside of the case. The antennas should be connected to these points. In the picture, the wireless network card’s plate did not fit the chassis and was removed because I didn’t feel like punching holes through the original plate.
  4. Antennas

Software Install

These directions specifically apply to a machine that is running the Ubuntu 12.04 operating system. I feel this goes without mentioning but have a monitor, keyboard, etc connected to the PC for the next install steps. Install SSH in order to shell into the device later without all that necessary crap. In order to create the wireless access point two packages need to be installed.

  1. sudo apt-get install hostapd
  2. sudo apt-get install dhcp3-server

Hostapd provides the hosting services of an access point. It is a daemon for wireless access and authentication servers. Dhcp3-server provides a network service that automatically assigns IP addresses to clients.

Configuration

The hostapd configuration file needs to be created and edited to contain access point information. The below settings utilize WPA2-PSK authentication.

  1. sudo vim /etc/hostapd/hostapd.conf
  2. Add
  3. interface=wlan0 #wireless network interface
    driver=nl80211 #802.11 standard
    ssid=TheShire #The hotspot name, I'm a sucker for Lord of the Rings :)
    country_code=US
    channel=11
    hw_mode=g
    auth_algs=1
    wpa=3
    wpa_passphrase=secretPassword #access point password
    wpa_key_mgmt=WPA-PSK
    wpa_pairwise=TKIP CCMP
    rsn_pairwise=CCMP
  4. Configure the interface for the DHCP server.
  5. sudo vim /etc/default/isc-dhcp-server
  6. Set
  7. INTERFACES=”wlan0″
  8. The next configuration is in the DHCP conf file. Set the range of IP addresses allowed to be allocated to connecting machines.
  9. sudo vim /etc/dhcp/dhcpd.conf
  10. Comment out all lines except:
  11. ddns-update-style none;
  12. Declare the IP range of addresses for DHCP.
  13. subnet 10.10.0.0 netmask 255.255.255.0 {
            range 10.10.0.2 10.10.0.24;
            option domain-name-servers 192.168.0.81, 192.168.0.4;
            option routers 10.10.0.1;
    }
  14. Enable the hostapd program to run on startup.
  15. sudo vim /etc/default/hostapd
  16. Set:
  17. RUN_DAEMON="yes"
    DAEMON_CONF="/etc/hostapd/hostapd.conf"
    DAEMON_OPTS="-dd"

IP Settings

  1. Configure the IP settings for the wireless network.
  2. sudo vim /etc/network/interfaces
  3. Add
  4. auto lo
    iface lo inet loopback
    
    auto wlan0 #Wireless Network Interface
    iface wlan0 inet static
    address 10.10.0.1 #Local Router IP
    netmask 255.255.255.0

Firewall Settings

Allow IP masquerading in the Iptables. This is a networking function that allows local machines to access the same connection the host router is utilizing.

  1. echo “1” > /proc/sys/net/ipv4/ip_forward
  2. iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

DHCP Monitoring

  1. All DHCP requests can be found in /var/log/syslog. Grep can be used to pull certain requests for monitoring.
  2. cat /var/log/syslog | grep DHCPOFFER

    DHCP

  3. Further DHCP settings can be supplied in the configuration file, such as:
  4. sudo vim /etc/dhcp/dhcpd.conf
  5. Edit
  6. subnet 10.10.0.0 netmask 255.255.255.0 {
            range 10.10.0.2 10.10.0.24;
            option domain-name-servers 192.168.0.81, 192.168.0.4;
            max-lease-time 120; #Set the max release time
            default-lease-time 120;#Set the default lease time
            option routers 10.10.0.1;
    }

To flush the DHCP leases, the following can be performed:

  1. cd /var/lib/dhcp/
  2. sudo rm dhcpd.leases~
  3. sudo echo “” > dhcpd.leases

Changing Signal Strength

It may be ideal to limit the signal strength to a specific room or region in order to prevent overlapping signals. For cards that support multiple transmit powers, this can be done through iwconfig.

  1. iwconfig wlan0 txpower <LEVEL IN DBM>

Wireless AP
There you have it!

Aliases, loosing command identity…

Today, I was looking into my environment setup and realized, aliases are really useful. So for your enjoyment, here is a quick reference into how to setup and utilize the flexibility of aliases in your own Unix setup.

What is alias?

Aliases in any platform is a command that lets you replace one word for another.  Nothing really confusing here. The alias command is:

alias <NAME>=<VALUE>

An example:

alias list='ls –l'

This will replace any instance where you type list with “ls –l.”

Screen Shot 2014-01-16 at 6.52.45 PM

Listing isn’t a big deal, but say you have a really long command, imagine replacing that really long command with one word. Seeing the benefits now?

To get rid of an alias, either close your shell or type the command:

unalias <NAME>

This is great and all, but the alias will only work for the current shell it was called in. As soon as I close my shell, my list alias will disappear. What if I want an alias to be a permanent fixture. I want every shell I open to have my list alias. How do I do this? Well, the bash configuration files will help us here.

Bash Files for Unix Systems

When you login to a Unix system over bash shell, ~/.bash_profile is read. From this file, the shell gathers settings for that particular bash shell. If by chance ~/.bash_profile is corrupted or does not exist, ~/.profile is read instead. Say you are already logged into a Unix environment and you open a shell, instead of ~/.bash_profile being read, ~/.bashrc is instead reviewed for shell settings.

So ~/.bash_profile is read by a login shell and ~/.bashrc is read the other shell. I hate being repetitive. I want my aliases in one spot, I don’t want to have to manage two sets.

Well, there is a really easy fix for this problem! Ensure your ~/.bash_profile invokes ~/.bashrc! Check to see if your ~/.bash_profile has the following lines of code that perform the operation or just add them yourself.

if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

Nice, now you can store all your aliases in one place, ~/.bashrc. I just stuck mine in at the bottom of the file.

Example Aliases

Sudo reboot every time:

alias reboot='sudo reboot'

Sudo update application package manager:

alias update='sudo apt-get upgrade'

List directories in color:

alias ls='ls --color=auto'

Forget vi, always use vim:

alias vi='vim'

Show open ports:

alias ports='netstat -tulanp'

Directory traversals made easy:

alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias .....='cd ../../../..'

Go to your web directory:

alias www='cd /var/www/html'

Grep with color:

alias grep='grep --color=auto'

Remove recursively by force:

alias rm='rm –rf'

The possibilities are endless! Have fun!

Pi Time!

Just bought my own Raspberry Pi (Model B), endearingly named the Lil Devil. I’ve worked with Pi’s at school but now I have my own, sweetness.

Lil Devil

“The Raspberry Pi is a credit-card sized computer that plugs into your TV and a keyboard. It is a capable little computer which can be used in electronics projects, and for many of the things that your desktop PC does, like spreadsheets, word-processing and games. It also plays high-definition video” (raspberrypi.org).

My environment:

So now that I have one, I’m going to put Kali back on it along with OpenVAS, see previous post.

Imaging the SD

This time to image my SD card I used dd on my Mac. When I imaged the SD on my PC, I used Win32 Disk Imager. For dd:

With the SD card inserted into your computer, check where it is mounted with either fdisk (Linux) or diskutil (Mac).

fdisk - l

or

diskutil list

Locate your SD. Mine was located at /dev/disk2 (seen in screenshot below).

Screen Shot 2014-01-10 at 7.50.24 PM

Unmount the SD.

unmount <SD LOCATION eg /dev/...>

or

diskutil unmountdisk <SD LOCATION /dev/...>

Screen Shot 2014-01-10 at 7.51.22 PM

Lastly, use dd to image the SD card, the command is the same on both platforms. You can either use a custom Kali Pi image or a normal Kali image.

sudo dd if=<IMG LOCATION> of=<SD LOCATION /dev/...>

WARNING: Make sure to select the write SD location, you do not want to wipe your computers HD!

This may take some time depending on the size of your SD.

Starting it Up

Plug all the pieces together (HDMI cable, mouse, keyboard, WiFi adapter, USB to power supply, and SD).

The default credentials for Kali is root:toor.

This was super annoying but dd did not image my entire SD card, it made a small 4GB image (The size of the image I had, most pi images are 2GB from what I hear.) I ended up installing raspy-config in order to expand my image partition on the card. I followed these instructions.

Once I had my PI going, I checked that the WiFi was working correctly. I followed this tutorial to get it working. Following, I was able to SSH immediately (I found the IP address on my router’s web interface), some of you might have to configure OpenSSL. This way you can SSH into the device without the need of a dedicated monitor, HDMI cable, keyboard or mouse.

rm /etc/ssh/ssh_host_*
dpkg-reconfigure openssh-server
service ssh restart

Always good to update your libraries and upgrade your system.

sudo apt-get update
sudo apt-get upgrade

Cool, the environment is now ready for whatever you want to do. If you are worried about security, bastion.sh is a really cool tool designed to tighten security on any Linux device. Worth trying.

More Pi fun to come!

Logwatch on Ubuntu

What is logwatch?

It is an awesome monitoring tool. I have it running on one of my servers. Every night I get a status report on the behavior of my server.

Logwatch benefits:

  • Perform daily log analysis every night on a host machine
  • Can be configured to email reports to admin users
  • System Administrator Usage
    • Easy setup
    • Monitor host machines for all access and usage stats
    • Alert suspicious usage or access attempts
    • Email reports in an organized and easy to read format

Simple Install

Just run the following command:
sudo apt-get install logwatch

Configuration

Look into the configuration file and edit the settings to reflect the email account you want reports to be sent. By default it uses local mail. Look into the email options section to get logwatch to email external accounts like Gmail.
vim /usr/share/logwatch/default.conf/logwatch.conf
Output = mail
Format = html
MailTo = <YOUR LOCAL EMAIL>

Email Options (For Gmail, etc.)

Either setup a mail server like postfix or utilize another agent to send out logs via email.
Here is a great tutorial explaining an alternative to a mail server using sendmail.

Run the Reports Daily

To have logwatch run daily, set the command to the crontab.
crontab -e

The format for a cron job is:
(minute) (hour) (day of the month) (month) (day of the week) command

A * stands for every.

Here is an example of a crontab entry to run logwatch daily:

0 0 * * * logwatch

 Reports

Below are just some screenshots of the reports I receive from the tool. The reports are outdated and I no longer use the machine they detail… just in case you were curious.

logwatched

logwatch2

logwatch4

OpenVAS Quick and Easy: Scheduling and Running Tasks

OpenVAS is a framework of several services and tools offering a comprehensive and powerful vulnerability scanning and vulnerability management solution” (http://www.openvas.org/).

So I’ve been using OpenVAS as an alternative to Nessus and I’ve actually been quite pleased with the tool. The initial installation was a little difficult (see post) but once up and running, it has been great. I haven’t been able to find a simple howto guide on the scanner so I have decided to write one from my own experience with OpenVAS server version 6 and the client tool GSAD version 3.03. I only provide this tutorial as a learning experience and I do not endorse illegal scanning activity.

  1. I used to GSAD web client interface to interact with OpenVAS once the tool was up and running (see post). I accessed the web interface at http://<OpenVAS IP Address>:<GSAD Port>.OpenVas Login
  2. Log into OpenVAS with credentials created during setup (see post). If you are unable to log in and you know your credentials are correct, its most likely your openVAS database is out-of-date. Try the following steps in a terminal window before attempting to login again:
    • Update the  openVAS database with the latest definition (This can take an hour or more.): openvasmd –update
    • Migrate the database (This can take an hour or more.): openvasmd –migrate
    • Rebuild one last time to be safe (This can take an hour or more.): openvasmd –rebuild
    • If your server date/time is off this could also cause a problem later on, to correct this you will have to first stop all openVAS processes then change the server date/time to the current. Lastly, you will need to repeat creating the necessary certificates and starting up all the openVAS tools similar to the installation process (see post).
  1. Upon a successful login, you will be greeted with a window of tasks scheduled and completed.OpenVAS Tasks
  2. So for a simple vulnerability scan, you will need to setup a target. This is the machine OpenVAS will scan. By default, the tool has localhost already configured as a target but I’m assuming you will want to scan machines other than the one running OpenVAS. To setup a target, hover over the Configuration tab then select Targets.
  3. In the next window, fill out the desired target fields. OpenVAS can be scheduled to scan one or more devices. This is determined by the Hosts field, you can either enter one IP address (x.x.x.x) for a singular host scan or a range of addresses (x.x.x.x-x.x.x.x) for a multiple host vulnerability scan. You may find your device can only handle scanning one IP at a time (This is what I found true on my Raspberry Pi). It is a best practice to always scan by IP addresses, a domain name can resolve to multiple hosts and provide conflicting results. In the picture below, I only entered into the form a target name and a singular IP address, everything else I left as default (you can experiment around with the settings for a more detailed scan). When you are finished entering in all the details, create the target by selecting the Create Target button.OpenVAS Target Creation
  4. The new target will be visible in the box below the form once successfully created. Make sure OpenVAS has a value under the IPs column. This is to ensure it found the target IP address or addresses.Targets
  5. Now it is time to create a task to scan the new target. Hover over the Scan Management tab then select New Task.
  6. Fill out the new task field with the desired task details. In the picture below, I only entered into the form a task name and selected a target to scan, everything else I left as default for a full and fast scan (you can experiment around with the settings for a more detailed scan). When you are finished entering in all the details, create the task by selecting the Create Task button. Task Setup
  7. The task will now appear in the task window and is ready to start. OpenVAS will not automatically start a task, you must select the green start icon under the Actions column in the task window to begin the scan. The other actions found in this column provide easy task management for when you want to start, pause or resume a task in order to pace server activity. New Target
  8. The scan will take a bit of time so be patient. If you want to view the progress of the scan, you can change the drop box settings above the task box to refresh ever X seconds and to no overrides. With these settings, the page will refresh every so often to notify you of the task progress under the Status column in the task box. Sometimes the task may stop itself, you can resume it by selecting the icon next to the start arrow under the Actions column.
  9. When the status of the scan shows Done, you can review the scan findings. Select the coordinating task date under the Last column. A summary of the report will be presented along with the capabilities to download a more detailed version of the report.OpenVAS Scan Results
  10. There you have it, you can review the findings in the report to learn of possible vulnerabilities in a host. Good luck!