Thursday, August 3, 2017

Perl Webpage status checker

How to check webpage status using Perl

We have several web pages that we needs to be monitored from outside of our work network especially after a maintenance window. I didn't want to do this manually (ever again), so I wrote a Perl script to run on my Linux server (laptop) from home.

This is the header portion. I imported these modules to be used by my script. Line 3 turns any expression that is deemed difficult to debug into error. And line 4 enabled optional warnings.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/usr/local/bin/perl
## to install modules, follow instruction from http://www.cpan.org/modules/INSTALL.html
use strict;
use warnings;
use WWW::Mechanize;
use HTTP::Cookies;
use IO::Socket::SSL;
use Email::Sender::Simple qw(sendmail);
use Email::Sender::Transport::SMTPS ();
use Email::Simple ();
use Email::Simple::Creator ();
use WWW::Wunderground::API;
use Try::Tiny;
binmode STDOUT, ':utf8'; # for degrees symbol

----
Below is to use Weather Underground API. You must obtain your own free API key to use.
1
2
3
4
5
my $weather = new WWW::Wunderground::API(
    location => 'pws:XXXXXXXXXX',
    api_key  => '1111111111111111',
    auto_api => 1,
);

---
In the below code, we paste Message of the Day to our email body and get a list of URLs from a file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
## For debugging purposes
#my $outfile = "/home/me/Documents/perl/output.htm";

## Message of day
my $motd = `exec /usr/games/fortune | /usr/games/cowsay -n`;

## List of websites to check from outside
my $filename = '/home/me/Documents/perl/serverlist.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
 or die "Could not open file '$filename' $!";

---
Below is the main section used to loop through the list of URLs and check their status using a function call (last block of codes below). In line 10, we also use the WeatherUnderground API to get our temperature.  

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
my $emailbody = "webpage status codes\n";
while (my $text = <$fh>) {
 chomp $text;
 $emailbody = $emailbody  . "$text: ";  
 my $answer = get_answer($text);
  $emailbody = $emailbody  . "$answer\n"; 
}
$emailbody = $emailbody  . "$motd\n"; 

my $currentTemp = $weather->conditions->temp_f;
my $cTempString = "Current Temperature is $currentTemp degrees";
$emailbody = $emailbody  . "$cTempString\n";

##For debugging purposes
#print $emailbody;

---
 The below block of code is to connect to my email service provider and send email to everyone in the address book.

 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
## Put SMTP authentication information here
my $smtpserver = 'smtp.office365.com';
my $smtpport = 587;
my $smtpuser   = 'me@outlook.com';
my $smtppassword = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
my $tousers='';
## List of email addresses
$filename = '/home/me/Documents/perl/addresses.txt';
open($fh, '<:encoding(UTF-8)', $filename)
  or die "Could not open file '$filename' $!";

while (my $row = <$fh>) {
   chomp $row;
   $tousers = $tousers  . "$row,";  
}
$tousers = $tousers  . "$smtpuser";

##setup the email server connection here
my $transport = Email::Sender::Transport::SMTPS->new({
   host => $smtpserver,
   port => $smtpport,
   ssl => "starttls",
   sasl_username => $smtpuser,
   sasl_password => $smtppassword,
});

##create email object
my $email = Email::Simple->create(
   header => [
      To      => $tousers,
      From    => $smtpuser,
      Subject => 'Status',
   ],
   body => $emailbody,
);

##send the email
sendmail($email, { transport => $transport });

---
The below code is my function that does the actual website checking. Notice the Try-Catch blocks, this is useful for checking webpage status because if the website is unreachable it is a Catch event. Also line 2 shows how we obtain the parameter value for this function call. Be sure to wrap the variable around ().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
sub get_answer {
 my ($row) = @_;
 try{
  chomp $row;
  ##print "$row\n";
      my $mech=WWW::Mechanize->new(ssl_opts => {
         verify_hostname => 0,
      }); 
     $mech->cookie_jar(HTTP::Cookies->new());
     $mech->get($row);
     ##my $output_page = $mech->content();
     my $output_status = $mech->status();
     ##print $output_page; 
  chomp $output_status;
  return $output_status;
 }catch{
    my $output_status = "Fail";
  return $output_status;
 };
}



Wednesday, August 2, 2017

ColdFusion and DataTable Example

ColdFusion and DataTable Example


If you are new to DataTable like me, this should provide you with the necessary basics to get you going and helps to make sense of examples over at Datables.net.

 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
<html>
<head>
<style>
tfoot input {
      width:100%;
      padding:3px;
      box-sizing:border-box;
}
th,td {
      padding:15px;
}
table#t00 {
      width:100%;
      border-spacing:5px;
      padding:15px;
      border:2px solid #dddddd;
      border-collapse:collapse;
      background-color: #eee;
}
</style>
<link type="text/css" 
      rel="stylesheet" 
      href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" 
      media="all"/>
<script type="text/javascript" 
        src="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
</script>
</head>

Here's the Head portion of HTML. Line 3-20 is optional, but it is in there so that I can override some style inside linked stylesheet (line 21). Line 12 is there so I can give one table a unique look. Line 21 is one linked stylesheet. You can link as many as you want. Line 25 is datatable JS file. You can also have as many of these as you like.

1
2
3
<cfquery name="somedata" datasource="MYSOURCE">
      select blah1,blah2,blah3 from sometable
</cfquery>

Above is the CFML to call a query.

1
2
3
4
5
6
<body>
  <table id="t00">
    <tr>
      <td>Main Menu</td>
    </tr>
  </table>

Above we have our use of the style we defined earlier for this table Id.

 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
<table id="meatTable" class="table table-striped table-bordered nowrap" border="1">
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </tfoot>
  <tbody>
    <cfoutput query="somedata">
      <tr>
        <th>#blah1#</th>
        <th>#blah2#</th>
        <th>#blah3#</th>
      </tr>
    </cfoutput>
  </tbody>
</table>

Above is our main table. We call the CFML in the tbody section to populate it with the previously called query. You need thead section for proper heading behavior (sort) for the table and tfoot section for footer behavior (search). This will become more obvious in the actual javascript portion in the end.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script type="text/javascript">
  $(document).ready(function(){
    $('#meatTable tfoot th').each( function () {
      var title = $(this).text();
      $(this).html( '<input type="text" placeholder="Search '+title+'" />');
    } );
    var table = $('#meatTable').DataTable();

    table.columns().every( function () {
      var that = this;
      $( 'input', this.footer() ).on( 'keyup change', function () {
        if ( that.search() !== this.value ) {
          that
              .search( this.value )
              .draw();
        }
      } );
    } );
  } );
</script>
</body>
</html>

This is the last portion. We can reference the table that is being used by using single pound sign (line 3 and 7). Line 3 populates the search by column by putting them in the footer of the table. Line 7 is used to declare the Datatable variable which is used in the rest of the script. That is it. Now you should be able to put the pieces together that you find in the DataTables examples page.
















Tuesday, August 1, 2017

AWS S3 - Policy to limit access to single bucket

How to limit access to only single S3 bucket

I was recently in a situation where an team wanted to allow someone access to their bucket in our account (from Web Console) but wanted to hide all other buckets. I thought this could be done with some sort of "Deny-All-Except-Condition" policy, but I found that this was harder than anticipated. First of all, I couldn't find a conditional statement that matches against bucket name or bucket tag. There are, however, conditional policy for both prefix string or object tag.

So the below is the best I could do and met the team half way. The below policy permits the user to List all bucket names but they cannot browse into any buckets. And grant user full access to one bucket. The "ListAllMyBuckets" is required, otherwise the user can't use S3 feature from AWS Web Console.

This is a IAM Policy that I attached to the IAM User.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1501602649000",
            "Effect": "Allow",
            "Action": [
                "s3:ListAllMyBuckets"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Sid": "Stmt1501602649090",
            "Effect": "Allow",
            "Action": [
                "s3:List*",
                "s3:Get*",
                "s3:Put*",
                "s3:DeleteObject",
                "s3:DeleteObjectVersion"
            ],
            "Resource": [
                "arn:aws:s3:::myBucketName",
                "arn:aws:s3:::myBucketName/*"
            ]
        }
    ]
}

Please share if you got an easier way to limit exposure of S3 buckets to users.

Friday, July 28, 2017

AWS Cloudwatch - Windows Logs

AWS Cloudwatch - Windows Logs

References:

Basic Steps to get it running (this was tested with EC2 service version 3.19.1153)

  1. Update EC2Config to the latest version
  2. Open EC2ConfigService Settings
  3. Under General Tab, Enable CloudWatch Logs
  4. Copy the sample JSON file to your EC2 install location's settings folder
    1. Download Sample JSON File
    2. c:\program files\amazon\ec2configservice\settings
  5. Edit the JSON file 
    1. "Id":"CloudWatchLogs" section should have your information. I leave AccessKey and SecretKey blank because I prefer to use IAM Role that has access to write to CloudWatch. Also, I prefer {hostname} to default, {instance_id} because hostname means something without cross referencing. 
    2. "Id":"CloudWatch" section should have your region and NameSpace. NameSpace is the name that you give to your CustomMetrics.
  6. Go to Services, restart "Ec2Config" service. 
  7. You should see Application and System Event Logs in your CloudWatch Logs

Configuring Logs in AWS.EC2.Windows.CloudWatch.json file

Windows Logs

Fullname
AWS.EC2.Windows.CloudWatch.EventLog.EventLogInputComponent,
AWS.EC2.Windows.CloudWatch

Id: Update the Id to something unique.

Edit the LogName and Levels to your desired Event and Type of messages. Below are possible values for them. 
Possible LogNames (not a complete list). These can be obtained from Windows Event Viewer.
  • Security
  • System
  • Application
  • Setup
  • EC2ConfigService
  • Microsoft-Windows-TerminalServices-LocalSessionManager/Operational
Possible Levels:
  • 1: Error Only
  • 2: Warning Only
  • 4. Information Only
  • 3: Error and Warning
  • 5: Error and Information
  • 6: Warning and Information
  • 7: Error, Warning, and Information

Performance Counters

Fullname
AWS.EC2.Windows.CloudWatch.PerformanceCounterComponent.PerformanceCounterInputComponent,
AWS.EC2.Windows.CloudWatch

Id: Update the Id to something unique. Example JSON file has "PerformanceCounter." You can use "MemoryCounter" instead. Do not use special characters or spaces in the ID. 

CategoryName: These can be obtained from Performance Monitor: Add Counter. Categories are first level values shown on the box on top left. They are shown in blue.

CounterName: These can be obtained by expanding the CategoryName. 

InstanceName: These can be obtained from Bottom Left of the Add Counter dialog box. For most this is blank.

MetricName: Some custom metric name that defines this metric

Unit. Possible Values:

Seconds | Microseconds | Milliseconds | Bytes | Kilobytes | Megabytes | Gigabytes | Terabytes | Bits | Kilobits | Megabits | Gigabits | Terabits | Percent | Count | Bytes/Second | Kilobytes/Second | Megabytes/Second | Gigabytes/Second | Terabytes/Second | Bits/Second | Kilobits/Second | Megabits/Second | Gigabits/Second | Terabits/Second | Count/Second | None

DimensionName: Name of the dimension that uniquely identifies this data value. For my situation, I used "ServerName"

DimensionValue: The value for the dimension. For my situation, I used the system variable called,     "{hostname}" Other possible values are {instance_id} and {ip_address}, or combination of these three.

Here's my setting:

Custom logs: 

Custom logs can be uploaded to cloudwatch provided that it meets certain criteria:
  • Each entry must begin with the date format following by a space
  • Log must be one of .NET framework supported text encoding: https://msdn.microsoft.com/en-us/library/system.text.encoding.aspx
Fullname
AWS.EC2.Windows.CloudWatch.CustomLog.CustomLogInputComponent,
AWS.EC2.Windows.CloudWatch"

LogDirectoryPath: Location of the logs



CultureName: Leave it blank to use local locality settings

TimeZoneKind: Local to use local timezone

LineCount: Number of lines in the header to identity the log file

Custom Metrics not found elsewhere:

If there are metrics that are not mentioned elsewhere, you can push the metrics up via cli (or SDK)
1
2
3
4
5
6
aws cloudwatch put-metric-data 
    --namespace "MyOwnNameSpace"
    --metric-name "Memory_Usage"
    --dimensions "Metric=MegabytesFree,OS=Win,ServerName=MyOwn"
    --unit "Megabytes"
    --value "3000"
Unless timestamp is used, it will upload the metric using current data/time. 

Other Logs not mentioned above

  • IIS Logs: Didn't use it, but it seems pretty simple enough. Just enable it in the Flows to use it as is.
  • ETW (Event Tracing for Windows): Also didn't use it. 

Configuring Flow to post the date in AWS.EC2.Windows.CloudWatch.json file


Find the "Flows" section. Each flow consists of Data ID followed by Destination ID. Using the example JSON file, the two destinations are CloudWatchLogs and CloudWatch. If there are more than one Data ID, then enclose them in (). Here's the example from AWS documentation. 




Friday, February 3, 2017

AWS DynamoDB

How to use DynamoDB from AWS CLI. No extra SDK or API. Examples.

These examples assumes you've followed AWS tutorial on setting up your own table. But so we're on the same page, here's my table details:
  • Primary partition key: thisDate (String)
  • That's it...
Why would you ever want to use DynamoDB from command line when you can use PHP, Java, .Net, etc? For me, I wanted to use DynamoDB for storage of metrics, logs, and flags that my PowerShell scripts may use to do (or not do) some activity for my servers. Hey, it's Tuesday, run this script unless there is an entry in the database that tells you otherwise. Until now, I've been using Oracle DB for this purpose which is way overkill. I'm doing this on Powershell, but I'm not using AWS CLI for Powershell. I could have ran these from Command Prompt or Bash. Be sure to format properly for JSON whatever environment you may try these on. Also these JSONs were created using AWS Web Console's DynamoDB Create Item button.

Putting an entry into the table
1
2
3
4
5
$item = '{"thisDate":{"S":"20170131"},"Enabled":{"S":"Yes"}}'
$jsonItem = $item | convertTo-json
aws dynamodb put-item --table-name myTest 
                      --item $jsonItem 
                      --condition-expression "attribute_not_exist(thisDate)"

The --condition-expression used here makes sure the thisDate column is unique and not overwrite existing value

Retrieving an entry from the table

1
2
3
4
$item = '{"Date":{"S":"20170131"}}'
$jsonItem = $item | convertTo-json
aws dynamodb get-item --table-name myTest 
                      --key $jsonItem

This will return the content in JSON format.

Retrieving content that matches certain criteria from the table

1
2
3
4
5
6
$attrib_names = '{"#d":"thisDate"}' | convertTo-json
$attrib_values = '{":year":{"S","2017"}}' | convertTo-json
aws dynamodb scan --table-name myTest
                  --expression-attribute-names $attrib_names
                  --expression-attribute-values $attrib_values
                  --filter-expression "begins_with(#d,:year)"

Attribute names are just substitution of the real column to a short form. These must begin with the "#" symbol. And these are mandatory if your column is a reserved word. If you don't want to take a chance, then just create a substitution attribute name for all your columns that you want to use in the filter expression. But here are list of all reserved words, http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html

Attribute values are variable name, definition, and the value that will be used in the filter expression. These variables must begin with the ":" symbol.

Filter-expression can also be your regular comparison operators (<,>,=,>=,<=). For example,
--filter-expression "#d >= :year" would also be a valid comparison. Here's a more detailed (and really complicated) explanation.
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#FilteringResults

Note that when doing scanning, the entire table is read, so you're not saving any read-times or reservations. And I haven't found a simple way to delete based on some "where" clause, so I just loop through the keys returned from the table scan.

Friday, May 8, 2015

ColdFusion Oddities

I started working [again] with ColdFusion at work recently. We've also migrated from version 9 to 10. And I'm frustrated a lot from certain 'features' that isn't working as expected. This is probably due to legacy settings when I took over the system. But it's annoying nonetheless and I thought I should document it for future reference. If you know of a better workaround, feel free to leave me a comment.

1. "The specific CFC [name] could not be found."

In an attempt to bind a CFC to a CFGRID, you may have seen its inability to find the said CFC file.
<cfgrid name="books" format="html" bind="cfc:books.getRS({cfgridpage},{...},{...},{...})"...
This is because, most likely, the ColdFusion is looking under installation directory's wwwroot (ie. c:\coldfusion10\cfusion\wwwroot). But why? In the same page, I can instantiate an object as follows:
<cfobject name = "book_object" component="books"/>
Whatever the reason, adding a mapping in my Application.cfc didn't do the trick. Instead, I ended up adding a mapping "/mycfc" in the CF Admin site. As a result, my working code looks like this:
<cfgrid name="books" format="html" bind="cfc:mycfc.books.getRS({cfgridpage},{...},{...},{...})"...

2. "Import for tag CFFORM are missing. Use CFAJAXIMPORT..."

So it may be a violation of some Web Programmer's ethics, but I have a single page, "Index.cfm" that uses CFLAYOUT and in it is how I display all my contents. Hence, no need to put header and footer onto each of my pages.
<cflayout type="vbox" name="mylayout">
  <cflayoutarea>header...</cflayoutarea>
  <cflayoutarea name = "body">
    <cfdiv id="contentHere" bind="url:home.cfm"/>
  </cflayoutarea>
  <cflayoutarea>footer...</cflayoutarea>
</cflayout>
So all the content goes in the highlighted portion. But if I try to put a page with CFFORM or CFGRID, it refuses with a something is missing error. If the same page is requested from outside of the cfdiv, it works without any problem. A way around this problem was to put the following line above the <cfdiv.../> line.
<cfajaximport tags="cfform,cfgrid">

3. A cfinput checkbox cannot be used alone.

So with the previously mentioned cfgrid, I had added a filter checkbox, and I passed this to the bind argument. But it kept seeing the value of the checkbox as "yes", even when it wasn't checked.
Admin Only?: <cfinput type="checkbox" name="adminOnly" value="yes" id="adminOnly" onClick="refreshGrid()">
For clarification, refreshGrid() is a javascript function that calls the ColdFusion.grid.refresh command.
The only way around this that I could tell was to add a second checkbox that had the "no" value and hide it.
<cfinput type="checkbox" name="adminOnly" value="no" disabled="disabled" style="opacity:0">


More to come...

Saturday, September 13, 2014

Kindle Fire HD 8.9

How to install custom ROM on your Kindle Fire HD 8.9 from Windows 7.

If you had any other version of Kindle Fire, you wouldn't be reading this post because you would have already found one that worked for you on XDA developers site. If you're at a point where you are getting the following errors, you've come to the right place. This instruction assumes you've already followed these instructions:

  1. Downloaded all the necessary files on Installing Cyanogenmod on Kindle 8.9
  2. Downloaded Google App package here
  3. You've downloaded Android SDK and followed the instruction in enabling ADB driver for your Kindle device here
  4. You've successfully followed Installing Cyanogenmod instruction up to,
    Installing CyanogenMod from Recovery

Now you're getting the following errors:

  • When issuing "adb devices" command you get nothing, hence you can't push files onto your device.
  • Your Kindle device in your Device Manager still shows up with a question make (despite what the Amazon developer told you in his instruction).
  • You try to mound from TRWP, but you get some funky error in your console. This just means that it couldn't mount it for R/W access like a flash drive for easy drag and drop access. 
Take the following steps to fix your issue.
  1. Enable ADB driver for your Kindle device
    1. Right Click on your Unknown Kindle device from Device Manager
    2. Click Update Driver Software...
    3. Browse for driver and Click "Let me pick from a list of devices on my computer"
    4. Select Android Composite ADB Interface (latest version)
    5. Now your ADB connection should work and you should have a new Device icon minus the question mark
  2. Go back to your terminal, and type, "adb devices"
  3. Now you should see a device in a recovery mode (if you left it in TWRP)
  4. Transfer files as instructed by the Installing Cyanogenmod provided above. 
  5. Enjoy.



AWS WAF log4j query

How to query AWS WAF log for log4j attacks 1. Setup your Athena table using this instruction https://docs.aws.amazon.com/athena/latest/ug/wa...