Monday, July 28, 2014

SSH Security - Stopping Server Scanners

I have to maintain my SSH connection to the home network for various reasons.  Because of that, my SSH connection is open to the world - and I'm a paranoid.  So, what do I do to maintain my sanity?  Most Linux distributions include a handy little program called "swatch".  It's a "simple watcher" application that uses regular expressions (hooray for Perl people!) and acts when something is "found".

Here's an example.  Let's say you opened up your log file and see a number of these :
    
    Apr 12 09:36:23 servername sshd[11307]: User root from 61.174.49.113 not allowed because not listed in AllowUsers
    Apr 12 09:36:23 servername sshd[11310]: input_userauth_request: invalid user root
    Apr 12 09:36:23 servername unix_chkpwd[11316]: password check failed for user (root)
    Apr 12 09:36:23 servername sshd[11306]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=61.174.49.113  user=root
    Apr 12 09:36:23 servername sshd[11308]: reverse mapping checking getaddrinfo for 113.49.174.61.dial.wz.zj.dynamic.163data.com.cn [61.174.49.113] failed - POSSIBLE BREAK-IN ATTEMPT!
    Apr 12 09:36:23 server name sshd[11308]: User root from 61.174.49.113 not allowed because not listed in AllowUsers
    
For anyone NOT security minded, here are a couple of quick points :
  • You know immediately that someone is scanning your server, trying to find an open account that is easily compromised.
  • You ALSO know that their attack fills up your network pipe - and communication is vital.
So, what do you do?  We simply watch the logs, and then trigger adding a route to the loop back interface.  This causes us to suddenly become "unresponsive" to whomever is doing the scan.  If, after a minute, they continue to scan, we simply block for a little longer each time, ultimately just making it semi-permanent.  So, here's how.

We create an rc file containing our instructions.  Create a configuration file in /etc (say, /etc/swatchrc), and add the following :
    # Bad authentication attempts from ssh
    watchfor   /Failed password for/
            exec "/usr/local/bin/failed_password.sh $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15"
    
This simply looks for the regular expression /Failed password for/ in /var/log/secure, and then runs a script of ours, /usr/local/bin/failed_password.sh.  This script consists of simple rules :
    #!/bin/bash
    
    ATTEMPTS_LIMIT=4
    NOTIFICATIONS_TO='email@address.com'
    
    # get the IP address :
    IP=`echo $* | sed 's/^.* from //' | awk '{print $1}' | sed 's/::ffff://'`
    
    # get the number of attempts from this IP :
    ATTEMPTS=`grep $IP /var/log/secure | grep "Failed password for"  | wc -l`
    
    if [ $ATTEMPTS -gt $ATTEMPTS_LIMIT ]; then
    
     # black list the IP by sending it to the loop back interface
     route add $IP lo
    
     # in the calculated number of minutes, un black list the IP
     # but, make this somewhat exponential
     ATTEMPTPOVER=`expr $ATTEMPTS - $ATTEMPTS_LIMIT`
     let MINUTES=$ATTEMPTPOVER*3
     echo "route del $IP lo 2> /dev/null" | at now +$MINUTES minutes 2>&1 > /tmp/.bad_user.$$
    
     # since we get a lot of people from China and Europe scanning
     # us, let's only send a notification if we hit a count of 5, or more than 20 attempts
    
     # first, five attempts
     if [ $ATTEMPTS -eq 5 ]; then
      # now let's send a notification for good measure
      (hostname ; echo $* ; echo "IP=$IP" ; echo "ATTEMPTS=$ATTEMPTS" ; \
       echo "Blocking for $MINUTES minutes" ; \
       cat /tmp/.bad_user.$$ ) | Mail -s "Scan Running From $IP" $NOTIFICATIONS_TO
     fi
     # next, 20 or more - and, let's simply iptables them until the next reboot
     if [ $ATTEMPTS -gt 19 ]; then
      /sbin/iptables -I INPUT 4 -s $IP -j REJECT
      # now let's send a notification for good measure
      (hostname ; echo $* ; echo "IP=$IP" ; echo "ATTEMPTS=$ATTEMPTS" ; \
       echo "Blocking for $MINUTES minutes" ; \
       cat /tmp/.bad_user.$$ ) | Mail -s "Permanently Blocking $IP" $NOTIFICATIONS_TO
     fi
    
     # also, ensure we log that we are blocking, and for how long
     /bin/logger -p authpriv.warn "Saw auth attempt $ATTEMPTS from $IP - blocking for $MINUTES minutes"
    fi
    
    # clean up after ourselves
    rm -f /tmp/.bad_user.$$
    
The script is explained by comments, but here's the gist. Ths script is executed every time /var/log/secure matches a "Failed password for" along with the full log line (including the IP address). It then "greps" for that IP in /var/log/secure and grabs a total of the failed attempts. If that number of events is greater than ATTEMPTS_LIMIT (4), we route anything to that IP through loopback and schedule a job to delete that route $MINUTES out (calculated as the number of attempts over the ATTEMPTS_LIMIT multiplied by 3). Then, if we have 5 attempts - it's a script that someone is letting run, so we send a single notification. If we get to 20 attempts (the last one is nearly an hour of being blocked before it can try again), we send a new notification that we've blocked the IP, and we run an iptables command to insert it into our firewall (the block should disappear on the next host reboot). So, that's how it works.

Next, we have to start swatch up :
    /usr/bin/swatch --config-file=/etc/swatchrc --tail-file=/var/log/secure \
     --awk-field-syntax --tail-args "-F" &
Also, make sure you add it to your /etc/rc.local in order to automatically start it up on boot (e.g. in case of a power outage).

Monday, June 30, 2014

Dead Man's Switch - Simple To Implement

One tool that has been discussed endlessly is called the "Dead Man's Switch". A "Dead Man's Switch" is a tool that requires interaction either continuously or regularly, and if that interaction doesn't work, the "switch" is triggered. These kinds of tools have been used in a number of areas. Usually, they are used in high-security areas, such as military triggers. Just a note, Wikileaks had an "Insurance File" that contained a number of encrypted documents that was available in the BitTorrent world, and a form of a Dead Man's Switch with the decryption key.

Anything that should happen if something else happens to you is a prime candidate to implement a switch like this, hence, I needed my own switch set up to get information to my wife.

Since I had just altered the process for my dead man's switch, I thought it might work well to illustrate how I had it set up, so if anyone wants to create one on a Linux platform, it is a simple process.

Here's how it worked.
  1. A cron was set up that checked the age of a file. If this file was too old, it triggered an action (e.g. mailing a copy of my "Insurance File" to a close friend). The cron ran once every day, e.g. (at midnight as an example) :

      0 0 * * * /usr/bin/run_like_a_deadman.sh

    The cron script looked like :
      
      #!/bin/sh
      
      MAX_AGE_IN_DAYS=5
      PRE_MAX_AGE_IN_DAYS=3
      SWITCH_FILE=/my/deadman/file/to/check
      SWITCH_FILE_LAST_MODIFIED=`stat --format='%Y' "$SWITCH_FILE"`
      CURRENT_TIME=`date +%s`
      AGE_IN_DAYS=`echo "($CURRENT_TIME - $SWITCH_FILE_LAST_MODIFIED) / 86400" | bc`
      
      if [ "$MAX_AGE_IN_DAYS" -lt "$AGE_IN_DAYS" ]; then
        # max_age exceeded, trigger deadman
        echo "If you are receiving this e-mail, please know the following.  (1) I haven't reset my digital deadman switch.  (2) I wish this hadn't had to happen like this.  (3) Since I have been unable to reset the timer, something bad must have happened to me in the last $AGE_IN_DAYS days. There is a floppy disk hidden in the LP collection of the cellar that includes some instructions.  Please review the instructions.  And, above all else, PLEASE know that I will miss all of you!" | mail -s 'CRITICAL: deadman switch activated' friendOne@gmail.com
        exit;
      fi;
      
      if [ "$PRE_MAX_AGE_IN_DAYS" -lt "$AGE_IN_DAYS" ]; then
        # warning, PRE_MAX_AGE_IN_DAYS exceeded, fire a warning shot
        echo "please follow the procedure prescribed to reset the deadman switch timer." | mail -s 'WARNING: deadman switch active' myself@gmail.com
      #else
      #  # all is well, let's do nothing
      fi;
      
    This said that if I didn't log in to my server in three days, I'd get an e-mail (if my address was myself@gmail.com) telling me I have to log in. If I hadn't logged in for 5 days, my friend (friendOne@gmail.com) would get an e-mail.
  2. Whenever I logged into my server, I had a .bashrc command that touched the trigger file.  For example, it simply ran :

      touch /my/deadman/file/to/check
      

    You could also accomplish this through a remote server, if you had a secure server somewhere else by adding something like :

      /usr/bin/wget -q -O /dev/null http://www.example.com/cgi-bin/reset_deadman_timer.pl

     A simple CGI could look like :

      #!/usr/bin/perl
      
      `touch /srv/.deadman`;
      print "Content-Type: text/plain\n\nOK";

     Please note that the above isn't really secure. Virtually anyone could post to the URL if they found it and prevent things from happening unless you had some SERIOUS mechanisms to keep things locked down.  And in that case, since it would be a public server, anyone with access to the server could possibly step through the process to figure it out.
Just a little bit of information that you might find beneficial.  Enjoy!

Thursday, June 12, 2014

Going to try the Google Book Scanner

I've decided I want another project (wait a minute... shouldn't I finish what I've already started?).  Here's the deal.  My father loves to collect books - and some of the older books are magnificent.  Not to look at, but because of the information in them.

For example, I've been thinking a lot about how the human race isolated elements in the first place.  Most modern books won't tell you how to obtain pure carbon, or helium.  But, one or two of my fathers old books (from around the 1940's) DO tell you how to isolate some basic elements.

Here's the problem... my father is thinking about just getting rid of all of his books.  That could pose a potential loss of valuable information.

Here's the solution... I started thinking about simply scanning the books to a digital format so that he could easily access them, and not have to drag them out.  I remembered a HackADay article once upon a time about a Google project for scanning books without cutting pages out, breaking bindings, or spending hundreds of thousands of dollars on equipment.  Ultimately, I found that some students at the University of Michigan built a new version of the scanner that seemed to run off of a Raspberry Pi.  Perfect!

There are some tasks I'm going to have to work around, though.  First, the Michigan students' project utilized laser cut plexiglass, anodized aluminum, and machined parts.  I can't really afford that, so I'm going to have to break out the old ingenuity for this one.  I like their adjustable vacuum for page turning, so I'll need to replicate that without having custom parts machined.  We'll see how this one turns out.

There are four major components from what I've been able to determine :

  1. The Frame
  2. Book Caddy/Movement (including a stepper motor)
  3. Page Turning/Vacuum and vacuum tube
  4. Scanning Elements/Raspberry Pi

The Frame

I'll probably settle for ordering some super-thin Delrin sheets online for the frame of the book scanner (less friction on the book) and epoxy them down to some small, cheap plywood for rigidity.  That would give me the frame needed to get things started.  I'd first build the frame using counter-sunk screws.  The Michigan project actually used some machinists to do this so that it would all be flush - I frankly don't care, since I'll be gluing the Delrin over the top of the screws.  I probably ought to use some hinges to make it collapsable so that I can break it down and store it out of the way.

The Scanning Element

You need two scanners.  I've located a cheap ($5 at a yard sale) HP All-In-One office printer that is SANE-compatable.  It's an HP 2410xi printer/scanner/fax/astronaut/AI chess player unit - it does anything an office might need regularly (not so serious about the astronaut/AI chess playing of it - please don't think it really does that).

That means I already have one scanning element, and I need a second one.  I'm in the hunt for that.

To make it work, it has to be SANE compatible.  Who wants to connect TWO USB wires to a computer and scan from two scanners at the same time?  So, I'll use a Raspberry Pi inside the machine, connected to both, and run a command-line scan under two processes, which is why the requirement is there.  Then I can use ImageMagick to crop images down to size, and create a PDF based on those.

The Page Turner

For this, I like the technique that the University of Michigan students did - and adjustable vacuum tube.  However, I cannot begin to think about dumping cash into a machine shop somewhere, so I'm probably doing to have to settle for a Delrin tube, threaded on one end, and slots cut into it.  It would then be attached to the a shop vacuum.  The blowing end of the vacuum would also be fed back into the unit to "blow" back at the spot to prevent double pages from getting turned and missing one.

The Book Caddy and Movement

So, I've already ordered some NEMA 17's (17PM-K402-P4V) motors to use in this.  They don't have to be strong, but I'd like to be able to have the Raspberry Pi operate them.  Of the motors I received, one of them had a damaged connector/circuit board on arrival:



It wasn't a packaging problem as the package was in great shape and showed no signs of damage, and only one was damaged, so I simply expect that the one motor had arrived at the vendor's "warehouse" (this was an eBay order) in that state, and wasn't inspected before being shipped.  After contacting the vendor, they are replacing it. Sounds like great people to work with!

S10 to Replace Civic

Well, I found a replacement vehicle for the Civic.  I'd prefer to have a small engine for a commuter, but this one has a V6.  It's a Chevy S10 V6 regular cab (a little tight for stuff inside the cab), and a long bed (a bit rare).  It's been working quite well for me.

However, it did cost a little more than the Civic, so it interfered with some of that cost going to headlight unit paint.  Finally saved up a little, and decided I'd better get to the wiring, and started playing with the wiring.

My fear was that I'd connect the batter and melt a wire, causing the whole car to burn to the ground (yeah, I kept a fire extinguisher close by, just in case, even if the odds of it being that bad were so minuscule).  So, I followed the advice of some experts, and threw in a little bit of a procedure for my own sanity.  Here's how I tested the electrical.

Preparation :

  1. Put the battery in place.
  2. Connect the positive battery cable end (+).
  3. Do NOT connect the ground cable yet.  Instead, wire some spare connectors to it that you can connect at will.
  4. Disconnect/remove all of the fuses.
  5. Obtain a headlight (this step is invaluable, and is the advice I received from some experts).
  6. Connect one side of the headlight to the negative (-) battery cable (not the battery).

I ran the first test with no fuses connected/in the vehicle, because I wanted to make sure all was well before proceeding.  I then re-connected one fuse at a time and re-tested, just to ensure each circuit was acceptable.

Actual Test :

  1. Connect the negative terminal of the battery (-) to the other terminal of the light.
  2. Check the headlight.  If it's on, something is shorted in the circuits that are still connected.  If it's off, you're okay.
  3. Turn the key to the accessory/on position (but not start, just in case you don't have fluids/etc) just to ensure things behave as expected, each time checking the headlight.
  4. Repeat as necessary for each circuit as you connect fuses.

So, that's what I kept doing.  I'd connect a fuse, and check that circuit.  Everything looked flawless...

... until I finished and decided to get the stupid door glass adjusted.  The power window regulators wouldn't move.  I started with the trusty old volt meter on the wiring.  Checking the whole thing out, I found the power window relay is bad.  Bypassing that to ensure the rest of the wiring was okay and the motors ran, I still couldn't get the motors to turn.  I checked the voltages on the connectors at the motor side, and... I had the right voltage.  It looks like the wiring is fine.  It means that the power window motors aren't so good.  Now I've got to replace the power window motors again (I have done that a couple of times already), and hope it's not a mechanical bind with the regulator.

So... I started out expecting the whole car was going to "blow up" from something being shorted out, and found out the opposite is true - the wiring is great, some components connected to it, not so much.

While I was at it, I decided to try an electrical pop-up headlight conversion.  I had obtained a couple of 1995 Ford Probe headlight motors from a junk yard.  I slapped them up to the battery, and they worked perfectly.  They have about the same throw as the C3 Corvette, so I'm in great shape.  Some others had done this conversion in the past, and I borrowed their process - I cut some brackets, soldered some wires together so that the motors work in tandem (and put heat shrink tubing around that), and bolted them in place.  I still have yet to adjust them (I'll need finished headlights), and I still have yet to finish the circuits, but I'm close.

At this point, here's the list of things to do :

  1. Replace power window motors and relay (can only find that through mail order services [sigh]).
  2. Adjust door glass
  3. Install door mirrors
  4. Install door panels
  5. Install A/C ducts
  6. Install dash panels
  7. Get headlight units painted and installed
  8. Complete circuit (two diodes and battery wiring) for the pop-up motors
  9. Install rear speakers/amplifier
  10. Ensure fluids are in the car
  11. Actually try to start it
It's amazing that I'm that close - and yet it's taking me so long to get there.  I will continue to work when I can, though.

Thursday, May 15, 2014

PDF Manipulation

I also have a car I have been rebuilding for 20 years - when I got the car, it was in bad shape and was in a state of being dismantled.  I've used a hard-copy of factory assembly engineering/instruction sheets that were used to put it together the first time to figure out where things should go, and what parts I was missing.  Now, I've been lucky enough to have access to an office "printer" for a little bit.  I decided I'd scan in the factory documents into a PDF to use on the tablets.

The printer will scan things to a USB disk, and allow me to scan entire documents, front and back.  One problem, though, is that I didn't know how to use it.  I ended up with a document that had the first 20 pages correct in a portrait layout, and the rest were in a landscape layout with every other page rotated the wrong direction.  I also had it scanned in sections, and realized I had taken pages and put them into another, temporary notebook for actual use (nothing like trying to lug around a 500-page, paper-in-sheet-protectors, thick book).  When I scanned in the missing pages, I got them into the reverse order.  Yeah, obviously, I didn't know what I was doing.  But, it was correctable.  I needed to get things oriented the right direction, missing pages added in the right place, and then every other page of engineering drawings rotated 180, reverse page ordering, and fix the "tops".  I had 4 scans (called scan1.pdf, scan2.pdf, scan3.pdf, scan4.pdf), and two scans with the missing pages (pages089-095.pdf and pages123-126.pdf).

First, I needed to split the PDF into two different files (or logical "sections"), each with a different orientation.  The first would be for the "table of contents", that was portrait-oriented.  This was done with
    pdftk scan1.pdf cat 1-26 output table_of_contents.pdf
    pdftk scan1.pdf cat 27-end output book-1.pdf
    mv book-1.pdf scan1.pdf
    
This essentially left me with a new file called table_of_contents.pdf, and scan1.pdf didn't have that table in it any more.  The rest of the book was in landscape orientation.  Next, I had to break the first scan once again to make room for the missing pages.
    pdftk scan1.pdf cat 1-88 output pages001-088.pdf
    pdftk scan1.pdf cat 89-117 output pages096-122.pdf
    pdftk scan1.pdf cat 118-end output pages127-143.pdf
    
As I was checking, I realized that pages089-095.pdf were actually pages 95 - 89 (e.g., backwards).  I needed to reverse the order of pages in the PDF file.  I did this using the pdf2ps tool, the psselect tool, and the ps2pdf tool in the following way :
    pdf2ps pages089-095.pdf pages089-095.ps
    rm pages089-095.pdf
    psselect -r pages089-095.ps pages089-095a.ps
    ps2pdf pages089-095a.ps pages089-095.pdf
    rm pages089-095.ps pages089-095a.ps
    
Next, I had scanned in the next missing pages with the pages face-down instead of face up.  That left me with a PDF containing pages 124, 123, 126, and then 125.  I went back to the pdftk tool to modify PDF page order in a granular fashion (you can reverse one or two pages with this technique).
    pdftk pages123-126.pdf cat 2 1 4 3 pages123-126a.pdf
    rm pages123-126.pdf
    mv pages123-126a.pdf pages123-126.pdf
    
This corrected that one.  Now, I had to merge all of the PDF files together.  I used the ghostscript tool gs to do this one instead of the pdftk tool (though I know it will do this well).
    gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=factory_drawings.pdf pages001-088.pdf pages089-095.pdf pages096-122.pdf pages123-126.pdf pages127-143.pdf scan2.pdf scan3.pdf scan4.pdf
    
This created a file called factory_drawings.pdf that had all of the pages in the correct order.  I needed to clean up the extra files now :
    rm pages* scan*
    
I was now left with two files, factory_drawings.pdf and table_of_contents.pdf.  However, since I had scanned this in using a 2-sided booklet format,every other page of the factory_drawings.pdf file had the top to the left and the rest of them had the top to the right.  I needed to rotate every other page of the PDF file.  For this, I resorted to the pdftk tool again.  The first step of this task is to split out the odd pages and rotate them one way :
    pdftk factory_drawings.pdf cat 1-endoddeast output factory_drawings-odd.pdf
    
Next, split out the even pages and rotate them the other way :
    pdftk factory_drawings.pdf cat 1-endevenwest output factory_drawings-even.pdf
    
And finally, "shuffle" them back together :
    rm factory_drawings.pdf
    pdftk factory_drawings-odd.pdf factory_drawings-even.pdf shuffle output factory_drawings.pdf
    rm factory_drawings-odd.pdf factory_drawings-even.pdf
    
SUCCESS!  At this point, I still have two files, factory_drawings.pdf and table_of_contents.pdf, and their orientation is where it should be (with the tops at the top).  The last thing I needed to do is merge them into one PDF file again (PDF's can handle different orientations in one file).
    gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=1977_corvette-factory_assembly_drawings.pdf table_of_contents.pdf factory_drawings.pdf
    rm table_of_contents.pdf factory_drawings.pdf
    
I instantly had a perfect PDF file for use on the tablet as I sat next to the car trying to assemble it.

NOTE -

If you use a custom font in your PDF, you can fix the PDF and embed the fonts using :

    gs -o file-with-embedded-fonts.pdf -sDEVICE=pdfwrite -dEmbedAllFonts=true -sFONTPATH="/path/to/ttf;/other/path/to/ttf" input-without-embedded-fonts.pdf
Another note: Convert Jpeg images to PDF using the jpeg2eps tool, found at :
jpeg2eps ../*.jpg
This will create EPS files of the same names as the Jpegs. Next, convert those to PDF :
for x in ../*.eps; do eps2eps $x $x.pdf; done
At this point, you can combine them into a book :
gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=newbook.pdf *.eps.pdf
Edit as of December 2023. I was REALLY lazy and didn't want to go download jpeg2eps code, compile it, etc. So, I used a few more mainstream command line apps. First, each image needs to be converted to a PDF. I used ImageMagick's "convert" command. You might need to first edit the policy config for ImageMagick to allow it to write PDF files (at the bottom of the /etc/ImageMagick-6/policy.xml configuration file) :
convert dowel_jig-1.jpg dowel_jig-1.pdf
Then, I could compile them into a new PDF (install pdftk-java).
pdftk dowel_jig-1.pdf dowel_jig-2.pdf dowel_jig-3.pdf dowel_jig-4.pdf  cat output dowl_jig.pdf
And finally, I could run an OCR tool (install ocrmypdf).
ocrmypdf dowl_jig.pdf dowel_jig.pdf
I have my PDF ready to view!

Tuesday, March 4, 2014

Status of the Home Brew Security System

I decided to upgrade from an Arduino and a large media server to an Udoo quad core (http://shop.udoo.org/usa/product/udoo-quad.html), because I didn't want to have to have the event server on the same network as everyone else.  I'm sort of paranoid.  What I found is :
  • The Udoo uses GPIO inputs that ARE available through the Linux image.
  • The Udoo failed to work with my relays.  This was because the relays were 5v relays (perfect for the Arduino Mega2560 I was using), but the Udoo uses a 3v logic level.  Simply put, the relays would never work.
  • I could put my entire event server package onto the Udoo, and have a self-contained alert system.  This was my goal.
Here's what happened.

I found a great tutorial from Adafruit at http://www.udoo.org/ProjectsAndTutorials/linux-gpio-manipulation/.  I slapped together some listener programs to watch the GPIO states, and I was suddenly in business again.  I no longer needed to upload any code to the Atmel chip on board - I could do it all in native C code, standard-Linux stuff.  Those tools were checked into the event server repository (subversion), and have been thoroughly tested.

Next, I needed to be able to work the garage door.  I toyed with building a separate, stand-alone device, but I'd already done that, and I was starting to get lazy.  I found a device on ebay, http://www.ebay.com/itm/111248757109?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1497.l2649, that was $50, and had two relays and Ethernet.  The downside is this came hard coded to an IP address of 192.168.1.199.  I had to use a crossover cable to connect it up, and reconfigure it to use DHCP.  It has a simple web-based interface.  So, being the nerd I am, I watched network traffic to see what requests were being sent.  When I'd click one of the relay buttons on the web page, it would send a request :
    http://192.168.1.199/relays.cgi?relay=1
    
When I turned it back off, it sent an identical request.  There was no "off" or "on" designation in the requests.  Apparently, the device simply took "toggle" commands".

I did find if I left off the ?relay=1, it simply gave me the following page:
    <div>
    <font size="5"> one                             <span style="color:red">0 </span> </font>
    <br />
    <br />
    <br />
    <font size="5"> two                             <span style="color:red">0 </span> </font>
    </div>
    
    <div>
    <p hidden>
    Status: 0 0 
    Relay1: one                          
    Relay2: two                          
    
Now I was getting somewhere.  I toggled it, ran the previous, and found that the "Status: 0 0" line went to "Status: 1 0".  It's a two relay board, so now I know how to get the current state.  Next, I needed to identify what had to be done to ensure it was always turning the switch off when it was done acting like a momentary push-button :
  1. Ensure the switch was in the off position.
  2. Toggle the switch to the "on" position.
  3. Wait for 1 second.
  4. Toggle the switch back to the "off" position.
So, I used the request without the "?relay=1" to get the "Status: " line for the relay I needed.  If it had a 1 for that one, I had to turn it off first.  In my case, it should ALWAYS be in the off position already.  Next, I had to toggle it to "on" position, and a simple request to the following would work perfectly :
    http://192.168.1.199/relays.cgi?relay=1
    
Then, I slept for a second, and then made that toggle request a second time to turn it off.  I hooked it up, and ran it.  Woohooo!  I'm back online again!  Here's the code I used :

#!/usr/bin/perl

use LWP;
use HTTP::Request;

my $relay_host = '192.168.1.199';
my $relay_index = 0;

my $ua = LWP::UserAgent->new('alarmsystem');
$ua->credentials($relay_host.':80',"Protected", 'admin', 'admin');

# FIRST - Ensure this thing is OFF
my $res = $ua->get('http://'.$relay_host.'/relays.cgi');
print $res->content;
exit;
if ($res->content =~ /status: ([\d\s]+)/i) {
  my (@rows) = split(/[\s\t]+/,$1);

  if ($rows[$relay_index] == 1) {
    my $res = $ua->get('http://'.$relay_host.'/relays.cgi?relay='.($relay_index+1));
  }
};

# SECOND - Turn it ON
my $res = $ua->get('http://'.$relay_host.'/relays.cgi?relay='.($relay_index+1));
# sleep for a second
sleep(1);
# LAST - Turn it back to OFF
my $res = $ua->get('http://'.$relay_host.'/relays.cgi?relay='.($relay_index+1));

Tuesday, February 18, 2014

The Civic - Life Moves On

Personally, it felt great to have a mechanic look at the civic and simply state that it was just fine.  It felt great to have paid professionals tell me that the work I had done was on.  It felt great to know that the car was in great shape... except for the shifting problem.

Two transmission shops, one muffler shop, and a mechanic later, and I followed the advice of the mechanic - I changed the catalytic converter.  Apparently, the shifting problem was a result of the catalytic converter breaking down.  It was a 14-year-old piece of fragile costly precious metals, with 249,088 miles on the clock.  So, I ordered a catalytic converter (after being told by some exhaust shops the cost would be $600 for parts, and $200 for the welding and flange fitting).  $250 and one week later, I had it installed.  I drove it a few times - it seemed to be much better.  But, I thought I'd better drain transmission fluid and fill it a few times just to make sure.

Then, I changed that pesky door lock actuator (passengers' side, front door only - this came as a result of teasing my brother when we were carpooling).  The hood still rattled (then I remembered I "adjusted" it once, and put it back to where it was - and the rattle was gone).  With all of that complete, it simply had a high-mileage transmission, and it had cosmetic issues.

It sold really fast.  150,000 miles were freeway miles, so I know it's in phenomenal shape.  But, it's time to move on and try something else for a while.  Who knows, maybe this will fund the rest of the headlight paint and the interior map pocket for the corvette.  It'd be nice to have that one done.