Pages

Tuesday, December 29, 2015

Varnish HTTP accelerator to make dynamic websites faster




Varnish is a HTTP proxy cache or an HTTP accelerator designed to cache http requests to make dynamic websites a lot faster. Varnish is used by high-profile, high-traffic websites including online newspaper sites

The principal configuration mechanism is Varnish Configuration Language (VCL)


############# Installation for centos/redhat/fedora ####################

yum install varnish


*** Listen port should be 80 and Assing our Allocate Memory of 512 MB for caching

vi /etc/sysconfig/varnish


VARNISH_LISTEN_PORT=80


VARNISH_VCL_CONF=/etc/varnish/default.vcl
VARNISH_LISTEN_ADDRESS=
VARNISH_LISTEN_PORT=80
VARNISH_MIN_THREADS=1
VARNISH_MAX_THREADS=1000
VARNISH_THREAD_TIMEOUT=120
VARNISH_STORAGE_SIZE=512M
VARNISH_STORAGE=”malloc,${VARNISH_STORAGE_SIZE}”
VARNISH_SECRET_FILE=/etc/varnish/secret
VARNISH_TTL=120




vi /etc/varnish/default.vcl



Modify the default backend default port 80 to port 81 instead, so the backend section should look like the following

backend default {
 .host = "127.0.0.1";
 .port = "81";
}


Edit the apache httpd.conf to configure apache to listen on port 81 instead

vi /etc/httpd/conf/httpd.conf
Listen 81

service httpd restart


chkconfig varnish on
service varnish start


Test Varnish
------------

yum install curl

curl -I http://localhost

or

Browse a page from this server  by firefox with firebug ....  (Install firefox and also firebug addon)

Try visiting your site and refresh the page multiple times to make sure it was cached, then using firebug go to the Net tab you should see under the fetched resources that it was served by varnish

visit site and refresh by F5 several times..->click firebug -> click "net" tab -> click cache  header





Monday, December 28, 2015

Linux IDS / IPS firewall by Suricata



Suricata is an open source high performance modern Network Intrusion Detection, Prevention and Security Monitoring System for Unix/Linux, FreeBSD and Windows based systems.
It was developed and owned by a non-profit foundation the OISF (Open Information Security Foundation)

IDS / IPS: Suricata is a rule-based Intrusion Detection and Prevention engine that make use of externally developed rules sets to monitor network traffic, as well as able to handle multiple gigabyte traffic and gives email alerts to the System/Network administrators.

Multi-threading: Suricata provides speed and importance in network traffic determination. The engine is developed to apply the increased processing power offered by modern multi-core hardware chip sets. The engine not only provides keywords for TCP, UDP, ICMP and IP, but also has an built-in support for HTTP, FTP, TLS and SMB. A system administrator can able to create its own rule to detect a match within an HTTP stream. This is going to become different Malware detection and control.



Install Prerequisites::
------------------------
# yum install epel-release
# yum -y install libpcap libpcap-devel libnet libnet-devel pcre pcre-devel gcc gcc-c++ automake autoconf libtool make libyaml \
libyaml-devel zlib zlib-devel libcap-ng libcap-ng-devel magic magic-devel file file-devel


IPS for 64 bit systems:   we to need “libnfnetlink” and “libnetfilter_queue” packages
---------------------------

 rpm -Uvh http://rules.emergingthreatspro.com/projects/emergingrepo/x86_64/libnfnetlink-0.0.30-1.x86_64.rpm

 rpm -Uvh http://rules.emergingthreatspro.com/projects/emergingrepo/x86_64/libnfnetlink-devel-0.0.30-1.x86_64.rpm

 rpm -Uvh http://rules.emergingthreatspro.com/projects/emergingrepo/x86_64/libnetfilter_queue-0.0.15-1.x86_64.rpm

 rpm -Uvh http://rules.emergingthreatspro.com/projects/emergingrepo/x86_64/libnetfilter_queue-devel-0.0.15-1.x86_64.rpm


Download latest Suricata source files and Install:
--------------------------------------------------------------

cd  /home/tayab/
wget http://www.openinfosecfoundation.org/download/suricata-1.4.4.tar.gz
tar -xvzf suricata-1.4.4.tar.gz
cd suricata-1.4.4

./configure && make && make install-conf
 ./configure && make && make install-rules
 ./configure && make && make install-full


IPS Installation for 64 bit:
----------------------------
By default, works as an IDS. If you want to add IDS support, install some needed packages as follows.

yum  -y install libnetfilter-queue-dev libnetfilter-queue1 libnfnetlink-dev libnfnetlink0


Suricata Basic Setup
--------------------
 mkdir /var/log/suricata
 mkdir /etc/suricata


 cd /home/tayab/suricata-1.4.4
 cp classification.config /etc/suricata
 cp reference.config /etc/suricata
 cp suricata.yaml /etc/suricata


### start the “Suricata Engine” first time and specify the interface device name of your preference. Instead of eth0,

suricata -c /etc/suricata/suricata.yaml -i eth0


##After several minutes later, check the engine is correctly working and receives and inspects traffic

cd /usr/local/var/log/suricata/
ls -l

total 300
drwxr-xr-x 3 root root   4096 Dec 28 16:13 .
drwxr-xr-x 3 root root   4096 Dec 28 16:04 ..
-rw-r--r-- 1 root root 145436 Dec 28 16:15 fast.log
drwxr-xr-x 2 root root   4096 Dec 28 16:04 files
-rw-r--r-- 1 root root  15287 Dec 28 16:15 http.log
-rw-r--r-- 1 root root  44844 Dec 28 16:15 stats.log
-rw-r--r-- 1 root root  85800 Dec 28 16:15 unified2.alert.1451297619


## Watch “stats.log” file and make sure the displayed information is up-dated in real time.

 tail -f stats.log


###########################

#### Snorby, the web interface frontend for managing IDS alerts
Ruby 1.9.3, at least version 1.9.2 is needed to support Snorby.
wkhtmltopdf, for export to pdf.

 wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.10.0_rc2-static-amd64.tar.bz2
bunzip2 wkhtmltopdf-0.10.0_rc2-static-amd64.tar.bz2
tar xvf wkhtmltopdf-0.10.0_rc2-static-amd64.tar
ls -lh
cp wkhtmltopdf-amd64 /usr/bin/wkhtmltopdf



gem install thor i18n bundler tzinfo bui
yum install git
git clone http://github.com/Snorby/snorby/snorby.git /var/www/html/snorby

or
 wget https://github.com/Snorby/snorby/archive/master.zip
 unzip master.zip
 mv snorby-master/ snorby
 cd snorby
 bundle install

#Configuring database.yml. Make a copy of the example database.yml
cd /var/www/html/snorby/config/ && cp database.yml.example database.yml

mysql -u root -p
create user 'snorbyuser'@'localhost' IDENTIFIED BY 'PASSWORD123';
grant all privileges on snorby.* to 'snorbyuser'@'localhost' with grant option;
flush privileges;

vi /etc/mysql/my.cnf
Comment the bind-address line. Then restart mysqld service.

 vi  /var/www/html/snorby/config/database.yml
 Update user: snorbyuser and Password: PASSWORD123


cd /var/www/html/snorby/config/
 cp snorby_config.yml.example snorby_config.yml

## vi /etc/httpd/conf/httpd.conf

<VirtualHost 203.190.X.X:80>
        ServerAdmin webmaster@localhost
        ServerName snorby.tayabkhan.com
        DocumentRoot /var/www/html/snorby/public

        <Directory "/var/www/html/snorby/public">
                AllowOverride all
                Order deny,allow
                Allow from all
                Options -MultiViews
        </Directory>

</VirtualHost>

## cd /var/www/html/snorby

Must have to Update ruby 1.8 to 1.9.3
*** If not updated... then
yum update
 yum install gcc-c++ patch readline readline-devel zlib zlib-devel
 yum install libyaml-devel libffi-devel openssl-devel make
 yum install bzip2 autoconf automake libtool bison iconv-devel
curl -L get.rvm.io | bash -s stable
 wget https://github.com/rvm/rvm/archive/1.26.11.tar.gz
tar -zxvf 1.26.11.tar.gz
cd rvm-1.26.11/
./install
 source /etc/profile.d/rvm.sh
rvm install 1.9.3
rvm use 1.9.3 --default
#Check Current Ruby Version
ruby --version

cd /var/www/html/snorby
gem install i18n -v '0.7.0'
bundle update activesupport railties rails
bundle pack && sudo bundle install --path vender/cache


MONIT to monitor Linux server


Monit is a free open source and very useful tool that automatically monitors and manages server processfiles,directorieschecksumspermissionsfilesystems and services like ApacheNginxMySQLFTPSSHSendmailand so on in a UNIX/Linux based systems and provides an excellent and helpful monitoring functionality to system administrators.The monit has user friendly web interface where you can directly view the system status and setup up processes using native HTTP(S) web server or via the command line interface.

Installing Moint for CentOS / Redhat / Fedora
-----------------------------------------------------------
yum install epel*
yum install monit
/etc/init.d/monit start
chkconfig monit on

# We can see logs from   tail -f /var/log/monit

## Config file

 vi /etc/monit.conf

** Can change those default settings

set httpd port 2812 and
    use address localhost  # only accept connection from localhost
    allow localhost        # allow localhost to connect to the server and
    allow admin:monit      # require user 'admin' with password 'monit'

----------- to

set httpd port 2812 and
    use address 203.190.X.X # only accept connection from server 203.190.X.X
    allow 203.190.X.0/21        # allow IP-Network to connect to the server and
    allow admin:tayab321      # require user 'admin' with password 'tayab321'

## Also can see in web format....

http://203.190.x.x:2812/
username: admin
password: tayab321

##########
Adding other services to Monit
-------------------------------------
# Adding HTTP service to Monitor
check process httpd with pidfile /var/run/httpd/httpd.pid
group apache
start program = "/etc/init.d/httpd start"
stop program = "/etc/init.d/httpd stop"
if failed host 203.190.X.X port 80
protocol http then restart
if 5 restarts within 5 cycles then timeout


# Adding MySQL service to Monitor
check process mysqld with pidfile /var/run/mysqld/mysqld.pid
group mysql
start program = "/etc/init.d/mysqld start"
stop program = "/etc/init.d/mysqld stop"
if failed host 203.190.10.90 port 3306 then restart
if 5 restarts within 5 cycles then timeout


# Adding MAIL POSTFIX service to Monitor

 check process postfix with pidfile /var/spool/postfix/pid/master.pid
    start program = "/etc/init.d/postfix start"
    stop program  = "/etc/init.d/postfix stop"
    if cpu > 60% for 2 cycles then alert
    if cpu > 80% for 5 cycles then restart
    if totalmem > 200.0 MB for 5 cycles then restart
    if children > 250 then restart
    if loadavg(5min) greater than 10 for 8 cycles then stop
    if failed host 203.190.x.x port 25 type tcp protocol smtp
       with timeout 15 seconds
      then alert
    if 3 restarts within 5 cycles then timeout


# Adding SSH service to Monitor
check process sshd with pidfile /var/run/sshd.pid
start program "/etc/init.d/sshd start"
stop program "/etc/init.d/sshd stop"
if failed host 203.190.X.X port 7707 protocol ssh then restart
if 5 restarts within 5 cycles then timeout


## To check monit syntax error in config file ::   monit -t

####### Enjoy this #tayab@tayabkhan.com###################################







Thursday, December 24, 2015

Denial-of-service (DoS) attack protection by MikroTik


 denial-of-service (DoS) attack is an attempt to make a machine or network resource unavailable to its intended users, such as to temporarily or indefinitely interrupt or suspend services of a host connected to the Internet.

Way to protect by MikroTik is : 

Limit incoming connections
Address with too much connections can be added to address list for blocking.

/ip firewall filter add chain=input protocol=tcp connection-limit=LIMIT,32 action=add-src-to-address-list  address-list=blocked-addr address-list-timeout=1d 

/ip firewall filter add chain=input protocol=tcp src-address-list=blocked-addr connection-limit=3,32 action=tarpit 


Description: 
where LIMIT is max. number of connection per IP. LIMIT should be 100 or higher as many services use multiple connection (HTTP, Torrent, other P2P programs).
Action tarpit. Instead of simply droping attackers packets(action=drop) router can capture and hold connections and with enough powerful router is can block the attacker.

NAT with MikroTik ( One to One Mapping)


Using Multiple Public IP to NAT private IP addresses


If we use private ip in our server and want to access that server from internet then we need to set 1 to 1 netmap bellow are the configuration of netmap, you just need to change the public IP, Private IP and WAN interface name as per your configuration.

say we have 4 public ip address 10.10.55.171 to 10.10.55.174
and we want to netmap private IP address 192.168.123.71 to 192.168.123.74


/ip address add address=10.10.55.171/32 interface=wan
/ip address add address=10.10.55.172/32 interface=wan
/ip address add address=10.10.55.173/32 interface=wan
/ip address add address=10.10.55.174/32 interface=wan

/ip firewall nat add chain=dstnat dst-address=103.10.55.171 action=dst-nat to-addresses=192.168.123.71
/ip firewall nat add chain=dstnat dst-address=103.10.55.172 action=dst-nat to-addresses=192.168.123.72
/ip firewall nat add chain=dstnat dst-address=103.10.55.173 action=dst-nat to-addresses=192.168.123.73
/ip firewall nat add chain=dstnat dst-address=103.10.55.174 action=dst-nat to-addresses=192.168.123.74

/ip firewall nat add chain=srcnat src-address=192.168.123.71 action=src-nat to-addresses=103.10.55.171
/ip firewall nat add chain=srcnat src-address=192.168.123.72 action=src-nat to-addresses=103.10.55.172
/ip firewall nat add chain=srcnat src-address=192.168.123.73 action=src-nat to-addresses=103.10.55.173
/ip firewall nat add chain=srcnat src-address=192.168.123.74 action=src-nat to-addresses=103.10.55.174

MikroTik Backup Auto/Schedule Send to EMAIL



Goto:  Tools -> Email 
smtp server : mail.tayabkhan.com
port: 25
from : tayab@tayabkhan.com

Here we will create schedule for auto backup sent to email address every 1 day and this will start work at every day 8:01PM(20:01:00)

Goto: System ->scheduler

Name :  mail full backup
start date : 20:01:00
Intervale : 1d 00:00:00 

/system backup save name=emailback
/tool e-mail send file=emailback.backup to="tayab@tayabkhan.com" body="Backup of Mikrotik" subject="$[/system identity get name] $[/system clock get time] $[/system clock get date] Backup"

Mail SPAM detect by MikroTik


We need to create a Firewall Filter Rule


/ip firewall filter

add chain=forward protocol=tcp dst-port=25 src-address-list=suspectedspambot \
    action=drop comment="Drop traffic from those on the suspect list"

add chain=forward protocol=tcp dst-port=25 \
    connection-limit=10,32 \
    action=add-src-to-address-list \
    address-list=suspectedspambot \
    address-list-timeout=2d \
    comment="More than 10 simultaneous connections looks spammer"


We use alternated colors for readability. The operation of this approach is quite simple. The first rule (in blue) simply drops any SMTP connection attempts from anyone who is found in the address list called “suspectedspambot”. The second rule (in red) is the one that does the work of actually detecting spammers. What this rule does is watch for SMTP connections and, if the count of connections from a single IP (/32) goes above 10, then the source address of that packet is added to an address list called “suspectedspambot”. On the next connection attempt, the packet will be dropped. The only problem with this approach is that it assumes that there are NO mail servers that MAY be sending more than 10 emails at a time legitimately. If this is the case, you can simply create another address list called “smtpservers” then add a rule as follows ABOVE the rule above (in blue):



add chain=forward protocol=tcp dst-port=25 \

       src-address-list=smtpservers action=accept \

       comment="Allow known smtp servers to send email"



This would allow your known mail servers to send email without fear of being “caught” and tagged as a spam source. One further comment on these rules. This set of rules does not take into account smtp traffic that is going TO your mail server. I will leave that fix as an exercise for the reader. If one of your customers is “tagged” as a suspected spambot, you will find their IP address in the address list and can begin troubleshooting from there.

Saturday, December 19, 2015

Juniper Real-Time Performance Monitoring (RPM)


tayab@MX#  edit services rpm


[edit services]
rpm {
  probe server-network-monitor {
   test icmp-test {
     probe-type icmp-ping-timestamp;
     target address 203.190.x.x;
     probe-count 15;
     probe-interval 1;
     test-interval 600;
   }
  }
}


set services rpm probe icmp-test test icmp probe-type icmp-ping-timestamp
set services rpm probe icmp-test test icmp target address 192.168.10.90
set services rpm probe icmp-test test icmp probe-count 15
set services rpm probe icmp-test test icmp probe-interval 1
set services rpm probe icmp-test test icmp test-interval 600
set services rpm probe icmp-test test http probe-type http-get
set services rpm probe icmp-test test http target url http://www.tayabkhan.com
set services rpm probe icmp-test test http probe-count 15
set services rpm probe icmp-test test http probe-interval 1

set services rpm probe icmp-test test http test-interval 600

** To see results

tayab@MX#   run show services rpm probe-results



Configure the target address as the loopback address of the remote device (in this case, the loopback address on any-router).
You must also configure the number of probes in each test, the length of time between probes, and the length of time between tests. Juniper recommends configuring between 10 and 20 probes at one-second intervals. This particular test is going to run every ten minutes

Real-Time Performance Monitoring (RPM) enables you to configure active probes to track and monitor traffic. Probes collect packets per destination and per application, including PING Internet Control Message Protocol (ICMP) packets, User Datagram Protocol and Transmission Control Protocol (UDP/TCP) packets with user-configured ports, user-configured Differentiated Services code point (DSCP) type-of-service (ToS) packets, and Hypertext Transfer Protocol (HTTP) packets. 

Probe configuration and probe results are supported by the command-line interface (CLI) and SNMP.

The following probe types are supported with DSCP marking:

ICMP echo
ICMP timestamp
HTTP get (not available for BGP RPM services)
UDP echo
TCP connection
UDP timestamp
With probes, you can monitor the following:

Minimum round-trip time
Maximum round-trip time
Average round-trip time
Standard deviation of the round-trip time
Jitter of the round-trip time—The difference between the minimum and maximum round-trip time
One-way measurements for ICMP timestamp probes include the following:

Minimum, maximum, standard deviation, and jitter measurements for egress and ingress times
Number of probes sent
Number of probe responses received
Percentage of lost probes

virtualmin domain edit problem



Error

Failed to modify server : Missing or invalid mail username prefix




Monday, December 7, 2015

Juniper Outputs in Web view




tayab@MX> show bgp summary | display xml
or
tayab@DOL-MX>  show route protocol bgp | display xml


XML Output of BGP Summary
--------------------------------------
<rpc-reply xmlns:junos="http://xml.juniper.net/junos/13.3R1/junos">
    <bgp-information xmlns="http://xml.juniper.net/junos/13.3R1/junos-routing">
        <group-count>4</group-count>
        <peer-count>4</peer-count>
        <down-peer-count>0</down-peer-count>
        <bgp-rib junos:style="brief">
            <name>inet.0</name>
            <total-prefix-count>1921</total-prefix-count>
            <received-prefix-count>1921</received-prefix-count>
            <accepted-prefix-count>1879</accepted-prefix-count>
            <active-prefix-count>1878</active-prefix-count>
            <suppressed-prefix-count>0</suppressed-prefix-count>
            <history-prefix-count>0</history-prefix-count>
            <damped-prefix-count>0</damped-prefix-count>
            <total-external-prefix-count>1921</total-external-prefix-count>
            <active-external-prefix-count>1878</active-external-prefix-count>
            <accepted-external-prefix-count>1879</accepted-external-prefix-count>
            <suppressed-external-prefix-count>0</suppressed-external-prefix-count>
            <total-internal-prefix-count>0</total-internal-prefix-count>
            <active-internal-prefix-count>0</active-internal-prefix-count>
            <accepted-internal-prefix-count>0</accepted-internal-prefix-count>
            <suppressed-internal-prefix-count>0</suppressed-internal-prefix-count>
            <pending-prefix-count>0</pending-prefix-count>
            <bgp-rib-state>BGP restart is complete</bgp-rib-state>
        </bgp-rib>
        <bgp-peer junos:style="terse" heading="Peer                     AS      InPkt     Ou
ted/Damped...">
            <peer-address>43.245.235.1</peer-address>
            <peer-as>58691</peer-as>
            <input-messages>59785</input-messages>
            <output-messages>60259</output-messages>
            <route-queue-count>0</route-queue-count>
            <flap-count>8</flap-count>
            <elapsed-time junos:seconds="1643733">2w5d0h</elapsed-time>
            <peer-state junos:format="1/43/1/0             0/0/0/0">Established</peer-state>
            <bgp-rib>
                <name>inet.0</name>
                <active-prefix-count>1</active-prefix-count>
                <received-prefix-count>43</received-prefix-count>
                <accepted-prefix-count>1</accepted-prefix-count>
                <suppressed-prefix-count>0</suppressed-prefix-count>
            </bgp-rib>
        </bgp-peer>
        <bgp-peer junos:style="terse">
            <peer-address>59.152.98.41</peer-address>
            <peer-as>58715</peer-as>
            <input-messages>15930</input-messages>
            <output-messages>16501</output-messages>
            <route-queue-count>0</route-queue-count>
            <flap-count>28</flap-count>
            <elapsed-time junos:seconds="357732">4d 3:22:12</elapsed-time>
            <peer-state junos:format="0/1/1/0              0/0/0/0">Established</peer-state>
            <bgp-rib>
                <name>inet.0</name>
                <active-prefix-count>0</active-prefix-count>
                <received-prefix-count>1</received-prefix-count>
                <accepted-prefix-count>1</accepted-prefix-count>
                <suppressed-prefix-count>0</suppressed-prefix-count>
            </bgp-rib>
        </bgp-peer>
        <bgp-peer junos:style="terse">
            <peer-address>59.152.98.45</peer-address>
            <peer-as>58715</peer-as>
            <input-messages>16048</input-messages>
            <output-messages>16559</output-messages>
            <route-queue-count>0</route-queue-count>
            <flap-count>26</flap-count>
            <elapsed-time junos:seconds="357731">4d 3:22:11</elapsed-time>
            <peer-state junos:format="2/2/2/0              0/0/0/0">Established</peer-state>
            <bgp-rib>
                <name>inet.0</name>
                <active-prefix-count>2</active-prefix-count>
                <received-prefix-count>2</received-prefix-count>
                <accepted-prefix-count>2</accepted-prefix-count>
                <suppressed-prefix-count>0</suppressed-prefix-count>
            </bgp-rib>
        </bgp-peer>
        <bgp-peer junos:style="terse">
            <peer-address>198.32.167.1</peer-address>
            <peer-as>65534</peer-as>
            <input-messages>34634</input-messages>
            <output-messages>25520</output-messages>
            <route-queue-count>0</route-queue-count>
            <flap-count>93</flap-count>
            <elapsed-time junos:seconds="677003">1w0d20h</elapsed-time>
            <peer-state junos:format="1875/1875/1875/0     0/0/0/0">Established</peer-state>
            <bgp-rib>
                <name>inet.0</name>
                <active-prefix-count>1875</active-prefix-count>
                <received-prefix-count>1875</received-prefix-count>
                <accepted-prefix-count>1875</accepted-prefix-count>
                <suppressed-prefix-count>0</suppressed-prefix-count>
            </bgp-rib>
        </bgp-peer>
    </bgp-information>
    <cli>
        <banner></banner>
    </cli>
</rpc-reply>
---------------------------

** Copy this XML to paste in any web server
You can also convert this XML file to HTML file  online 
 http://codebeautify.org/xml-to-html-converter


*****  call  this  route.xml file to an HTML file this way....
-----------------------------------------------------------------------

      <html>
<head>
<title>BGP Route OUTPUT</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>

<?php
// Loading the XML file
$xml = new SimpleXMLElement("route.xml", 0, true);
?>

<div class="container">
<div class="page-header">
<h3><a href="testcode1.php">Test-ISP</a> <small>ISP Description</small></h3>
</div>

<table class="table table-hover">
<thead>
<tr>
<th>Route</th>
<th>AS Path</th>
<th>Protocol</th>
<th>Validation</th>
</tr>
</thead>

<?php

$startPage = $_GET['page'];
$perPage = 500;
$currentRecord = 0;
foreach($xml->{'route-information'}->{'route-table'}->{'rt'} as $record){
$currentRecord += 1;
if($currentRecord > ($startPage * $perPage) && $currentRecord < ($startPage * $perPage + $perPage)){

$route = str_replace("\n", "", $record->{'rt-destination'});
$aspath = str_replace("\n", "", $record->{'rt-entry'}->{'as-path'});
$protocolname = str_replace("\n", "", $record->{'rt-entry'}->{'protocol-name'});
$validation = str_replace("\n", "", $record->{'rt-entry'}->{'validation-state'});
echo "<tbody>";
echo "<tr>";
echo "<td class=\"small\">{$route}</td>";
echo "<td class=\"small\">{$aspath}</td>";
echo "<td class=\"small\">{$protocolname}</td>";
if ($validation=="invalid")
{echo "<td class=\"small\"><span class=\"label label-danger\">$validation</span></td>";}
elseif ($validation=="valid")
{echo "<td class=\"small\"><span class=\"label label-success\">$validation</span></td>";}
else
{echo "<td class=\"small\"><span class=\"label label-default\">$validation</span></td>";}
echo "</tr>";
echo "</tbody>";
}//end of if loop
}//endo of foreach loop

//pagination
for ($i = 1; $i <= ($currentRecord / $perPage); $i++) {
echo("<a href='testcode1.php?page=".$i."'>\t".$i."</a>");
}
?>
</table>
</div>
</body>
</html>

--------------------------------------------------------------------------------------------



Thursday, December 3, 2015

Juniper System Management






show host ns lookup
show version displays software running on the box
show system software displays installed packages
show system uptime uptime of the router
show system processes Show the process table
show system statistics Show protocol statistics
show system connections lists only active IP sockets on RE
show system users Show users currently logged into the system
show system storage displays the amount of amount of free disk space on file system
root% df -k show system storage from Shell
show system boot-messages displays contents of boot log  (boot-up messages)
show system virtual-memory displays current memory state
request system reboot Restarts the system
request system halt Stops the router and prepares it to be shut down
request system reboot Reboot the system
request system snapshot Save config in /altconfig and software in /altroot before upgrade
request support information show tech
request system software add <pkgname> performs bsd pgkadd; always use jbundle (4->5 jinstall)

Tuesday, November 17, 2015

Use of Windows Search

উইন্ডোজ সার্চ এর ব্যবহার 
---------------------------

এক্সপ্লোরারের ওপরে ডান পাশের কোণার সার্চবার ব্যবহার করে বা Ctrl+F চেপে সহজেই দরকারি ফাইল খোঁজা যায়। সার্চের ঘরে গিয়ে type: application লিখলে অ্যাপ্লিকেশন ফাইলগুলো খুঁজবে। এভাবে ছবির ফাইল খুঁজতে type: image লিখুন। সব ছবির ফাইল দেখাবে। যে রকম ফাইল দরকার type:-এর পর লিখলে সেটি খুঁজে নিয়ে দেখাবে। এভাবে type:pdf লিখলে পিডিএফ ফাইল আর type:word লিখলে ওয়ার্ড ফাইল দেখাবে। size: লিখে তারপর পছন্দমতো আকার উল্লেখ করলে সেটা ধরেও দেখাবে।
উইন্ডোজ এক্সপ্লোরারের Sort by অপশন ব্যবহার করে দরকারি ফাইল, অ্যাপ্লিকেশন, লেখা বা ছবিকে তার Size, Name, Type, Date modified আকারে খুঁজে নেওয়া যাবে। যেকোনো ফোল্ডারে গিয়ে ফাঁকা জায়গায় ডান ক্লিক করে Sort by-এর কনট্যাক্টস তালিকার Name নির্বাচন করলে বর্ণানুক্রমে ফাইল দেখাবে। Type নির্বাচন করলে সে ফাইলের ধরন অনুযায়ী দেখাবে (যেমন *.doc গুলো একসঙ্গে থাকবে)। Size নির্বাচন করলে ফাইলের আকার অনুযায়ী দেখাবে।
সর্বশেষ কোন ফাইলটি রেখেছেন সেটি আগে দেখতে চাইলে তালিকা থেকে Date modified নির্বাচন করতে হবে। অনেক সময় এটি তালিকায় থাকে না। এটি আনতে Sort by-এর তালিকার More ক্লিক করুন। Choose Details উইন্ডো চালু হলে এখান থেকে Date modified-এর ঘরে টিক চিহ্ন দিন। এভাবে এখানে থাকা প্রয়োজনীয় অপশনগুলোর পাশে টিক চিহ্ন দিয়ে ওকে চাপলে সেটি Sort by-এর তালিকায় যুক্ত হয়ে যাবে। প্রয়োজন অনুযায়ী সেই অপশন নির্বাচন করলে সেভাবে ফাইল বা ফোল্ডার দেখাবে। এভাবে সর্ট বাই তালিকার Ascending-এ ক্লিক করলে A থেকে Z আকারে দেখাবে। আর descending-এ ক্লিক করলে Z থেকে A আকারে ফাইল দেখাবে। আবার ফাঁকা জায়গায় মাউসের রাইট বোতাম চেপে Group by ক্লিক করলে সর্ট বাইয়ের কাজগুলোয় প্রতিটি আলাদা আলাদা গ্রুপ আকারে দেখাবে।

Sunday, November 15, 2015

Shell Scripts to See Linux Info and Error Exit




#!/bin/bash
# system_page - A script to produce an system information HTML file
 
##### Constants
 
TITLE="System Information for $HOSTNAME"
RIGHT_NOW=$(date +"%x %r %Z")
TIME_STAMP="Updated on $RIGHT_NOW by $USER"
 
##### Functions
 
function system_info
{
echo "<h2>System Information</h2>"
    echo "<pre>"
    uname -a
    echo "</pre>"
}
 
function show_uptime
{
echo "<h2>System uptime</h2>"
    echo "<pre>"
    uptime
    echo "</pre>"
}
 
function drive_space
{
echo "<h2>Filesystem space</h2>"
    echo "<pre>"
    df -h
    echo "</pre>"
}
 
function home_space
{
echo "<h2>Home directory space by user</h2>"
    echo "<pre>"
    echo "Bytes Directory"
    du -s /home/* | sort -nr
    echo "</pre>"
}
 
##### Main
 
cat <<- _EOF_
  <html>
  <head>
      <title>$TITLE</title>
  </head>
 
  <body>
      <h1>$TITLE</h1>
      <p>$TIME_STAMP</p>
      $(system_info)
      $(show_uptime)
      $(drive_space)
      $(home_space)
  </body>
  </html>
_EOF_


===========================
===========================
Error exit function
=========================
#!/bin/bash

# A slicker error handling routine

# I put a variable in my scripts named PROGNAME which
# holds the name of the program being run.  You can get this
# value from the first item on the command line ($0).

PROGNAME=$(basename $0)

function error_exit
{

# ----------------------------------------------------------------
# Function for exit due to fatal program error
#  Accepts 1 argument:
#   string containing descriptive error message
# ----------------------------------------------------------------


 echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
 exit 1
}

# Example call of the error_exit function.  Note the inclusion
# of the LINENO environment variable.  It contains the current
# line number.

echo "Example of error with line number and message"
error_exit "$LINENO: An error has occurred."

=======================================================

Wednesday, October 21, 2015

Roundcube Installation in ISPCONFIG linux



## Go to phpmyadmin or mysql root login by command prompt

##
Database name: dbroundcube
Database user: roundcubeuser
Database user password: xxxxxx

## Dump SQL or import the SQL file from
(download this sql file from server location after untar roundcube)
/usr/share/roundcube/SQL/mysql.initial.sql

## mkdir /usr/share/roundcube
cd /usr/share/roundcube

## Download the latest version from the web of roundcube and
   uncompress in the current directory

wget http://jaist.dl.sourceforge.net/project/roundcubemail/roundcubemail/1.1.3/roundcubemail-1.1.3.tar.gz
tar -zxvf roundcubemail-1.1.3.tar.gz
mv roundcubemail-1.1.3 roundcube


wget http://jaist.dl.sourceforge.net/project/roundcubemail/roundcubemail/1.1.3/roundcube-framework-1.1.3.tar.gz
tar -zxvf roundcube-framework-1.1.3.tar.gz

mv roundcube/* .

mkdir /usr/share/roundcube/installer/Roundcube
cp /usr/share/roundcube/roundcube-framework-1.1.3/bootstrap.php /usr/share/roundcube/installer/Roundcube


chown root:root -R /usr/share/roundcube
chmod 777 -R /usr/share/roundcube/temp/
chmod 777 -R /usr/share/roundcube/logs/



## vi  /etc/httpd/conf/sites-enabled/000-ispconfig.conf

<Directory /usr/share/roundcube>
  Order allow,deny
  Allow from all
</Directory>



##  vi  /etc/httpd/conf.d/roundcube.conf

##########################################
# Roundcube is a webmail package written in PHP.

Alias /roundcube /usr/share/roundcube

<Directory /usr/share/roundcube/config>
  Order Deny,Allow
  Deny from All
</Directory>

<Directory /usr/share/roundcube/temp>
  Order Deny,Allow
  Deny from All
</Directory>

<Directory /usr/share/roundcube/logs>
  Order Deny,Allow
  Deny from All
</Directory>

# this section makes Roundcube use https connections only, for this you
# need to have mod_ssl installed. If you want to use unsecure http
# connections, just remove this section:
<Directory /usr/share/roundcube>
  RewriteEngine  on
  RewriteCond    %{HTTPS} !=on
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</Directory>

###############################

#  vi /usr/share/roundcube/installer/index.php

Change
require_once 'bc.php';
 to
require_once '/usr/share/roundcube/program/include/bc.php';



yum -y install libicu-devel
yum -y install php-intl

## service httpd restart

### https://server-ip/roundcube/installer

## /usr/share/roundcube/config/config.inc.php.

 mv config.inc.php.sample config.inc.php
 vi config.inc.php
 $config['enable_installer'] = true;

$config['db_dsnw'] = 'mysql://roundcubeuser:Password@localhost/dbroundcube';

## vi /etc/httpd/conf/httpd.conf
**Uncomment this line
TypesConfig /etc/mime.types


### https://server-ip/roundcube/installer


## rm -rf /usr/share/roundcube/installer

#########################

modification
######################

vi /usr/share/roundcube/config/config.inc.php

$config['product_name'] = 'Corporate Webmail';

############ Change logo #########

# find /usr/share/roundcube/ | grep roundcube_logo

/usr/share/roundcube/skins/classic/images/roundcube_logo.png
/usr/share/roundcube/skins/larry/images/roundcube_logo.png


=============================
Roundcube Password Change Plugin Installation
====================================

 # cd /usr/share/roundcube/
# vi config/config.inc.php

// Add 'password' plugin here

// List of active plugins (in plugins/ directory)
$config['plugins'] = array(
    'archive',
    'zipdownload',
    'password',
);

# cd plugins/password/
#   vi config.inc.php

$config['password_driver'] = 'sql';
// Determine whether current password is required to change password.
// Default: false.
$config['password_confirm_current'] = true;

// set to blank to allow passwords of any length
$config['password_minimum_length'] = 8;

// Require the new password to contain a letter and punctuation character
// Change to false to remove this check.
$config['password_require_nonalpha'] = true;


// BLOCK THIS     $config['password_db_dsn'] = '';

$config['password_db_dsn'] = 'mysql://ispconfig:passwordofispconfigdbase@localhost/dbispconfig';


// BLOCK THIS $config['password_query'] = 'SELECT update_passwd(%c, %u)';

$config['password_query'] = 'UPDATE mail_user SET password=%c WHERE email=%u LIMIT 1';


#### see ispconfig db password::  cat  /usr/local/ispconfig/server/lib/config.inc.php


### Login RoundCube Webmail and Click Settings  and Click Password tab 

and then reset  your password.


=========================================

Use HTML Signature or company logo with Email.

At first, put your logo in a web directory that can be accessible and then ....

Goto-- Settings -> Identities -> Html Signature -> Click HTML button (Edit HTML source)
->

<pre>--
Thanking you,

Tayab khan,
MSC,MCP,CCNA,CCNP,CCNSP,JNCIA,JNCIS-SEC,
Manager(System &amp; Network)
Daffodil Online Ltd.
Cell: +8801914035805
</pre>
<p><img src="http://mail.daffodilnet.com/roundcube/skins/classic/images/roundcube_logo.png" alt="" /></p>

----------------------------------------

Mounting NTFS disk / usb in Linux

***  At first install epel  repository

# yum install epel*

*** Then install package  ntfs-3g  to mount ntsf files

# yum install ntfs-3g

*** Now Mount your USB directory by  
# fdisk -l

# mount -t ntfs-3g /dev/sdb1 /mnt/

*** Now check disk

# df -h



Sunday, September 20, 2015

Juniper FTP server to Upload file or OS




##################################################
Enable FTP server from configure mode

# set system services ftp
# commit

and upload any file using Filezilla FTP client to Juniper
Use  any username and passowrd by created
(#set system login user tayab class super-user
#set system login user tayab authentication plain-text-password)

*** Upload file will find from shell

tayab@MX> start shell
% cd /var/home/tayab
% ls
% mv osname.tar /var/tmp

** You will find your file ***
#####################################################

Sunday, August 16, 2015

Juniper Warning Boot from Backup after corruption primary root partition and Auto recovery


Juniper Warning Boot from Backup after corruption primary root partition and Auto recovery



*** When we loging to any Juniper Router / Switch if this shows like bellow....

THIS DEVICE HAS BOOTED FROM THE BACKUP JUNOS IMAGE


***********************************************************************
**                                                                   **
**  WARNING: THIS DEVICE HAS BOOTED FROM THE BACKUP JUNOS IMAGE      **
**                                                                   **
**  It is possible that the primary copy of JUNOS failed to boot up  **
**  properly, and so this device has booted from the backup copy.    **
**                                                                   **
**  Please re-install JUNOS to recover the primary copy in case      **
**  it has been corrupted.                                           **
**                                                                   **
***********************************************************************


### Solutions ####
##################


* Check Alarms by bellow command

## show chassis alarms

2 alarms currently active
Alarm time               Class  Description
2015-07-10 21:09:58 UTC  Major  PEM 1 Output Failure
2015-07-10 21:09:53 UTC  Minor  Host 0 Boot from backup root



* Now check partitions by bellow command

### show system storage partitions

Boot Media: internal (ad0)
Active Partition: ad0s1a
Backup Partition: ad0s2a
Currently booted from: backup (ad0s2a)

Partitions information:
  Partition  Size   Mountpoint
  s1a        619M   altroot
  s2a        620M   /      
  s3e        49M    /config
  s3f        615M   /var    
  s4a        54M    recovery
  s4e        5.6M


* We can repair the primary partition, by using "request system snapshot media internal slice alternate" without any downtime.

** Copy from backup to Active partition (Also Format Primary Active Partition) by bellow command
### request system snapshot media internal slice alternate

Formatting alternate root (/dev/ad0s1a)...
Copying '/dev/ad0s2a' to '/dev/ad0s1a' .. (this may take a few minutes)
The following filesystems were archived: /


* The following commands are issued to verify the Junos image installed on each slice:

        ###show system snapshot media internal slice 1
        ###show system snapshot media internal slice 2

** againg see alarms by ## show chassis alarms 

** To avoid alarms, use the following command to ensure that the switch boots from the primary partition:

## For EX2200 Switch **  request system reboot slice alternate media internal

### request system reboot slice alternate media internal
*N.B. to reboot now and show the effect  ## request system reboot

** after reboot check Currently booted from:  active or backup ?? if active then ok....
## show system storage partitions          
Boot Media: internal (ad0)
Active Partition: ad0s1a
Backup Partition: ad0s2a
Currently booted from: active (ad0s1a)


** Use auto recovery for some Juniper devices like SRX
### request system autorecovery state save