collecting SSL expiration information

This small function gathers expiry information from an SSL certificate and calculates days remaining until expire. You may query multiple domains by calling get_cert_exp function in a loop.

Enjoy!

<?php

function get_cert_exp($url){
$orignal_parse = parse_url($url, PHP_URL_HOST);
$get = stream_context_create(array(“ssl” => array(“capture_peer_cert” => TRUE)));
$read = stream_socket_client(“ssl://”.$orignal_parse.”:443″, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
$cert = stream_context_get_params($read);
$certinfo = openssl_x509_parse($cert[‘options’][‘ssl’][‘peer_certificate’]);

//$expired= getdate($certinfo[validTo]);
$end=($certinfo[validTo]);
$end=substr($end, 0, -1); //remove last char from string
$chunks = str_split($end, 2);
//Convert array to string. Each element separated by the given separator.
$expire_date = implode(‘:’, $chunks);
$expire_date=’20’.$expire_date;

// Days left to expire date //
$gd_a = getdate( $certinfo[‘validTo_time_t’] );
$gd_b = getdate( time() );

$a_new = mktime( 12, 0, 0, $gd_a[‘mon’], $gd_a[‘mday’], $gd_a[‘year’] );
$b_new = mktime( 12, 0, 0, $gd_b[‘mon’], $gd_b[‘mday’], $gd_b[‘year’] );

$days_left=round( abs( $a_new – $b_new ) / 86400 );
// end of calculation //
if ($days_left <= 50 ) {
$days_left=”<b><font color=red>”.$days_left.”</font></b>”;
}else{
$days_left=”<b><font color=green>”.$days_left.”</font></b>”;
}

echo “SSL Certificate of <b> $url </b>is valid until “.$expire_date.'</br>’;
echo “Days remaining until expiration : “. $days_left.'</br>’;
}

 

get_cert_exp(“https://your.nice.expiring.domain/”);

?>

collecting IBM v7000 and Netapp storage information with PHP

I wrote this small code for our early morning checks to see the summary of IBM v700 and Netapp storage systems.

This simply collects Failed Disks, Aggregates, Volumes and battery status information and Alerts of each system for managerial reports on request. Or, can be situated at intranet portal.

Enjoy!

<?php
include_once(‘header.php’); //here you have session and menu information
//
//20-01-2016 – Cem DOGAN
//
// Report all PHP errors
#error_reporting(E_ALL);
//required php libraries for ssh connection. php net_ssh2
set_include_path(‘lib/’);
include(‘Net/SSH2.php’);
include(‘File/ANSI.php’);

$filer_username=”YOUR-READ-ONLY-USER”;
$filer_password=”YOUR-PASSWORD”;

function Visit_ssh($server, $username, $password, $command) {

#echo $server, $username, $password, $command;

$ssh = new Net_SSH2($server);
if (!$ssh->login($username, $password)) {
return (‘Login Failed’);
}
else {
return $ssh->exec($command);
}
}

/////////////////////////////////
//IBM v7000 Part /
/////////////////////////////////

$v7000_ip = array(
“AMS-SV7-01″=>”10.104.1.183”,
“DUS-SV7-01″=>”10.104.14.110”,
);

 

foreach($v7000_ip as $x => $x_value){
echo ‘<h6><u>’.$x.’ ‘.$curdate.’ : </u></h6>’;
echo ‘<pre>’;
echo “<u>Pool Usage;</u></br>”;
$filer_result=Visit_ssh($x_value, $filer_username, $filer_password, “lsmdiskgrp -delim :”);
// echo $filer_result;

$lines = explode(PHP_EOL, $filer_result); //put every line into array
$lines=array_filter($lines); //clean empty array objects

$line_counter=0;
$line_count=count($lines);
echo ‘<table>’;
foreach ($lines as $line) {
$item= explode(‘:’, $line);
echo ‘<tr>’;
if ($line_counter == 0) {
//display table header
echo “<th>$item[0]</th>”;//id
echo “<th>$item[1]</th>”;//name
echo “<th>$item[2]</th>”;//status
echo “<th>$item[5]</th>”;//capacity
echo “<th>$item[7]</th>”;//free capacity
echo “<th>$item[15]</th>”;//compression active

} else {
// table content
echo “<td>$item[0]</td>”;
echo “<td>$item[1]</td>”;
echo “<td>”;
if (preg_match(‘/online/’,$item[2])) {
echo “<b><font color=green>$item[2]</font></b>”;
}else {
echo “<font color=red>”.$item[2].”</font>”;
}
echo “</td>”;
echo “<td>$item[5]</td>”;
echo “<td>$item[7]</td>”;
echo “<td>$item[15]</td>”;
}
echo ‘</tr>’;
$line_counter++;
}
echo ‘</table>’;

echo “<u>Battery Status;</u> </br>”;
$filer_result=Visit_ssh($x_value, $filer_username, $filer_password, “lsenclosurebattery -delim :”);

$lines = explode(PHP_EOL, $filer_result); //put every line into array
$lines=array_filter($lines); //clean empty array objects

$line_counter=0;
$line_count=count($lines);
echo ‘<table>’;
foreach ($lines as $line) {
$item= explode(‘:’, $line);
echo ‘<tr>’;
if ($line_counter == 0) {
//display table header
echo “<th>$item[0]</th>”;//enclosure_id
echo “<th>$item[1]</th>”;//battery_id
echo “<th>$item[2]</th>”;//status
echo “<th>$item[3]</th>”;//charging_status
echo “<th>$item[4]</th>”;//recondition_needed
echo “<th>$item[5]</th>”;//percent_charged
echo “<th>$item[6]</th>”;//end_of_life_warning

} else {
// table content
echo “<td>$item[0]</td>”;
echo “<td>$item[1]</td>”;
echo “<td>”;
if (preg_match(‘/online/’,$item[2])) {
echo “<b><font color=green>$item[2]</font></b>”;
}else {
echo “<font color=red>”.$item[2].”</font>”;
}
echo “</td>”;
echo “<td>$item[3]</td>”;
echo “<td>$item[4]</td>”;
echo “<td>$item[5]</td>”;
echo “<td>$item[6]</td>”;
}
echo ‘</tr>’;
$line_counter++;
}
echo ‘</table>’;

echo “<u>Alert(s);</u> </br>”;
$filer_result=Visit_ssh($x_value, $filer_username, $filer_password, ‘lseventlog -filtervalue “status=alert” -fixed no -delim :’);

$lines = explode(PHP_EOL, $filer_result); //put every line into array
$lines=array_filter($lines); //clean empty array objects

$line_counter=0;
$line_count=count($lines);
echo ‘<table>’;
foreach ($lines as $line) {
$item= explode(‘:’, $line);
echo ‘<tr>’;
if ($line_counter == 0) {
//display table header
echo “<th>$item[0]</th>”;//sequence_number
echo “<th>$item[1]</th>”;//last_timestamp
echo “<th>$item[2]</th>”;//object_type
echo “<th>$item[3]</th>”;//object_id
echo “<th>$item[4]</th>”;//object_name
echo “<th>$item[6]</th>”;//status
echo “<th>$item[7]</th>”;//fixed
echo “<th>$item[10]</th>”;//description

} else {
// table content
echo “<td>$item[0]</td>”;
echo “<td>$item[1]</td>”;
echo “<td>$item[2]</td>”;
echo “<td>$item[3]</td>”;
echo “<td>$item[4]</td>”;
echo “<td>”;
if (preg_match(‘/alert/’,$item[6])) {
echo “<b><font color=red>$item[6]</font></b>”;
}
echo “</td>”;

echo “<td>”;
if (preg_match(‘/no/’,$item[7])) {
echo “<b><font color=red>$item[7]</font></b>”;
}
echo “</td>”;
echo “<td>$item[10]</td>”;
}
echo ‘</tr>’;
$line_counter++;
}
echo ‘</table>’;

 

echo ‘</pre>’;
}
/////////////////////////////////
//NetApp Part /
/////////////////////////////////

$storage_ip = array(
“ASD-FILER-A10A”=>”10.104.102.14”,
“ASD-FILER-A20A “=>”10.104.102.10”,
“ASD-FILER-A20B “=>”10.104.102.12”,
“DUS-FILER-A10A “=>”10.104.14.214”,
“DUS-FILER-A20A “=>”10.104.14.210”,
“DUS-FILER-A20B “=>”10.104.14.212”,
);

 

foreach($storage_ip as $x => $x_value){
echo ‘<h6><u>’.$x.’ ‘.$curdate.’ : </u></h6>’;
echo ‘<pre>’;
echo “<u>Failed disks;</u></br>”;
$filer_result=Visit_ssh($x_value, $filer_username, $filer_password, “vol status -f”);
if (preg_match(‘/empty/’,$filer_result)){
$filer_result = preg_replace( “/\r|\n/”, “”, $filer_result );
echo $filer_result.” -<b><font color=green> OK</font></b></br>”;
}
else {
echo “<font color=red>”.$filer_result.”</font>”;
}

 

echo “<u>Aggregates;</u> </br>”;
$filer_result=Visit_ssh($x_value, $filer_username, $filer_password, “df -Ah”);

$pattern=”snap”;
$lines = explode(PHP_EOL, $filer_result);
$exclude = array();

foreach ($lines as $line) {
if (strpos($line, ‘snap’) !== FALSE) {
continue;
}
preg_match(‘/(\d{2,3})\%/’,$line,$s_line); //match percentages
$s_line=array_filter($s_line); //clean empty array
if ( $s_line[1] >= 95 ) {
$line=str_replace($s_line[0],”<b><font color=red>”.$s_line[0].”</font></b>”,$line);
}
else {
$line=str_replace($s_line[0],”<b><font color=green>”.$s_line[0].”</font></b>”,$line);
}
$exclude[] = $line;
}
echo implode(“\n”, $exclude);
echo “<u>Volumes;</u> </br>”;
$filer_result=Visit_ssh($x_value, $filer_username, $filer_password, “df -h”);

$pattern=”snap”;
$lines = explode(PHP_EOL, $filer_result);
$exclude = array();

foreach ($lines as $line) {
if (strpos($line, ‘snap’) !== FALSE) {
continue;
}
preg_match(‘/(\d{2,3})\%/’,$line,$s_line); //match percentages
$s_line=array_filter($s_line); //clean empty array
if ( $s_line[1] >= 95 ) {
$line=str_replace($s_line[0],”<b><font color=red>”.$s_line[0].”</font></b>”,$line);
}
else {
$line=str_replace($s_line[0],”<b><font color=green>”.$s_line[0].”</font></b>”,$line);
}
$exclude[] = $line;
}
echo implode(“\n”, $exclude);

 

echo “<u>Environment;</u> </br>”;
$filer_result=Visit_ssh($x_value, $filer_username, $filer_password, “environment chassis”);

$lines = explode(PHP_EOL, $filer_result);
$exclude = array();

foreach ($lines as $line) {
preg_match(‘/ok/’,$line,$s_line); //match word
$s_line=array_filter($s_line); //clean empty array
if ( isset($s_line[0])) {
$line=str_replace($s_line[0],”<b><font color=green>”.strtoupper($s_line[0]).”</font></b>”,$line);
}
else{
$line=str_replace($s_line[0],”<b><font color=red>”.strtoupper($s_line[0]).”</font></b>”,$line);
}
$exclude[] = $line;
}
echo implode(“\n”, $exclude);

 

echo ‘</pre>’;
}

?>

Monitoring Paloalto firewall status by XML API

I wrote this small code for our early morning checks to see the summary of firewalls.

In order to make it working, create a read only user on Device -> Administrators. Then create your API key by following steps described here.

Enjoy!

<?php
include_once(‘header.php’); //here you have session and menu information
// 17/03/2015 Cem DOGAN
// Report all PHP errors
error_reporting(E_ALL);
// Set timezone
#date_default_timezone_set(‘Europe/Amsterdam’);

//proxy information if any. if you have proxy authentication you can enable $proxyauth here
$proxy_ext = ‘10.104.100.13:3128’;
//$proxyauth = ‘user:password’;

function Visit_pa($url,$proxy){
// echo “url : “.$url.” proxy : “.$proxy.”<br/>”;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
if ($proxy == 1){
curl_setopt($ch, CURLOPT_PROXY, $proxy_ext);
}
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CAPATH, “./cacert.pem”);
$curl_scraped_page = curl_exec($ch);
//echo curl_error($ch).”<br/>”;
curl_close($ch);
return $curl_scraped_page;
}
// Palo Alto systems check – OVERWIEW
//this section displays general overview of PaloAlto Firewall.
//key value is your API Key generated before
$pa_status1 = Visit_pa(“https://your.nice.paloalto.url/api/?type=op&cmd=%3Cshow%3E%3Chigh-availability%3E%3Cstate%3E%3C%2Fstate%3E%3C%2Fhigh-availability%3E%3C%2Fshow%3E&key=YOUR-API-KEY-HERE”);

 

$pa_status1 = new SimpleXMLElement($pa_status1);
echo ‘<h6><u>Palo Alto ‘.$curdate.’ : </u></h6><pre>’;
echo ‘<u>PA-Model:</u> ‘.$pa_status1->result->group->{‘local-info’}->{‘platform-model’};
echo ‘<u> Management IP:</u> ‘.$pa_status1->result->group->{‘local-info’}->{‘mgmt-ip’};
echo ‘<u> State:</u> ‘.$pa_status1->result->group->{‘local-info’}->{‘state’};
echo ‘<u> Sync:</u> ‘.$pa_status1->result->group->{‘local-info’}->{‘state-sync’};
echo ‘<br/>’;
echo ‘<u>PA-Model:</u> ‘.$pa_status1->result->group->{‘peer-info’}->{‘platform-model’};
echo ‘<u> Management IP:</u> ‘.$pa_status1->result->group->{‘peer-info’}->{‘mgmt-ip’};
echo ‘<u> State:</u> ‘.$pa_status1->result->group->{‘peer-info’}->{‘state’};
echo ‘<br/>’;
echo ‘<u> Running Sync:</u> ‘.$pa_status1->result->group->{‘running-sync’};
echo ‘<br/>’;

// Palo Alto systems check – SYSTEM CRITICAL LOGS –
//this section checks PA critical logs and displays if any in defined time period.
$days_ago = 3;
$pa_days = date(“Y/m/d%20H:m:s”, ( time( ) – 86400 * $days_ago) );
$days_ago = date(“d-m-Y”, ( time( ) – 86400 * $days_ago) );

$pa_status2 = Visit_pa(“https://your.nice.paloalto.url/api/?type=log&log-type=system&query=(%20severity%20eq%20critical%20)%20and%20(%20receive_time%20geq%20%27$pa_days%27%20)&key=YOUR-API-KEY-HERE”);
$pa_status2 = new SimpleXMLElement($pa_status2);
$pa_status2 = $pa_status2->result->{‘job’};
$pa_status2 = Visit_pa(“https://your.nice.paloalto.url/api/?type=log&action=get&job-id=$pa_status2&key=YOUR-API-KEY-HERE”);
$pa_status2 = new SimpleXMLElement($pa_status2);
$pa_log_count= $pa_status2->result->log->{‘logs’}[count];
echo ‘<u>PA-log count:</u> ‘.$pa_log_count.'<br/>’;
if ($pa_log_count > 0 ) {
echo “PA-system critical logs since $days_ago<br/>”;
$pa_logs=$pa_status2->result->log->logs;
for ($i = 0; $i < $pa_log_count; $i++) {
echo “<u>Seq no: </u>”.$pa_logs->entry[$i]->seqno
.” – <u>Type: </u>”.$pa_logs->entry[$i]->type
.” – <u>Subtype: </u>”.$pa_logs->entry[$i]->subtype
.” – <u>Time: </u>”.$pa_logs->entry[$i]->time_generated
.” – <u>Event ID: </u>”.$pa_logs->entry[$i]->eventid
.” – <u>Opaque: </u>”.$pa_logs->entry[$i]->opaque.”<br/></pre>”;
}
}
else {
echo “<font color=green>No critical log(s) found on PA systems since $days_ago”.”</font></pre>”;

}

?>

php’nin mail fonksiyonuyla gönderilen posta kaydını tutmak


php’nin mail() fonksiyonuyla gönderilen e-postalar varsayılan olarak tanımlı sendmail yazılımı vasıtasıyla gönderilir. Sendmail’in ayarlarından LOG düzeyini arttırsanız da hangi dosyadan veya hangi kullanıcı tarafından gönderildiğini bulamazsınız. Hele web sağlayıcısı olarak hizmet veren bir makinanız varsa hangi kullanıcı sizin kaynaklarınızı kullanarak önemsiz e-posta gönderiyor tespit etmek zordur. Akla gelen yöntemse php ile posta sunucusu arasında sendmail e köprü görevi üstlenen ve aynı zamanda kayıt tutan bir yazılım eklemek. Şöyle;

vi /usr/sbin/sendmail.spamkontrol

diyerek içine

#!/usr/bin/perl
# use strict;
 use Env;
 my $date = `date`;
 chomp $date;
 open (INFO, ">>/var/log/spam_log") || die "Dosya Acilmadi ::$!";
 my $uid = $>;
 my @info = getpwuid($uid);
 if($REMOTE_ADDR) {
 print INFO "$date - $REMOTE_ADDR ran $SCRIPT_NAME at $SERVER_NAME n n";
 print 'n';
}
 else {
print INFO "$date - $PWD -  @infonn";
 print 'n';
}
 my $mailprog = '/usr/sbin/sendmail';
 foreach  (@ARGV) {
 $arg="$arg" . " $_";
 }
open (MAIL,"|$mailprog $arg") || die "cannot open $mailprog: $!n";
 while ( ) {
 print MAIL;
 }
 close (INFO);
 close (MAIL);

dosyayı kaydettikten sonra ;

chmod +x /usr/sbin/sendmail.spamkontrol 
touch /var/log/spam_log 
chmod 0777 /var/log/spam_log

Şeklinde gerekli yetkileri verdikten sonra isterseniz php.ini deki sendmail tarifini yeni dosyamız olan /usr/sbin/sendmail.spamkontrol olarak girebilirsiniz yada apache deki Virtual Host tanımına aşağıdaki gibi bir tanımlama girebilirsiniz.

php_admin_value sendmail_path '/usr/sbin/sendmail.spamkontrol'

Bu değeri herbir VirtualHost tanımına da girebilirsiniz.  Apache’yi tekrar başlattıktan sonra /var/log/spam_log dosyasında ağaşıdaki örnek kayıt dosyası gibi çıktı alacaksınız.

[root@immortal ~]# tail /var/log/spam_log
 Fri Aug 28 15:37:20 EEST 2009 - /home/testuser1 -
 Fri Aug 28 15:45:01 EEST 2009 - /home/testuser2 -
 Fri Aug 28 15:53:30 EEST 2009 - /home/testuser1 -
 Fri Aug 28 15:57:43 EEST 2009 - /home/testuser1 -
 Fri Aug 28 15:58:47 EEST 2009 - /home/testuser2 -
 Fri Aug 28 16:21:21 EEST 2009 - /home/testuser2 -

Eğer log dosyanızın boyutu çok büyürse log rotasyonu için /etc/logrotate.conf dosyasına aşağıdakileri ekleyebilirsiniz.


# SPAM LOG rotation
 /var/log/spam_log { 
 monthly 
 create 0777 root root     
 rotate 1
 }

[MattF ve ramprage’e teşekkürler]